From 91eee8a9f39e643cd3201eb1ce925c9f46d997ae Mon Sep 17 00:00:00 2001 From: Rohit P Date: Thu, 3 Dec 2026 16:01:36 -0800 Subject: [PATCH] Detect configured coding agents in the skill installer --- skills/README.md | 25 +++++++++++- skills/install.mjs | 90 +++++++++++++++++++++++++++++++++++------ skills/install.test.mjs | 61 +++++++++++++++++++++++++++- skills/package.test.mjs | 8 +++- 4 files changed, 168 insertions(+), 16 deletions(-) diff --git a/skills/README.md b/skills/README.md index 6040cf472..46f1e9029 100644 --- a/skills/README.md +++ b/skills/README.md @@ -48,8 +48,8 @@ npx @openworkerai/openworker-harness-builder --dir /path/to/that-agent/skills That creates `/path/to/that-agent/skills/openworker-harness-builder/`. The folder containing `--dir` must already exist; the installer keeps its lock and backups there, next to the skills -folder rather than inside it. `--dir` replaces `--agent`, `--project` and `--global`. An unknown -`--agent` name prints the valid choices. Run the command once per agent if you use several. +folder rather than inside it. `--dir` replaces the agent and scope flags. An unknown +`--agent` name prints the valid choices. The installer supports quoted project paths on Windows and macOS and leaves global settings alone. If a skill already exists, @@ -76,6 +76,27 @@ Cowork, change account settings, or require `npm install -g` or administrator access. Choose either `--global` or `--project`, not both. Both modes require confirmation or the explicit replacement flag before replacing an existing skill. +### Detect configured agents + +Use `--agent opencode` to select OpenCode directly. To install for agents that +already have known configuration folders, use `--detect-agents` in place of `--agent`. + +```sh +npx @openworkerai/openworker-harness-builder --detect-agents --global +npx @openworkerai/openworker-harness-builder --detect-agents --project . +``` + +Global detection checks your home directory and the OpenWorker state folder. +Project detection also checks the selected project, and writes only to that +project. For example, `.opencode/` or `~/.config/opencode/` signals OpenCode. +The installer prints the agents it detected and installs one copy for agents +that share `.agents/skills`. Use `--agent` for an agent that has yet to create +its settings, or `--dir` to specify a custom destination. + +Existing copies follow the usual replacement prompts and backup rules. +If one destination fails, the installer reports it, attempts the others, and +exits with an error status. + ### Update an existing installation Run the same install command again. In an interactive terminal it asks: diff --git a/skills/install.mjs b/skills/install.mjs index 90824b2f5..7e773392a 100644 --- a/skills/install.mjs +++ b/skills/install.mjs @@ -20,7 +20,19 @@ export const AGENTS = Object.freeze({ codex:shared, cursor:shared, gemini:shared, opencode:shared, windsurf:shared, agents:shared, }); const agentNames = Object.keys(AGENTS).join(', '); -const usage = 'openworker-harness-builder (--agent (--project /path/to/your-app | --global) | --dir /path/to/skills) [--replace-existing]'; +const usage = 'openworker-harness-builder ((--agent | --detect-agents) (--project /path/to/your-app | --global) | --dir /path/to/skills) [--replace-existing]'; +// Detection hints are separate from the destinations the agents can read. +const agentFolders = { + openworker:{project:['.coworker']}, + claude:{project:['.claude'], home:['.claude']}, + copilot:{project:['.github','skills'], home:['.copilot']}, + codex:{project:['.codex'], home:['.codex']}, + cursor:{project:['.cursor'], home:['.cursor']}, + gemini:{project:['.gemini'], home:['.gemini']}, + opencode:{project:['.opencode'], home:['.config','opencode']}, + windsurf:{project:['.windsurf'], home:['.codeium','windsurf']}, + agents:{project:['.agents','skills'], home:['.agents','skills']}, +}; const files = ['SKILL.md','references/desktop.md','references/web.md','references/sdk.md','references/tools.md','references/approvals.md','references/local-script.md','references/runtime-options.md','references/subagents.md','references/observability.md','references/railway.md','assets/railway/Dockerfile','assets/railway/.dockerignore','assets/local-script/file-tools.mjs','assets/local-script/organizer.mjs']; const agentFiles = [...new Set(Object.values(AGENTS).flatMap(entry => entry.extraFiles))]; const scopeError = () => Error(`Use ${usage}; choose exactly one installation scope.`); @@ -62,12 +74,42 @@ async function target({agent, project, global: userWide = false, dir}, {userHome return {root: await realpath(state), parts: ['skills'], ...entry}; } export function parseInstallArgs(args) { - const {values} = parseArgs({args, options:{agent:{type:'string'}, project:{type:'string'}, global:{type:'boolean'}, dir:{type:'string'}, 'replace-existing':{type:'boolean'}}}); - const {'replace-existing': replaceExisting, ...options} = values; + const {values} = parseArgs({args, options:{agent:{type:'string'}, 'detect-agents':{type:'boolean'}, project:{type:'string'}, global:{type:'boolean'}, dir:{type:'string'}, 'replace-existing':{type:'boolean'}}}); + const {'replace-existing': replaceExisting, 'detect-agents': detect, ...options} = values; if (replaceExisting !== undefined) options.replaceExisting = replaceExisting; + if (detect) { + if (options.agent !== undefined || options.dir !== undefined) throw Error('--detect-agents cannot be combined with --agent or --dir.'); + validate({...options, agent:'agents'}); + return {...options, detect}; + } validate(options); return options; } +async function hasAgentFolder(root, parts) { + try { + for (const part of parts) { + root = join(root, part); + if (!(await lstat(root)).isDirectory()) return false; + } + return true; + } catch (error) { + if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return false; + throw error; + } +} +async function detectAgents({project}, environment) { + const userHome = await realpath(environment.userHome); + const projectRoot = project === undefined ? undefined : await realpath(project); + const state = openworkerStateDir(environment); + const detected = []; + for (const [agent, folders] of Object.entries(agentFolders)) { + const atHome = agent === 'openworker' + ? await hasAgentFolder(dirname(state), [basename(state)]) + : await hasAgentFolder(userHome, folders.home); + if (atHome || (projectRoot && await hasAgentFolder(projectRoot, folders.project))) detected.push(agent); + } + return detected; +} async function realDirectory(path) { try { await mkdir(path); } catch(error) { if(error.code !== 'EEXIST') throw error; } const stat = await lstat(path); @@ -160,6 +202,8 @@ const help = `${usage} copilot .github/skills | ~/.copilot/skills codex, cursor, gemini, opencode, windsurf, agents .agents/skills | ~/.agents/skills (one shared copy these agents all read) +--detect-agents checks for known folders in your home directory and selected project, + then installs once per detected destination. Use --global or --project with it. --dir installs into /openworker-harness-builder for any other agent; the installer keeps its lock and backups in the folder that contains . Existing skills prompt in an interactive terminal; --replace-existing skips that prompt. @@ -169,7 +213,16 @@ export async function runCli(args, {input = stdin, output = stdout, errorOutput if(args.length === 1 && args[0] === '--help') { output.write(help); return 0; } try { const options = parseInstallArgs(args); - let backup; + const {detect, ...scope} = options; + const environment = {userHome,env,platform}; + let installations = [scope]; + if (detect) { + const agents = await detectAgents(scope, environment); + if (!agents.length) throw Error('No known agent folders detected. Choose an agent with --agent or a skills folder with --dir.'); + output.write(`Detected: ${agents.join(', ')}\n`); + const destinations = new Map(agents.map(agent => [AGENTS[agent], agent])); + installations = [...destinations.values()].map(agent => ({...scope,agent})); + } const confirmReplace = input.isTTY && output.isTTY ? async destination => { output.write(`Existing skill: ${destination}\n`); const terminal = createInterface({input,output,terminal:false}); @@ -181,14 +234,27 @@ export async function runCli(args, {input = stdin, output = stdout, errorOutput } catch { return false; } // EOF/cancel never authorizes replacement. finally { terminal.close(); } } : undefined; - const destination = await install(options, {userHome,env,platform,confirmReplace,onBackup:path => {backup = path;}}); - if(backup) output.write(`Backup saved: ${backup}\n`); - const readers = options.dir === undefined ? AGENTS[options.agent].readers : 'the agent that reads that folder'; - const next = options.agent === 'openworker' - ? `OpenWorker picks it up from your next message${options.global ? '' : ' in a conversation using that project folder'}.` - : `Open a new coding-agent session${options.global ? '' : options.dir === undefined ? ' in that project' : ''} to use openworker-harness-builder.`; - output.write(`Installed: ${destination}\nRead by ${readers}.\n${next}\n`); - return 0; + let status = 0; + for (const selection of installations) { + try { + let backup; + const destination = await install(selection, {...environment,confirmReplace,onBackup:path => {backup = path;}}); + if(backup) output.write(`Backup saved: ${backup}\n`); + const readers = selection.dir === undefined ? AGENTS[selection.agent].readers : 'the agent that reads that folder'; + const next = selection.agent === 'openworker' + ? `OpenWorker picks it up from your next message${selection.global ? '' : ' in a conversation using that project folder'}.` + : `Open a new coding-agent session${selection.global || selection.dir !== undefined ? '' : ' in that project'} to use openworker-harness-builder.`; + output.write(`Installed: ${destination}\nRead by ${readers}.\n${next}\n`); + } catch(error) { + if (!detect) throw error; + if (error.code === 'INSTALL_CANCELLED') output.write(`${selection.agent}: ${error.message}\n`); + else { + errorOutput.write(`${selection.agent}: ${error.message}\n`); + status = 1; + } + } + } + return status; } catch(error) { if(error.code === 'INSTALL_CANCELLED') { output.write(error.message+'\n'); return 0; } errorOutput.write(error.message+'\n'); return 1; diff --git a/skills/install.test.mjs b/skills/install.test.mjs index 0f72fcd56..b27399dfe 100644 --- a/skills/install.test.mjs +++ b/skills/install.test.mjs @@ -109,7 +109,7 @@ for(const [label,extra,expected] of [ ['COWORKER_STATE_DIR',root=>({env:{COWORKER_STATE_DIR:join(root,'state override')}}),root=>join(root,'state override')], ['OPENWORKER_BASE_DIR',root=>({env:{OPENWORKER_BASE_DIR:join(root,'box')}}),root=>join(root,'box','state')], ]) test(`OpenWorker global install uses ${label}; lock, staging and backups stay outside its skills folder`,async()=>{ - const root=await mkdtemp(join(tmpdir(),'ow-openworker-state-')); + const root=await realpath(await mkdtemp(join(tmpdir(),'ow-openworker-state-'))); try { const options={agent:'openworker',global:true},deps=sandbox(join(root,'home'),extra(root)); if(label.startsWith('Windows'))await mkdir(join(root,'Roaming')); @@ -134,6 +134,10 @@ test('require exactly one scope and reject unknown CLI arguments',async()=>{ assert.deepEqual({...parseInstallArgs(['--agent','openworker','--project',root])},{agent:'openworker',project:root}); assert.deepEqual({...parseInstallArgs(['--agent','claude','--global','--replace-existing'])},{agent:'claude',global:true,replaceExisting:true}); assert.deepEqual({...parseInstallArgs(['--dir',root,'--replace-existing'])},{dir:root,replaceExisting:true}); + assert.deepEqual({...parseInstallArgs(['--detect-agents','--project',root])},{detect:true,project:root}); + assert.deepEqual({...parseInstallArgs(['--global','--detect-agents'])},{detect:true,global:true}); + for(const args of [['--detect-agents'],['--detect-agents','--dir',root],['--detect-agents','--agent','opencode','--global'],['--detect-agents','--global','--project',root]]) + assert.throws(()=>parseInstallArgs(args)); for(const args of [[],['--agent','claude'],['--global'],['--agent','claude','--global','--project',root],['--agent','claude','--global','extra'],['--agent','claude','--globall'],['--agent','claude','--project',''], ['--dir',''],['--dir',root,'--global'],['--dir',root,'--project',root],['--dir',root,'--agent','claude'],['--agent','claude,openworker','--project',root]]) assert.throws(()=>parseInstallArgs(args)); @@ -185,6 +189,61 @@ test('CLI success message names who reads the folder',async()=>{ } finally {await rm(root,{recursive:true,force:true});} }); +test('detect uses configured agents and writes one shared copy at the selected scope',async()=>{ + const root=await mkdtemp(join(tmpdir(),'ow-skill-detect-')); + try { + const home=join(root,'home'),project=join(root,'project'); + for(const folder of [join(home,'.config','opencode'),join(home,'.codex'),join(home,'.claude'),join(project,'.cursor'),join(project,'.github')]) + await mkdir(folder,{recursive:true}); + const output=new PassThrough();let text='';output.on('data',chunk=>{text+=chunk;}); + assert.equal(await runCli(['--detect-agents','--project',project],{...sandbox(home),output}),0); + assert.match(text,/^Detected: claude, codex, cursor, opencode$/m); + assert.equal((text.match(/^Installed: /gm)??[]).length,2); + for(const agent of ['claude','codex']) assert.match(await readFile(join(expectedSkills(agent,false,project),skill,'SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m); + await assert.rejects(lstat(join(home,'.agents')),{code:'ENOENT'}); + await assert.rejects(lstat(join(project,'.github','skills')),{code:'ENOENT'}); + text=''; + assert.equal(await runCli(['--detect-agents','--global'],{...sandbox(home),output}),0); + assert.match(text,/^Detected: claude, codex, opencode$/m); + assert.equal((text.match(/^Installed: /gm)??[]).length,2); + } finally {await rm(root,{recursive:true,force:true});} +}); + +test('detection skips missing, non-directory, and linked markers without creating folders',async()=>{ + const root=await mkdtemp(join(tmpdir(),'ow-skill-undetected-')); + try { + await writeFile(join(root,'.codex'),'not a directory'); + await mkdir(join(root,'.github')); + await symlink(join(root,'.github'),join(root,'.claude'),process.platform==='win32'?'junction':'dir'); + const errorOutput=new PassThrough();let errors='';errorOutput.on('data',chunk=>{errors+=chunk;}); + assert.equal(await runCli(['--detect-agents','--project',root],{...sandbox(root),output:new PassThrough(),errorOutput}),1); + assert.match(errors,/No known agent folders detected/); + assert.deepEqual((await readdir(root)).sort(),['.claude','.codex','.github']); + } finally {await rm(root,{recursive:true,force:true});} +}); + +test('detect leaves customized copies alone without the flag and backs up each replaced copy',async()=>{ + const root=await mkdtemp(join(tmpdir(),'ow-skill-detect-replace-')); + try { + const claude=await install({agent:'claude',global:true},sandbox(root)); + await writeFile(join(claude,'SKILL.md'),'custom Claude'); + await mkdir(join(root,'.config','opencode'),{recursive:true}); + const output=new PassThrough(),errorOutput=new PassThrough(); + let text='',errors='';output.on('data',chunk=>{text+=chunk;});errorOutput.on('data',chunk=>{errors+=chunk;}); + const config={...sandbox(root),output,errorOutput}; + assert.equal(await runCli(['--detect-agents','--global'],config),1); + assert.match(errors,/^claude: An installation already exists/m); + assert.equal(await readFile(join(claude,'SKILL.md'),'utf8'),'custom Claude'); + const shared=join(expectedSkills('opencode',true,root),skill); + assert.match(await readFile(join(shared,'SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m); + await writeFile(join(shared,'SKILL.md'),'custom shared'); + text=''; + assert.equal(await runCli(['--detect-agents','--global','--replace-existing'],config),0); + const copies=await Promise.all([...text.matchAll(/^Backup saved: (.+)$/gm)].map(([,path])=>readFile(join(path,'SKILL.md'),'utf8'))); + assert.deepEqual(copies,['custom Claude','custom shared']); + } finally {await rm(root,{recursive:true,force:true});} +}); + for(const agent of agents)for(const global of [false,true]) { const scope = global ? 'global' : 'project'; test(`${agent} ${scope} replacement backs up custom files and removes obsolete active files`,async()=>{ diff --git a/skills/package.test.mjs b/skills/package.test.mjs index f4451732b..395f10725 100644 --- a/skills/package.test.mjs +++ b/skills/package.test.mjs @@ -32,7 +32,7 @@ test('packed installer works outside the checkout without SDK or native dependen const run = (args) => process.platform === 'win32' ? execFileSync(process.execPath,[join(installed,'install.mjs'),...args],{cwd:consumer,encoding:'utf8'}) : execFileSync(bin,args,{cwd:consumer,encoding:'utf8'}); - for (const name of ['openworker','claude','codex','copilot','cursor','gemini','opencode','windsurf','agents','--dir']) + for (const name of ['openworker','claude','codex','copilot','cursor','gemini','opencode','windsurf','agents','--dir','--detect-agents']) assert.ok(run(['--help']).includes(name), `help lists ${name}`); assert.match(run(['--help']), /--global/); assert.match(run(['--help']), /--replace-existing/); @@ -47,6 +47,12 @@ test('packed installer works outside the checkout without SDK or native dependen const stateDir=join(root,'openworker state'); const env={...process.env,COWORKER_STATE_DIR:stateDir};delete env.OPENWORKER_BASE_DIR; const runGlobal=(args)=>execFileSync(process.execPath,['--import',pathToFileURL(preload).href,join(installed,'install.mjs'),...args],{cwd:consumer,env,encoding:'utf8',stdio:'pipe'}); + const detectedProject=join(root,'detected app'); + for(const hint of ['.opencode','.cursor'])await mkdir(join(detectedProject,hint),{recursive:true}); + const detected=runGlobal(['--detect-agents','--project',detectedProject]); + assert.match(detected,/^Detected: cursor, opencode$/m); + assert.equal((detected.match(/^Installed: /gm)??[]).length,1); + assert.match(await readFile(join(detectedProject,'.agents/skills/openworker-harness-builder/SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m); const folderOf=agent=>({codex:'.agents',claude:'.claude',openworker:'.coworker'})[agent]; for (const agent of ['codex','claude','openworker']) { const project = join(root, `new ${agent} app`);