cyberlegion 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.plugin/pins.json +1 -1
- package/CHANGELOG.md +6 -0
- package/dist/cli.mjs +68 -14
- package/dist/index.d.mts +25 -4
- package/dist/index.mjs +68 -14
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/readme.md +1 -1
- package/skills/dispatch-governance/SKILL.md +1 -1
- package/skills/dispatch-governance/scripts/cyberlegion.mjs +15 -15
- package/skills/init-cyberlegion/scripts/cyberlegion.mjs +15 -15
- package/skills/legate/SKILL.md +1 -1
- package/skills/legate/scripts/cyberlegion.mjs +15 -15
- package/skills/manage-inbox/SKILL.md +1 -1
- package/skills/manage-inbox/scripts/cyberlegion.mjs +15 -15
- package/skills/relay-governance/SKILL.md +1 -1
- package/skills/relay-governance/scripts/cyberlegion.mjs +15 -15
- package/skills/subagent-backend-governance/SKILL.md +1 -1
- package/skills/subagent-backend-governance/scripts/cyberlegion.mjs +15 -15
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Compiled by `universal-plugin plugin build` from src/skill-script.ts. Edit the source, not this file.
|
|
2
|
-
globalThis.__SKILL_SCRIPT__ = {"package":null,"bin":null,"version":"2.0.
|
|
2
|
+
globalThis.__SKILL_SCRIPT__ = {"package":null,"bin":null,"version":"2.0.1","entry":"skills/legate/scripts/cyberlegion.mjs","commands":{}};
|
|
3
3
|
import e,{chmodSync as t,existsSync as n,mkdirSync as r,readFileSync as i,readdirSync as a,realpathSync as o,renameSync as s,rmSync as c,statSync as l,writeFileSync as u}from"node:fs";import d,{basename as f,dirname as p,isAbsolute as m,join as h,resolve as g,sep as _}from"node:path";import{EventEmitter as v}from"node:events";import y,{execFile as ee,execFileSync as te}from"node:child_process";import b from"node:process";import{stripVTControlCharacters as ne}from"node:util";import{homedir as re}from"node:os";import{createHash as ie,randomBytes as ae,randomUUID as oe}from"node:crypto";import{lstat as se,readFile as ce,readdir as le,readlink as ue,realpath as de,unlink as fe,writeFile as pe}from"node:fs/promises";var me=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},he=class extends me{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},ge=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new he(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function _e(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var ve=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description).helpGroup(n.helpGroupHeading)):n.short&&!r&&t.push(e.createOption(n.short,n.description).helpGroup(n.helpGroupHeading))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(e=>_e(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
4
4
|
`)}displayWidth(e){return ne(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
5
5
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
@@ -55,26 +55,26 @@ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let
|
|
|
55
55
|
|
|
56
56
|
`).map(e=>e.trim()).filter(e=>e.startsWith(`worktree `)).map(e=>Ur(e,r))),a=await Pr(t,e.primaryRoot,i.find(e=>!e.linked)?.branch),o=await Fr(t,e.primaryRoot,a,e.forge);for(let n of i){let r=await Ir(n.branch,o);if(r.merged!==void 0&&(n.merged=r.merged),r.signal!==void 0&&(n.mergedSignal=r.signal),!n.prunable){let r=await Mr(n.root,{exec:t,ignore:e.ignore});r!==void 0&&(n.dirty=r)}}return i}async function Ur(e,t){let n=e.split(`
|
|
57
57
|
`),r=await Vr(Gr(n[0].slice(9))),i=e=>{let t=n.find(t=>t===e||t.startsWith(`${e} `));return t===void 0?void 0:Gr(t.slice(e.length+1))},a={root:r,detached:n.includes(`detached`),linked:r!==t,prunable:i(`prunable`)!==void 0},o=i(`HEAD`);o&&(a.head=o);let s=i(`branch`)?.replace(/^refs\/heads\//,``);s&&(a.branch=s);let c=i(`locked`);return c!==void 0&&(a.locked=c),a}const Wr={a:`\x07`,b:`\b`,f:`\f`,n:`
|
|
58
|
-
`,r:`\r`,t:` `,v:`\v`};function Gr(e){if(e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`))return e;let t=[],n=e.slice(1,-1);for(let e=0;e<n.length;e++){let r=n[e];if(r!==`\\`){t.push(...Buffer.from(r));continue}let i=n[++e]??``,a=/^[0-7]{3}/.exec(n.slice(e));a?(t.push(Number.parseInt(a[0],8)),e+=2):t.push(...Buffer.from(Wr[i]??i))}return Buffer.from(t).toString(`utf8`)}function Kr(e){return h(p(e),`${f(e)}.worktrees`)}function qr(e,t){return h(Kr(e),`${f(e)}-${t}`)}function Jr(e,t){if(p(t)!==Kr(e))return;let n=`${f(e)}-`,r=f(t);if(!r.startsWith(n))return;let i=r.slice(n.length);return/^[1-9]\d*$/.test(i)?Number(i):void 0}function Yr(e){if(!e)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let{library:n,leaseId:r,holder:i}=t;if(n===`cyber-agentkit`&&typeof r==`string`&&typeof i==`string`)return{library:n,leaseId:r,holder:i}}function Xr(e,t){return Yr(e.locked)?{owner:`self`,research:[`E-GIT-L1`,`E-GIT-L2`]}:e.locked?.startsWith(`claude session `)?{owner:`claude-code`,research:[`E-CC-W4`,`E-PROC-CC5`]}:e.linked?e.locked===void 0&&Jr(t.primaryRoot,e.root)!==void 0?{owner:`self`,research:[]}:Zr(e.root,`${t.primaryRoot}${_}.claude${_}worktrees`)?{owner:`claude-code`,research:[`E-CC-W1`]}:t.codexHome&&Zr(e.root,`${t.codexHome}${_}worktrees`)?{owner:`codex`,research:[`E-CODEX-W1`]}:{owner:`unknown`,research:[]}:{owner:`user`,research:[]}}function Zr(e,t){return e.startsWith(`${t}${_}`)}const Qr={async createExclusive(e,t){try{return await pe(e,t,{flag:`wx`}),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}},async readText(e){try{return await ce(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}},async remove(e){try{await fe(e)}catch(e){if(e.code!==`ENOENT`)throw e}}};async function $r(e,t=Nr,n){let r=await t(`git`,[`-C`,e,`rev-parse`,`--path-format=absolute`,`--git-dir`]);if(r)return h(r,`locked`);let i=n&&await ei(e,n);return i?h(i,`locked`):void 0}async function ei(e,t){let n=h(t,`worktrees`),r=await ti(e),i;try{i=await le(n)}catch{return}for(let e of i){let t;try{t=(await ce(h(n,e,`gitdir`),`utf8`)).trim()}catch{continue}if(await ti(p(t))===r)return h(n,e)}}async function ti(e){return h(await Vr(p(e)),f(e),`.git`)}async function ni(e,t,n={}){let r=n.exec??Nr,i=n.fs??Qr,a=await $r(e,r);if(!a)return;let o=await r(`git`,[`-C`,e,`rev-parse`,`--path-format=absolute`,`--git-common-dir`]),s={worktree:e,leaseId:n.leaseId??oe(),holder:t,commonDir:o??void 0},c={library:`cyber-agentkit`,leaseId:s.leaseId,holder:t};if(await i.createExclusive(a,JSON.stringify(c)))return await ri(s,{exec:r,fs:i})?s:void 0}async function ri(e,t={}){let n=await $r(e.worktree,t.exec??Nr,e.commonDir);return n?Yr(await(t.fs??Qr).readText(n))?.leaseId===e.leaseId:!1}async function ii(e,t={}){let n=t.exec??Nr,r=t.fs??Qr,i=await $r(e.worktree,n,e.commonDir);return!i||Yr(await r.readText(i))?.leaseId!==e.leaseId?{released:!1,reason:`lost`}:(await r.remove(i),{released:!0})}function ai(e=`/proc`){return async()=>{if(e===`/proc`&&process.platform!==`linux`)return null;let t;try{t=await le(e)}catch{return null}return(await Promise.all(t.filter(e=>/^\d+$/.test(e)).map(t=>oi(h(e,t),Number(t))))).filter(e=>e!==void 0)}}async function oi(e,t){let[n,r,i,a,o]=await Promise.all([ci(h(e,`stat`)),ci(h(e,`cmdline`)),li(h(e,`exe`)),li(h(e,`cwd`)),ci(h(e,`environ`))]);if(n===void 0)return;let s={pid:t,argv:r?si(r):[]},c=Number(n.slice(n.lastIndexOf(`)`)+2).split(` `)[1]);if(Number.isInteger(c)&&(s.ppid=c),i!==void 0&&(s.exe=i),a!==void 0&&(s.cwd=a),o!==void 0){let e={};for(let t of si(o)){let n=t.indexOf(`=`);n>0&&(e[t.slice(0,n)]=t.slice(n+1))}s.env=e}return s}const si=e=>e.split(`\0`).filter(e=>e.length>0);async function ci(e){try{return await ce(e,`utf8`)}catch{return}}async function li(e){try{return(await ue(e)).replace(/ \(deleted\)$/,``)}catch{return}}const ui=e=>e?.slice(e.lastIndexOf(`/`)+1),di=(e,t)=>ui(e.exe)===t,fi=(e,t)=>e.exe!==void 0&&t.test(e.exe),pi=e=>di(e,`node`)||ui(e.argv[0])===`node`,mi=(e,t)=>e.argv.some(e=>t.test(e)),hi=[{harness:`claude-code`,research:[`E-PROC-CC1`,`E-PROC-CC2`,`E-PROC-CC3`],isSession:e=>fi(e,/\/claude\/versions\/[^/]+$/),link:{pid:`CLAUDE_PID`,id:`CLAUDE_CODE_SESSION_ID`}},{harness:`codex`,research:[`E-PROC-CX1`,`E-PROC-CX2`],isSession:e=>di(e,`codex`)&&!gi(e),helper:e=>gi(e)?`session`:void 0,link:{id:`CODEX_SESSION_ID`}},{harness:`copilot-cli`,research:[`E-PROC-COP1`,`E-PROC-COP2`],isSession:e=>di(e,`copilot`),link:{id:`COPILOT_AGENT_SESSION_ID`}},{harness:`cursor`,research:[`E-PROC-CUR1`,`E-PROC-CUR3`,`E-PROC-CUR4`],isSession:e=>_i(e)&&e.env?.AGENT_CLI_SOCKET_PATH===void 0,helper:e=>_i(e)&&e.env?.AGENT_CLI_SOCKET_PATH!==void 0?`session`:void 0,link:{id:`CURSOR_CONVERSATION_ID`}},{harness:`opencode`,research:[`E-PROC-OC1`],isSession:e=>di(e,`opencode`),link:{pid:`OPENCODE_PID`}},{harness:`kilo`,research:[`E-PROC-KILO1`],isSession:e=>fi(e,/\/cli-linux-x64\/bin\/kilo$/)||pi(e)&&mi(e,/\/@kilocode\/cli\/bin\/kilo$/),link:{pid:`KILO_PID`,id:`KILO_RUN_ID`}},{harness:`qwen-code`,research:[`E-PROC-QWEN1`],isSession:e=>pi(e)&&mi(e,/\/qwen-code\/cli-entry\.js$/),link:{id:`QWEN_CODE_SESSION_ID`}},{harness:`crush`,research:[`E-PROC-CRUSH1`],isSession:e=>fi(e,/\/crush\/bin\/crush$/)||pi(e)&&mi(e,/\/@charmland\/crush(\/|$)/)},{harness:`gemini-cli`,research:[`E-PROC-GEM1`],isSession:e=>pi(e)&&mi(e,/\/gemini-cli\/bundle\/gemini\.js$/)},{harness:`goose`,research:[`E-PROC-GOOSE1`],isSession:e=>di(e,`goose`)&&(e.argv[1]===`run`||e.argv[1]===`session`),link:{id:`AGENT_SESSION_ID`}},{harness:`openhands`,research:[`E-PROC-OH1`],isSession:e=>/^python[\d.]*$/.test(ui(e.exe)??``)&&mi(e,/\/openhands$/),helper:e=>di(e,`tmux`)&&(e.argv.includes(`-Lopenhands`)||/-L openhands( |$)/.test(e.argv.join(` `)))?`shared`:void 0},{harness:`cline`,research:[`E-PROC-CLINE1`],isSession:e=>vi(e)&&!e.argv.includes(`--cline-hub-daemon`),helper:e=>vi(e)&&e.argv.includes(`--cline-hub-daemon`)?`shared`:void 0},{harness:`augment`,research:[`E-PROC-AUG1`],isSession:e=>pi(e)&&mi(e,/\/@augmentcode\/auggie\/augment\.mjs$/)},{harness:`antigravity-cli`,research:[`E-PROC-AGY1`],isSession:e=>di(e,`agy`),link:{id:`ANTIGRAVITY_CONVERSATION_ID`}}];function gi(e){return ui(e.exe)===`codex-code-mode-host`||e.argv.some(e=>ui(e)===`codex-code-mode-host`)}function _i(e){return pi(e)&&mi(e,/(^|\/)cursor-agent$/)}function vi(e){return fi(e,/\/cli-linux-x64\/bin\/cline$/)||pi(e)&&mi(e,/\/cline\/bin\/cline$/)}async function yi(e={}){let t=await(e.source??ai())();return t===null?{verified:!1,occupancy:(e,t)=>({busy:t?.strict===!0,verified:!1,occupants:[],lingering:[],unlinked:[]})}:bi(t)}function bi(e){let t=new Map(e.map(e=>[e.pid,e])),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let t of e)for(let e of hi){let i=e.helper?.(t);if(i){r.set(t.pid,{signature:e,scope:i});break}if(e.isSession(t)){n.set(t.pid,e);break}}let i=e=>e.ppid===void 0||e.ppid===e.pid?void 0:t.get(e.ppid),a=/* @__PURE__ */ new Map,o=e=>{let t=i(e);return t&&n.get(t.pid)===n.get(e.pid)?o(t):e};for(let[e,r]of n){let n=o(t.get(e)),i=a.get(n.pid);i||(i={signature:r,members:[],ids:/* @__PURE__ */ new Set},a.set(n.pid,i)),i.members.push(t.get(e)),a.set(e,i)}let s=[...new Set(a.values())],c=e=>{let t=/* @__PURE__ */ new Set;for(let n=i(e);n&&!t.has(n.pid);n=i(n)){t.add(n.pid);let e=a.get(n.pid);if(e)return e}};for(let t of e){if(n.has(t.pid))continue;let e=c(t),r=e?.signature.link?.id,i=r&&t.env?.[r];e&&i&&e.ids.add(i)}let l=e=>s.filter(t=>t.signature.harness===e),u=(e,t)=>{let n=l(e.harness),r=e.link?.pid;if(r&&t[r]){let e=Number(t[r]);return n.some(t=>t.members.some(t=>t.pid===e))?`live`:`dead`}let i=e.link?.id,a=i&&t[i];if(a)return n.some(e=>e.ids.has(a))?`live`:n.every(e=>e.ids.size>0)?`dead`:`unknown`},d=e=>{let t=r.get(e.pid);if(t?.scope===`shared`)return l(t.signature.harness).length>0?void 0:{pid:e.pid,argv:e.argv,harness:t.signature.harness,reason:`harness-idle`};if(c(e))return;if(t)return{pid:e.pid,argv:e.argv,harness:t.signature.harness,reason:`helper-orphaned`};if(!e.env)return{pid:e.pid,argv:e.argv,reason:`env-unreadable`};let n=hi.map(t=>({signature:t,link:u(t,e.env)})).filter(e=>e.link!==void 0);if(n.some(e=>e.link===`live`))return;if(n.length===0)return{pid:e.pid,argv:e.argv,reason:`no-link`};let i=n.every(e=>e.link===`dead`)?`session-gone`:`unresolved-link`;return{pid:e.pid,argv:e.argv,harness:n[0].signature.harness,reason:i}};return{verified:!0,occupancy(t,r={}){let i=(e,t)=>e!==void 0&&(e===t||e.startsWith(t.endsWith(_)?t:t+_)),a=e=>i(e,t)&&!(r.nested??[]).some(t=>i(e,t)),c=[];for(let e of s){if(!e.members.some(e=>a(e.cwd)))continue;let t={harness:e.signature.harness,pid:(e.members.find(e=>o(e)===e)??e.members[0]).pid,pids:e.members.map(e=>e.pid).sort((e,t)=>e-t),research:e.signature.research};e.ids.size===1&&(t.sessionId=[...e.ids][0]),c.push(t)}let l=[],u=[];for(let t of e){if(n.has(t.pid)||!a(t.cwd))continue;let e=d(t);if(!e)continue;let r={...e,cwd:t.cwd};t.ppid!==void 0&&(r.ppid=t.ppid),(e.reason===`session-gone`||e.reason===`helper-orphaned`||e.reason===`harness-idle`?l:u).push(r)}return{busy:c.length>0,verified:!0,occupants:c,lingering:l,unlinked:u}}}}async function xi(e){let t=e.exec??Nr,n=await Vr(e.primaryRoot??await Br({from:e.from,exec:t})),r=await Hr({primaryRoot:n,exec:t,ignore:e.ignore,forge:e.forge}),i=e.base??await Pr(t,n,r.find(e=>!e.linked)?.branch),a=e.codexHome&&await Vr(e.codexHome),o=e.probe,s=[];for(let c of r){let l=Xr(c,{primaryRoot:n,codexHome:a}),u={worktree:c,owner:l,verified:!0};if(s.push(u),!c.linked){u.skip=`primary`;continue}if(l.owner!==`self`){u.skip=`foreign`;continue}let d=Yr(c.locked);if(d){u.skip=`leased`,u.holder=d.holder;continue}if(c.prunable){u.skip=`prunable`;continue}o??=await yi();let f=r.map(e=>e.root).filter(e=>e!==c.root&&e.startsWith(c.root+_)),p=o.occupancy(c.root,{strict:e.strict,nested:f});u.occupancy=p,u.verified=p.verified,p.busy?u.skip=p.verified?`busy`:`unverified`:c.dirty===!1?await Si(t,n,c,i)?e.available&&!await e.available(c)&&(u.skip=`rejected`):u.skip=`unmerged`:u.skip=`dirty`}return{primary:n,exec:t,base:i,entries:r,verdicts:s}}async function Si(e,t,n,r){return n.merged===!0?!0:!n.head||!r?!1:await e(`git`,[`-C`,t,`merge-base`,`--is-ancestor`,n.head,r])!==null}function Ci(e=Nr){return async({primaryRoot:t,path:n,base:r,branch:i})=>{let a=[`-C`,t,`worktree`,`add`,`--quiet`];if(i?await Ai(e,t,i)?a.push(n,i):a.push(`-b`,i,n,r):a.push(`--detach`,n,r),await e(`git`,a)===null)throw Error(`git worktree add failed: ${n}`)}}var wi=class extends Error{code;verdicts;constructor(e,t,n){super(t),this.code=e,this.verdicts=n,this.name=`AcquireError`}};async function Ti(e){let t=[];for(let n=0;n<3;n++){let n=await xi(e);t=n.verdicts;let{primary:r,exec:i,entries:a}=n;if(!n.base)throw new wi(`no-base`,"no base ref: pass `base` or set origin/HEAD",t);let o=await i(`git`,[`-C`,r,`rev-parse`,`--verify`,`--quiet`,`${n.base}^{commit}`]);if(!o)throw new wi(`no-base`,`base does not resolve to a commit: ${n.base}`,t);let s=t.filter(e=>e.skip===void 0).sort((e,t)=>Ei(r,e)-Ei(r,t));for(let t of s){let n=await Di(t,o,e,i,r);if(n)return n}let c=a.filter(e=>e.linked&&Jr(r,e.root)!==void 0);if(e.max!==void 0&&c.length>=e.max)throw new wi(`pool-full`,`all ${e.max} worktrees are in use`,t);let l=await Oi(r,o,e,i,c);if(l)return{...l,reused:!1,branch:e.branch,verified:!0,lingering:[]}}throw new wi(`contended`,`another caller took every worktree this one tried`,t)}function Ei(e,t){return Jr(e,t.worktree.root)??1/0}async function Di(e,t,n,r,i){let a=e.worktree,o={exec:r,fs:n.fs},s=await ni(a.root,n.holder,{...o,leaseId:n.newLeaseId?.()});if(!s)return;let c=await r(`git`,[`-C`,a.root,`rev-parse`,`HEAD`]),l=await Mr(a.root,{exec:r,ignore:n.ignore});if(c!==a.head||l!==!1||!await ri(s,o)){await ii(s,o);return}let u=(...e)=>r(`git`,[`-C`,a.root,...e]),d=async e=>{throw await ii(s,o),Error(`${e}: ${a.root}`)};if(await u(`read-tree`,`--reset`,`-u`,t)===null||await u(`clean`,`-fd`)===null)return d(`recycle failed`);if((n.branch?await Ai(r,i,n.branch)?await u(`switch`,`--quiet`,`--discard-changes`,n.branch):await u(`switch`,`--quiet`,`--discard-changes`,`-c`,n.branch,t):await u(`switch`,`--quiet`,`--discard-changes`,`--detach`,t))===null)return d(`recycle could not switch to ${n.branch??t}`);let f={...s,reused:!0,branch:n.branch,verified:e.verified,lingering:e.occupancy?.lingering??[]},p=a.branch;return p&&(f.previousBranch=p,a.merged===!0&&p!==n.branch&&(f.previousBranchDeleted=await r(`git`,[`-C`,i,`branch`,`-D`,p])!==null)),f}async function Oi(e,t,n,r,i){let a=new Set(i.map(t=>Jr(e,t.root))),o=1;for(;a.has(o)||await ji(qr(e,o));)o++;let s=qr(e,o),c=n.create??Ci(r),l={primaryRoot:e,path:s,base:t,branch:n.branch};try{await c(l)}catch(e){if(await ji(s))return;throw e}let u;try{u=await ni(await Vr(s),n.holder,{exec:r,fs:n.fs,leaseId:n.newLeaseId?.()})}catch(e){throw await ki(n.undoCreate,l),e}return u||await ki(n.undoCreate,l),u}async function ki(e,t){try{await e?.(t)}catch{}}async function Ai(e,t,n){return await e(`git`,[`-C`,t,`rev-parse`,`--verify`,`--quiet`,`refs/heads/${n}`])!==null}async function ji(e){try{return await se(e),!0}catch{return!1}}var Mi=class extends Error{};const Ni={add(e,t){let n=[`-C`,t.primaryRoot,`worktree`,`add`,`-b`,t.branch,t.path];if(t.base&&n.push(t.base),e(`git`,n)===null)throw new Mi(`git worktree add failed for ${t.path}`);return{root:g(t.path),branch:t.branch}},remove(e,t,n){if(e(`git`,[`-C`,n.primaryRoot,`worktree`,`remove`,t,`--force`])===null)throw new Mi(`git worktree remove failed for ${t}`)}};function Pi(e){let t=e(`git`,[`rev-parse`,`--path-format=absolute`,`--git-common-dir`]);if(!t)throw new Mi(`cannot resolve the primary checkout — not inside a git repository`);return p(t)}function Fi(e,t){if(g(e)===g(t))throw new Mi(`refusing to run in the primary checkout — spawn a worktree distinct from the primary checkout`)}const Ii=`config.json`,Li=`.agents/cyberlegion/${Ii}`;function Ri(e=process.cwd()){let t=g(e);for(;;){if(n(h(t,`.git`)))return t;let r=p(t);if(r===t)return g(e);t=r}}function zi(e={}){let t=e.env??process.env,n=e.root??e.space??t.CYBERLEGION_ROOT;if(n)return g(n);let r=re();return h(r||Ri(e.cwd),`.agents`,`cyberlegion`)}function Bi(e){r(e,{recursive:!0});let t=h(e,Ii);n(t)||u(t,`${JSON.stringify({version:1},null,2)}\n`)}var Vi=class extends Error{kind;value;constructor(e,t){super(`invalid ${e} ${JSON.stringify(t)} — must not be empty, ".", "..", or contain a path separator`),this.kind=e,this.value=t,this.name=`InvalidIdError`}};const Hi=/[\\/\0]/;function k(e,t){if(!e||e===`.`||e===`..`||Hi.test(e))throw new Vi(t,e);return e}const A={agentsDir:e=>h(e,`agents`),agentFile:(e,t)=>h(e,`agents`,`${k(t,`agent id`)}.json`),panesDir:e=>h(e,`panes`),paneFile:(e,t)=>h(e,`panes`,`${Ui(t)}.id`),inboxDir:(e,t)=>h(e,`inbox`,k(t,`agent id`)),inboxReadDir:(e,t)=>h(e,`inbox`,k(t,`agent id`),`read`),dataDir:(e,t)=>h(e,`data`,k(t,`agent id`)),briefFile:(e,t)=>h(e,`data`,k(t,`agent id`),`brief.md`),mainPaneFile:e=>h(e,`main-pane.id`),projectsDir:e=>h(e,`projects`),serviceLeaseFile:(e,t,n)=>h(e,`services`,k(t,`project id`),`${k(n,`service name`)}.json`),projectFile:(e,t)=>h(e,`projects`,`${k(t,`project id`)}.json`),messageFile:(e,t,n)=>h(A.inboxDir(e,t),`${k(n,`message id`)}.json`),messageReadFile:(e,t,n)=>h(A.inboxReadDir(e,t),`${k(n,`message id`)}.json`)};function Ui(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`)}function j(e){let t=e.CYBER_MUX!==void 0||e.CYBER_MUX_PANE!==void 0,n=e.CYBERLEGION_MUX!==void 0||e.CYBERLEGION_MUX_PANE!==void 0;return t||!n?e:{...e,CYBER_MUX:e.CYBERLEGION_MUX,CYBER_MUX_PANE:e.CYBERLEGION_MUX_PANE}}const M=Oe;function Wi(e){let t=je(j(e));return t&&(t.mux===`tmux`||t.mux===`herdr`)?{mux:t.mux,pane:t.pane}:void 0}function Gi(e){return Ki(Wi(e.env??process.env),e.exec??M)}function Ki(e,t){if(e?.mux!==`herdr`)return e;let n=Ji(t);return n?n.pane===e.pane?{...e,...n.terminal?{terminal:n.terminal}:{}}:qi(t)?{...e,pane:n.pane,...n.terminal?{terminal:n.terminal}:{}}:e:e}function qi(e){let t=e(`herdr`,[`--version`])?.match(/(\d+)\.(\d+)\.(\d+)/);if(!t)return!1;let[n,r,i]=t.slice(1).map(Number);return n>0||r>8||r===8&&i>=2}function Ji(e){return Yi(e(`herdr`,[`pane`,`current`]))}function Yi(e){if(e)try{let t=JSON.parse(e)?.result?.pane,n=t?.pane_id;if(typeof n!=`string`||!n)return;let r=t.terminal_id;return{pane:n,...typeof r==`string`&&r?{terminal:r}:{}}}catch{return}}function Xi(e,t){return Yi(e(`herdr`,[`pane`,`get`,t]))?.terminal}function Zi(e,t,n){if(t===`tmux`)return{mux:t,id:n};if(t!==`herdr`)return null;let r=Xi(e,n);return{mux:t,id:n,...r?{terminal:r}:{}}}function Qi(e){let t=/* @__PURE__ */ new Map,n=e(`herdr`,[`pane`,`list`]);if(!n)return t;try{let e=JSON.parse(n)?.result?.panes;if(!Array.isArray(e))return t;for(let n of e)typeof n?.terminal_id==`string`&&typeof n?.pane_id==`string`&&t.set(n.terminal_id,n.pane_id)}catch{return t}return t}function $i(e,t,n={}){if(n.terminals??=Qi(e),n.terminals.size===0)return;let r=n.terminals.get(t);return r?{id:r}:`gone`}function ea(e,t,n){let r=t.pane;r&&r.id!==n&&(e.store.resolvePaneId(r.id)===t.id&&e.store.removePaneIndex(r.id),t.pane={...r,id:n},P(e.store,t),e.store.putPaneIndex(n,t.id))}const ta=e=>new Date(e.now?.()??Date.now()).toISOString();function na(){return ae(8).toString(`hex`)}function N(e,t){return e.getAgent(t)}function P(e,t){e.putAgent(t)}function F(e){return e.listAgents()}function ra(e,t){if(e){if(e===`claude`||e===`cursor`||e===`codex`)return e;throw Error(`unknown --harness "${e}" (expected claude | cursor | codex)`)}let n=t.env??process.env;if(n.CLAUDECODE||n.CLAUDE_CODE_ENTRYPOINT)return`claude`;if(Object.keys(n).some(e=>e.startsWith(`CURSOR`)))return`cursor`;if(Object.keys(n).some(e=>e.startsWith(`CODEX`)))return`codex`;let r=n.TMUX_PANE;if(r){let e=(t.exec??M)(`tmux`,[`display-message`,`-p`,`-t`,r,`#{pane_current_command}`]);if(e?.includes(`cursor`))return`cursor`;if(e?.includes(`codex`))return`codex`;if(e?.includes(`claude`))return`claude`}}function I(e){return ia(e).id}function ia(e){let t=e.env??process.env,n=Ki(je(j(t)),e.exec??M);return n?{id:aa(e.store,n),cur:n}:{id:t.CYBERLEGION_AGENT_ID||void 0,cur:n}}function aa(e,t){let n=e.resolvePaneId(t.pane);if(!t.terminal)return n;let r=n?N(e,n)?.pane?.terminal:void 0;return n&&(!r||r===t.terminal)?n:F(e).find(e=>e.pane?.mux===`herdr`&&e.pane.terminal===t.terminal)?.id}function oa(e,t){e.store.ensureMarker();let n=e.env??process.env,r=ra(t.harness,e);if(!r)throw Error(`could not detect harness — pass --harness claude|cursor|codex`);let i=I(e),a=i?N(e.store,i):void 0,o=a?.id??i??na(),s=ta(e),c=e.exec??M,l=Ki(Wi(n),c),u={id:o,handle:t.handle??a?.handle??o.slice(0,6),harness:r,cwd:process.cwd(),...ha(e.store,c,o,a),pane:l?sa(l,c,n):null,status:`active`,createdAt:a?.createdAt??s,lastSeen:s,...a?.brief?{brief:a.brief}:{},...a?.spawnedBy?{spawnedBy:a.spawnedBy}:{}};return P(e.store,u),l&&e.store.putPaneIndex(l.pane,o),u}function sa(e,t,n){return e.mux===`tmux`?{mux:`tmux`,id:e.pane,window:t(`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#{window_id}`])??void 0,session:n.TMUX?.split(`,`)[0]}:{mux:e.mux,id:e.pane,...e.terminal?{terminal:e.terminal}:{}}}function ca(e){return`standing-${Ui(e)}`}function la(e,t){e.store.ensureMarker();let n=ca(t.handle);return e.store.withLock(`presence:${n}`,()=>ua(e,n,t))}function ua(e,t,n){let r=N(e.store,t),i=ta(e),a={id:t,handle:n.handle,kind:`standing`,pane:null,harness:void 0,cwd:process.cwd(),status:`active`,createdAt:r?.createdAt??i,lastSeen:i};r?.presence!==void 0&&(a.presence=r.presence);let o=n.home===void 0?r?.home:n.home??void 0;return o&&(a.home=o),P(e.store,a),a}function da(e,t){let n=t===void 0?e:(n,r)=>e(n,n===`git`?[`-C`,t,...r]:r),r=n(`git`,[`rev-parse`,`--show-toplevel`]);if(!r)return null;let i=n(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`])??void 0,a=ga(n);return{root:r,...i===void 0?{}:{branch:i},...a===void 0?{}:{primaryRoot:a}}}function fa(e,t,n){let r=g(t);return F(e).find(e=>e.id!==n&&e.worktree?.root&&g(e.worktree.root)===r)?.id}function pa(e,t,n){let r=fa(e,t.root,n);return{...t,...r?{owner:r}:{}}}function ma(e,t,n){let r=da(t,n);return r?pa(e,r):void 0}function ha(e,t,n,r){let i=r?.sharedWorktree?{sharedWorktree:r.sharedWorktree}:{};if(r?.worktree)return{worktree:_a(r.worktree,t),...i};let a=da(t);return a?r?.sharedWorktree||fa(e,a.root,n)?{worktree:null,sharedWorktree:pa(e,a,n)}:{worktree:a}:{worktree:null,...i}}function ga(e){try{return Pi(e)}catch{return}}function _a(e,t){if(!e||e.primaryRoot!==void 0)return e;let n=da(t);return n?.root!==e.root||n.primaryRoot===void 0?e:{...e,primaryRoot:n.primaryRoot}}function va(e,t){let n=t.find(e=>e.kind===`standing`);if(n)return n;if(t.length>1)throw Error(`"${e}" names ${t.length} units — pass an id (${t.map(e=>e.id).join(`, `)})`);return t[0]}function ya(e,t){let n=e.filter(e=>e.handle===t);return{live:n.filter(e=>e.status!==`exited`),exited:n.filter(e=>e.status===`exited`)}}function ba(e,t,n){if(t.length>0){let n=t.map(e=>`${e.id.slice(0,6)}${e.pane?` (${e.pane.id})`:``}`).join(`, `);return/* @__PURE__ */ Error(`"${e}" matches only exited unit(s) — ${n} — which have no reader. Address a live unit ('cyberlegion unit who'), or run 'cyberlegion unit register --standing --handle ${e}' for a durable inbox.`)}return/* @__PURE__ */ Error(`no agent addressable as "${e}" (tried ${n})`)}function xa(e,t){let n=F(e).find(e=>e.handle===t&&e.kind===`standing`);if(!n)throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return n.id}function Sa(e,t){let n=N(e,t);if(n?.kind===`service`||n?.kind===`standing`)return n.id;let r=F(e);if(r.some(e=>e.handle===t&&e.kind===`standing`))return xa(e,t);let i=r.filter(e=>e.handle===t&&e.kind===`service`);if(i.length===1)return i[0].id;if(i.length>1)throw Error(`"${t}" names ${i.length} service endpoints — pass an endpoint id (${i.map(e=>e.id).join(`, `)})`);return xa(e,t)}function Ca(e,t){let n=N(e,t);if(n)return n;let{live:r,exited:i}=ya(F(e),t),a=va(t,r);if(a)return a;if(i.length>1)throw Error(`"${t}" names ${i.length} exited units — pass an id (${i.map(e=>e.id).join(`, `)})`);if(i[0])return i[0];throw Error(`no unit addressable as "${t}" (tried id and handle)`)}function wa(e,t){let n=xa(e.store,t);if(!N(e.store,n))throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);if(Me(e.exec??M,j(e.env??process.env)).mux===`none`)throw Error(`claiming a presence needs a multiplexer to open panes`);let r=I(e);if(!r)throw Error("no identity in this session — run `cyberlegion unit register` first");return e.store.withLock(`presence:${n}`,()=>{let i=N(e.store,n);if(!i)throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return i.presence=r,P(e.store,i),i})}function Ta(e,t){let n=xa(e.store,t);if(!N(e.store,n))throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return e.store.withLock(`presence:${n}`,()=>{let r=N(e.store,n);if(!r)throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return r.presence!==void 0&&(r.presence=void 0,P(e.store,r)),r})}function Ea(e,t){if(!t.presence)return;let n=N(e,t.presence);if(n&&n.status!==`exited`)return n}function Da(e,t){let n=N(e,xa(e,t));if(n)return Ea(e,n)}function Oa(e,t){if(N(e,t))return t;let{live:n,exited:r}=ya(F(e),t),i=va(t,n);if(!i)throw ba(t,r,`id and handle`);return i.id}function L(e,t){let n=N(e,t);if(n)return n;let r=F(e),{live:i,exited:a}=ya(r,t),o=va(t,i);if(o)return o;let s=r.filter(e=>e.worktree?.branch===t),c=s.find(e=>e.status!==`exited`);if(c)return c;throw ba(t,[...a,...s.filter(e=>e.status===`exited`)].filter((e,t,n)=>n.findIndex(t=>t.id===e.id)===t),`id, handle, and worktree branch/CR`)}function ka(e){return f(e.worktree?.primaryRoot??e.cwd)}function Aa(e,t){let{repo:n,branch:r}=t;if(n===void 0&&r===void 0)throw Error(`a ref, --repo, or --branch is required`);let i=[...n===void 0?[]:[`--repo "${n}"`],...r===void 0?[]:[`--branch "${r}"`]].join(` `),a=F(e).filter(e=>e.status!==`exited`&&(r===void 0||e.worktree?.branch===r)&&(n===void 0||ka(e)===n)),[o]=a;if(!o)throw Error(`no live unit matches ${i}`);if(a.length>1){let e=a.map(e=>`${e.id} (${e.handle}${e.worktree?.branch?`, ${e.worktree.branch}`:``}, ${ka(e)})`).join(`, `);throw Error(`${i} matches ${a.length} units — ${e} — address one by its id`)}return o}function ja(e,t){let n=N(e.store,t);n&&(n.lastSeen=ta(e),P(e.store,n))}function R(e){let{id:t,cur:n}=ia(e);if(!t||(ja(e,t),n?.mux!==`herdr`||!n.terminal))return;let r=N(e.store,t);r?.pane?.mux===`herdr`&&(r.pane.terminal!==n.terminal&&(r.pane={...r.pane,terminal:n.terminal},P(e.store,r)),ea(e,r,n.pane))}function Ma(e){return e.kind===`standing`||e.kind===`service`}function Na(e){return!Ma(e)&&e.status!==`exited`&&e.status!==`stopped`}function Pa(e,t){if(t.status===`exited`||t.status===`stopped`)return!1;if(!t.pane)return!0;let n=e.exec??M;if(t.pane.mux===`herdr`&&t.pane.terminal)return $i(n,t.pane.terminal)!==`gone`;let r=Fa[t.pane.mux].listPanes(n);if(r.length===0)return!0;let i=t.pane.id;return r.some(e=>e.id===i)}const Fa={tmux:D,herdr:T};function Ia(e){if(e){if(e.includes(`cursor`))return`cursor`;if(e.includes(`codex`))return`codex`;if(e.includes(`claude`))return`claude`}}function La(e,t){let n=F(e.store),r=[];for(let i of t){if(i.mux!==`tmux`&&i.mux!==`herdr`)continue;let t=Ia(i.harness);if(!t)continue;let a=e.store.resolvePaneId(i.id);if(a&&N(e.store,a)||n.some(e=>e.pane?.mux===i.mux&&e.pane.id===i.id))continue;let o=na(),s=ta(e),c={id:o,handle:i.cwd?Ui(f(i.cwd)):o.slice(0,6),harness:t,cwd:i.cwd??``,pane:{mux:i.mux,id:i.id},status:`active`,createdAt:s,lastSeen:s};P(e.store,c),e.store.putPaneIndex(i.id,o),r.push(c)}return r}function Ra(e,t){let n=e.exec??M,r=Wi(e.env??process.env);if(!r)return[];let i=Fa[r.mux].listPanes(n);if(i.length===0)return[];let a=new Set(i.map(e=>e.id)),o=[],s={};for(let t of F(e.store))Na(t)&&t.pane&&t.pane.mux===r.mux&&(t.pane.mux===`herdr`&&t.pane.terminal?Ba(e,t,t.pane.terminal,s):!a.has(t.pane.id))&&(t.status=`exited`,P(e.store,t),o.push(t));return t?.adopt&&o.push(...La(e,i)),o}function za(e,t,n){let r=Fa[t.mux];if(r.paneExists(e,{id:t.id}))return!1;let i=n.get(t.mux);return i||(i=r.listPanes(e),n.set(t.mux,i)),i.length>0&&!i.some(e=>e.id===t.id)}function Ba(e,t,n,r){let i=$i(e.exec??M,n,r);return i===`gone`||(i&&ea(e,t,i.id),!1)}function Va(e){let t=e.exec??M,n=e.now?.()??Date.now(),r=Ra(e),i=/* @__PURE__ */ new Map,a={};for(let o of F(e.store))Na(o)&&(o.pane?o.pane.mux===`herdr`&&o.pane.terminal?Ba(e,o,o.pane.terminal,a):za(t,o.pane,i):n-new Date(o.lastSeen).getTime()>9e5)&&(o.status=`exited`,P(e.store,o),r.push(o));let o=Wa(e),s=new Set(o.map(e=>e.id));return[...r.filter(e=>!s.has(e.id)).map(e=>({...e,pruned:`exited`})),...o.map(e=>({...e,pruned:`deleted`}))]}function Ha(e){return e.worktree?.root==null||!n(e.worktree.root)?!1:!Ua(e.worktree.root,e.worktree.primaryRoot)}function Ua(e,t){return e!=null&&t!=null&&g(e)===g(t)}function Wa(e){let t=e.exec??M,r=[];for(let i of F(e.store)){if(i.status!==`exited`||Ma(i)||Ha(i))continue;let a=i.worktree?.primaryRoot;a&&n(a)&&t(`git`,[`-C`,a,`worktree`,`prune`]);let o=i.pane?.id??e.store.findPaneByAgentId(i.id);o&&e.store.resolvePaneId(o)===i.id&&e.store.removePaneIndex(o),e.store.removeAgent(i.id),e.store.removeAgentData(i.id),e.store.removeMailbox(i.id),r.push(i)}return r}const Ga=/* @__PURE__ */ new Set([`Ask Codex to do anything`,`Explain this codebase`,`Summarize recent commits`,`Implement {feature}`,`Find and fix a bug in @filename`,`Write tests for @filename`,`Improve documentation in @filename`,`Run /review on my current changes`,`Use /skills to list available skills`]),Ka={claude:{head:/^❯(?:[ ](.*))?$/,indent:` `,ruled:!0,placeholder:e=>/^Try ".*"$/.test(e)},codex:{head:/^›(?: (.*))?$/,indent:` `,ruled:!1,placeholder:e=>Ga.has(e)},cursor:{head:/^ {2}→(?: (.*))?$/,indent:` `,ruled:!1,placeholder:e=>e===`Plan, search, build anything`}},qa=e=>/^─{3,}/.test(e);function Ja(e,t){for(let n=e.length-1;n>=0;n--){let r=t.head.exec(e[n]??``);if(!r||t.ruled&&!qa(e[n-1]??``))continue;let i=[(r[1]??``).trimEnd()],a=n+1;for(;a<e.length&&(e[a]??``).startsWith(t.indent)&&e[a]?.trim();)i.push((e[a]??``).slice(t.indent.length).trimEnd()),a++;if(t.ruled){if(!qa(e[a]??``))continue}else if((e[a]??``).trim()!==``&&a<e.length||e.slice(a).filter(e=>e.trim()).length>6)continue;let o=i.join(`
|
|
59
|
-
`);return o===``||i.length===1&&t.placeholder(o)?{kind:`empty`}:{kind:`draft`,text:o,rows:i.length}}return{kind:`unknown`}}function
|
|
60
|
-
`),r=t&&
|
|
61
|
-
`).filter(e=>e.replace(/\s+/g,` `).includes(n)).length}function
|
|
62
|
-
`))if(t.trim()!==``)return t;return``}function
|
|
58
|
+
`,r:`\r`,t:` `,v:`\v`};function Gr(e){if(e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`))return e;let t=[],n=e.slice(1,-1);for(let e=0;e<n.length;e++){let r=n[e];if(r!==`\\`){t.push(...Buffer.from(r));continue}let i=n[++e]??``,a=/^[0-7]{3}/.exec(n.slice(e));a?(t.push(Number.parseInt(a[0],8)),e+=2):t.push(...Buffer.from(Wr[i]??i))}return Buffer.from(t).toString(`utf8`)}function Kr(e){return h(p(e),`${f(e)}.worktrees`)}function qr(e,t){return h(Kr(e),`${f(e)}-${t}`)}function Jr(e,t){if(p(t)!==Kr(e))return;let n=`${f(e)}-`,r=f(t);if(!r.startsWith(n))return;let i=r.slice(n.length);return/^[1-9]\d*$/.test(i)?Number(i):void 0}function Yr(e){if(!e)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let{library:n,leaseId:r,holder:i}=t;if(n===`cyber-agentkit`&&typeof r==`string`&&typeof i==`string`)return{library:n,leaseId:r,holder:i}}function Xr(e,t){return Yr(e.locked)?{owner:`self`,research:[`E-GIT-L1`,`E-GIT-L2`]}:e.locked?.startsWith(`claude session `)?{owner:`claude-code`,research:[`E-CC-W4`,`E-PROC-CC5`]}:e.linked?e.locked===void 0&&Jr(t.primaryRoot,e.root)!==void 0?{owner:`self`,research:[]}:Zr(e.root,`${t.primaryRoot}${_}.claude${_}worktrees`)?{owner:`claude-code`,research:[`E-CC-W1`]}:t.codexHome&&Zr(e.root,`${t.codexHome}${_}worktrees`)?{owner:`codex`,research:[`E-CODEX-W1`]}:{owner:`unknown`,research:[]}:{owner:`user`,research:[]}}function Zr(e,t){return e.startsWith(`${t}${_}`)}const Qr={async createExclusive(e,t){try{return await pe(e,t,{flag:`wx`}),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}},async readText(e){try{return await ce(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}},async remove(e){try{await fe(e)}catch(e){if(e.code!==`ENOENT`)throw e}}};async function $r(e,t=Nr,n){let r=await t(`git`,[`-C`,e,`rev-parse`,`--path-format=absolute`,`--git-dir`]);if(r)return h(r,`locked`);let i=n&&await ei(e,n);return i?h(i,`locked`):void 0}async function ei(e,t){let n=h(t,`worktrees`),r=await ti(e),i;try{i=await le(n)}catch{return}for(let e of i){let t;try{t=(await ce(h(n,e,`gitdir`),`utf8`)).trim()}catch{continue}if(await ti(p(t))===r)return h(n,e)}}async function ti(e){return h(await Vr(p(e)),f(e),`.git`)}async function ni(e,t,n={}){let r=n.exec??Nr,i=n.fs??Qr,a=await $r(e,r);if(!a)return;let o=await r(`git`,[`-C`,e,`rev-parse`,`--path-format=absolute`,`--git-common-dir`]),s={worktree:e,leaseId:n.leaseId??oe(),holder:t,commonDir:o??void 0},c={library:`cyber-agentkit`,leaseId:s.leaseId,holder:t};if(await i.createExclusive(a,JSON.stringify(c)))return await ri(s,{exec:r,fs:i})?s:void 0}async function ri(e,t={}){let n=await $r(e.worktree,t.exec??Nr,e.commonDir);return n?Yr(await(t.fs??Qr).readText(n))?.leaseId===e.leaseId:!1}async function ii(e,t={}){let n=t.exec??Nr,r=t.fs??Qr,i=await $r(e.worktree,n,e.commonDir);return!i||Yr(await r.readText(i))?.leaseId!==e.leaseId?{released:!1,reason:`lost`}:(await r.remove(i),{released:!0})}function ai(e=`/proc`){return async()=>{if(e===`/proc`&&process.platform!==`linux`)return null;let t;try{t=await le(e)}catch{return null}return(await Promise.all(t.filter(e=>/^\d+$/.test(e)).map(t=>oi(h(e,t),Number(t))))).filter(e=>e!==void 0)}}async function oi(e,t){let[n,r,i,a,o]=await Promise.all([ci(h(e,`stat`)),ci(h(e,`cmdline`)),li(h(e,`exe`)),li(h(e,`cwd`)),ci(h(e,`environ`))]);if(n===void 0)return;let s={pid:t,argv:r?si(r):[]},c=Number(n.slice(n.lastIndexOf(`)`)+2).split(` `)[1]);if(Number.isInteger(c)&&(s.ppid=c),i!==void 0&&(s.exe=i),a!==void 0&&(s.cwd=a),o!==void 0){let e={};for(let t of si(o)){let n=t.indexOf(`=`);n>0&&(e[t.slice(0,n)]=t.slice(n+1))}s.env=e}return s}const si=e=>e.split(`\0`).filter(e=>e.length>0);async function ci(e){try{return await ce(e,`utf8`)}catch{return}}async function li(e){try{return(await ue(e)).replace(/ \(deleted\)$/,``)}catch{return}}const ui=e=>e?.slice(e.lastIndexOf(`/`)+1),di=(e,t)=>ui(e.exe)===t,fi=(e,t)=>e.exe!==void 0&&t.test(e.exe),pi=e=>di(e,`node`)||ui(e.argv[0])===`node`,mi=(e,t)=>e.argv.some(e=>t.test(e)),hi=[{harness:`claude-code`,research:[`E-PROC-CC1`,`E-PROC-CC2`,`E-PROC-CC3`],isSession:e=>fi(e,/\/claude\/versions\/[^/]+$/),link:{pid:`CLAUDE_PID`,id:`CLAUDE_CODE_SESSION_ID`}},{harness:`codex`,research:[`E-PROC-CX1`,`E-PROC-CX2`],isSession:e=>di(e,`codex`)&&!gi(e),helper:e=>gi(e)?`session`:void 0,link:{id:`CODEX_SESSION_ID`}},{harness:`copilot-cli`,research:[`E-PROC-COP1`,`E-PROC-COP2`],isSession:e=>di(e,`copilot`),link:{id:`COPILOT_AGENT_SESSION_ID`}},{harness:`cursor`,research:[`E-PROC-CUR1`,`E-PROC-CUR3`,`E-PROC-CUR4`],isSession:e=>_i(e)&&e.env?.AGENT_CLI_SOCKET_PATH===void 0,helper:e=>_i(e)&&e.env?.AGENT_CLI_SOCKET_PATH!==void 0?`session`:void 0,link:{id:`CURSOR_CONVERSATION_ID`}},{harness:`opencode`,research:[`E-PROC-OC1`],isSession:e=>di(e,`opencode`),link:{pid:`OPENCODE_PID`}},{harness:`kilo`,research:[`E-PROC-KILO1`],isSession:e=>fi(e,/\/cli-linux-x64\/bin\/kilo$/)||pi(e)&&mi(e,/\/@kilocode\/cli\/bin\/kilo$/),link:{pid:`KILO_PID`,id:`KILO_RUN_ID`}},{harness:`qwen-code`,research:[`E-PROC-QWEN1`],isSession:e=>pi(e)&&mi(e,/\/qwen-code\/cli-entry\.js$/),link:{id:`QWEN_CODE_SESSION_ID`}},{harness:`crush`,research:[`E-PROC-CRUSH1`],isSession:e=>fi(e,/\/crush\/bin\/crush$/)||pi(e)&&mi(e,/\/@charmland\/crush(\/|$)/)},{harness:`gemini-cli`,research:[`E-PROC-GEM1`],isSession:e=>pi(e)&&mi(e,/\/gemini-cli\/bundle\/gemini\.js$/)},{harness:`goose`,research:[`E-PROC-GOOSE1`],isSession:e=>di(e,`goose`)&&(e.argv[1]===`run`||e.argv[1]===`session`),link:{id:`AGENT_SESSION_ID`}},{harness:`openhands`,research:[`E-PROC-OH1`],isSession:e=>/^python[\d.]*$/.test(ui(e.exe)??``)&&mi(e,/\/openhands$/),helper:e=>di(e,`tmux`)&&(e.argv.includes(`-Lopenhands`)||/-L openhands( |$)/.test(e.argv.join(` `)))?`shared`:void 0},{harness:`cline`,research:[`E-PROC-CLINE1`],isSession:e=>vi(e)&&!e.argv.includes(`--cline-hub-daemon`),helper:e=>vi(e)&&e.argv.includes(`--cline-hub-daemon`)?`shared`:void 0},{harness:`augment`,research:[`E-PROC-AUG1`],isSession:e=>pi(e)&&mi(e,/\/@augmentcode\/auggie\/augment\.mjs$/)},{harness:`antigravity-cli`,research:[`E-PROC-AGY1`],isSession:e=>di(e,`agy`),link:{id:`ANTIGRAVITY_CONVERSATION_ID`}}];function gi(e){return ui(e.exe)===`codex-code-mode-host`||e.argv.some(e=>ui(e)===`codex-code-mode-host`)}function _i(e){return pi(e)&&mi(e,/(^|\/)cursor-agent$/)}function vi(e){return fi(e,/\/cli-linux-x64\/bin\/cline$/)||pi(e)&&mi(e,/\/cline\/bin\/cline$/)}async function yi(e={}){let t=await(e.source??ai())();return t===null?{verified:!1,occupancy:(e,t)=>({busy:t?.strict===!0,verified:!1,occupants:[],lingering:[],unlinked:[]})}:bi(t)}function bi(e){let t=new Map(e.map(e=>[e.pid,e])),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let t of e)for(let e of hi){let i=e.helper?.(t);if(i){r.set(t.pid,{signature:e,scope:i});break}if(e.isSession(t)){n.set(t.pid,e);break}}let i=e=>e.ppid===void 0||e.ppid===e.pid?void 0:t.get(e.ppid),a=/* @__PURE__ */ new Map,o=e=>{let t=i(e);return t&&n.get(t.pid)===n.get(e.pid)?o(t):e};for(let[e,r]of n){let n=o(t.get(e)),i=a.get(n.pid);i||(i={signature:r,members:[],ids:/* @__PURE__ */ new Set},a.set(n.pid,i)),i.members.push(t.get(e)),a.set(e,i)}let s=[...new Set(a.values())],c=e=>{let t=/* @__PURE__ */ new Set;for(let n=i(e);n&&!t.has(n.pid);n=i(n)){t.add(n.pid);let e=a.get(n.pid);if(e)return e}};for(let t of e){if(n.has(t.pid))continue;let e=c(t),r=e?.signature.link?.id,i=r&&t.env?.[r];e&&i&&e.ids.add(i)}let l=e=>s.filter(t=>t.signature.harness===e),u=(e,t)=>{let n=l(e.harness),r=e.link?.pid;if(r&&t[r]){let e=Number(t[r]);return n.some(t=>t.members.some(t=>t.pid===e))?`live`:`dead`}let i=e.link?.id,a=i&&t[i];if(a)return n.some(e=>e.ids.has(a))?`live`:n.every(e=>e.ids.size>0)?`dead`:`unknown`},d=e=>{let t=r.get(e.pid);if(t?.scope===`shared`)return l(t.signature.harness).length>0?void 0:{pid:e.pid,argv:e.argv,harness:t.signature.harness,reason:`harness-idle`};if(c(e))return;if(t)return{pid:e.pid,argv:e.argv,harness:t.signature.harness,reason:`helper-orphaned`};if(!e.env)return{pid:e.pid,argv:e.argv,reason:`env-unreadable`};let n=hi.map(t=>({signature:t,link:u(t,e.env)})).filter(e=>e.link!==void 0);if(n.some(e=>e.link===`live`))return;if(n.length===0)return{pid:e.pid,argv:e.argv,reason:`no-link`};let i=n.every(e=>e.link===`dead`)?`session-gone`:`unresolved-link`;return{pid:e.pid,argv:e.argv,harness:n[0].signature.harness,reason:i}};return{verified:!0,occupancy(t,r={}){let i=(e,t)=>e!==void 0&&(e===t||e.startsWith(t.endsWith(_)?t:t+_)),a=e=>i(e,t)&&!(r.nested??[]).some(t=>i(e,t)),c=[];for(let e of s){if(!e.members.some(e=>a(e.cwd)))continue;let t={harness:e.signature.harness,pid:(e.members.find(e=>o(e)===e)??e.members[0]).pid,pids:e.members.map(e=>e.pid).sort((e,t)=>e-t),research:e.signature.research};e.ids.size===1&&(t.sessionId=[...e.ids][0]),c.push(t)}let l=[],u=[];for(let t of e){if(n.has(t.pid)||!a(t.cwd))continue;let e=d(t);if(!e)continue;let r={...e,cwd:t.cwd};t.ppid!==void 0&&(r.ppid=t.ppid),(e.reason===`session-gone`||e.reason===`helper-orphaned`||e.reason===`harness-idle`?l:u).push(r)}return{busy:c.length>0,verified:!0,occupants:c,lingering:l,unlinked:u}}}}async function xi(e){let t=e.exec??Nr,n=await Vr(e.primaryRoot??await Br({from:e.from,exec:t})),r=await Hr({primaryRoot:n,exec:t,ignore:e.ignore,forge:e.forge}),i=e.base??await Pr(t,n,r.find(e=>!e.linked)?.branch),a=e.codexHome&&await Vr(e.codexHome),o=e.probe,s=[];for(let c of r){let l=Xr(c,{primaryRoot:n,codexHome:a}),u={worktree:c,owner:l,verified:!0};if(s.push(u),!c.linked){u.skip=`primary`;continue}if(l.owner!==`self`){u.skip=`foreign`;continue}let d=Yr(c.locked);if(d){u.skip=`leased`,u.holder=d.holder;continue}if(c.prunable){u.skip=`prunable`;continue}o??=await yi();let f=r.map(e=>e.root).filter(e=>e!==c.root&&e.startsWith(c.root+_)),p=o.occupancy(c.root,{strict:e.strict,nested:f});u.occupancy=p,u.verified=p.verified,p.busy?u.skip=p.verified?`busy`:`unverified`:c.dirty===!1?await Si(t,n,c,i)?e.available&&!await e.available(c)&&(u.skip=`rejected`):u.skip=`unmerged`:u.skip=`dirty`}return{primary:n,exec:t,base:i,entries:r,verdicts:s}}async function Si(e,t,n,r){return n.merged===!0?!0:!n.head||!r?!1:await e(`git`,[`-C`,t,`merge-base`,`--is-ancestor`,n.head,r])!==null}function Ci(e=Nr){return async({primaryRoot:t,path:n,base:r,branch:i})=>{let a=[`-C`,t,`worktree`,`add`,`--quiet`];if(i?await Ai(e,t,i)?a.push(n,i):a.push(`-b`,i,n,r):a.push(`--detach`,n,r),await e(`git`,a)===null)throw Error(`git worktree add failed: ${n}`)}}var wi=class extends Error{code;verdicts;constructor(e,t,n){super(t),this.code=e,this.verdicts=n,this.name=`AcquireError`}};async function Ti(e){let t=[];for(let n=0;n<3;n++){let n=await xi(e);t=n.verdicts;let{primary:r,exec:i,entries:a}=n;if(!n.base)throw new wi(`no-base`,"no base ref: pass `base` or set origin/HEAD",t);let o=await i(`git`,[`-C`,r,`rev-parse`,`--verify`,`--quiet`,`${n.base}^{commit}`]);if(!o)throw new wi(`no-base`,`base does not resolve to a commit: ${n.base}`,t);let s=t.filter(e=>e.skip===void 0).sort((e,t)=>Ei(r,e)-Ei(r,t));for(let t of s){let n=await Di(t,o,e,i,r);if(n)return n}let c=a.filter(e=>e.linked&&Jr(r,e.root)!==void 0);if(e.max!==void 0&&c.length>=e.max)throw new wi(`pool-full`,`all ${e.max} worktrees are in use`,t);let l=await Oi(r,o,e,i,c);if(l)return{...l,reused:!1,branch:e.branch,verified:!0,lingering:[]}}throw new wi(`contended`,`another caller took every worktree this one tried`,t)}function Ei(e,t){return Jr(e,t.worktree.root)??1/0}async function Di(e,t,n,r,i){let a=e.worktree,o={exec:r,fs:n.fs},s=await ni(a.root,n.holder,{...o,leaseId:n.newLeaseId?.()});if(!s)return;let c=await r(`git`,[`-C`,a.root,`rev-parse`,`HEAD`]),l=await Mr(a.root,{exec:r,ignore:n.ignore});if(c!==a.head||l!==!1||!await ri(s,o)){await ii(s,o);return}let u=(...e)=>r(`git`,[`-C`,a.root,...e]),d=async e=>{throw await ii(s,o),Error(`${e}: ${a.root}`)};if(await u(`read-tree`,`--reset`,`-u`,t)===null||await u(`clean`,`-fd`)===null)return d(`recycle failed`);if((n.branch?await Ai(r,i,n.branch)?await u(`switch`,`--quiet`,`--discard-changes`,n.branch):await u(`switch`,`--quiet`,`--discard-changes`,`-c`,n.branch,t):await u(`switch`,`--quiet`,`--discard-changes`,`--detach`,t))===null)return d(`recycle could not switch to ${n.branch??t}`);let f={...s,reused:!0,branch:n.branch,verified:e.verified,lingering:e.occupancy?.lingering??[]},p=a.branch;return p&&(f.previousBranch=p,a.merged===!0&&p!==n.branch&&(f.previousBranchDeleted=await r(`git`,[`-C`,i,`branch`,`-D`,p])!==null)),f}async function Oi(e,t,n,r,i){let a=new Set(i.map(t=>Jr(e,t.root))),o=1;for(;a.has(o)||await ji(qr(e,o));)o++;let s=qr(e,o),c=n.create??Ci(r),l={primaryRoot:e,path:s,base:t,branch:n.branch};try{await c(l)}catch(e){if(await ji(s))return;throw e}let u;try{u=await ni(await Vr(s),n.holder,{exec:r,fs:n.fs,leaseId:n.newLeaseId?.()})}catch(e){throw await ki(n.undoCreate,l),e}return u||await ki(n.undoCreate,l),u}async function ki(e,t){try{await e?.(t)}catch{}}async function Ai(e,t,n){return await e(`git`,[`-C`,t,`rev-parse`,`--verify`,`--quiet`,`refs/heads/${n}`])!==null}async function ji(e){try{return await se(e),!0}catch{return!1}}var Mi=class extends Error{};const Ni={add(e,t){let n=[`-C`,t.primaryRoot,`worktree`,`add`,`-b`,t.branch,t.path];if(t.base&&n.push(t.base),e(`git`,n)===null)throw new Mi(`git worktree add failed for ${t.path}`);return{root:g(t.path),branch:t.branch}},remove(e,t,n){if(e(`git`,[`-C`,n.primaryRoot,`worktree`,`remove`,t,`--force`])===null)throw new Mi(`git worktree remove failed for ${t}`)}};function Pi(e){let t=e(`git`,[`rev-parse`,`--path-format=absolute`,`--git-common-dir`]);if(!t)throw new Mi(`cannot resolve the primary checkout — not inside a git repository`);return p(t)}function Fi(e,t){if(g(e)===g(t))throw new Mi(`refusing to run in the primary checkout — spawn a worktree distinct from the primary checkout`)}const Ii=`config.json`,Li=`.agents/cyberlegion/${Ii}`;function Ri(e=process.cwd()){let t=g(e);for(;;){if(n(h(t,`.git`)))return t;let r=p(t);if(r===t)return g(e);t=r}}function zi(e={}){let t=e.env??process.env,n=e.root??e.space??t.CYBERLEGION_ROOT;if(n)return g(n);let r=re();return h(r||Ri(e.cwd),`.agents`,`cyberlegion`)}function Bi(e){r(e,{recursive:!0});let t=h(e,Ii);n(t)||u(t,`${JSON.stringify({version:1},null,2)}\n`)}var Vi=class extends Error{kind;value;constructor(e,t){super(`invalid ${e} ${JSON.stringify(t)} — must not be empty, ".", "..", or contain a path separator`),this.kind=e,this.value=t,this.name=`InvalidIdError`}};const Hi=/[\\/\0]/;function k(e,t){if(!e||e===`.`||e===`..`||Hi.test(e))throw new Vi(t,e);return e}const A={agentsDir:e=>h(e,`agents`),agentFile:(e,t)=>h(e,`agents`,`${k(t,`agent id`)}.json`),panesDir:e=>h(e,`panes`),paneFile:(e,t)=>h(e,`panes`,`${Ui(t)}.id`),inboxDir:(e,t)=>h(e,`inbox`,k(t,`agent id`)),inboxReadDir:(e,t)=>h(e,`inbox`,k(t,`agent id`),`read`),dataDir:(e,t)=>h(e,`data`,k(t,`agent id`)),briefFile:(e,t)=>h(e,`data`,k(t,`agent id`),`brief.md`),mainPaneFile:e=>h(e,`main-pane.id`),projectsDir:e=>h(e,`projects`),serviceLeaseFile:(e,t,n)=>h(e,`services`,k(t,`project id`),`${k(n,`service name`)}.json`),projectFile:(e,t)=>h(e,`projects`,`${k(t,`project id`)}.json`),messageFile:(e,t,n)=>h(A.inboxDir(e,t),`${k(n,`message id`)}.json`),messageReadFile:(e,t,n)=>h(A.inboxReadDir(e,t),`${k(n,`message id`)}.json`)};function Ui(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`)}function j(e){let t=e.CYBER_MUX!==void 0||e.CYBER_MUX_PANE!==void 0,n=e.CYBERLEGION_MUX!==void 0||e.CYBERLEGION_MUX_PANE!==void 0;return t||!n?e:{...e,CYBER_MUX:e.CYBERLEGION_MUX,CYBER_MUX_PANE:e.CYBERLEGION_MUX_PANE}}const M=Oe;function Wi(e){let t=je(j(e));return t&&(t.mux===`tmux`||t.mux===`herdr`)?{mux:t.mux,pane:t.pane}:void 0}function Gi(e){return Ki(Wi(e.env??process.env),e.exec??M)}function Ki(e,t){if(e?.mux!==`herdr`)return e;let n=Ji(t);return n?n.pane===e.pane?{...e,...n.terminal?{terminal:n.terminal}:{}}:qi(t)?{...e,pane:n.pane,...n.terminal?{terminal:n.terminal}:{}}:e:e}function qi(e){let t=e(`herdr`,[`--version`])?.match(/(\d+)\.(\d+)\.(\d+)/);if(!t)return!1;let[n,r,i]=t.slice(1).map(Number);return n>0||r>8||r===8&&i>=2}function Ji(e){return Yi(e(`herdr`,[`pane`,`current`]))}function Yi(e){if(e)try{let t=JSON.parse(e)?.result?.pane,n=t?.pane_id;if(typeof n!=`string`||!n)return;let r=t.terminal_id;return{pane:n,...typeof r==`string`&&r?{terminal:r}:{}}}catch{return}}function Xi(e,t){return Yi(e(`herdr`,[`pane`,`get`,t]))?.terminal}function Zi(e,t,n){if(t===`tmux`)return{mux:t,id:n};if(t!==`herdr`)return null;let r=Xi(e,n);return{mux:t,id:n,...r?{terminal:r}:{}}}function Qi(e){let t=/* @__PURE__ */ new Map,n=e(`herdr`,[`pane`,`list`]);if(!n)return t;try{let e=JSON.parse(n)?.result?.panes;if(!Array.isArray(e))return t;for(let n of e)typeof n?.terminal_id==`string`&&typeof n?.pane_id==`string`&&t.set(n.terminal_id,n.pane_id)}catch{return t}return t}function $i(e,t,n={}){if(n.terminals??=Qi(e),n.terminals.size===0)return;let r=n.terminals.get(t);return r?{id:r}:`gone`}function ea(e,t,n){let r=t.pane;r&&r.id!==n&&(e.store.resolvePaneId(r.id)===t.id&&e.store.removePaneIndex(r.id),t.pane={...r,id:n},P(e.store,t),e.store.putPaneIndex(n,t.id))}const ta=e=>new Date(e.now?.()??Date.now()).toISOString();function na(){return ae(8).toString(`hex`)}function N(e,t){return e.getAgent(t)}function P(e,t){e.putAgent(t)}function F(e){return e.listAgents()}function ra(e,t){if(e){if(e===`claude`||e===`cursor`||e===`codex`)return e;throw Error(`unknown --harness "${e}" (expected claude | cursor | codex)`)}let n=t.env??process.env;if(n.CLAUDECODE||n.CLAUDE_CODE_ENTRYPOINT)return`claude`;if(Object.keys(n).some(e=>e.startsWith(`CURSOR`)))return`cursor`;if(Object.keys(n).some(e=>e.startsWith(`CODEX`)))return`codex`;let r=n.TMUX_PANE;if(r){let e=(t.exec??M)(`tmux`,[`display-message`,`-p`,`-t`,r,`#{pane_current_command}`]);if(e?.includes(`cursor`))return`cursor`;if(e?.includes(`codex`))return`codex`;if(e?.includes(`claude`))return`claude`}}function I(e){return ia(e).id}function ia(e){let t=e.env??process.env,n=Ki(je(j(t)),e.exec??M);return n?{id:aa(e.store,n),cur:n}:{id:t.CYBERLEGION_AGENT_ID||void 0,cur:n}}function aa(e,t){let n=e.resolvePaneId(t.pane);if(!t.terminal)return n;let r=n?N(e,n)?.pane?.terminal:void 0;return n&&(!r||r===t.terminal)?n:F(e).find(e=>e.pane?.mux===`herdr`&&e.pane.terminal===t.terminal)?.id}function oa(e,t){e.store.ensureMarker();let n=e.env??process.env,r=ra(t.harness,e);if(!r)throw Error(`could not detect harness — pass --harness claude|cursor|codex`);let i=I(e),a=i?N(e.store,i):void 0,o=a?.id??i??na(),s=ta(e),c=e.exec??M,l=Ki(Wi(n),c),u={id:o,handle:t.handle??a?.handle??o.slice(0,6),harness:r,cwd:process.cwd(),...ha(e.store,c,o,a),pane:l?sa(l,c,n):null,status:`active`,createdAt:a?.createdAt??s,lastSeen:s,...a?.brief?{brief:a.brief}:{},...a?.spawnedBy?{spawnedBy:a.spawnedBy}:{}};return P(e.store,u),l&&e.store.putPaneIndex(l.pane,o),u}function sa(e,t,n){return e.mux===`tmux`?{mux:`tmux`,id:e.pane,window:t(`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#{window_id}`])??void 0,session:n.TMUX?.split(`,`)[0]}:{mux:e.mux,id:e.pane,...e.terminal?{terminal:e.terminal}:{}}}function ca(e){return`standing-${Ui(e)}`}function la(e,t){e.store.ensureMarker();let n=ca(t.handle);return e.store.withLock(`presence:${n}`,()=>ua(e,n,t))}function ua(e,t,n){let r=N(e.store,t),i=ta(e),a={id:t,handle:n.handle,kind:`standing`,pane:null,harness:void 0,cwd:process.cwd(),status:`active`,createdAt:r?.createdAt??i,lastSeen:i};r?.presence!==void 0&&(a.presence=r.presence);let o=n.home===void 0?r?.home:n.home??void 0;return o&&(a.home=o),P(e.store,a),a}function da(e,t){let n=t===void 0?e:(n,r)=>e(n,n===`git`?[`-C`,t,...r]:r),r=n(`git`,[`rev-parse`,`--show-toplevel`]);if(!r)return null;let i=n(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`])??void 0,a=ga(n);return{root:r,...i===void 0?{}:{branch:i},...a===void 0?{}:{primaryRoot:a}}}function fa(e,t,n){let r=g(t);return F(e).find(e=>e.id!==n&&e.worktree?.root&&g(e.worktree.root)===r)?.id}function pa(e,t,n){let r=fa(e,t.root,n);return{...t,...r?{owner:r}:{}}}function ma(e,t,n){let r=da(t,n);return r?pa(e,r):void 0}function ha(e,t,n,r){let i=r?.sharedWorktree?{sharedWorktree:r.sharedWorktree}:{};if(r?.worktree)return{worktree:_a(r.worktree,t),...i};let a=da(t);return a?r?.sharedWorktree||fa(e,a.root,n)?{worktree:null,sharedWorktree:pa(e,a,n)}:{worktree:a}:{worktree:null,...i}}function ga(e){try{return Pi(e)}catch{return}}function _a(e,t){if(!e||e.primaryRoot!==void 0)return e;let n=da(t);return n?.root!==e.root||n.primaryRoot===void 0?e:{...e,primaryRoot:n.primaryRoot}}function va(e,t){let n=t.find(e=>e.kind===`standing`);if(n)return n;if(t.length>1)throw Error(`"${e}" names ${t.length} units — pass an id (${t.map(e=>e.id).join(`, `)})`);return t[0]}function ya(e,t){let n=e.filter(e=>e.handle===t);return{live:n.filter(e=>e.status!==`exited`),exited:n.filter(e=>e.status===`exited`)}}function ba(e,t,n){if(t.length>0){let n=t.map(e=>`${e.id.slice(0,6)}${e.pane?` (${e.pane.id})`:``}`).join(`, `);return/* @__PURE__ */ Error(`"${e}" matches only exited unit(s) — ${n} — which have no reader. Address a live unit ('cyberlegion unit who'), or run 'cyberlegion unit register --standing --handle ${e}' for a durable inbox.`)}return/* @__PURE__ */ Error(`no agent addressable as "${e}" (tried ${n})`)}function xa(e,t){let n=F(e).find(e=>e.handle===t&&e.kind===`standing`);if(!n)throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return n.id}function Sa(e,t){let n=N(e,t);if(n?.kind===`service`||n?.kind===`standing`)return n.id;let r=F(e);if(r.some(e=>e.handle===t&&e.kind===`standing`))return xa(e,t);let i=r.filter(e=>e.handle===t&&e.kind===`service`);if(i.length===1)return i[0].id;if(i.length>1)throw Error(`"${t}" names ${i.length} service endpoints — pass an endpoint id (${i.map(e=>e.id).join(`, `)})`);return xa(e,t)}function Ca(e,t){let n=N(e,t);if(n)return n;let{live:r,exited:i}=ya(F(e),t),a=va(t,r);if(a)return a;if(i.length>1)throw Error(`"${t}" names ${i.length} exited units — pass an id (${i.map(e=>e.id).join(`, `)})`);if(i[0])return i[0];throw Error(`no unit addressable as "${t}" (tried id and handle)`)}function wa(e,t){let n=xa(e.store,t);if(!N(e.store,n))throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);if(Me(e.exec??M,j(e.env??process.env)).mux===`none`)throw Error(`claiming a presence needs a multiplexer to open panes`);let r=I(e);if(!r)throw Error("no identity in this session — run `cyberlegion unit register` first");return e.store.withLock(`presence:${n}`,()=>{let i=N(e.store,n);if(!i)throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return i.presence=r,P(e.store,i),i})}function Ta(e,t){let n=xa(e.store,t);if(!N(e.store,n))throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return e.store.withLock(`presence:${n}`,()=>{let r=N(e.store,n);if(!r)throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return r.presence!==void 0&&(r.presence=void 0,P(e.store,r)),r})}function Ea(e,t){if(!t.presence)return;let n=N(e,t.presence);if(n&&n.status!==`exited`)return n}function Da(e,t){let n=N(e,xa(e,t));if(n)return Ea(e,n)}function Oa(e,t){if(N(e,t))return t;let{live:n,exited:r}=ya(F(e),t),i=va(t,n);if(!i)throw ba(t,r,`id and handle`);return i.id}function L(e,t){let n=N(e,t);if(n)return n;let r=F(e),{live:i,exited:a}=ya(r,t),o=va(t,i);if(o)return o;let s=r.filter(e=>e.worktree?.branch===t),c=s.find(e=>e.status!==`exited`);if(c)return c;throw ba(t,[...a,...s.filter(e=>e.status===`exited`)].filter((e,t,n)=>n.findIndex(t=>t.id===e.id)===t),`id, handle, and worktree branch/CR`)}function ka(e){return f(e.worktree?.primaryRoot??e.cwd)}function Aa(e,t){let{repo:n,branch:r}=t;if(n===void 0&&r===void 0)throw Error(`a ref, --repo, or --branch is required`);let i=[...n===void 0?[]:[`--repo "${n}"`],...r===void 0?[]:[`--branch "${r}"`]].join(` `),a=F(e).filter(e=>e.status!==`exited`&&(r===void 0||e.worktree?.branch===r)&&(n===void 0||ka(e)===n)),[o]=a;if(!o)throw Error(`no live unit matches ${i}`);if(a.length>1){let e=a.map(e=>`${e.id} (${e.handle}${e.worktree?.branch?`, ${e.worktree.branch}`:``}, ${ka(e)})`).join(`, `);throw Error(`${i} matches ${a.length} units — ${e} — address one by its id`)}return o}function ja(e,t){let n=N(e.store,t);n&&(n.lastSeen=ta(e),P(e.store,n))}function R(e){let{id:t,cur:n}=ia(e);if(!t||(ja(e,t),n?.mux!==`herdr`||!n.terminal))return;let r=N(e.store,t);r?.pane?.mux===`herdr`&&(r.pane.terminal!==n.terminal&&(r.pane={...r.pane,terminal:n.terminal},P(e.store,r)),ea(e,r,n.pane))}function Ma(e){return e.kind===`standing`||e.kind===`service`}function Na(e){return!Ma(e)&&e.status!==`exited`&&e.status!==`stopped`}function Pa(e,t){if(t.status===`exited`||t.status===`stopped`)return!1;if(!t.pane)return!0;let n=e.exec??M;if(t.pane.mux===`herdr`&&t.pane.terminal)return $i(n,t.pane.terminal)!==`gone`;let r=Fa[t.pane.mux].listPanes(n);if(r.length===0)return!0;let i=t.pane.id;return r.some(e=>e.id===i)}const Fa={tmux:D,herdr:T};function Ia(e){if(e){if(e.includes(`cursor`))return`cursor`;if(e.includes(`codex`))return`codex`;if(e.includes(`claude`))return`claude`}}function La(e,t){let n=F(e.store),r=[];for(let i of t){if(i.mux!==`tmux`&&i.mux!==`herdr`)continue;let t=Ia(i.harness);if(!t)continue;let a=e.store.resolvePaneId(i.id);if(a&&N(e.store,a)||n.some(e=>e.pane?.mux===i.mux&&e.pane.id===i.id))continue;let o=na(),s=ta(e),c={id:o,handle:i.cwd?Ui(f(i.cwd)):o.slice(0,6),harness:t,cwd:i.cwd??``,pane:{mux:i.mux,id:i.id},status:`active`,createdAt:s,lastSeen:s};P(e.store,c),e.store.putPaneIndex(i.id,o),r.push(c)}return r}function Ra(e,t){let n=e.exec??M,r=Wi(e.env??process.env);if(!r)return[];let i=Fa[r.mux].listPanes(n);if(i.length===0)return[];let a=new Set(i.map(e=>e.id)),o=[],s={};for(let t of F(e.store))Na(t)&&t.pane&&t.pane.mux===r.mux&&(t.pane.mux===`herdr`&&t.pane.terminal?Ba(e,t,t.pane.terminal,s):!a.has(t.pane.id))&&(t.status=`exited`,P(e.store,t),o.push(t));return t?.adopt&&o.push(...La(e,i)),o}function za(e,t,n){let r=Fa[t.mux];if(r.paneExists(e,{id:t.id}))return!1;let i=n.get(t.mux);return i||(i=r.listPanes(e),n.set(t.mux,i)),i.length>0&&!i.some(e=>e.id===t.id)}function Ba(e,t,n,r){let i=$i(e.exec??M,n,r);return i===`gone`||(i&&ea(e,t,i.id),!1)}function Va(e,t={}){let n=e.exec??M,r=e.now?.()??Date.now(),i=Ra(e),a=/* @__PURE__ */ new Map,o={};for(let t of F(e.store))Na(t)&&(t.pane?t.pane.mux===`herdr`&&t.pane.terminal?Ba(e,t,t.pane.terminal,o):za(n,t.pane,a):r-new Date(t.lastSeen).getTime()>9e5)&&(t.status=`exited`,P(e.store,t),i.push(t));let s=Ka(e,t.landed??(()=>!1)),c=new Set(s.map(e=>e.id));return[...i.filter(e=>!c.has(e.id)).map(e=>({...e,pruned:`exited`})),...s.map(e=>({...e,pruned:`deleted`}))]}function Ha(e){return e?.root!=null&&n(e.root)&&!Ga(e.root,e.primaryRoot)}function Ua(e,t,n){let r=g(t);return F(e).some(e=>e.id!==n&&(e.worktree?.root!=null&&g(e.worktree.root)===r||e.sharedWorktree?.root!=null&&g(e.sharedWorktree.root)===r))}function Wa(e,t,n){if(Ha(t.worktree))return!0;let r=t.sharedWorktree;return Ha(r)&&!Ua(e,r.root,t.id)&&!n(r.root)}function Ga(e,t){return e!=null&&t!=null&&g(e)===g(t)}function Ka(e,t){let r=e.exec??M,i=[];for(let a of F(e.store)){if(a.status!==`exited`||Ma(a)||Wa(e.store,a,t))continue;let o=a.worktree?.primaryRoot;o&&n(o)&&r(`git`,[`-C`,o,`worktree`,`prune`]);let s=a.pane?.id??e.store.findPaneByAgentId(a.id);s&&e.store.resolvePaneId(s)===a.id&&e.store.removePaneIndex(s),e.store.removeAgent(a.id),e.store.removeAgentData(a.id),e.store.removeMailbox(a.id),i.push(a)}return i}const qa=/* @__PURE__ */ new Set([`Ask Codex to do anything`,`Explain this codebase`,`Summarize recent commits`,`Implement {feature}`,`Find and fix a bug in @filename`,`Write tests for @filename`,`Improve documentation in @filename`,`Run /review on my current changes`,`Use /skills to list available skills`]),Ja={claude:{head:/^❯(?:[ ](.*))?$/,indent:` `,ruled:!0,placeholder:e=>/^Try ".*"$/.test(e)},codex:{head:/^›(?: (.*))?$/,indent:` `,ruled:!1,placeholder:e=>qa.has(e)},cursor:{head:/^ {2}→(?: (.*))?$/,indent:` `,ruled:!1,placeholder:e=>e===`Plan, search, build anything`}},Ya=e=>/^─{3,}/.test(e);function Xa(e,t){for(let n=e.length-1;n>=0;n--){let r=t.head.exec(e[n]??``);if(!r||t.ruled&&!Ya(e[n-1]??``))continue;let i=[(r[1]??``).trimEnd()],a=n+1;for(;a<e.length&&(e[a]??``).startsWith(t.indent)&&e[a]?.trim();)i.push((e[a]??``).slice(t.indent.length).trimEnd()),a++;if(t.ruled){if(!Ya(e[a]??``))continue}else if((e[a]??``).trim()!==``&&a<e.length||e.slice(a).filter(e=>e.trim()).length>6)continue;let o=i.join(`
|
|
59
|
+
`);return o===``||i.length===1&&t.placeholder(o)?{kind:`empty`}:{kind:`draft`,text:o,rows:i.length}}return{kind:`unknown`}}function Za(e){return e!==void 0&&Ja[e]!==void 0}function Qa(e,t){let n=e.split(`
|
|
60
|
+
`),r=t&&Ja[t]?[Ja[t]]:Object.values(Ja);for(let e of r){let t=Xa(n,e);if(t.kind!==`unknown`)return t}return{kind:`unknown`}}async function $a(e,t,n,r,i={}){let a=i.idleMs??2e4,o=i.maxWaitMs??6e4,s=i.pollMs??1e3,c=i.sleep??(e=>new Promise(t=>setTimeout(t,e))),l=i.now??Date.now,u=()=>{try{return Qa(e.read(t,n).text,i.harness)}catch{return{kind:`unknown`}}},d=e=>e.kind===`draft`&&i.ownText?.(e.text)===!0,f=u(),p=l(),m=p;for(;f.kind===`draft`&&!d(f)&&l()-m<a;){if(l()-p+s>o)throw Error(`pane ${n.id} holds a draft the user is still editing — gave up after ${o/1e3}s without typing`);await c(s);let e=u();(e.kind!==`draft`||e.text!==f.text)&&(m=l()),f=e}if(f.kind!==`draft`)return r();if(d(f))return await eo(e,t,n,c),r();if(f.rows>1)throw Error(`pane ${n.id} holds an idle draft spanning ${f.rows} rows, which cannot be typed back exactly — left it untouched`);let h=f.text;await eo(e,t,n,c);let g=u();if(g.kind===`draft`&&g.text===h)return r();try{return await r()}finally{await c(150),e.sendText(t,n,h)}}async function eo(e,t,n,r){e.sendText(t,n,`\u0005`),await r(150),e.sendText(t,n,`\u0015`),await r(150)}function to(e,t){if(!e)return 0;let n=t.replace(/\s+/g,` `).trim().slice(0,40);return n===``?0:e.split(`
|
|
61
|
+
`).filter(e=>e.replace(/\s+/g,` `).includes(n)).length}function no(e,t,n){let r=e?Qa(e,n):{kind:`unknown`};if(r.kind===`unknown`)return{boxKnown:!1,staged:kr(e,t),outside:to(e,t)};let i=r.kind===`draft`?to(r.text,t):0;return{boxKnown:!0,staged:i>0,outside:to(e,t)-i}}async function ro(e,t,n,r,i={}){let a=i.attempts??10,o=i.settleMs??400,s=i.sleep??(e=>new Promise(t=>setTimeout(t,e)));if(!e.paneExists(t,n))throw Error(`nudge failed: pane ${n.id} no longer exists — the peer's session is gone, not busy.`);let c=e.read(t,n).text;if(i.requirePosted&&Za(i.harness))for(let l=0;l<a&&!no(c,r,i.harness).boxKnown;l++)await s(o),c=e.read(t,n).text;let l=no(c,r,i.harness).outside,u=()=>{let a=no(e.read(t,n).text,r,i.harness),o=a.outside>=l+(a.boxKnown||!a.staged?1:2);return a.staged?o?`taken`:`staged`:o||!i.requirePosted?`taken`:`lost`};e.submit(t,n,r),await s(o);let d=u();if(d===`taken`)return{taken:!0,resubmits:0};let f=+(d===`lost`);for(let i=1;i<=a;i++){if(d===`staged`?e.submit(t,n):f>=2&&(e.submit(t,n,r),f=0),await s(o),d=u(),d===`taken`)return{taken:!0,resubmits:i};f=d===`lost`?f+1:0}let p=d===`lost`?`the text vanished without the harness posting it`:`input still staged after ${a} re-submit attempts`;throw Error(`nudge failed: peer at pane ${n.id} never took the turn — ${p}`)}const io=`You have unread mail — check your inbox.`;function ao(e){return`Read your brief at ${e}, then begin work.`}const oo=/^Readyourbriefat.+,thenbeginwork\.$/,so=/^Yoursessionwasrestartedwithitsconversationresumed—continueyourwork\.Ifyouhavenoearlierconversation,readyourbriefat.+,thenbeginwork\.$/;function co(e,t){let n=e=>e.replace(/\s+/g,``),r=n(e);return r===``?!1:r===n(`You have unread mail — check your inbox.`)||oo.test(r)||so.test(r)||t!==void 0&&r===n(t)}function lo(e){return`Your session was restarted with its conversation resumed — continue your work. If you have no earlier conversation, read your brief at ${e}, then begin work.`}const uo={attempts:20,settleMs:400};function fo(e,t){let n=t instanceof Error?t.message:String(t);return`standing owner "${e}" has a home, but no presence could be spawned: ${n}${/session backend/.test(n)?` — a sender outside any multiplexer pane can reach a running one by setting CYBER_MUX=herdr or CYBER_MUX=tmux`:``}`}function po(e,t){return N(e,t)?.pane?.id??e.findPaneByAgentId(t)}async function mo(e,t,n,r,i,a){if(r.noNudge)return{rung:!1};let o=N(e,r.toId);if(!o)return{rung:!1};let s,c,l=!1,u;if(o.kind===`standing`){let t=Ea(e,o);if(!t&&o.home&&r.spawnHome)try{let e=await r.spawnHome(o);if(e.kind===`existing`)t=e.presence;else{let t=e.trustBlocked??e.warning;return{rung:e.rung,pane:e.pane,spawned:e.presence.id,...t?{warning:t}:{}}}}catch(e){u=fo(o.handle,e)}t?(s=po(e,t.id),c=t.harness):(s=e.getMainPane(),l=!0)}else s=po(e,o.id),c=o.harness;let d=await f();return u?{...d,warning:d.warning?`${u}; ${d.warning}`:u}:d;async function f(){if(!s||s===po(e,r.fromId))return{rung:!1};if(l){let e;try{e=t().isPaneFocused(n,{id:s})}catch{e=void 0}if(e===!1)return{rung:!1,pane:s}}try{let e=t(),r={id:s};return await $a(e,n,r,()=>ro(e,n,r,io,{...i,harness:c}),{...a,harness:c,ownText:e=>co(e)}),{rung:!0,pane:s}}catch(e){return{rung:!1,pane:s,warning:e instanceof Error?e.message:String(e)}}}}async function ho(e,t,n,r=uo,i){if(n.noWake)return{rung:!1};try{let a=e(),o=(n.resumed?lo:ao)(n.briefPath);return await $a(a,t,n.target,()=>ro(a,t,n.target,o,{...r,requirePosted:!0,harness:n.harness}),{...i,harness:n.harness,ownText:e=>co(e)}),{rung:!0,pane:n.target.id}}catch(e){return{rung:!1,pane:n.target.id,warning:e instanceof Error?e.message:String(e)}}}const go={claude:{markers:[[`Quick safety check`,`Yes, I trust this folder`]],accept:[{keys:[`Down`],until:/❯\s*Yes, I trust this folder/},{keys:[`Enter`]}]},codex:{markers:[[`Do you trust the contents of this directory?`,`Yes, continue`],[`Trust this folder?`,`Trust and continue`]],accept:[{text:`1`,until:/›\s*1\.\s*(?:Yes, continue|Trust and continue)/},{keys:[`Enter`]}]},cursor:{markers:[[`Workspace Trust Required`,`Trust this workspace`]],accept:[{text:`a`}]}},_o=e=>e.replace(/\s+/g,` `);function vo(e,t){let n=_o(t);return go[e].markers.some(e=>e.every(e=>n.includes(_o(e))))}async function yo(e,t,n,r,i={}){let a=i.pollMs??500,o=i.timeoutMs??2e4,s=i.stableReads??3,c=i.blankReads??6,l=i.keyDelayMs??1e3,u=i.attempts??5,d=i.sleep??(e=>new Promise(t=>setTimeout(t,e))),f=()=>{try{return e.read(t,n).text??``}catch{return``}},p=e=>vo(r.harness,e),m=f(),h=p(m),g=m,_=!1,v=1;for(let e=0;!h&&e<o;e+=a){await d(a);let e=f();if(p(e)){h=!0;break}if(e!==m&&(_=!0),v=e===g?v+1:1,g=e,_&&v>=s)return{state:`none`};if(!_&&m.trim()===``&&v>=c)return{state:`unsettled`}}if(!h)return{state:`unsettled`};let y=`${r.harness} in pane ${r.pane} is asking whether to trust ${r.folder}`;if(r.policy===`ask`)return{state:`needs-human`,message:`${y}. unit spawn does not trust a folder it did not create, so a person must answer that prompt. The unit is registered and its brief written; once the prompt is answered, nudge the unit to its brief.`};await d(l);for(let i of go[r.harness].accept){let r=i.until?i.until.test(f()):!1;for(let o=0;!r&&o<u;o++)i.keys&&e.sendKeys(t,n,i.keys),i.text&&e.sendText(t,n,i.text),await d(a),r=!i.until||i.until.test(f());if(!r)return bo(y)}for(let e=0;e<u;e++){if(!p(f()))return{state:`accepted`};await d(a)}return bo(y)}function bo(e){return{state:`stuck`,message:`${e}, and the prompt is still showing after spawn sent the keys that accept it. A person must answer it.`}}function z(e,t=M){let n=Me(t,j(e));if(n.mux===`tmux`)return D;if(n.mux===`herdr`)return T;throw n.mux===`wezterm`||n.mux===`zellij`?Error(`spawn detected ${n.mux}, a backend unit/registry cannot store a pane locator under (only tmux and herdr) — refusing before opening anything`):Error(`spawn requires a session backend — run inside tmux ($TMUX) or herdr ($HERDR_ENV=1)`)}const xo=/* @__PURE__ */ new Set([`clean`,`cleanup`,`decommission`,`delete`,`deprecate`,`disable`,`drop`,`prune`,`purge`,`remove`,`retire`,`revert`,`revoke`,`rollback`,`teardown`,`undo`,`uninstall`,`unregister`]),So=/* @__PURE__ */ new Set(/* @__PURE__ */ `analyze.assess.audit.check.compare.debug.diagnose.evaluate.examine.explain.explore.find.identify.inspect.investigate.locate.measure.profile.read.reproduce.research.review.scan.survey.trace.triage.verify`.split(`.`)),Co=/* @__PURE__ */ new Set(/* @__PURE__ */ `add.backfill.build.create.document.enable.extend.fix.generalize.harden.implement.introduce.make.migrate.move.port.refactor.rename.replace.rework.ship.split.support.swap.update.wire.write`.split(`.`)),wo=/* @__PURE__ */ new Set([`a`,`an`,`the`]);function To(e){let t=Do(Eo(e.brief)),n=t[0],r=`2B-`,i=!1;n&&xo.has(n)?(r=`A2-`,i=!0):n&&So.has(n)?(r=`9S-`,i=!0):n&&Co.has(n)&&(i=!0);let a;e.handle?a=Do(e.handle):(a=i?t.slice(1):t.slice(),a[0]&&wo.has(a[0])&&a.shift());let o=Oo(a,27)||e.id.slice(0,6);return`${r}${o}`}function Eo(e){for(let t of e.split(`
|
|
62
|
+
`))if(t.trim()!==``)return t;return``}function Do(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e!==``)}function Oo(e,t){if(e.length===0)return``;let n=e[0].slice(0,t);for(let r of e.slice(1)){let e=`${n}-${r}`;if(e.length>t)break;n=e}return n}const ko={acquire:Ti,release:ii};function Ao(e){return async(t,n)=>e(t,[...n])}function jo(e){return`cyberlegion:${e}`}const Mo=[Li],B={claude:`claude`,cursor:`cursor-agent`,codex:`codex`},No={claude:`/clear`,codex:`/clear`,copilot:`/clear`,cursor:`/new-chat`},Po=/* @__PURE__ */ new Set([`gemini`]);function Fo(e){let t=No[e];if(t)return t;throw Po.has(e)?Error(`"${e}" has no honest fresh-context command — its own "/clear" clears only the terminal screen, not the model context, so unit clear refuses to send a false-friend reset that would leave stale context behind`):Error(`"${e}" is not in the reset map (${Object.keys(No).join(` | `)}) — unit clear refuses to guess a command`)}async function Io(e,t){try{return await Br({from:g(t),exec:Ao(e)})}catch{throw Error(`--repo ${t} is not inside a git repository`)}}function Lo(e,t){let n=g(t);try{return Pi((t,r)=>e(t,t===`git`?[`-C`,n,...r]:r))}catch{return}}function Ro(e,t,n){if(n)return{ref:n};let r=(...n)=>e(`git`,[`-C`,t,...n]),i=e=>({ref:`HEAD`,fallback:e});if(r(`remote`,`get-url`,`origin`)===null)return i(`there is no origin remote`);if(r(`fetch`,`--quiet`,`origin`)===null)return i(`the fetch of origin failed`);let a=r(`symbolic-ref`,`--quiet`,`--short`,`refs/remotes/origin/HEAD`);return a?{ref:a}:i(`origin's default branch is unknown (origin/HEAD is not set)`)}async function zo(e,t){e.store.ensureMarker();let r=e.env??process.env,i=e.exec??M,a=z(r,i),o=j(r),s=t.harness;if(!s||!(s in B))throw Error(`spawn needs a --harness in the launch map (${Object.keys(B).join(` | `)})`);let c=is(t);if(c==null)throw Error(`spawn needs a brief — pass --task <text>, --task - (stdin), or --brief-file <path>`);if(t.cwd&&(t.branch||t.worktreePath||t.repo||t.base))throw Error(`--cwd cannot combine with the worktree-creating flags --branch/--worktree-path/--repo/--base`);let l=na(),u=t.cwd!==void 0&&t.cwdOwnRepo===!0?Lo(i,t.cwd):t.repo?await Io(i,t.repo):await Br({exec:Ao(i)}),d=t.command??B[s],f=()=>Go(e,a.name,l,d),p=Ar(a,o),m,_,v,y,ee,te;if(t.cwd){if(!n(t.cwd))throw Error(`--cwd directory must already exist: ${t.cwd}`);m=g(t.cwd),u!==void 0&&Fi(m,u),_=null,v=ma(e.store,i,m);let r=t.at??`tab`;te=a.open(i,{cwd:m,launch:f(),at:r,from:p,...Wo(r,t,c,l)})}else{if(u===void 0)throw Error(`a worktree spawn needs a primary checkout`);let e=t.branch??`cyberlegion/unit-${l}`,n=t.at??`workspace`;t.worktreePath&&Fi(g(t.worktreePath),u),y=Ro(i,u,t.base);let r=Wo(n,t,c,l),o=n===`workspace`?a.worktree:void 0,s,d=o?async t=>{let n=o.createInWorkspace(i,{primaryRoot:u,branch:e,path:t.path,base:t.base,launch:f(),...r});Fi(n.worktree.root,u),s=n.target}:Ci(Ao(i)),v;if(t.worktreePath)await d({primaryRoot:u,path:t.worktreePath,base:y.ref,branch:e}),v=g(t.worktreePath),_={root:v,branch:e,primaryRoot:u};else{let t=jo(l),n=await ko.acquire({primaryRoot:u,holder:t,branch:e,base:y.ref,exec:Ao(i),ignore:Mo,create:d});v=n.worktree,ee=n.reused,_={root:v,branch:e,primaryRoot:u,lease:{leaseId:n.leaseId,holder:t}}}Fi(v,u),Bi(h(v,`.agents`,`cyberlegion`)),m=v,te=s??(o?o.openInWorkspace(i,{primaryRoot:u,path:v,launch:f(),...r}).target:a.open(i,{cwd:m,launch:f(),at:n,from:p,...r}))}let b=new Date(e.now?.()??Date.now()).toISOString(),ne=a.name,re={id:l,handle:t.handle??l.slice(0,6),harness:s,cwd:m,worktree:_,...v?{sharedWorktree:v}:{},pane:Zi(i,ne,te.id),status:`active`,createdAt:b,lastSeen:b,brief:A.briefFile(e.store.root,l),launch:d,...I(e)?{spawnedBy:I(e)}:{}};return P(e.store,re),e.store.putPaneIndex(te.id,l),e.store.writeBrief(l,rs(c,t.briefInstructions)),{agent:re,pane:te.id,launch:d,...y?{base:y}:{},...ee===void 0?{}:{reused:ee}}}async function Bo(e,t,n={}){let r=await zo(e,t),i=await Vo(e,r,n);return i.trustBlocked?{...r,...i}:{...r,...await Ho(e,r,i,n)}}async function Vo(e,t,n){let r=await Uo(e,t,n.trustOpts,n.trustFolder);return r.state===`needs-human`||r.state===`stuck`?{rung:!1,trust:r.state,trustBlocked:r.message}:{rung:!1,trust:r.state}}async function Ho(e,t,n,r){let i=e.env??process.env,a=e.exec??M,o=t.agent.brief,s=await ho(()=>z(i,a),a,{target:{id:t.pane},briefPath:o??``,noWake:r.noWake||!o,harness:t.agent.harness},r.nudgeOpts);return{rung:s.rung,trust:n.trust,...s.warning?{warning:s.warning}:{}}}async function Uo(e,t,n,r=!1){let i=e.exec??M,a;try{a=z(e.env??process.env,i)}catch{return{state:`unsettled`}}return yo(a,i,{id:t.pane},{harness:t.agent.harness,folder:t.agent.cwd,pane:t.pane,policy:t.agent.worktree||r?`accept`:`ask`},n)}function Wo(e,t,n,r){return e===`workspace`?{label:To({brief:n,handle:t.handle,id:r})}:{}}function Go(e,t,n,r,i={}){let a=e.self?Zo(A.dataDir(e.store.root,n),e.self):void 0,o=a&&i.bindSelf?`${V(a)} unit rebind ${V(n)} --space ${V(e.store.root)} >/dev/null 2>&1; `:``,s=`${a?Jo(a):``}${Yo(t)}`;return`${o}${s}${r}${i.fallback?` || ${s}${i.fallback}`:``}`}const Ko={claude:e=>`--resume ${V(e)}`,codex:e=>`resume ${V(e)}`};function qo(e,t,n){let r=Ko[e];if(r&&t.split(/\s+/)[0]===B[e])return`${t} ${r(n)}`}function Jo(e){return`PATH=${V(p(e))}:"$PATH" CYBERLEGION_CLI=${V(e)} `}function Yo(e){return e===`tmux`?`CYBER_MUX=tmux CYBER_MUX_PANE=$TMUX_PANE `:e===`herdr`?`CYBER_MUX=herdr `:``}function Xo(){let e=process.argv[1];return[process.execPath,...process.execArgv,...e?[o(e)]:[]]}function Zo(e,n){let i=h(e,`bin`);r(i,{recursive:!0});let a=h(i,`cyberlegion`);return u(a,`#!/bin/sh\nexec ${n.map(V).join(` `)} "$@"\n`),t(a,493),a}function V(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Qo(e,t){let n=typeof t==`string`?L(e.store,t):Aa(e.store,t),r=n.pane?.id??e.store.findPaneByAgentId(n.id);if(!r)throw Error(`unit "${typeof t==`string`?t:n.id}" has no known session pane`);return{agent:n,target:{id:r}}}function $o(e,t){let{agent:n,target:r}=Qo(e,t),i=e.exec??M;return z(e.env??process.env,i).focus(i,r),{agent:n,pane:r.id}}async function es(e,t,n={}){let{agent:r,target:i}=Qo(e,t),a=e.exec??M,o=n.message||`You have unread mail — check your inbox.`,s=z(e.env??process.env,a),c=await $a(s,a,i,()=>ro(s,a,i,o,n.nudgeOpts),{...n.guardOpts,harness:r.harness,ownText:e=>co(e,o)});return{agent:r,pane:i.id,message:o,resubmits:c.resubmits}}function ts(e,t,n={}){let{agent:r,target:i}=Qo(e,t),a=e.exec??M,o=z(e.env??process.env,a).read(a,i,{lines:n.lines}).text;return{agent:r,pane:i.id,output:o}}async function ns(e,t,n={}){let{agent:r,target:i}=Qo(e,t),a=i.id;if(!r.harness)throw Error(`unit "${t}" has no harness on record — cannot resolve its reset command`);let o=Fo(r.harness),s=e.env??process.env,c=e.exec??M,l=z(s,c);return await $a(l,c,i,async()=>l.submit(c,i,o),{...n.guardOpts,harness:r.harness,ownText:e=>co(e)}),{agent:r,pane:a,command:o}}function rs(e,t){return t?`## Agent instructions\n\n${t}\n\n## Brief\n\n${e}`:e}function is(e,t=()=>i(0,`utf8`)){return e.briefFile?i(e.briefFile,`utf8`):e.task===`-`?t():e.task!=null&&e.task!==``?e.task:null}function as(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n)?([\s\S]*)$/.exec(e);if(!t)return{fm:{},instructions:e.trim()};let[,n,r]=t,i={},a=n.split(`
|
|
63
63
|
`),o=0;for(;o<a.length;){let e=a[o].replace(/\r$/,``);if(e.trim()===``||e.trim().startsWith(`#`)||e.length-e.trimStart().length>0){o++;continue}let t=e.indexOf(`:`);if(t===-1){o++;continue}let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(o++,r===`>`||r===`>-`||r===`|`||r===`|-`){let e=[];for(;o<a.length;){let t=a[o].replace(/\r$/,``);if(t.trim()===``)o++;else{if(t.length-t.trimStart().length===0)break;e.push(t.trim()),o++}}r=e.join(r.startsWith(`|`)?`
|
|
64
|
-
`:` `)}i[n]=
|
|
65
|
-
`).map(e=>e.trim().replace(/^[-*•]\s+/,``).split(/\s+/)[0]??``).filter(e=>e!==``)}function
|
|
66
|
-
`).some(e=>e&&e!==`?? .agents/cyberlegion/config.json`)}const
|
|
67
|
-
`)}function W(e,t,n,r){return[`${e}[${t.length}]{${n.map(e=>e.key).join(`,`)}}:`,...t.map(e=>n.map(t=>
|
|
68
|
-
`)}function G(e,t){console.log(e===`json`?JSON.stringify(t.json,null,2):t.toon)}function K(e){console.error(`→ ${e}`)}function q(e){console.error(JSON.stringify({error:e})),process.exit(1)}const
|
|
69
|
-
`)}async function
|
|
64
|
+
`:` `)}i[n]=os(r)}return{fm:i,instructions:r.trim()}}function os(e){return e.length>=2&&(e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`))?e.slice(1,-1):e}function ss(e){if(e!==void 0){if(e===`true`)return!0;if(e===`false`)return!1}}const cs=Object.keys(B);function ls(e,t){if(e===void 0||cs.includes(e))return e;throw Error(`agent def "${t}" has unknown harness "${e}" — expected one of ${cs.join(`, `)}`)}function us(e,t,n){let{fm:r,instructions:i}=as(t);return{name:r.name??n,description:r.description,model:r.model,effort:r.effort,harness:ls(r.harness,e),warm:ss(r.warm),interactive:ss(r.interactive),instructions:i,path:e}}function ds(e){return h(Ri(e),`.agents`,`agents`)}function fs(e){if(e.file){let t=g(e.file);if(!n(t))throw Error(`agent def file "${e.file}" does not exist`);return us(t,i(t,`utf8`),f(t).replace(/\.md$/,``))}if(!e.name)throw Error(`resolveAgentDef needs a --agent <name> or --agent-file <path>`);let t=[...e.searchRoots??[],ds(e.cwd)];for(let r of t){let t=h(r,`${e.name}.md`);if(n(t))return us(t,i(t,`utf8`),e.name)}throw Error(`no agent definition named "${e.name}" found under .agents/agents/`)}function ps(e={}){let t=[...e.searchRoots??[],ds(e.cwd)],r=/* @__PURE__ */ new Set,o=[];for(let e of t)if(n(e))for(let t of a(e)){if(!t.endsWith(`.md`))continue;let n=h(e,t);r.has(n)||(r.add(n),o.push(us(n,i(n,`utf8`),t.replace(/\.md$/,``))))}return o}function ms(e){return`'${e.replace(/'/g,`'\\''`)}'`}function hs(e,t,n=()=>[]){if(!e||!t)return{model:e,effortApplied:!t};let r=n(),i=`-${t}`;if(e.endsWith(i)&&r.includes(e))return{model:e,effortApplied:!0};let a=`${e}${i}`;return r.includes(a)?{model:a,effortApplied:!0}:{model:e,effortApplied:!1}}function gs(e,t,n){let r=t?[`--model`,ms(t)]:[];return!n||e===`cursor`?r:e===`codex`?[...r,`-c`,ms(`model_reasoning_effort="${n}"`)]:[...r,`--effort`,ms(n)]}function _s(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function vs(e,t){return!t||e===`cursor`?[]:e===`claude`?[`--append-system-prompt`,ms(t)]:[`-c`,ms(`developer_instructions=${_s(t)}`)]}function ys(e,t={}){let n=t.harness??e.harness??`claude`,r=t.effort??e.effort,i=t.model??e.model,a=n===`cursor`?hs(i,r,t.listCursorModels):void 0,o=a?a.model:i,s=[B[n],...gs(n,o,r),...vs(n,e.instructions)],c=n===`cursor`&&e.instructions?e.instructions:void 0,l=a&&!a.effortApplied?r:void 0;return{harness:n,command:s.join(` `),model:o,...l?{effortNotApplied:l}:{effort:r},...c?{briefInstructions:c}:{}}}function bs(e){let t={harness:e.harness,model:e.model,effort:e.effort,listCursorModels:e.listCursorModels};return!e.agent&&!e.agentFile?!e.harness||!e.model&&!e.effort?{harness:e.harness}:ys({name:e.harness,instructions:``,path:``},t):ys(fs({name:e.agent,file:e.agentFile,...e.cwd?{cwd:e.cwd}:{},...e.searchRoots?{searchRoots:e.searchRoots}:{}}),t)}function xs(e,t){let{harness:n,command:r,model:i,effort:a,effortNotApplied:o,briefInstructions:s}=bs({agent:e.agent,agentFile:e.agentFile,harness:e.harness,model:e.model,effort:e.effort,listCursorModels:t});if(!n)throw Error(`unit spawn needs --harness, or --agent/--agent-file resolving one`);return{input:{harness:n,command:r,briefInstructions:s,task:e.task,briefFile:e.briefFile,handle:e.handle,branch:e.branch,worktreePath:e.worktreePath,cwd:e.cwd,repo:e.repo,base:e.base,at:e.at},noWake:e.wake===!1,launched:{model:i,effort:a,effortNotApplied:o}}}function Ss(e,t){return e===`json`?JSON.stringify(t,null,2):t.output}function Cs(e){return ne(e).split(`
|
|
65
|
+
`).map(e=>e.trim().replace(/^[-*•]\s+/,``).split(/\s+/)[0]??``).filter(e=>e!==``)}function ws(){try{return Cs(te(`cursor-agent`,[`models`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:15e3}))}catch{return[]}}function Ts(e,t){let n=Oa(e.store,t.to),r=N(e.store,t.fromId),i=e.now?.()??Date.now(),a={id:`${i}-${ae(3).toString(`hex`)}`,from:t.fromId,fromHandle:r?.handle??t.fromId,to:n,...t.subject?{subject:t.subject}:{},body:t.body,...t.thread?{thread:t.thread}:{},...t.replyTo?{replyTo:t.replyTo}:{},ts:i,sentAt:new Date(i).toISOString()};return e.store.putMessage(n,a),a}function Es(e,t,n=()=>i(0,`utf8`)){if(e!=null)return e;if(t)return t===`-`?n():i(t,`utf8`);throw Error(`provide --body <text> or --body-file <path|->`)}function H(e,t){let n=e.store.listInbox(t.meId),r=n.unread.map(e=>({...e,read:!1})),i=t.unread?[]:n.read.map(e=>({...e,read:!0})),a=[...r,...i];return t.from&&(a=a.filter(e=>e.from===t.from||e.fromHandle===t.from)),t.thread&&(a=a.filter(e=>e.thread===t.thread)),a.sort((e,t)=>e.id.localeCompare(t.id))}function Ds(e,t){if(!e.store.hasMailbox(t.meId))return{mailbox:`none`,messages:[]};try{return{mailbox:`present`,messages:H(e,t)}}catch(e){return{mailbox:`unreadable`,messages:[],error:e instanceof Error?e.message:String(e)}}}function Os(e,t,n){let r=e.store.listInbox(t);return[...r.unread,...r.read].find(e=>e.id===n)}function ks(e,t,n){return e.store.ackMessage(t,n)}function As(e,t,n){let r=e.store.listInbox(t);if(r.unread.some(e=>e.id===n))return{msg:e.store.ackMessage(t,n),acked:!0};let i=r.read.find(e=>e.id===n);if(i)return{msg:i,acked:!1};throw Error(`"${n}" is not a message in this inbox`)}function js(e,t,n){e.store.removeMessage(t,n)}function Ms(e,t){e.removeMailbox(t)}async function Ns(e,t){let r=N(e.store,t.id);if(!r)throw Error(`no unit registered as agents/${t.id}.json — nothing to decommission`);if(r.kind===`service`)throw Error(`refusing to decommission "${t.id}" — it is a service endpoint, not a unit`);let i=e.exec??M,a=e.env??process.env,o=r.worktree?.root,s=o!=null&&n(o),c=s?await Ps(i,o):r.worktree?.primaryRoot,l=r.worktree?.lease,u=Ga(o,c);if(u&&t.force)throw Error(`refusing to close "${t.id}" with --force — its worktree is the primary checkout, which close never alters; close it without --force to end its session and reap its record`);let d=s&&!t.keepWorktree&&!l&&!u;if(d&&!t.force&&Fs(i,o))throw Error(`unit "${t.id}" has uncommitted changes in its worktree — pass --force to discard them`);let f=r.pane?.id??e.store.findPaneByAgentId(t.id);o&&!s&&c&&n(c)&&i(`git`,[`-C`,c,`worktree`,`prune`]);let p;if(l&&o&&(p=await ko.release({worktree:o,...l},{exec:Ao(i)})),d)try{Ni.remove(i,o,{primaryRoot:c})}catch(e){throw Error(`decommission "${t.id}" aborted — worktree removal failed, record left intact for retry: ${e instanceof Error?e.message:String(e)}`)}if(f)try{z(a,i).teardown(i,{id:f})}catch{}return e.store.removeAgent(t.id),f&&e.store.removePaneIndex(f),e.store.removeAgentData(t.id),Ms(e.store,t.id),{agent:r,worktreeRoot:o,retainedWorktree:s&&!u&&(t.keepWorktree||l)?o:void 0,...p?{lease:p}:{},pane:f}}async function Ps(e,t){try{return await Br({from:t,exec:Ao(e)})}catch{throw Error(`cannot resolve the repository of worktree ${t} — git does not know it`)}}function Fs(e,t){let n=e(`git`,[`-C`,t,`status`,`--porcelain`,`--untracked-files=all`]);return!!n&&n.split(`
|
|
66
|
+
`).some(e=>e&&e!==`?? .agents/cyberlegion/config.json`)}const Is=/^[0-9A-Za-z][0-9A-Za-z._+-]*$/;function Ls(e){if(!Is.test(e))throw Error(`invalid --pin "${e}" — expected a version or dist-tag token like 0.2.0 or latest (no spaces, ranges, or shell metacharacters)`)}const Rs=(e,t)=>`if command -v cyberlegion >/dev/null 2>&1; then cyberlegion mail hook --event ${e}; else npx -y cyberlegion${t?`@${t}`:``} mail hook --event ${e}; fi`,zs=[/^(?:npx (?:-y )?cyberlegion(?:@\S+)?|cyberlegion) mail hook --event (\w+)$/,/^if command -v cyberlegion >\/dev\/null 2>&1; then cyberlegion mail hook --event (\w+); else npx -y cyberlegion(?:@\S+)? mail hook --event \1; fi$/];function Bs(e){for(let t of zs){let n=e.match(t)?.[1];if(n)return n}}const Vs={claude:{file:`.claude/settings.json`,shape:`claude`,events:{SessionStart:`SessionStart`},pluginHook:!0},cursor:{file:`.cursor/hooks.json`,shape:`cursor`,events:{SessionStart:`sessionStart`},pluginHook:!1},codex:{file:`.codex/hooks.json`,shape:`cursor`,events:{SessionStart:`SessionStart`},pluginHook:!0}},Hs=[`PostToolUse`];function Us(e){if(!n(e))return{};try{return JSON.parse(i(e,`utf8`))}catch{return{}}}function Ws(e,t){r(p(e),{recursive:!0}),u(e,`${JSON.stringify(t,null,2)}\n`)}function Gs(e,t=process.cwd(),n){let r=Vs[e];if(!r)throw Error(`unknown harness "${e}" (expected claude | cursor | codex)`);n!==void 0&&Ls(n);let i=h(t,r.file),a=Us(i),o=[],s=!1;for(let[t,c]of Object.entries(r.events)){let l;if(r.pluginHook){let e=r.shape===`claude`?Ys(a,c,t):Xs(a,c,t);l=e?`removed project hook`:`provided by plugin`,s||=e}else{let e=Rs(t,n);l=r.shape===`claude`?Ks(a,c,e):qs(a,c,e),s=!0}o.push({harness:e,event:t,vendorEvent:c,file:i,status:l})}if(r.pluginHook)for(let t of Hs)(r.shape===`claude`?Ys(a,t,t):Xs(a,t,t))&&(s=!0,o.push({harness:e,event:t,vendorEvent:t,file:i,status:`removed project hook`}));return s&&Ws(i,a),o}function Ks(e,t,n){let r=e.hooks??={},i=r[t]??=[],a=Bs(n);for(let e of i)for(let t of e.hooks??[]){if(t.command===n)return`already present`;if(a&&Bs(t.command)===a)return t.command=n,`already present`}return i.push({hooks:[{type:`command`,command:n}]}),`registered`}function qs(e,t,n){e.version??=1;let r=e.hooks??={},i=r[t]??=[],a=Bs(n);for(let e of i){if(e.command===n)return`already present`;if(a&&Bs(e.command)===a)return e.command=n,`already present`}return i.push({command:n}),`registered`}const Js=(e,t)=>e!==void 0&&Bs(e)===t;function Ys(e,t,n){let r=e.hooks,i=r?.[t];if(!r||!i)return!1;let a=!1,o=[];for(let e of i){let t=(e.hooks??[]).filter(e=>!Js(e.command,n));t.length!==(e.hooks??[]).length&&(a=!0),t.length>0&&o.push({...e,hooks:t})}return a?(o.length>0?r[t]=o:delete r[t],!0):!1}function Xs(e,t,n){let r=e.hooks,i=r?.[t];if(!r||!i)return!1;let a=i.filter(e=>!Js(e.command,n));return a.length!==i.length&&(a.length>0?r[t]=a:delete r[t],!0)}async function Zs(e){let t=Ao(e.exec??M),r=/* @__PURE__ */ new Map;for(let t of F(e.store)){let e=t.sharedWorktree;e?.root&&n(e.root)&&r.set(e.root,e.primaryRoot)}let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set;for(let[e,n]of r){let r=await Br({from:e,exec:t}).catch(()=>n);if(!r||a.has(r))continue;a.add(r);let o=await Hr({primaryRoot:r,exec:t,ignore:Mo}).catch(()=>[]);for(let e of o)e.linked&&e.merged===!0&&e.dirty===!1&&i.add(e.root)}let o=/* @__PURE__ */ new Map;for(let e of r.keys())o.set(e,i.has(await Vr(e)));return e=>o.get(e)??!1}function Qs(e){if(e==null)return``;let t=String(e);return/[,\n"]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}function U(e){return Object.entries(e).filter(([,e])=>e!=null).map(([e,t])=>`${e}: ${t}`).join(`
|
|
67
|
+
`)}function W(e,t,n,r){return[`${e}[${t.length}]{${n.map(e=>e.key).join(`,`)}}:`,...t.map(e=>n.map(t=>Qs(t.get(e))).join(`,`)).map(e=>` ${e}`),r].join(`
|
|
68
|
+
`)}function G(e,t){console.log(e===`json`?JSON.stringify(t.json,null,2):t.toon)}function K(e){console.error(`→ ${e}`)}function q(e){console.error(JSON.stringify({error:e})),process.exit(1)}const $s=`cyberlegion:unit/`;function ec(e){return`cyberlegion:hub/${ie(`sha256`).update(e).digest(`hex`).slice(0,16)}`}function tc(e){return`${$s}${e}`}function nc(e){return e.kind===void 0||e.kind===`session`}function rc(e,t){let n={registered:[],retired:[],renamed:[]},r=e.registerParticipant({key:ec(t.root),kind:`service`,name:`cyberlegion`}).participant.id,i=/* @__PURE__ */ new Map;for(let t of e.participants({registeredBy:r}))t.key?.startsWith($s)&&i.set(t.key.slice(17),t);let a=new Map(t.listAgents().filter(nc).map(e=>[e.id,e]));for(let t of a.values()){if(t.status===`exited`)continue;let a=i.get(t.id);a&&a.status!==`retired`||(a=e.registerParticipant({key:tc(t.id),kind:`agent`,name:t.handle,registeredBy:r}).participant,n.registered.push(t.id)),a.name!==t.handle&&(e.renameParticipant(a.id,t.handle,r),n.renamed.push(t.id))}for(let[t,o]of i){if(o.status!==`live`)continue;let i=a.get(t);i&&i.status!==`exited`||(e.retireParticipant(o.id,r),n.retired.push(t))}return n}function ic(e,t){let n=e(`git`,[`-C`,t,`remote`,`get-url`,`origin`]);if(!n)return;let r=e(`gh`,[`repo`,`view`,n,`--json`,`id`,`--jq`,`.id`]);return r?{store:`gh`,nativeId:r}:void 0}async function ac(e,t,n,r=process.env,i=oc){let a;try{if(a=await sc(r,i),!a)return;let o=t.subject;if(!o){if(o=ic(n,t.root),!o)return;e.putProject({...t,subject:o})}let s=a.getChannelBySubject(o);return{subject:o,...s?{channel:{id:s.id,handle:s.handle}}:{}}}catch(e){console.error(`cynapse: project address skipped — ${e instanceof Error?e.message:String(e)}`);return}finally{a?.close()}}const oc=async()=>{let{silenceSqliteWarning:e}=await import(`cynapse/sqlite-warning`);return e(),await import(`cynapse`)};async function sc(e=process.env,t=oc){let n;try{n=await t()}catch{return}return n.openStore({path:n.resolveDbPath(e)})}async function cc(e,t=process.env,n=oc){let r;try{if(r=await sc(t,n),!r)return;let i=r;return e.withLock(`cynapse-participants`,()=>rc(i,e))}catch(e){console.error(`cynapse: participant sync skipped — ${e instanceof Error?e.message:String(e)}`);return}finally{r?.close()}}const lc=`Bash(cyberlegion *)`,uc=/^Bash(?:\((?:\*|cyberlegion(?: \*|:\*|\*))\))?$/;function dc(e=process.env){return h(e.CLAUDE_CONFIG_DIR||h(re(),`.claude`),`settings.json`)}function fc(e){if(!n(e))return{settings:{},allow:[]};let t;try{t=JSON.parse(i(e,`utf8`))}catch{throw Error(`cannot parse Claude Code settings ${e} — fix it by hand, then re-run`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Claude Code settings ${e} is not a JSON object — fix it by hand, then re-run`);let{permissions:r}=t,a=r?.allow??[];if(r!==void 0&&(typeof r!=`object`||!r)||!Array.isArray(a))throw Error(`Claude Code settings ${e} has a malformed permissions.allow — fix it by hand, then re-run`);return{settings:t,allow:a}}const pc=e=>e.some(e=>typeof e==`string`&&uc.test(e));function mc(e){try{return pc(fc(e).allow)?`present`:`missing`}catch{return`unreadable`}}function hc(e){let{settings:t,allow:n}=fc(e);return pc(n)?`present`:(t.permissions={...t.permissions??{},allow:[...n,lc]},r(p(e),{recursive:!0}),u(e,`${JSON.stringify(t,null,2)}\n`),`added`)}function gc(e){return[`You stand in for the standing owner "${e}": you are its presence, spawned because mail was delivered to it and no unit was standing in.`,``,`Read its mail: cyberlegion mail inbox --owner ${e}, then cyberlegion mail read --owner ${e} <id>.`,`Ack what you have handled: cyberlegion mail ack --owner ${e} <id>.`].join(`
|
|
69
|
+
`)}async function _c(e,t,n={}){let r=t.home;if(!r)throw Error(`standing owner "${t.handle}" has no home`);let i=await e.store.withLockAsync(`presence:${t.id}`,async()=>{let i=N(e.store,t.id);if(!i)throw Error(`standing owner "${t.handle}" is gone`);let a=Ea(e.store,i);if(a)return{existing:a};let o=bs({agent:r.agent,harness:r.harness,cwd:r.dir}),s=await zo(e,{harness:o.harness,command:o.command,briefInstructions:o.briefInstructions,task:gc(t.handle),cwd:r.dir,cwdOwnRepo:!0,at:`workspace`});i.presence=s.agent.id,P(e.store,i);let c=()=>{let n=N(e.store,t.id);return n?.presence===s.agent.id&&(n.presence=void 0,P(e.store,n),!0)},l;try{l=await Vo(e,s,{...n,trustFolder:!0})}catch(e){throw c(),e}let u=l.trustBlocked?c():!1;return{spawned:s,trust:l,unbound:u}});if(i.existing)return{kind:`existing`,presence:i.existing};let{spawned:a,trust:o,unbound:s}=i,c=o.trustBlocked?o:await Ho(e,a,o,n);return{kind:`spawned`,presence:a.agent,pane:a.pane,unbound:s,...c}}function vc(e,t){let n=e(`git`,[`-C`,t,`rev-parse`,`--path-format=absolute`,`--git-common-dir`]);if(n)return bc(n)}function yc(e){return`prj-${ie(`sha256`).update(e).digest(`hex`).slice(0,16)}`}function bc(e){try{return o(e)}catch{return g(e)}}function xc(e,t,n){let r=e(`git`,[`-C`,t,`rev-parse`,`--path-format=absolute`,`--git-dir`]),i=e(`git`,[`-C`,t,`rev-parse`,`--show-toplevel`]);return r&&i&&bc(r)===n?{root:bc(i),exact:!0}:{root:p(n),exact:!1}}function Sc(e,t={}){let n=e.exec??M,r=g(t.dir??process.cwd()),i=vc(n,r);if(!i)throw Error(`cannot register a project at "${r}" — not inside a git repository`);e.store.ensureMarker();let a=yc(i),o=e.store.getProject(a),s=xc(n,r,i),c=s.exact||!o?s.root:o.root,l={id:a,name:f(c),root:c,commonDir:i,registeredAt:o?.registeredAt??new Date(e.now?.()??Date.now()).toISOString()};return e.store.putProject(l),l}function Cc(e){return e.listProjects()}function wc(e){return m(e)||e.startsWith(`.`)||e.includes(_)||e.includes(`/`)}function Tc(e){return n(e)&&l(e).isDirectory()}function Ec(e,t){let n=e.store.getProject(t);if(n)return n;let r=g(t);if(wc(t)&&Tc(r))return Dc(e,r);let i=e.store.listProjects().filter(e=>e.name===t);if(i.length===1)return i[0];if(i.length>1)throw Error(`project name "${t}" is ambiguous — ${i.map(e=>`${e.id} (${e.root})`).join(`, `)}; pass an id or a path`);if(Tc(r))return Dc(e,r);throw Error(`no registered project "${t}" (tried id, path, and name) — pass a path inside the repository to register it`)}function Dc(e,t){let n=vc(e.exec??M,t);if(!n)throw Error(`"${t}" is not inside a git repository`);return e.store.getProject(yc(n))??Sc(e,{dir:t})}const Oc=[`SessionStart`];function kc(e,t){if(!Oc.includes(t))throw Error(`unsupported --event "${t}" (expected ${Oc.join(` | `)})`);let n=I(e);if(!n){if(je(j(e.env??process.env)))try{oa(e,{}),n=I(e)}catch{return null}if(!n)return null}let r=[],i=N(e.store,n),a=H({store:e.store},{meId:n,unread:!0});if(a.length>0){let e=a.map(e=>`- **${e.fromHandle}**${e.subject?` — ${e.subject}`:``}: ${e.body} \`(${e.id})\``);r.push(`## Unread mail (${a.length})\n\n${e.join(`
|
|
70
70
|
`)}`)}let o=je(j(e.env??process.env));if(i&&!i.spawnedBy)try{let t=e.store.getMainPane();if(!t||o?.pane===t){let t=F(e.store).filter(e=>e.kind===`standing`);for(let n of t){let t=H({store:e.store},{meId:n.id,unread:!0});if(t.length===0)continue;let i=t.map(e=>`- **${e.fromHandle}**${e.subject?` — ${e.subject}`:``}: ${e.body} \`(${e.id})\``);r.push(`## Owner mail — ${n.handle} (${t.length})\n\n${i.join(`
|
|
71
71
|
`)}`)}}}catch{}return r.length===0?null:{hookSpecificOutput:{hookEventName:t,additionalContext:r.join(`
|
|
72
72
|
|
|
73
|
-
`)}}}var Dc=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`ServiceOwnershipError`}};const Oc=/^[a-z0-9][a-z0-9_-]{0,62}$/;function kc(e){if(!Oc.test(e))throw Error(`invalid service name "${e}" — use lowercase letters, digits, "-" or "_" (max 63)`)}function Ac(e,t){return`svc-${e}-${t}`}const jc=e=>e.now?.()??Date.now(),Mc=e=>new Date(e).toISOString();function Nc(e,t){return`service-${e}-${t}`}function Pc(e,t){return t.status===`exited`?!1:e.isLive?e.isLive(t):Pa(e,t)}function Fc(e,t,n){let r=Ac(t.id,n),i=N(e.store,r);if(i)return i;e.store.ensureMarker();let a=Mc(jc(e)),o={id:r,handle:`${n}@${t.name}`,kind:`service`,service:{project:t.id,name:n},cwd:t.root,pane:null,status:`active`,createdAt:a,lastSeen:a};return P(e.store,o),o}function Ic(e,t,n,r){let i={project:t,endpoint:n,lease:r};if(r.state===`vacant`)return{...i,health:`vacant`,control:`none`};if(r.state===`reserved`){let t=jc(e)>Date.parse(r.reservation?.expiresAt??``);return{...i,health:t?`expired`:`starting`,control:`none`,...t?{note:`the reservation expired without a bound owner; the next acquire takes over`}:{}}}let a=r.holder?N(e.store,r.holder):void 0;if(!a)return{...i,health:`unhealthy`,control:`none`,note:`the owner has no unit record`};let o=a.pane||e.store.findPaneByAgentId(a.id)?`pane`:`none`,s=o===`none`?`the owner resolves, but its session control is not recoverable from here (no multiplexer pane — e.g. a native subagent only its parent can drive)`:void 0;return Pc(e,a)?{...i,owner:a,health:`healthy`,control:o,...s?{note:s}:{}}:{...i,owner:a,health:`unhealthy`,control:o,note:`the owner session is gone`}}function Lc(e,t,n){return{project:t,service:n,endpoint:Ac(t,n),generation:0,state:`vacant`,updatedAt:Mc(jc(e))}}function Rc(e,t,n,r){kc(n);let i=Cc(e,t),a=e.store.getServiceLease(i.id,n),o=N(e.store,Ac(i.id,n));if(a&&o)return{project:i,endpoint:o,lease:a};if(!r)throw Error(`no service "${n}" in project ${i.name} (${i.id})`);return{project:i,endpoint:Fc(e,i,n),lease:a??Lc(e,i.id,n)}}function zc(e,t,n,r,i){kc(n);let a=Cc(e,t);return e.store.withLock(Nc(a.id,n),()=>i(Rc(e,a.id,n,r)))}function Bc(e,t){let n={...t,updatedAt:Mc(jc(e))};return e.store.putServiceLease(n),n}function Vc(e){return new Dc(`stale`,e)}function Hc(e,t,n){let{project:r,endpoint:i,lease:a}=Rc(e,t,n,!1);return Ic(e,r,i,a)}function Uc(e,t,n,r={}){return zc(e,t,n,!0,({project:t,endpoint:i,lease:a})=>{let o=Ic(e,t,i,a);if(r.force){if(r.force.generation!==a.generation)throw Vc(`cannot force: generation ${r.force.generation} is not the current ${a.generation}`)}else if(o.health===`healthy`)return{outcome:`resolved`,lease:a,view:o};else if(o.health===`starting`)return{outcome:`starting`,lease:a,view:o};let s=jc(e),c=ae(8).toString(`hex`),l=Bc(e,{project:t.id,service:n,endpoint:i.id,generation:a.generation+1,state:`reserved`,reservation:{token:c,...r.by?{by:r.by}:{},at:Mc(s),expiresAt:Mc(s+(r.ttlMs??3e5)),...r.force?{forced:!0}:{}},updatedAt:Mc(s)});return{outcome:`reserved`,lease:l,view:Ic(e,t,i,l),token:c}})}function Wc(e,t){let n=N(e.store,t);if(!n)throw new Dc(`unknown-unit`,`no unit "${t}"`);if(!Pc(e,n))throw new Dc(`unit-not-live`,`unit "${t}" has no live session`);return n}function Gc(e,t,n,r){return zc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(i.state!==`reserved`||i.generation!==r.generation||i.reservation?.token!==r.token)throw Vc(`reservation for generation ${r.generation} is no longer current (now ${i.state} at ${i.generation})`);return Wc(e,r.unit),Ic(e,t,n,Bc(e,{project:i.project,service:i.service,endpoint:i.endpoint,generation:i.generation,state:`active`,holder:r.unit,updatedAt:i.updatedAt}))})}function Kc(e,t,n,r){return zc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(!(i.generation===r.generation&&(i.state===`reserved`&&r.token!==void 0&&i.reservation?.token===r.token||i.state===`active`&&r.unit!==void 0&&i.holder===r.unit)))throw Vc(`nothing to release at generation ${r.generation} (now ${i.state} at ${i.generation})`);return Ic(e,t,n,Bc(e,{project:i.project,service:i.service,endpoint:i.endpoint,generation:i.generation,state:`vacant`,updatedAt:i.updatedAt}))})}function qc(e,t,n,r){return zc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(i.state!==`active`||i.generation!==r.generation||i.holder!==r.from)throw Vc(`"${r.from}" is not the owner at generation ${r.generation}`);return Wc(e,r.to),Ic(e,t,n,Bc(e,{...i,generation:i.generation+1,holder:r.to}))})}function Jc(e,t,n,r){let{project:i,endpoint:a,lease:o}=Rc(e,t,n,!1);if(o.state!==`active`||o.holder!==r.unit||o.generation!==r.generation)throw Vc(`"${r.unit}" at generation ${r.generation} is not the owner (now ${o.state}${o.holder?` by ${o.holder}`:``} at ${o.generation})`);return Ic(e,i,a,o)}async function Yc(e,t,n,r){let i=Uc(e,t,n,r);if(i.outcome!==`reserved`)return{outcome:i.outcome,view:i.view};let{generation:a,endpoint:o}=i.lease,s;try{s=await r.launch({generation:a,endpoint:o})}catch(r){try{Kc(e,t,n,{generation:a,token:i.token})}catch{}throw r}try{return{outcome:`started`,view:Gc(e,t,n,{generation:a,token:i.token,unit:s.unit}),launched:s}}catch(e){throw e instanceof Dc?new Dc(e.code,`launched unit "${s.unit}" could not become the owner — ${e.message}; stop it`):e}}function Xc(e,t){if((t.home!==void 0||t.clearHome===!0||t.agent!==void 0)&&!(t.standing&&t.handle))throw Error(`a home belongs only to a named standing owner — pass --standing --handle <name>`);if(!t.standing)return;if(t.home!==void 0&&t.clearHome)throw Error(`--home and --clear-home contradict — pass one`);if(t.home===void 0&&(t.agent!==void 0||t.harness!==void 0))throw Error(`a launch needs --home: --agent and --harness name how to start a session in it`);if(t.clearHome)return null;if(t.home===void 0)return;let r=g(t.home);if(!n(r)||!l(r).isDirectory())throw Error(`the home must already exist: ${t.home}`);if(t.agent===void 0==(t.harness===void 0))throw Error(`a home needs exactly one of --agent or --harness`);let i;if(t.harness!==void 0){if(!(t.harness in B))throw Error(`unrecognized --harness "${t.harness}" (${Object.keys(B).join(` | `)})`);i={harness:t.harness}}else{let e=t.agent;try{us({name:e,cwd:r})}catch{throw Error(`the agent definition "${e}" does not resolve from the home ${r}`)}i={agent:e}}let a=Fo(e,r);if(a!==void 0&&o(a)===o(r))throw Error(`the home refuses the primary checkout ${r} — a spawned unit never works there`);return{dir:r,...i}}var Zc=class extends Error{file;constructor(e,t){super(`corrupt record at "${e}": ${t instanceof Error?t.message:String(t)}`,{cause:t}),this.file=e,this.name=`CorruptRecordError`}};function Qc(e){if(e===process.pid)return`alive`;try{return process.kill(e,0),`alive`}catch(e){return e.code===`ESRCH`?`dead`:`unknown`}}var $c=class extends Error{name;constructor(e){super(`timed out waiting for lock "${e}"`),this.name=e,this.name=`LockTimeoutError`}};function el(e){return h(e,`locks`)}function tl(e,t){return h(el(e),`${t}.lock`)}function nl(e){try{return JSON.parse(i(h(e,`holder.json`),`utf8`))}catch{return}}function rl(e){return Qc(e)!==`dead`}function il(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function al(e){let t=`${e}.stale-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;try{s(e,t)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n=nl(t);if(n&&rl(n.pid)){try{s(t,e)}catch{c(t,{recursive:!0,force:!0})}return!1}return c(t,{recursive:!0,force:!0}),!0}function ol(e,t,n={}){let i=n.retryDelayMs??20,a=n.timeoutMs??5e3,o=tl(e,t);r(el(e),{recursive:!0});let s=Date.now()+a;for(;;)try{return r(o),u(h(o,`holder.json`),JSON.stringify({pid:process.pid,acquiredAt:Date.now()})),{release:()=>c(o,{recursive:!0,force:!0})}}catch(e){if(e.code!==`EEXIST`)throw e;let n=nl(o);if(n&&!rl(n.pid)&&al(o))continue;if(Date.now()>s)throw new $c(t);il(i)}}function sl(e,t,n,r){let i=ol(e,t,r);try{return n()}finally{i.release()}}async function cl(e,t,n,r){let i=ol(e,t,r);try{return await n()}finally{i.release()}}function ll(e){let t=i(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Zc(e,t)}}function ul(e){return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>ll(h(e,t))):[]}let dl=0;function fl(e,t){r(p(e),{recursive:!0});let n=`${e}.${process.pid}.${dl++}.tmp`;u(n,t),s(n,e)}function pl(e,t){fl(e,`${JSON.stringify(t,null,2)}\n`)}function ml(e,t){fl(e,t)}function J(e){try{return e()}catch(e){if(e instanceof Vi)return;throw e}}var hl=class{root;constructor(e){this.root=e}ensureMarker(){Bi(this.root)}putMessage(e,t){fl(A.messageFile(this.root,e,t.id),`${JSON.stringify(t,null,2)}\n`)}listInbox(e){let t=J(()=>A.inboxDir(this.root,e)),n=J(()=>A.inboxReadDir(this.root,e));return{unread:t?ul(t):[],read:n?ul(n):[]}}hasMailbox(e){let t=J(()=>A.inboxDir(this.root,e));return t!==void 0&&n(t)}ackMessage(e,t){let i=J(()=>A.messageFile(this.root,e,t));if(!i||!n(i))throw Error(`"${t}" is not an unread message in this inbox`);let a=ll(i),o=A.messageReadFile(this.root,e,t);return r(p(o),{recursive:!0}),s(i,o),a}removeMessage(e,t){let r=J(()=>A.messageFile(this.root,e,t));if(r&&n(r)){c(r);return}let i=J(()=>A.messageReadFile(this.root,e,t));if(i&&n(i))c(i);else throw Error(`"${t}" is not a message in this inbox`)}removeMailbox(e){c(A.inboxDir(this.root,e),{recursive:!0,force:!0})}putAgent(e){pl(A.agentFile(this.root,e.id),e)}getAgent(e){let t=J(()=>A.agentFile(this.root,e));if(t&&n(t))return ll(t)}listAgents(){let e=A.agentsDir(this.root);return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>ll(h(e,t))).sort((e,t)=>e.createdAt.localeCompare(t.createdAt)):[]}removeAgent(e){c(A.agentFile(this.root,e),{force:!0})}removeAgentData(e){c(A.dataDir(this.root,e),{recursive:!0,force:!0})}putProject(e){pl(A.projectFile(this.root,e.id),e)}getProject(e){let t=J(()=>A.projectFile(this.root,e));if(t&&n(t))return ll(t)}listProjects(){let e=A.projectsDir(this.root);return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>ll(h(e,t))).sort((e,t)=>e.registeredAt.localeCompare(t.registeredAt)):[]}putServiceLease(e){pl(A.serviceLeaseFile(this.root,e.project,e.service),e)}getServiceLease(e,t){let r=J(()=>A.serviceLeaseFile(this.root,e,t));if(r&&n(r))return ll(r)}putPaneIndex(e,t){ml(A.paneFile(this.root,e),t)}resolvePaneId(e){let t=A.paneFile(this.root,e);return n(t)?i(t,`utf8`).trim():void 0}findPaneByAgentId(e){let t=A.panesDir(this.root);if(n(t)){for(let n of a(t))if(n.endsWith(`.id`)&&i(h(t,n),`utf8`).trim()===e)return n.slice(0,-3)}}removePaneIndex(e){c(A.paneFile(this.root,e),{force:!0})}writeBrief(e,t){ml(A.briefFile(this.root,e),t)}readBrief(e){let t=J(()=>A.briefFile(this.root,e));return t&&n(t)?i(t,`utf8`):void 0}setMainPane(e){sl(this.root,`main-pane`,()=>{let t=A.mainPaneFile(this.root);e?ml(t,e):c(t,{force:!0})})}getMainPane(){let e=A.mainPaneFile(this.root);return n(e)?i(e,`utf8`).trim():void 0}withLock(e,t){return sl(this.root,e,t)}withLockAsync(e,t){return cl(this.root,e,t)}};function gl(e,t){if(e.kind===`standing`||e.kind===`service`)throw Error(`"${t}" is a ${e.kind} record — it has no runtime to stop, restart, or rebind`)}function _l(e,t,n){if(I(e)===t.id)throw Error(`a unit cannot ${n} its own session — run unit ${n} ${t.handle} from another session`)}function vl(e,t){return t.pane?.id??e.store.findPaneByAgentId(t.id)}function yl(e,t){if(e.adapter)return e.adapter;if(t.pane?.mux===`tmux`)return D;if(t.pane?.mux===`herdr`)return T;try{return z(e.env??process.env,e.exec??M)}catch{return}}function bl(e,t,n){let r={...t,status:`stopped`,pane:null};return P(e.store,r),n&&e.store.removePaneIndex(n),r}function xl(e,t){let n=vl(e,t);if(!n)return{agent:bl(e,t,void 0),verified:!1};let r=e.exec??M,i=yl(e,t);if(!i)return{agent:bl(e,t,n),pane:n,verified:!1};try{i.teardown(r,{id:n})}catch{}let a=i.listPanes(r);if(a.some(e=>e.id===n))throw Error(`stop did not take effect — the backend still lists pane ${n} for unit "${t.handle}"; its record is unchanged`);return{agent:bl(e,t,n),pane:n,verified:a.length>0}}function Sl(e,t){let n=L(e.store,t);return gl(n,t),_l(e,n,`stop`),n.status===`stopped`?{agent:n,verified:!0,alreadyStopped:!0}:{...xl(e,n),alreadyStopped:!1}}async function Cl(e,t,r={}){let i=L(e.store,t);if(gl(i,t),_l(e,i,`restart`),i.status===`exited`)throw Error(`unit "${i.handle}" has exited — restart takes only a running or stopped unit; spawn a new unit instead, or run unit rebind ${i.handle} from a session resumed by hand`);let a=i.harness;if(!a||!(a in B))throw Error(`unit "${i.handle}" has harness "${i.harness??``}", not in the launch map (${Object.keys(B).join(` | `)}) — cannot restart it`);if(!n(i.cwd))throw Error(`unit "${i.handle}" cannot restart — its cwd ${i.cwd} is gone; spawn a new unit instead`);let o=i,s;if(i.status!==`stopped`){let t=xl(e,i);o=t.agent,s=t.pane}let c=e.env??process.env,l=e.exec??M,u=o.launch??B[a],d=o.conversation&&!r.fresh?Go(a,u,o.conversation):void 0,f=o.worktree?`workspace`:`tab`,p,m;try{m=e.adapter??z(c,l);let t=f===`workspace`?{label:Co({brief:e.store.readBrief(i.id)??``,handle:i.handle,id:i.id})}:{};p=m.open(l,{cwd:o.cwd,launch:d?Uo(e,m.name,i.id,d,{bindSelf:!0,fallback:u}):Uo(e,m.name,i.id,u,{bindSelf:!0}),at:f,from:Ar(m,j(c)),...t})}catch(e){throw Error(`restart could not open a session — unit "${i.handle}" is stopped, with its inbox, brief, and worktree kept; rerun unit restart ${i.handle}: ${e instanceof Error?e.message:String(e)}`)}let h=m.name,g={...o,status:`active`,pane:Zi(l,h,p.id),lastSeen:new Date(e.now?.()??Date.now()).toISOString()};P(e.store,g),e.store.putPaneIndex(p.id,i.id);let _=g.brief,v=await po(()=>m,l,{target:p,briefPath:_??``,noWake:r.noWake||!_,resumed:!!d},r.nudgeOpts);return{agent:g,...s?{previousPane:s}:{},pane:p.id,launch:u,resumed:!!d,rung:v.rung,...v.warning?{warning:v.warning}:{}}}function wl(e,t){if(t.kind===`standing`||t.kind===`service`)return`none`;if(t.status===`stopped`)return`stopped`;if(t.status===`exited`)return`exited`;if(t.pane?.mux===`herdr`&&t.pane.terminal){let n=$i(e.exec??M,t.pane.terminal);return n===void 0?`unknown`:n===`gone`?`gone`:`live`}let n=vl(e,t),r=n?yl(e,t):void 0;if(!n||!r)return`unknown`;let i=r.listPanes(e.exec??M);return i.length===0?`unknown`:i.some(e=>e.id===n)?`live`:`gone`}function Tl(e,t){let n=L(e.store,t);gl(n,t);let r=Gi(e);if(!r)throw Error(`unit rebind needs to run inside a tmux or herdr pane — there is no pane to bind`);let i=vl(e,n);if(n.pane?.mux===r.mux&&n.pane.id===r.pane&&e.store.resolvePaneId(r.pane)===n.id)return n;let a=e.store.resolvePaneId(r.pane),o=a&&a!==n.id?N(e.store,a):void 0;if(o&&o.status!==`stopped`&&o.status!==`exited`)throw Error(`this pane belongs to unit "${o.handle}" (${o.id}) — rebind never takes another unit's pane`);let s=wl(e,n),c=!!r.terminal&&n.pane?.mux===`herdr`&&n.pane.terminal===r.terminal;if(i&&i!==r.pane&&!c&&(s===`live`||s===`unknown`))throw Error(`unit "${n.handle}" may still be running in pane ${i} — stop it first (unit stop ${n.handle})`);let l={...n,status:`active`,pane:{mux:r.mux,id:r.pane,...r.terminal?{terminal:r.terminal}:{}},lastSeen:new Date(e.now?.()??Date.now()).toISOString()};return P(e.store,l),i&&i!==r.pane&&e.store.removePaneIndex(i),e.store.putPaneIndex(r.pane,n.id),l}function El(e){if(!e)return!1;try{return No(e),!0}catch{return!1}}function Dl(e,t,r){if(r===`none`)return[];let i=[];return r===`live`&&(i.push(`focus`,`nudge`,`read`),El(t.harness)&&i.push(`clear`)),vl(e,t)!==void 0&&(r===`live`||r===`gone`||r===`unknown`)&&i.push(`stop`),r!==`exited`&&t.harness&&t.harness in B&&n(t.cwd)&&i.push(`restart`),(r===`stopped`||r===`exited`||r===`gone`)&&i.push(`rebind`),i.push(`close`),i}function Ol(e,t){let n=L(e.store,t),r=wl(e,n),i=vl(e,n),a=n.pane?.mux??(i?yl(e,n)?.name:void 0);return{id:n.id,handle:n.handle,...n.harness?{harness:n.harness}:{},status:n.status,liveness:r,pane:i&&a?{mux:a,id:i}:null,cwd:n.cwd,worktree:n.worktree??null,sharedWorktree:n.sharedWorktree??null,lastSeen:n.lastSeen,controls:Dl(e,n,r)}}function kl(e,t){let n;try{n=JSON.parse(t)?.session_id}catch{return}if(typeof n!=`string`||n===``)return;let r=I(e),i=r?N(e.store,r):void 0;i&&i.kind!==`standing`&&i.kind!==`service`&&i.conversation!==n&&P(e.store,{...i,conversation:n})}async function Al(e,t){let n=t.timeoutMs??6e5,r=(t.maxWaitS??240)*1e3,i=t.now??(()=>Date.now()),a=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),o=i(),s=o+r;for(;;){let r=H(e,{meId:t.meId,unread:!0,thread:t.thread,from:t.from});if(r.length>0){let n=r[0];return Ds(e,t.meId,n.id),{kind:`matched`,message:n}}let c=i()-o;if(n!==0&&c>=n)return{kind:`timed-out`};if(i()>=s)return{kind:`waiting`};await a(1e3)}}async function jl(e,t,n,r={}){let i=r.sleep??(e=>new Promise(t=>setTimeout(t,e))),a=/* @__PURE__ */ new Set;for(let n of H(e,{meId:t.meId,thread:t.thread,from:t.from}))a.add(n.id);let o=0;for(;;){let s=H(e,{meId:t.meId,thread:t.thread,from:t.from});for(let e of s)a.has(e.id)||(a.add(e.id),n(e));if(o++,r.maxIterations!=null&&o>=r.maxIterations)return;await i(1e3)}}const Ml=globalThis.__SKILL_SCRIPT__?.version??JSON.parse(i(new URL(`../package.json`,import.meta.url),`utf8`)).version;function Y(e){return{store:new hl(zi({space:e.space})),env:process.env,self:Jo()}}function X(e){return e.format===`json`?`json`:`toon`}function Nl(e){let t=I(e);return t||q("no identity in this session — run `cyberlegion unit register` first"),ja(e,t),t}function Z(e){return e.option(`--space <path>`,`isolate the hub root (overrides the global hub / $CYBERLEGION_ROOT)`).addOption(new ye(`--format <format>`,`output format`).choices([`toon`,`json`]).default(`toon`))}function Pl(e){return e.hook(`postAction`,async(e,t)=>{let n=t.opts();(t.name()!==`who`||n.reconcile)&&await ac(Y(n).store)})}const Q=new Te;Q.name(`cyberlegion`).description(`Harness-agnostic agent session spawning and messaging over the filesystem`).version(Ml).enablePositionalOptions();const $=Q.command(`unit`).description(`legion units — register, discover, spawn, and reap`);function Fl(e,t,n){if(!t.handle){let n=F(e.store).filter(e=>e.kind===`standing`);G(X(t),{toon:W(`agents`,n,[{key:`id`,get:e=>e.id},{key:`handle`,get:e=>e.handle},{key:`harness`,get:e=>e.harness??`-`},{key:`status`,get:e=>e.status}],`${n.length} standing`),json:n});return}let r=F(e.store).find(e=>e.handle===t.handle&&e.kind!==`standing`&&e.status!==`exited`),i=la(e,{handle:t.handle,home:n});r&&console.error(`a live session already claims handle "${t.handle}"`),G(X(t),{toon:U({id:i.id,handle:i.handle,kind:i.kind,status:i.status,home:i.home?.dir??`none`,...i.home?{launch:i.home.agent?`agent ${i.home.agent}`:`harness ${i.home.harness}`}:{}}),json:i})}Pl(Z($.command(`register`))).description(`register or refresh this session identity (or --standing: a session-independent owner inbox)`).option(`--handle <name>`,`human handle for this agent`).option(`--harness <h>`,`claude | cursor | codex (else auto-detected)`).option(`--standing`,`mint a standing, session-independent owner inbox (bare, with no --handle: list them)`).option(`--home <dir>`,`with --standing: the existing folder a presence is spawned in when mail arrives and none is live`).option(`--agent <name>`,`with --home: launch that agent definition, resolved from the home`).option(`--clear-home`,`with --standing: drop the owner's home`).action(e=>{let t=Y(e),n;try{n=Xc(t.exec??M,e)}catch(e){q(e instanceof Error?e.message:String(e))}if(e.standing){Fl(t,e,n);return}let r=oa(t,{handle:e.handle,harness:e.harness});G(X(e),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status}),json:r})}),Z($.command(`claim`)).description(`bind the caller's unit as a standing owner's presence; --show reads it, --clear unbinds`).argument(`<handle>`,`standing owner handle`).option(`--clear`,`unbind the presence (a no-op when nothing is bound)`).option(`--show`,`print the bound presence instead of claiming`).action((e,t)=>{let n=Y(t);if(t.show){let r;try{r=Da(n.store,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({presence:r?.id??`none`}),json:{presence:r?.id??null}});return}if(t.clear){try{Ta(n,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({presence:`none`}),json:{presence:null}});return}let r;try{r=wa(n,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({owner:r.handle,presence:r.presence}),json:{owner:r.handle,presence:r.presence}})}),Z($.command(`whoami`)).description(`print this session own identity`).action(e=>{let t=Y(e),n=I(t);n||q("no identity in this session — run `cyberlegion unit register` first");let r=N(t.store,n);r||q(`registered self id "${n}" has no agent record`),G(X(e),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status}),json:r})});function Il(e){let t=Y(e);R(t),e.reconcile&&Ra(t,{adopt:!0});let n=F(t.store).filter(t=>e.all||t.status!==`exited`);G(X(e),{toon:W(`units`,n,[{key:`id`,get:e=>e.id},{key:`handle`,get:e=>e.handle},{key:`harness`,get:e=>e.harness??`-`},{key:`status`,get:e=>e.status},{key:`pane`,get:e=>e.pane?.id??`-`},{key:`shared`,get:e=>e.sharedWorktree?.root??`-`}],`${n.length} units`),json:n}),n.length===0&&K(`cyberlegion unit register to join`)}Pl(Z($.command(`who`))).description(`list the addressable units`).option(`--all`,`include exited units`).option(`--reconcile`,`live-probe the current mux: cull dead-pane records and adopt unbound harness-bearing panes before listing`).action(Il),Pl(Z($.command(`prune`))).description(`mark dead units exited and delete exited units with no worktree on disk`).action(e=>{let t=Y(e);R(t);let n=Va(t);G(X(e),{toon:W(`pruned`,n,[{key:`id`,get:e=>e.id},{key:`handle`,get:e=>e.handle},{key:`pruned`,get:e=>e.pruned}],`${n.length} pruned (${n.filter(e=>e.pruned===`deleted`).length} deleted)`),json:n})});const Ll=`(harness default)`;function Rl(e){return e.effortNotApplied?`${e.effortNotApplied} (not applied)`:e.effort??Ll}function zl(e){let{effortNotApplied:t,model:n}=e.launched;t&&console.error(n?`${e.input.harness} carries effort only in a model id that cursor-agent models lists, and it lists no "${n}-${t}"; effort "${t}" not applied — launching ${n} at its default effort (run cursor-agent models to pick an id)`:`${e.input.harness} carries effort only as a parameter on a named model and none was set; effort "${t}" not applied — launching at the harness default model and effort (pass --model to apply it)`)}function Bl(e){return Z(e).option(`--harness <h>`,`claude | cursor | codex (required unless --agent/--agent-file resolves one)`).option(`--agent <name>`,`resolve an agent def (.agents/agents/<name>.md) for harness/model/effort/instructions`).option(`--agent-file <path>`,`read an exact agent def file instead of resolving by name`).option(`--model <name>`,`model for this launch only (flag > agent def > harness default)`).option(`--effort <level>`,`effort for this launch only (flag > agent def > harness default)`).option(`--task <text>`,`brief text, or - for stdin`).option(`--brief-file <path>`,`read the brief from a file`).option(`--handle <name>`,`handle for the new peer`).option(`--branch <name>`,`branch for the new worktree (default cyberlegion/unit-<id>)`).option(`--worktree-path <path>`,`where to check out the new worktree`).option(`-C, --repo <path>`,`create the worktree from the git repository containing <path>, not the current directory's`).option(`--base <ref>`,`start the new worktree's branch from <ref> (default: fetch origin and use its default branch, else local HEAD)`).option(`--cwd <path>`,`spawn the session in an existing directory; create no worktree (mutually exclusive with --branch/--worktree-path/--repo/--base)`).addOption(new ye(`--at <placement>`,`where to open the new session (default: new-worktree → workspace, --cwd → tab)`).choices([`pane:right`,`pane:down`,`tab`,`workspace`])).option(`--no-wake`,`suppress the first-turn doorbell (spawn idle; the caller drives the first turn itself)`)}function Vl(e){if(e.trustBlocked){if(console.error(e.trustBlocked),e.agent.brief){let t=ro(e.agent.brief).replaceAll(`'`,`'\\''`);console.error(`then: cyberlegion unit nudge ${e.agent.handle} --message '${t}'`)}process.exitCode=1}}function Hl(e){e.base?.fallback&&console.error(`base: fell back to local HEAD — ${e.base.fallback}`)}function Ul(e){return Pl(Bl(e)).description(`launch a new peer session in its own git worktree (tmux or herdr)`).action(async e=>{let t=Y(e);R(t);let n;try{n=ys(e,Ss)}catch(e){q(e instanceof Error?e.message:String(e))}zl(n);let r=await Ro(t,n.input,{noWake:n.noWake});r.warning&&console.error(`first-turn doorbell not confirmed (peer still spawned; nudge it manually): ${r.warning}`),Vl(r),Hl(r),G(X(e),{toon:U({spawned:r.agent.id,handle:r.agent.handle,harness:r.agent.harness,model:n.launched.model??Ll,effort:Rl(n.launched),worktree:r.agent.worktree?.root,reused:r.reused??`-`,base:r.base?.ref,pane:r.pane,rung:r.rung,trust:r.trust}),json:{agent:r.agent,pane:r.pane,launch:r.launch,base:r.base,...r.reused===void 0?{}:{reused:r.reused},model:n.launched.model??Ll,effort:Rl(n.launched),rung:r.rung,trust:r.trust}}),K(`cyberlegion unit read ${r.agent.id}`)})}Ul($.command(`spawn`)),Pl(Z($.command(`close`))).description(`release the unit's worktree lease (or remove a worktree it holds no lease on), tear down its session, and reap its state (the inverse of spawn)`).argument(`<id>`,`unit id, handle, or worktree branch/CR ref`).option(`--force`,`discard uncommitted changes in a worktree close removes (refused for a unit on the primary checkout)`).option(`--keep-worktree`,`leave the worktree on disk for reuse and reap everything else (skips the dirty check)`).action(async(e,t)=>{let n=Y(t);R(n);let r=L(n.store,e),i=await js(n,{id:r.id,force:t.force,keepWorktree:t.keepWorktree});G(X(t),{toon:U({closed:r.id,worktree:i.worktreeRoot??`-`,retained:i.retainedWorktree??`-`,lease:i.lease?i.lease.released?`released`:i.lease.reason:`-`,pane:i.pane??`-`}),json:i})}),Z($.command(`stop`)).description(`end a unit's session and keep the unit — its id, handle, inbox, brief, and worktree stay (unit close destroys them)`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action((e,t)=>{let n=Y(t);R(n);let r=Sl(n,e);G(X(t),{toon:U({stopped:r.agent.id,pane:r.pane??`-`,verified:r.verified,already:r.alreadyStopped}),json:{stopped:r.agent.id,pane:r.pane??null,verified:r.verified,alreadyStopped:r.alreadyStopped}}),r.alreadyStopped||K(`cyberlegion unit restart ${r.agent.handle}`)}),Z($.command(`restart`)).description(`give a unit a new session and keep the unit — stops a running session, relaunches it resuming the harness's recorded conversation where it can, and otherwise rebriefs it`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).option(`--no-wake`,`do not ring the new session to read its brief (the caller briefs it by mail)`).option(`--fresh`,`start an empty session and rebrief it, even when the unit's conversation could be resumed`).action(async(e,t)=>{let n=Y(t);R(n);let r=await Cl(n,e,{noWake:t.wake===!1,fresh:t.fresh===!0});G(X(t),{toon:U({restarted:r.agent.id,previous:r.previousPane??`-`,pane:r.pane,resumed:r.resumed,rung:r.rung}),json:r}),r.warning&&K(`warning: ${r.warning}`)}),Z($.command(`rebind`)).description(`bind a stopped unit to the calling pane — for a session started by hand that should be this unit`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action((e,t)=>{let n=Tl(Y(t),e);G(X(t),{toon:U({rebound:n.id,pane:n.pane?.id??`-`}),json:{rebound:n.id,pane:n.pane}})}),Z($.command(`show`)).description(`show a unit's runtime: where it is, whether it is live now, and the controls that work on it (read-only)`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action((e,t)=>{let n=Y(t);R(n);let r=Ol(n,e);G(X(t),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status,liveness:r.liveness,pane:r.pane?`${r.pane.mux}:${r.pane.id}`:`-`,cwd:r.cwd,worktree:r.worktree?.root??`-`,shared:r.sharedWorktree?.root??`-`,lastSeen:r.lastSeen,controls:r.controls.join(`,`)||`-`}),json:r})}),Z($.command(`focus`)).description(`move input focus to a peer's session, named by a ref or picked by its worktree's repo/branch`).argument(`[ref]`,`unit id, handle, or worktree branch/CR ref`).option(`--repo <name>`,`pick the one live unit in this repository (its primary checkout's folder name, else its cwd's)`).option(`--branch <name>`,`pick the one live unit whose worktree is on this branch`).action((e,t)=>{let n={repo:t.repo,branch:t.branch};e!==void 0&&(n.repo!==void 0||n.branch!==void 0)&&q(`a ref and --repo/--branch cannot be combined — pass one or the other`);let r=Y(t);R(r);let{agent:i,pane:a}=Zo(r,e??n),o=e??i.id;G(X(t),{toon:U({focused:o,pane:a}),json:{ref:o,pane:a}})}),Z($.command(`nudge`)).description(`deliver text as a turn in a peer's session — by default a doorbell telling them to check their mail; --message relays any text (e.g. a decision) instead`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).option(`--message <text>`,`text delivered as a turn in the peer session`,no).action(async(e,t)=>{let n=Y(t);R(n);let{pane:r,message:i,resubmits:a}=await Qo(n,e,{message:t.message});G(X(t),{toon:U({nudged:e,pane:r}),json:{ref:e,pane:r,message:i,resubmits:a}})}),Z($.command(`read`)).description(`scrape a peer's session screen`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).option(`--lines <n>`,`trailing lines to capture`,e=>Number.parseInt(e,10)).action((e,t)=>{let n=Y(t);R(n);let{pane:r,output:i}=$o(n,e,{lines:t.lines});console.log(bs(X(t),{ref:e,pane:r,output:i}))}),Z($.command(`clear`)).description(`reset a warm peer's context to cold by injecting its own harness fresh-context command — keeps the pane/session warm; tears down nothing`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action(async(e,t)=>{let n=Y(t);R(n);let r;try{r=await es(n,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({cleared:e,pane:r.pane,command:r.command}),json:{cleared:e,pane:r.pane,command:r.command}})});const Wl=Q.command(`project`).description(`register and resolve projects (one per git repository)`);function Gl(e){return{id:e.id,name:e.name,root:e.root}}async function Kl(e,t,n){let r=await nc(e.store,n,e.exec??M),i=r?{...n,subject:r.subject}:n;G(X(t),{toon:U({...Gl(i),...r?{channel:r.channel?.handle??`none`}:{}}),json:r?{...i,...r.channel?{channel:r.channel}:{}}:i})}Z(Wl.command(`register`)).description(`register (or refresh) the project containing a directory — any checkout of it`).option(`--dir <path>`,`a directory inside the project (default: the current directory)`).action(async e=>{let t=Y(e),n;try{n=yc({store:t.store},{dir:e.dir})}catch(e){q(e instanceof Error?e.message:String(e))}await Kl(t,e,n)}),Z(Wl.command(`list`)).description(`list the registered projects`).action(e=>{let t=bc(Y(e).store);G(X(e),{toon:W(`projects`,t,[{key:`id`,get:e=>e.id},{key:`name`,get:e=>e.name},{key:`root`,get:e=>e.root}],`${t.length} projects`),json:t}),t.length===0&&K(`cyberlegion project register to add the current repository`)}),Z(Wl.command(`show`)).description(`resolve a registered project by id, path, or unique name`).argument(`<ref>`,`project id, a path inside any of its checkouts, or its name`).action(async(e,t)=>{let n=Y(t),r;try{r=Cc({store:n.store},e)}catch(e){q(e instanceof Error?e.message:String(e))}await Kl(n,t,r)});const ql=Q.command(`service`).description(`project services — one authoritative owner each, fenced by generation`);function Jl(e){return{project:e.project.id,service:e.lease.service,endpoint:e.endpoint.id,generation:e.lease.generation,state:e.lease.state,holder:e.lease.holder??null,health:e.health,control:e.control,...e.note?{note:e.note}:{}}}function Yl(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t??`-`]))}function Xl(e,t){G(X(e),{toon:U(Yl(t)),json:t})}function Zl(e){try{return e()}catch(e){q(e instanceof Error?e.message:String(e))}}const Ql=e=>Number.parseInt(e,10);function $l(e,t){return t===void 0?[`.`,e]:[e,t]}function eu(e,t){return t?Zl(()=>L(e.store,t)).id:Nl(e)}Z(ql.command(`resolve`)).description(`show a service's owner, generation, health, and whether its session is controllable`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).action((e,t,n)=>{let[r,i]=$l(e,t),a=Y(n);Xl(n,Jl(Zl(()=>Hc(a,r,i))))}),Z(ql.command(`acquire`)).description(`resolve the healthy owner, or reserve the right to start one (exactly one caller wins)`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).option(`--ttl <ms>`,`how long the reservation holds before another caller may take over`,Ql).option(`--force-generation <n>`,`reserve even over a healthy owner — must name the current generation`,Ql).action((e,t,n)=>{let[r,i]=$l(e,t),a=Y(n),o=Zl(()=>Uc(a,r,i,{by:I(a),ttlMs:n.ttl,...n.forceGeneration===void 0?{}:{force:{generation:n.forceGeneration}}}));Xl(n,{outcome:o.outcome,...Jl(o.view),...o.outcome===`reserved`?{token:o.token,expiresAt:o.lease.reservation?.expiresAt}:{}}),o.outcome===`reserved`?K(`start the runtime, then: cyberlegion service bind ${r} ${i} --generation ${o.lease.generation} --token ${o.token}`):o.outcome===`starting`&&K(`another caller is starting it — re-run to resolve: cyberlegion service resolve ${r} ${i}`)}),Z(ql.command(`bind`)).description(`complete a reservation: make a live unit (default: this session) the owner`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the reserved generation`,Ql).requiredOption(`--token <token>`,`the reservation token from acquire`).option(`--unit <ref>`,`the unit to bind (default: this session)`).action((e,t,n)=>{let[r,i]=$l(e,t),a=Y(n),o=eu(a,n.unit);Xl(n,Jl(Zl(()=>Gc(a,r,i,{generation:n.generation,token:n.token,unit:o}))))}),Z(ql.command(`release`)).description(`abandon a reservation (--token) or step down as owner (default: this session)`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the current generation`,Ql).option(`--token <token>`,`release a reservation instead of an active ownership`).option(`--unit <ref>`,`the owning unit (default: this session)`).action((e,t,n)=>{let[r,i]=$l(e,t),a=Y(n),o=n.token?{generation:n.generation,token:n.token}:{generation:n.generation,unit:eu(a,n.unit)};Xl(n,Jl(Zl(()=>Kc(a,r,i,o))))}),Z(ql.command(`handoff`)).description(`transfer ownership to another live unit under a new generation`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the current generation`,Ql).requiredOption(`--to <ref>`,`the unit taking over`).option(`--from <ref>`,`the current owner (default: this session)`).action((e,t,n)=>{let[r,i]=$l(e,t),a=Y(n),o=eu(a,n.from),s=Zl(()=>L(a.store,n.to)).id;Xl(n,Jl(Zl(()=>qc(a,r,i,{generation:n.generation,from:o,to:s}))))}),Z(ql.command(`verify`)).description(`the fencing check: exit 0 only when the unit (default: this session) owns the service at this generation`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the generation the caller believes it owns`,Ql).option(`--unit <ref>`,`the unit to check (default: this session)`).action((e,t,n)=>{let[r,i]=$l(e,t),a=Y(n),o=eu(a,n.unit);Xl(n,Jl(Zl(()=>Jc(a,r,i,{unit:o,generation:n.generation}))))}),Pl(Bl(ql.command(`start`))).description(`resolve the healthy owner, or spawn one peer and bind it — concurrent starts launch once`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).option(`--ttl <ms>`,`how long the reservation holds while the peer launches`,Ql).action(async(e,t,n)=>{let[r,i]=$l(e,t),a=Y(n);R(a);let o;try{o=ys(n,Ss)}catch(e){q(e instanceof Error?e.message:String(e))}zl(o);let s,c;try{c=await Yc(a,r,i,{by:I(a),ttlMs:n.ttl,launch:async()=>{let e=await Ro(a,o.input,{noWake:o.noWake});return s=e.warning,Vl(e),Hl(e),{unit:e.agent.id,pane:e.pane}}})}catch(e){q(e instanceof Error?e.message:String(e))}s&&console.error(`first-turn doorbell not confirmed (peer still spawned; nudge it manually): ${s}`),Xl(n,{outcome:c.outcome,...Jl(c.view)}),c.outcome===`starting`&&K(`another caller is starting it — re-run to resolve: cyberlegion service resolve ${r} ${i}`)});const tu=Q.command(`mail`).description(`durable inter-agent messaging`);function nu(e){return Z(e).description(`send a message to a peer (by handle or id)`).requiredOption(`--to <peer>`,`recipient handle or id`).option(`--from <id>`,`sender id (else this session own identity)`).option(`--subject <s>`,`subject`).option(`--body <text>`,`message body`).option(`--body-file <path>`,`read body from a file, or - for stdin`).option(`--thread <id>`,`thread id`).option(`--reply-to <msg>`,`message id this replies to`).option(`--no-nudge`,`suppress the delivery doorbell (do not wake the recipient's pane)`).action(async e=>{let t=Y(e),n=e.from??Nl(t),r=ws(e.body,e.bodyFile),i=Cs({store:t.store},{fromId:n,to:e.to,subject:e.subject,body:r,thread:e.thread,replyTo:e.replyTo}),a=await fo(t.store,()=>z(t.env??process.env),M,{toId:i.to,fromId:n,noNudge:e.nudge===!1,spawnHome:e=>mc(t,e)});a.warning&&console.error(`delivery doorbell not confirmed (message still delivered): ${a.warning}`),G(X(e),{toon:U({sent:i.id,to:e.to,subject:i.subject,rung:a.rung,...a.spawned?{spawned:a.spawned}:{}}),json:{...i,rung:a.rung,...a.spawned?{spawned:a.spawned}:{}}})})}nu(tu.command(`send`));function ru(e,t,n,r){let i=H({store:e.store},{meId:n,unread:t.unread,from:t.from,thread:t.thread}),a=i.filter(e=>!e.read).length;G(X(t),{toon:W(`messages`,i,[{key:`id`,get:e=>e.id},{key:`from`,get:e=>e.fromHandle},{key:`subject`,get:e=>e.subject??``},{key:`read`,get:e=>e.read}],`${i.length} messages (${a} unread)`),json:i});let o=i.find(e=>!e.read);o&&K(`${r} ${o.id}`)}function iu(e,t,n){let r;try{r=Ca(e.store,n)}catch(e){q(e instanceof Error?e.message:String(e))}let i=Ts({store:e.store},{meId:r.id,unread:t.unread,from:t.from,thread:t.thread}),a=i.messages.filter(e=>!e.read).length,o=i.mailbox===`none`?`no mailbox`:i.mailbox===`unreadable`?`mailbox unreadable: ${i.error}`:`${i.messages.length} messages (${a} unread)`;G(X(t),{toon:[U({unit:r.id,handle:r.handle,mailbox:i.mailbox}),W(`messages`,i.messages,[{key:`id`,get:e=>e.id},{key:`from`,get:e=>e.fromHandle},{key:`subject`,get:e=>e.subject??``},{key:`read`,get:e=>e.read}],o)].join(`
|
|
74
|
-
`),json:{unit:r.id,handle:r.handle,...i}}),i.mailbox===`unreadable`&&(console.error(JSON.stringify({error:`mailbox of ${r.id} is unreadable: ${i.error}`})),process.exitCode=1)}function
|
|
73
|
+
`)}}}var Ac=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`ServiceOwnershipError`}};const jc=/^[a-z0-9][a-z0-9_-]{0,62}$/;function Mc(e){if(!jc.test(e))throw Error(`invalid service name "${e}" — use lowercase letters, digits, "-" or "_" (max 63)`)}function Nc(e,t){return`svc-${e}-${t}`}const Pc=e=>e.now?.()??Date.now(),Fc=e=>new Date(e).toISOString();function Ic(e,t){return`service-${e}-${t}`}function Lc(e,t){return t.status===`exited`?!1:e.isLive?e.isLive(t):Pa(e,t)}function Rc(e,t,n){let r=Nc(t.id,n),i=N(e.store,r);if(i)return i;e.store.ensureMarker();let a=Fc(Pc(e)),o={id:r,handle:`${n}@${t.name}`,kind:`service`,service:{project:t.id,name:n},cwd:t.root,pane:null,status:`active`,createdAt:a,lastSeen:a};return P(e.store,o),o}function zc(e,t,n,r){let i={project:t,endpoint:n,lease:r};if(r.state===`vacant`)return{...i,health:`vacant`,control:`none`};if(r.state===`reserved`){let t=Pc(e)>Date.parse(r.reservation?.expiresAt??``);return{...i,health:t?`expired`:`starting`,control:`none`,...t?{note:`the reservation expired without a bound owner; the next acquire takes over`}:{}}}let a=r.holder?N(e.store,r.holder):void 0;if(!a)return{...i,health:`unhealthy`,control:`none`,note:`the owner has no unit record`};let o=a.pane||e.store.findPaneByAgentId(a.id)?`pane`:`none`,s=o===`none`?`the owner resolves, but its session control is not recoverable from here (no multiplexer pane — e.g. a native subagent only its parent can drive)`:void 0;return Lc(e,a)?{...i,owner:a,health:`healthy`,control:o,...s?{note:s}:{}}:{...i,owner:a,health:`unhealthy`,control:o,note:`the owner session is gone`}}function Bc(e,t,n){return{project:t,service:n,endpoint:Nc(t,n),generation:0,state:`vacant`,updatedAt:Fc(Pc(e))}}function Vc(e,t,n,r){Mc(n);let i=Ec(e,t),a=e.store.getServiceLease(i.id,n),o=N(e.store,Nc(i.id,n));if(a&&o)return{project:i,endpoint:o,lease:a};if(!r)throw Error(`no service "${n}" in project ${i.name} (${i.id})`);return{project:i,endpoint:Rc(e,i,n),lease:a??Bc(e,i.id,n)}}function Hc(e,t,n,r,i){Mc(n);let a=Ec(e,t);return e.store.withLock(Ic(a.id,n),()=>i(Vc(e,a.id,n,r)))}function Uc(e,t){let n={...t,updatedAt:Fc(Pc(e))};return e.store.putServiceLease(n),n}function Wc(e){return new Ac(`stale`,e)}function Gc(e,t,n){let{project:r,endpoint:i,lease:a}=Vc(e,t,n,!1);return zc(e,r,i,a)}function Kc(e,t,n,r={}){return Hc(e,t,n,!0,({project:t,endpoint:i,lease:a})=>{let o=zc(e,t,i,a);if(r.force){if(r.force.generation!==a.generation)throw Wc(`cannot force: generation ${r.force.generation} is not the current ${a.generation}`)}else if(o.health===`healthy`)return{outcome:`resolved`,lease:a,view:o};else if(o.health===`starting`)return{outcome:`starting`,lease:a,view:o};let s=Pc(e),c=ae(8).toString(`hex`),l=Uc(e,{project:t.id,service:n,endpoint:i.id,generation:a.generation+1,state:`reserved`,reservation:{token:c,...r.by?{by:r.by}:{},at:Fc(s),expiresAt:Fc(s+(r.ttlMs??3e5)),...r.force?{forced:!0}:{}},updatedAt:Fc(s)});return{outcome:`reserved`,lease:l,view:zc(e,t,i,l),token:c}})}function qc(e,t){let n=N(e.store,t);if(!n)throw new Ac(`unknown-unit`,`no unit "${t}"`);if(!Lc(e,n))throw new Ac(`unit-not-live`,`unit "${t}" has no live session`);return n}function Jc(e,t,n,r){return Hc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(i.state!==`reserved`||i.generation!==r.generation||i.reservation?.token!==r.token)throw Wc(`reservation for generation ${r.generation} is no longer current (now ${i.state} at ${i.generation})`);return qc(e,r.unit),zc(e,t,n,Uc(e,{project:i.project,service:i.service,endpoint:i.endpoint,generation:i.generation,state:`active`,holder:r.unit,updatedAt:i.updatedAt}))})}function Yc(e,t,n,r){return Hc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(!(i.generation===r.generation&&(i.state===`reserved`&&r.token!==void 0&&i.reservation?.token===r.token||i.state===`active`&&r.unit!==void 0&&i.holder===r.unit)))throw Wc(`nothing to release at generation ${r.generation} (now ${i.state} at ${i.generation})`);return zc(e,t,n,Uc(e,{project:i.project,service:i.service,endpoint:i.endpoint,generation:i.generation,state:`vacant`,updatedAt:i.updatedAt}))})}function Xc(e,t,n,r){return Hc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(i.state!==`active`||i.generation!==r.generation||i.holder!==r.from)throw Wc(`"${r.from}" is not the owner at generation ${r.generation}`);return qc(e,r.to),zc(e,t,n,Uc(e,{...i,generation:i.generation+1,holder:r.to}))})}function Zc(e,t,n,r){let{project:i,endpoint:a,lease:o}=Vc(e,t,n,!1);if(o.state!==`active`||o.holder!==r.unit||o.generation!==r.generation)throw Wc(`"${r.unit}" at generation ${r.generation} is not the owner (now ${o.state}${o.holder?` by ${o.holder}`:``} at ${o.generation})`);return zc(e,i,a,o)}async function Qc(e,t,n,r){let i=Kc(e,t,n,r);if(i.outcome!==`reserved`)return{outcome:i.outcome,view:i.view};let{generation:a,endpoint:o}=i.lease,s;try{s=await r.launch({generation:a,endpoint:o})}catch(r){try{Yc(e,t,n,{generation:a,token:i.token})}catch{}throw r}try{return{outcome:`started`,view:Jc(e,t,n,{generation:a,token:i.token,unit:s.unit}),launched:s}}catch(e){throw e instanceof Ac?new Ac(e.code,`launched unit "${s.unit}" could not become the owner — ${e.message}; stop it`):e}}function $c(e,t){if((t.home!==void 0||t.clearHome===!0||t.agent!==void 0)&&!(t.standing&&t.handle))throw Error(`a home belongs only to a named standing owner — pass --standing --handle <name>`);if(!t.standing)return;if(t.home!==void 0&&t.clearHome)throw Error(`--home and --clear-home contradict — pass one`);if(t.home===void 0&&(t.agent!==void 0||t.harness!==void 0))throw Error(`a launch needs --home: --agent and --harness name how to start a session in it`);if(t.clearHome)return null;if(t.home===void 0)return;let r=g(t.home);if(!n(r)||!l(r).isDirectory())throw Error(`the home must already exist: ${t.home}`);if(t.agent===void 0==(t.harness===void 0))throw Error(`a home needs exactly one of --agent or --harness`);let i;if(t.harness!==void 0){if(!(t.harness in B))throw Error(`unrecognized --harness "${t.harness}" (${Object.keys(B).join(` | `)})`);i={harness:t.harness}}else{let e=t.agent;try{fs({name:e,cwd:r})}catch{throw Error(`the agent definition "${e}" does not resolve from the home ${r}`)}i={agent:e}}let a=Lo(e,r);if(a!==void 0&&o(a)===o(r))throw Error(`the home refuses the primary checkout ${r} — a spawned unit never works there`);return{dir:r,...i}}var el=class extends Error{file;constructor(e,t){super(`corrupt record at "${e}": ${t instanceof Error?t.message:String(t)}`,{cause:t}),this.file=e,this.name=`CorruptRecordError`}};function tl(e){if(e===process.pid)return`alive`;try{return process.kill(e,0),`alive`}catch(e){return e.code===`ESRCH`?`dead`:`unknown`}}var nl=class extends Error{name;constructor(e){super(`timed out waiting for lock "${e}"`),this.name=e,this.name=`LockTimeoutError`}};function rl(e){return h(e,`locks`)}function il(e,t){return h(rl(e),`${t}.lock`)}function al(e){try{return JSON.parse(i(h(e,`holder.json`),`utf8`))}catch{return}}function ol(e){return tl(e)!==`dead`}function sl(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function cl(e){let t=`${e}.stale-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;try{s(e,t)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n=al(t);if(n&&ol(n.pid)){try{s(t,e)}catch{c(t,{recursive:!0,force:!0})}return!1}return c(t,{recursive:!0,force:!0}),!0}function ll(e,t,n={}){let i=n.retryDelayMs??20,a=n.timeoutMs??5e3,o=il(e,t);r(rl(e),{recursive:!0});let s=Date.now()+a;for(;;)try{return r(o),u(h(o,`holder.json`),JSON.stringify({pid:process.pid,acquiredAt:Date.now()})),{release:()=>c(o,{recursive:!0,force:!0})}}catch(e){if(e.code!==`EEXIST`)throw e;let n=al(o);if(n&&!ol(n.pid)&&cl(o))continue;if(Date.now()>s)throw new nl(t);sl(i)}}function ul(e,t,n,r){let i=ll(e,t,r);try{return n()}finally{i.release()}}async function dl(e,t,n,r){let i=ll(e,t,r);try{return await n()}finally{i.release()}}function fl(e){let t=i(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new el(e,t)}}function pl(e){return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>fl(h(e,t))):[]}let ml=0;function hl(e,t){r(p(e),{recursive:!0});let n=`${e}.${process.pid}.${ml++}.tmp`;u(n,t),s(n,e)}function gl(e,t){hl(e,`${JSON.stringify(t,null,2)}\n`)}function _l(e,t){hl(e,t)}function J(e){try{return e()}catch(e){if(e instanceof Vi)return;throw e}}var vl=class{root;constructor(e){this.root=e}ensureMarker(){Bi(this.root)}putMessage(e,t){hl(A.messageFile(this.root,e,t.id),`${JSON.stringify(t,null,2)}\n`)}listInbox(e){let t=J(()=>A.inboxDir(this.root,e)),n=J(()=>A.inboxReadDir(this.root,e));return{unread:t?pl(t):[],read:n?pl(n):[]}}hasMailbox(e){let t=J(()=>A.inboxDir(this.root,e));return t!==void 0&&n(t)}ackMessage(e,t){let i=J(()=>A.messageFile(this.root,e,t));if(!i||!n(i))throw Error(`"${t}" is not an unread message in this inbox`);let a=fl(i),o=A.messageReadFile(this.root,e,t);return r(p(o),{recursive:!0}),s(i,o),a}removeMessage(e,t){let r=J(()=>A.messageFile(this.root,e,t));if(r&&n(r)){c(r);return}let i=J(()=>A.messageReadFile(this.root,e,t));if(i&&n(i))c(i);else throw Error(`"${t}" is not a message in this inbox`)}removeMailbox(e){c(A.inboxDir(this.root,e),{recursive:!0,force:!0})}putAgent(e){gl(A.agentFile(this.root,e.id),e)}getAgent(e){let t=J(()=>A.agentFile(this.root,e));if(t&&n(t))return fl(t)}listAgents(){let e=A.agentsDir(this.root);return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>fl(h(e,t))).sort((e,t)=>e.createdAt.localeCompare(t.createdAt)):[]}removeAgent(e){c(A.agentFile(this.root,e),{force:!0})}removeAgentData(e){c(A.dataDir(this.root,e),{recursive:!0,force:!0})}putProject(e){gl(A.projectFile(this.root,e.id),e)}getProject(e){let t=J(()=>A.projectFile(this.root,e));if(t&&n(t))return fl(t)}listProjects(){let e=A.projectsDir(this.root);return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>fl(h(e,t))).sort((e,t)=>e.registeredAt.localeCompare(t.registeredAt)):[]}putServiceLease(e){gl(A.serviceLeaseFile(this.root,e.project,e.service),e)}getServiceLease(e,t){let r=J(()=>A.serviceLeaseFile(this.root,e,t));if(r&&n(r))return fl(r)}putPaneIndex(e,t){_l(A.paneFile(this.root,e),t)}resolvePaneId(e){let t=A.paneFile(this.root,e);return n(t)?i(t,`utf8`).trim():void 0}findPaneByAgentId(e){let t=A.panesDir(this.root);if(n(t)){for(let n of a(t))if(n.endsWith(`.id`)&&i(h(t,n),`utf8`).trim()===e)return n.slice(0,-3)}}removePaneIndex(e){c(A.paneFile(this.root,e),{force:!0})}writeBrief(e,t){_l(A.briefFile(this.root,e),t)}readBrief(e){let t=J(()=>A.briefFile(this.root,e));return t&&n(t)?i(t,`utf8`):void 0}setMainPane(e){ul(this.root,`main-pane`,()=>{let t=A.mainPaneFile(this.root);e?_l(t,e):c(t,{force:!0})})}getMainPane(){let e=A.mainPaneFile(this.root);return n(e)?i(e,`utf8`).trim():void 0}withLock(e,t){return ul(this.root,e,t)}withLockAsync(e,t){return dl(this.root,e,t)}};function yl(e,t){if(e.kind===`standing`||e.kind===`service`)throw Error(`"${t}" is a ${e.kind} record — it has no runtime to stop, restart, or rebind`)}function bl(e,t,n){if(I(e)===t.id)throw Error(`a unit cannot ${n} its own session — run unit ${n} ${t.handle} from another session`)}function xl(e,t){return t.pane?.id??e.store.findPaneByAgentId(t.id)}function Sl(e,t){if(e.adapter)return e.adapter;if(t.pane?.mux===`tmux`)return D;if(t.pane?.mux===`herdr`)return T;try{return z(e.env??process.env,e.exec??M)}catch{return}}function Cl(e,t,n){let r={...t,status:`stopped`,pane:null};return P(e.store,r),n&&e.store.removePaneIndex(n),r}function wl(e,t){let n=xl(e,t);if(!n)return{agent:Cl(e,t,void 0),verified:!1};let r=e.exec??M,i=Sl(e,t);if(!i)return{agent:Cl(e,t,n),pane:n,verified:!1};try{i.teardown(r,{id:n})}catch{}let a=i.listPanes(r);if(a.some(e=>e.id===n))throw Error(`stop did not take effect — the backend still lists pane ${n} for unit "${t.handle}"; its record is unchanged`);return{agent:Cl(e,t,n),pane:n,verified:a.length>0}}function Tl(e,t){let n=L(e.store,t);return yl(n,t),bl(e,n,`stop`),n.status===`stopped`?{agent:n,verified:!0,alreadyStopped:!0}:{...wl(e,n),alreadyStopped:!1}}async function El(e,t,r={}){let i=L(e.store,t);if(yl(i,t),bl(e,i,`restart`),i.status===`exited`)throw Error(`unit "${i.handle}" has exited — restart takes only a running or stopped unit; spawn a new unit instead, or run unit rebind ${i.handle} from a session resumed by hand`);let a=i.harness;if(!a||!(a in B))throw Error(`unit "${i.handle}" has harness "${i.harness??``}", not in the launch map (${Object.keys(B).join(` | `)}) — cannot restart it`);if(!n(i.cwd))throw Error(`unit "${i.handle}" cannot restart — its cwd ${i.cwd} is gone; spawn a new unit instead`);let o=i,s;if(i.status!==`stopped`){let t=wl(e,i);o=t.agent,s=t.pane}let c=e.env??process.env,l=e.exec??M,u=o.launch??B[a],d=o.conversation&&!r.fresh?qo(a,u,o.conversation):void 0,f=o.worktree?`workspace`:`tab`,p,m;try{m=e.adapter??z(c,l);let t=f===`workspace`?{label:To({brief:e.store.readBrief(i.id)??``,handle:i.handle,id:i.id})}:{};p=m.open(l,{cwd:o.cwd,launch:d?Go(e,m.name,i.id,d,{bindSelf:!0,fallback:u}):Go(e,m.name,i.id,u,{bindSelf:!0}),at:f,from:Ar(m,j(c)),...t})}catch(e){throw Error(`restart could not open a session — unit "${i.handle}" is stopped, with its inbox, brief, and worktree kept; rerun unit restart ${i.handle}: ${e instanceof Error?e.message:String(e)}`)}let h=m.name,g={...o,status:`active`,pane:Zi(l,h,p.id),lastSeen:new Date(e.now?.()??Date.now()).toISOString()};P(e.store,g),e.store.putPaneIndex(p.id,i.id);let _=g.brief,v=await ho(()=>m,l,{target:p,briefPath:_??``,noWake:r.noWake||!_,resumed:!!d},r.nudgeOpts);return{agent:g,...s?{previousPane:s}:{},pane:p.id,launch:u,resumed:!!d,rung:v.rung,...v.warning?{warning:v.warning}:{}}}function Dl(e,t){if(t.kind===`standing`||t.kind===`service`)return`none`;if(t.status===`stopped`)return`stopped`;if(t.status===`exited`)return`exited`;if(t.pane?.mux===`herdr`&&t.pane.terminal){let n=$i(e.exec??M,t.pane.terminal);return n===void 0?`unknown`:n===`gone`?`gone`:`live`}let n=xl(e,t),r=n?Sl(e,t):void 0;if(!n||!r)return`unknown`;let i=r.listPanes(e.exec??M);return i.length===0?`unknown`:i.some(e=>e.id===n)?`live`:`gone`}function Ol(e,t){let n=L(e.store,t);yl(n,t);let r=Gi(e);if(!r)throw Error(`unit rebind needs to run inside a tmux or herdr pane — there is no pane to bind`);let i=xl(e,n);if(n.pane?.mux===r.mux&&n.pane.id===r.pane&&e.store.resolvePaneId(r.pane)===n.id)return n;let a=e.store.resolvePaneId(r.pane),o=a&&a!==n.id?N(e.store,a):void 0;if(o&&o.status!==`stopped`&&o.status!==`exited`)throw Error(`this pane belongs to unit "${o.handle}" (${o.id}) — rebind never takes another unit's pane`);let s=Dl(e,n),c=!!r.terminal&&n.pane?.mux===`herdr`&&n.pane.terminal===r.terminal;if(i&&i!==r.pane&&!c&&(s===`live`||s===`unknown`))throw Error(`unit "${n.handle}" may still be running in pane ${i} — stop it first (unit stop ${n.handle})`);let l={...n,status:`active`,pane:{mux:r.mux,id:r.pane,...r.terminal?{terminal:r.terminal}:{}},lastSeen:new Date(e.now?.()??Date.now()).toISOString()};return P(e.store,l),i&&i!==r.pane&&e.store.removePaneIndex(i),e.store.putPaneIndex(r.pane,n.id),l}function kl(e){if(!e)return!1;try{return Fo(e),!0}catch{return!1}}function Al(e,t,r){if(r===`none`)return[];let i=[];return r===`live`&&(i.push(`focus`,`nudge`,`read`),kl(t.harness)&&i.push(`clear`)),xl(e,t)!==void 0&&(r===`live`||r===`gone`||r===`unknown`)&&i.push(`stop`),r!==`exited`&&t.harness&&t.harness in B&&n(t.cwd)&&i.push(`restart`),(r===`stopped`||r===`exited`||r===`gone`)&&i.push(`rebind`),i.push(`close`),i}function jl(e,t){let n=L(e.store,t),r=Dl(e,n),i=xl(e,n),a=n.pane?.mux??(i?Sl(e,n)?.name:void 0);return{id:n.id,handle:n.handle,...n.harness?{harness:n.harness}:{},status:n.status,liveness:r,pane:i&&a?{mux:a,id:i}:null,cwd:n.cwd,worktree:n.worktree??null,sharedWorktree:n.sharedWorktree??null,lastSeen:n.lastSeen,controls:Al(e,n,r)}}function Ml(e,t){let n;try{n=JSON.parse(t)?.session_id}catch{return}if(typeof n!=`string`||n===``)return;let r=I(e),i=r?N(e.store,r):void 0;i&&i.kind!==`standing`&&i.kind!==`service`&&i.conversation!==n&&P(e.store,{...i,conversation:n})}async function Nl(e,t){let n=t.timeoutMs??6e5,r=(t.maxWaitS??240)*1e3,i=t.now??(()=>Date.now()),a=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),o=i(),s=o+r;for(;;){let r=H(e,{meId:t.meId,unread:!0,thread:t.thread,from:t.from});if(r.length>0){let n=r[0];return ks(e,t.meId,n.id),{kind:`matched`,message:n}}let c=i()-o;if(n!==0&&c>=n)return{kind:`timed-out`};if(i()>=s)return{kind:`waiting`};await a(1e3)}}async function Pl(e,t,n,r={}){let i=r.sleep??(e=>new Promise(t=>setTimeout(t,e))),a=/* @__PURE__ */ new Set;for(let n of H(e,{meId:t.meId,thread:t.thread,from:t.from}))a.add(n.id);let o=0;for(;;){let s=H(e,{meId:t.meId,thread:t.thread,from:t.from});for(let e of s)a.has(e.id)||(a.add(e.id),n(e));if(o++,r.maxIterations!=null&&o>=r.maxIterations)return;await i(1e3)}}const Fl=globalThis.__SKILL_SCRIPT__?.version??JSON.parse(i(new URL(`../package.json`,import.meta.url),`utf8`)).version;function Y(e){return{store:new vl(zi({space:e.space})),env:process.env,self:Xo()}}function X(e){return e.format===`json`?`json`:`toon`}function Il(e){let t=I(e);return t||q("no identity in this session — run `cyberlegion unit register` first"),ja(e,t),t}function Z(e){return e.option(`--space <path>`,`isolate the hub root (overrides the global hub / $CYBERLEGION_ROOT)`).addOption(new ye(`--format <format>`,`output format`).choices([`toon`,`json`]).default(`toon`))}function Ll(e){return e.hook(`postAction`,async(e,t)=>{let n=t.opts();(t.name()!==`who`||n.reconcile)&&await cc(Y(n).store)})}const Q=new Te;Q.name(`cyberlegion`).description(`Harness-agnostic agent session spawning and messaging over the filesystem`).version(Fl).enablePositionalOptions();const $=Q.command(`unit`).description(`legion units — register, discover, spawn, and reap`);function Rl(e,t,n){if(!t.handle){let n=F(e.store).filter(e=>e.kind===`standing`);G(X(t),{toon:W(`agents`,n,[{key:`id`,get:e=>e.id},{key:`handle`,get:e=>e.handle},{key:`harness`,get:e=>e.harness??`-`},{key:`status`,get:e=>e.status}],`${n.length} standing`),json:n});return}let r=F(e.store).find(e=>e.handle===t.handle&&e.kind!==`standing`&&e.status!==`exited`),i=la(e,{handle:t.handle,home:n});r&&console.error(`a live session already claims handle "${t.handle}"`),G(X(t),{toon:U({id:i.id,handle:i.handle,kind:i.kind,status:i.status,home:i.home?.dir??`none`,...i.home?{launch:i.home.agent?`agent ${i.home.agent}`:`harness ${i.home.harness}`}:{}}),json:i})}Ll(Z($.command(`register`))).description(`register or refresh this session identity (or --standing: a session-independent owner inbox)`).option(`--handle <name>`,`human handle for this agent`).option(`--harness <h>`,`claude | cursor | codex (else auto-detected)`).option(`--standing`,`mint a standing, session-independent owner inbox (bare, with no --handle: list them)`).option(`--home <dir>`,`with --standing: the existing folder a presence is spawned in when mail arrives and none is live`).option(`--agent <name>`,`with --home: launch that agent definition, resolved from the home`).option(`--clear-home`,`with --standing: drop the owner's home`).action(e=>{let t=Y(e),n;try{n=$c(t.exec??M,e)}catch(e){q(e instanceof Error?e.message:String(e))}if(e.standing){Rl(t,e,n);return}let r=oa(t,{handle:e.handle,harness:e.harness});G(X(e),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status}),json:r})}),Z($.command(`claim`)).description(`bind the caller's unit as a standing owner's presence; --show reads it, --clear unbinds`).argument(`<handle>`,`standing owner handle`).option(`--clear`,`unbind the presence (a no-op when nothing is bound)`).option(`--show`,`print the bound presence instead of claiming`).action((e,t)=>{let n=Y(t);if(t.show){let r;try{r=Da(n.store,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({presence:r?.id??`none`}),json:{presence:r?.id??null}});return}if(t.clear){try{Ta(n,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({presence:`none`}),json:{presence:null}});return}let r;try{r=wa(n,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({owner:r.handle,presence:r.presence}),json:{owner:r.handle,presence:r.presence}})}),Z($.command(`whoami`)).description(`print this session own identity`).action(e=>{let t=Y(e),n=I(t);n||q("no identity in this session — run `cyberlegion unit register` first");let r=N(t.store,n);r||q(`registered self id "${n}" has no agent record`),G(X(e),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status}),json:r})});function zl(e){let t=Y(e);R(t),e.reconcile&&Ra(t,{adopt:!0});let n=F(t.store).filter(t=>e.all||t.status!==`exited`);G(X(e),{toon:W(`units`,n,[{key:`id`,get:e=>e.id},{key:`handle`,get:e=>e.handle},{key:`harness`,get:e=>e.harness??`-`},{key:`status`,get:e=>e.status},{key:`pane`,get:e=>e.pane?.id??`-`},{key:`shared`,get:e=>e.sharedWorktree?.root??`-`}],`${n.length} units`),json:n}),n.length===0&&K(`cyberlegion unit register to join`)}Ll(Z($.command(`who`))).description(`list the addressable units`).option(`--all`,`include exited units`).option(`--reconcile`,`live-probe the current mux: cull dead-pane records and adopt unbound harness-bearing panes before listing`).action(zl),Ll(Z($.command(`prune`))).description(`mark dead units exited and delete exited units that leave no work on disk`).action(async e=>{let t=Y(e);R(t);let n=Va(t,{landed:await Zs(t)});G(X(e),{toon:W(`pruned`,n,[{key:`id`,get:e=>e.id},{key:`handle`,get:e=>e.handle},{key:`pruned`,get:e=>e.pruned}],`${n.length} pruned (${n.filter(e=>e.pruned===`deleted`).length} deleted)`),json:n})});const Bl=`(harness default)`;function Vl(e){return e.effortNotApplied?`${e.effortNotApplied} (not applied)`:e.effort??Bl}function Hl(e){let{effortNotApplied:t,model:n}=e.launched;t&&console.error(n?`${e.input.harness} carries effort only in a model id that cursor-agent models lists, and it lists no "${n}-${t}"; effort "${t}" not applied — launching ${n} at its default effort (run cursor-agent models to pick an id)`:`${e.input.harness} carries effort only as a parameter on a named model and none was set; effort "${t}" not applied — launching at the harness default model and effort (pass --model to apply it)`)}function Ul(e){return Z(e).option(`--harness <h>`,`claude | cursor | codex (required unless --agent/--agent-file resolves one)`).option(`--agent <name>`,`resolve an agent def (.agents/agents/<name>.md) for harness/model/effort/instructions`).option(`--agent-file <path>`,`read an exact agent def file instead of resolving by name`).option(`--model <name>`,`model for this launch only (flag > agent def > harness default)`).option(`--effort <level>`,`effort for this launch only (flag > agent def > harness default)`).option(`--task <text>`,`brief text, or - for stdin`).option(`--brief-file <path>`,`read the brief from a file`).option(`--handle <name>`,`handle for the new peer`).option(`--branch <name>`,`branch for the new worktree (default cyberlegion/unit-<id>)`).option(`--worktree-path <path>`,`where to check out the new worktree`).option(`-C, --repo <path>`,`create the worktree from the git repository containing <path>, not the current directory's`).option(`--base <ref>`,`start the new worktree's branch from <ref> (default: fetch origin and use its default branch, else local HEAD)`).option(`--cwd <path>`,`spawn the session in an existing directory; create no worktree (mutually exclusive with --branch/--worktree-path/--repo/--base)`).addOption(new ye(`--at <placement>`,`where to open the new session (default: new-worktree → workspace, --cwd → tab)`).choices([`pane:right`,`pane:down`,`tab`,`workspace`])).option(`--no-wake`,`suppress the first-turn doorbell (spawn idle; the caller drives the first turn itself)`)}function Wl(e){if(e.trustBlocked){if(console.error(e.trustBlocked),e.agent.brief){let t=ao(e.agent.brief).replaceAll(`'`,`'\\''`);console.error(`then: cyberlegion unit nudge ${e.agent.handle} --message '${t}'`)}process.exitCode=1}}function Gl(e){e.base?.fallback&&console.error(`base: fell back to local HEAD — ${e.base.fallback}`)}function Kl(e){return Ll(Ul(e)).description(`launch a new peer session in its own git worktree (tmux or herdr)`).action(async e=>{let t=Y(e);R(t);let n;try{n=xs(e,ws)}catch(e){q(e instanceof Error?e.message:String(e))}Hl(n);let r=await Bo(t,n.input,{noWake:n.noWake});r.warning&&console.error(`first-turn doorbell not confirmed (peer still spawned; nudge it manually): ${r.warning}`),Wl(r),Gl(r),G(X(e),{toon:U({spawned:r.agent.id,handle:r.agent.handle,harness:r.agent.harness,model:n.launched.model??Bl,effort:Vl(n.launched),worktree:r.agent.worktree?.root,reused:r.reused??`-`,base:r.base?.ref,pane:r.pane,rung:r.rung,trust:r.trust}),json:{agent:r.agent,pane:r.pane,launch:r.launch,base:r.base,...r.reused===void 0?{}:{reused:r.reused},model:n.launched.model??Bl,effort:Vl(n.launched),rung:r.rung,trust:r.trust}}),K(`cyberlegion unit read ${r.agent.id}`)})}Kl($.command(`spawn`)),Ll(Z($.command(`close`))).description(`release the unit's worktree lease (or remove a worktree it holds no lease on), tear down its session, and reap its state (the inverse of spawn)`).argument(`<id>`,`unit id, handle, or worktree branch/CR ref`).option(`--force`,`discard uncommitted changes in a worktree close removes (refused for a unit on the primary checkout)`).option(`--keep-worktree`,`leave the worktree on disk for reuse and reap everything else (skips the dirty check)`).action(async(e,t)=>{let n=Y(t);R(n);let r=L(n.store,e),i=await Ns(n,{id:r.id,force:t.force,keepWorktree:t.keepWorktree});G(X(t),{toon:U({closed:r.id,worktree:i.worktreeRoot??`-`,retained:i.retainedWorktree??`-`,lease:i.lease?i.lease.released?`released`:i.lease.reason:`-`,pane:i.pane??`-`}),json:i})}),Z($.command(`stop`)).description(`end a unit's session and keep the unit — its id, handle, inbox, brief, and worktree stay (unit close destroys them)`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action((e,t)=>{let n=Y(t);R(n);let r=Tl(n,e);G(X(t),{toon:U({stopped:r.agent.id,pane:r.pane??`-`,verified:r.verified,already:r.alreadyStopped}),json:{stopped:r.agent.id,pane:r.pane??null,verified:r.verified,alreadyStopped:r.alreadyStopped}}),r.alreadyStopped||K(`cyberlegion unit restart ${r.agent.handle}`)}),Z($.command(`restart`)).description(`give a unit a new session and keep the unit — stops a running session, relaunches it resuming the harness's recorded conversation where it can, and otherwise rebriefs it`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).option(`--no-wake`,`do not ring the new session to read its brief (the caller briefs it by mail)`).option(`--fresh`,`start an empty session and rebrief it, even when the unit's conversation could be resumed`).action(async(e,t)=>{let n=Y(t);R(n);let r=await El(n,e,{noWake:t.wake===!1,fresh:t.fresh===!0});G(X(t),{toon:U({restarted:r.agent.id,previous:r.previousPane??`-`,pane:r.pane,resumed:r.resumed,rung:r.rung}),json:r}),r.warning&&K(`warning: ${r.warning}`)}),Z($.command(`rebind`)).description(`bind a stopped unit to the calling pane — for a session started by hand that should be this unit`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action((e,t)=>{let n=Ol(Y(t),e);G(X(t),{toon:U({rebound:n.id,pane:n.pane?.id??`-`}),json:{rebound:n.id,pane:n.pane}})}),Z($.command(`show`)).description(`show a unit's runtime: where it is, whether it is live now, and the controls that work on it (read-only)`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action((e,t)=>{let n=Y(t);R(n);let r=jl(n,e);G(X(t),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status,liveness:r.liveness,pane:r.pane?`${r.pane.mux}:${r.pane.id}`:`-`,cwd:r.cwd,worktree:r.worktree?.root??`-`,shared:r.sharedWorktree?.root??`-`,lastSeen:r.lastSeen,controls:r.controls.join(`,`)||`-`}),json:r})}),Z($.command(`focus`)).description(`move input focus to a peer's session, named by a ref or picked by its worktree's repo/branch`).argument(`[ref]`,`unit id, handle, or worktree branch/CR ref`).option(`--repo <name>`,`pick the one live unit in this repository (its primary checkout's folder name, else its cwd's)`).option(`--branch <name>`,`pick the one live unit whose worktree is on this branch`).action((e,t)=>{let n={repo:t.repo,branch:t.branch};e!==void 0&&(n.repo!==void 0||n.branch!==void 0)&&q(`a ref and --repo/--branch cannot be combined — pass one or the other`);let r=Y(t);R(r);let{agent:i,pane:a}=$o(r,e??n),o=e??i.id;G(X(t),{toon:U({focused:o,pane:a}),json:{ref:o,pane:a}})}),Z($.command(`nudge`)).description(`deliver text as a turn in a peer's session — by default a doorbell telling them to check their mail; --message relays any text (e.g. a decision) instead`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).option(`--message <text>`,`text delivered as a turn in the peer session`,io).action(async(e,t)=>{let n=Y(t);R(n);let{pane:r,message:i,resubmits:a}=await es(n,e,{message:t.message});G(X(t),{toon:U({nudged:e,pane:r}),json:{ref:e,pane:r,message:i,resubmits:a}})}),Z($.command(`read`)).description(`scrape a peer's session screen`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).option(`--lines <n>`,`trailing lines to capture`,e=>Number.parseInt(e,10)).action((e,t)=>{let n=Y(t);R(n);let{pane:r,output:i}=ts(n,e,{lines:t.lines});console.log(Ss(X(t),{ref:e,pane:r,output:i}))}),Z($.command(`clear`)).description(`reset a warm peer's context to cold by injecting its own harness fresh-context command — keeps the pane/session warm; tears down nothing`).argument(`<ref>`,`unit id, handle, or worktree branch/CR ref`).action(async(e,t)=>{let n=Y(t);R(n);let r;try{r=await ns(n,e)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({cleared:e,pane:r.pane,command:r.command}),json:{cleared:e,pane:r.pane,command:r.command}})});const ql=Q.command(`project`).description(`register and resolve projects (one per git repository)`);function Jl(e){return{id:e.id,name:e.name,root:e.root}}async function Yl(e,t,n){let r=await ac(e.store,n,e.exec??M),i=r?{...n,subject:r.subject}:n;G(X(t),{toon:U({...Jl(i),...r?{channel:r.channel?.handle??`none`}:{}}),json:r?{...i,...r.channel?{channel:r.channel}:{}}:i})}Z(ql.command(`register`)).description(`register (or refresh) the project containing a directory — any checkout of it`).option(`--dir <path>`,`a directory inside the project (default: the current directory)`).action(async e=>{let t=Y(e),n;try{n=Sc({store:t.store},{dir:e.dir})}catch(e){q(e instanceof Error?e.message:String(e))}await Yl(t,e,n)}),Z(ql.command(`list`)).description(`list the registered projects`).action(e=>{let t=Cc(Y(e).store);G(X(e),{toon:W(`projects`,t,[{key:`id`,get:e=>e.id},{key:`name`,get:e=>e.name},{key:`root`,get:e=>e.root}],`${t.length} projects`),json:t}),t.length===0&&K(`cyberlegion project register to add the current repository`)}),Z(ql.command(`show`)).description(`resolve a registered project by id, path, or unique name`).argument(`<ref>`,`project id, a path inside any of its checkouts, or its name`).action(async(e,t)=>{let n=Y(t),r;try{r=Ec({store:n.store},e)}catch(e){q(e instanceof Error?e.message:String(e))}await Yl(n,t,r)});const Xl=Q.command(`service`).description(`project services — one authoritative owner each, fenced by generation`);function Zl(e){return{project:e.project.id,service:e.lease.service,endpoint:e.endpoint.id,generation:e.lease.generation,state:e.lease.state,holder:e.lease.holder??null,health:e.health,control:e.control,...e.note?{note:e.note}:{}}}function Ql(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t??`-`]))}function $l(e,t){G(X(e),{toon:U(Ql(t)),json:t})}function eu(e){try{return e()}catch(e){q(e instanceof Error?e.message:String(e))}}const tu=e=>Number.parseInt(e,10);function nu(e,t){return t===void 0?[`.`,e]:[e,t]}function ru(e,t){return t?eu(()=>L(e.store,t)).id:Il(e)}Z(Xl.command(`resolve`)).description(`show a service's owner, generation, health, and whether its session is controllable`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).action((e,t,n)=>{let[r,i]=nu(e,t),a=Y(n);$l(n,Zl(eu(()=>Gc(a,r,i))))}),Z(Xl.command(`acquire`)).description(`resolve the healthy owner, or reserve the right to start one (exactly one caller wins)`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).option(`--ttl <ms>`,`how long the reservation holds before another caller may take over`,tu).option(`--force-generation <n>`,`reserve even over a healthy owner — must name the current generation`,tu).action((e,t,n)=>{let[r,i]=nu(e,t),a=Y(n),o=eu(()=>Kc(a,r,i,{by:I(a),ttlMs:n.ttl,...n.forceGeneration===void 0?{}:{force:{generation:n.forceGeneration}}}));$l(n,{outcome:o.outcome,...Zl(o.view),...o.outcome===`reserved`?{token:o.token,expiresAt:o.lease.reservation?.expiresAt}:{}}),o.outcome===`reserved`?K(`start the runtime, then: cyberlegion service bind ${r} ${i} --generation ${o.lease.generation} --token ${o.token}`):o.outcome===`starting`&&K(`another caller is starting it — re-run to resolve: cyberlegion service resolve ${r} ${i}`)}),Z(Xl.command(`bind`)).description(`complete a reservation: make a live unit (default: this session) the owner`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the reserved generation`,tu).requiredOption(`--token <token>`,`the reservation token from acquire`).option(`--unit <ref>`,`the unit to bind (default: this session)`).action((e,t,n)=>{let[r,i]=nu(e,t),a=Y(n),o=ru(a,n.unit);$l(n,Zl(eu(()=>Jc(a,r,i,{generation:n.generation,token:n.token,unit:o}))))}),Z(Xl.command(`release`)).description(`abandon a reservation (--token) or step down as owner (default: this session)`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the current generation`,tu).option(`--token <token>`,`release a reservation instead of an active ownership`).option(`--unit <ref>`,`the owning unit (default: this session)`).action((e,t,n)=>{let[r,i]=nu(e,t),a=Y(n),o=n.token?{generation:n.generation,token:n.token}:{generation:n.generation,unit:ru(a,n.unit)};$l(n,Zl(eu(()=>Yc(a,r,i,o))))}),Z(Xl.command(`handoff`)).description(`transfer ownership to another live unit under a new generation`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the current generation`,tu).requiredOption(`--to <ref>`,`the unit taking over`).option(`--from <ref>`,`the current owner (default: this session)`).action((e,t,n)=>{let[r,i]=nu(e,t),a=Y(n),o=ru(a,n.from),s=eu(()=>L(a.store,n.to)).id;$l(n,Zl(eu(()=>Xc(a,r,i,{generation:n.generation,from:o,to:s}))))}),Z(Xl.command(`verify`)).description(`the fencing check: exit 0 only when the unit (default: this session) owns the service at this generation`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).requiredOption(`--generation <n>`,`the generation the caller believes it owns`,tu).option(`--unit <ref>`,`the unit to check (default: this session)`).action((e,t,n)=>{let[r,i]=nu(e,t),a=Y(n),o=ru(a,n.unit);$l(n,Zl(eu(()=>Zc(a,r,i,{unit:o,generation:n.generation}))))}),Ll(Ul(Xl.command(`start`))).description(`resolve the healthy owner, or spawn one peer and bind it — concurrent starts launch once`).argument(`<project-or-name>`,`project id, path, or unique name — omit to use the current directory`).argument(`[name]`,`service name`).option(`--ttl <ms>`,`how long the reservation holds while the peer launches`,tu).action(async(e,t,n)=>{let[r,i]=nu(e,t),a=Y(n);R(a);let o;try{o=xs(n,ws)}catch(e){q(e instanceof Error?e.message:String(e))}Hl(o);let s,c;try{c=await Qc(a,r,i,{by:I(a),ttlMs:n.ttl,launch:async()=>{let e=await Bo(a,o.input,{noWake:o.noWake});return s=e.warning,Wl(e),Gl(e),{unit:e.agent.id,pane:e.pane}}})}catch(e){q(e instanceof Error?e.message:String(e))}s&&console.error(`first-turn doorbell not confirmed (peer still spawned; nudge it manually): ${s}`),$l(n,{outcome:c.outcome,...Zl(c.view)}),c.outcome===`starting`&&K(`another caller is starting it — re-run to resolve: cyberlegion service resolve ${r} ${i}`)});const iu=Q.command(`mail`).description(`durable inter-agent messaging`);function au(e){return Z(e).description(`send a message to a peer (by handle or id)`).requiredOption(`--to <peer>`,`recipient handle or id`).option(`--from <id>`,`sender id (else this session own identity)`).option(`--subject <s>`,`subject`).option(`--body <text>`,`message body`).option(`--body-file <path>`,`read body from a file, or - for stdin`).option(`--thread <id>`,`thread id`).option(`--reply-to <msg>`,`message id this replies to`).option(`--no-nudge`,`suppress the delivery doorbell (do not wake the recipient's pane)`).action(async e=>{let t=Y(e),n=e.from??Il(t),r=Es(e.body,e.bodyFile),i=Ts({store:t.store},{fromId:n,to:e.to,subject:e.subject,body:r,thread:e.thread,replyTo:e.replyTo}),a=await mo(t.store,()=>z(t.env??process.env),M,{toId:i.to,fromId:n,noNudge:e.nudge===!1,spawnHome:e=>_c(t,e)});a.warning&&console.error(`delivery doorbell not confirmed (message still delivered): ${a.warning}`),G(X(e),{toon:U({sent:i.id,to:e.to,subject:i.subject,rung:a.rung,...a.spawned?{spawned:a.spawned}:{}}),json:{...i,rung:a.rung,...a.spawned?{spawned:a.spawned}:{}}})})}au(iu.command(`send`));function ou(e,t,n,r){let i=H({store:e.store},{meId:n,unread:t.unread,from:t.from,thread:t.thread}),a=i.filter(e=>!e.read).length;G(X(t),{toon:W(`messages`,i,[{key:`id`,get:e=>e.id},{key:`from`,get:e=>e.fromHandle},{key:`subject`,get:e=>e.subject??``},{key:`read`,get:e=>e.read}],`${i.length} messages (${a} unread)`),json:i});let o=i.find(e=>!e.read);o&&K(`${r} ${o.id}`)}function su(e,t,n){let r;try{r=Ca(e.store,n)}catch(e){q(e instanceof Error?e.message:String(e))}let i=Ds({store:e.store},{meId:r.id,unread:t.unread,from:t.from,thread:t.thread}),a=i.messages.filter(e=>!e.read).length,o=i.mailbox===`none`?`no mailbox`:i.mailbox===`unreadable`?`mailbox unreadable: ${i.error}`:`${i.messages.length} messages (${a} unread)`;G(X(t),{toon:[U({unit:r.id,handle:r.handle,mailbox:i.mailbox}),W(`messages`,i.messages,[{key:`id`,get:e=>e.id},{key:`from`,get:e=>e.fromHandle},{key:`subject`,get:e=>e.subject??``},{key:`read`,get:e=>e.read}],o)].join(`
|
|
74
|
+
`),json:{unit:r.id,handle:r.handle,...i}}),i.mailbox===`unreadable`&&(console.error(JSON.stringify({error:`mailbox of ${r.id} is unreadable: ${i.error}`})),process.exitCode=1)}function cu(e){let t=Y(e);R(t),e.unit?su(t,e,e.unit):ou(t,e,e.owner?Sa(t.store,e.owner):Il(t),`cyberlegion mail read`)}Z(iu.command(`inbox`)).description(`list your mail`).option(`--unread`,`only un-acked mail`).option(`--from <id>`,`filter by sender`).option(`--thread <id>`,`filter to messages carrying this thread id`).option(`--owner <handle>`,`target a standing owner's mailbox instead of this session's own`).addOption(new ye(`--unit <handle|id>`,`list another unit's mailbox read-only (exited units too); never acks, reports mailbox: none|present|unreadable`).conflicts(`owner`)).action(cu),Z(iu.command(`read`)).description(`read a message; --ack consumes it in the same step, otherwise it only peeks`).argument(`<msg-id>`,`message id`).option(`--ack`,`acknowledge the message in the same step (idempotent — no error if already acked)`).option(`--owner <handle>`,`read a standing owner's mailbox instead of this session's own`).action((e,t)=>{let n=Y(t),r=t.owner?Sa(n.store,t.owner):Il(n);if(t.ack){let{msg:i,acked:a}=As({store:n.store},r,e);G(X(t),{toon:U({id:i.id,from:i.fromHandle,subject:i.subject,body:i.body,acked:a}),json:{...i,acked:a}});return}let i=Os({store:n.store},r,e);i||q(`"${e}" is not a message in this inbox`),G(X(t),{toon:U({id:i.id,from:i.fromHandle,subject:i.subject,body:i.body}),json:i}),K(`cyberlegion mail ack ${i.id}${t.owner?` --owner ${t.owner}`:``}`)}),Z(iu.command(`ack`)).description(`acknowledge a message (moves it out of the unread set)`).argument(`<msg-id>`,`message id`).option(`--owner <handle>`,`ack a standing owner's mailbox instead of this session's own`).action((e,t)=>{let n=Y(t),r=t.owner?Sa(n.store,t.owner):Il(n),i=ks({store:n.store},r,e);G(X(t),{toon:U({acked:i.id,from:i.fromHandle,subject:i.subject}),json:i})}),Z(iu.command(`delete`)).description(`permanently remove a message from your inbox (unread or already-acked)`).argument(`<msg-id>`,`message id`).action((e,t)=>{let n=Y(t),r=Il(n);js({store:n.store},r,e),G(X(t),{toon:U({deleted:e}),json:{deleted:e}})}),Z(iu.command(`await`)).description(`block until a thread-correlated reply arrives, print it, and ack it`).requiredOption(`--thread <id>`,`thread id to wait on`).option(`--from <h>`,`only match a reply from this sender`).option(`--timeout <ms>`,`give up after this many ms with no match (0 = wait forever); exits non-zero on timeout`,e=>Number.parseInt(e,10),6e5).option(`--max-wait <s>`,`self-cap for one internal poll cycle, in seconds — returns the clean "waiting" sentinel at this cap so the caller can re-arm rather than blocking past a harness tool-timeout`,e=>Number.parseInt(e,10),240).addHelpText(`after`,`
|
|
75
75
|
Three outcomes:
|
|
76
76
|
matched — exit 0; the message is printed on stdout and acked (moved out of the unread set).
|
|
77
77
|
waiting — exit 0; a stderr "waiting" line and nothing on stdout — the per-call --max-wait
|
|
78
78
|
cap was hit with no match yet; re-run the same command to keep waiting.
|
|
79
79
|
timed-out — exit 1; a clear stderr message and nothing on stdout — --timeout elapsed with no match.
|
|
80
|
-
`).action(async e=>{let t=Y(e),n=
|
|
80
|
+
`).action(async e=>{let t=Y(e),n=Il(t),r=await Nl({store:t.store},{meId:n,thread:e.thread,from:e.from,timeoutMs:e.timeout,maxWaitS:e.maxWait});if(r.kind===`matched`){let t=r.message;G(X(e),{toon:U({id:t.id,from:t.fromHandle,subject:t.subject,body:t.body}),json:t})}else r.kind===`waiting`?console.error(`waiting — no reply on thread "${e.thread}" within --max-wait ${e.maxWait}s; re-run to keep waiting`):q(`no reply on thread "${e.thread}" within ${e.timeout}ms`)}),Z(iu.command(`watch`)).description(`stream new matching mail as it arrives — an observer only, it never acks; Ctrl-C to stop`).option(`--thread <id>`,`filter to a thread`).option(`--from <h>`,`filter by sender`).action(async e=>{let t=Y(e),n=Il(t);await Pl({store:t.store},{meId:n,thread:e.thread,from:e.from},t=>{G(X(e),{toon:U({id:t.id,from:t.fromHandle,subject:t.subject,body:t.body}),json:t})})}),Z(iu.command(`hook`)).description(`emit the harness hook injection payload (raw JSON on stdout, not TOON)`).option(`--event <event>`,`SessionStart`,`SessionStart`).action(e=>{let t=Y(e);if(R(t),!process.stdin.isTTY)try{Ml(t,i(0,`utf8`))}catch{}let n=kc(t,e.event);n&&console.log(JSON.stringify(n))});const lu=Q.command(`agent`).description(`resolve reusable agent definitions`);function uu(e,t){return t||e.length<=200?e:`${e.slice(0,200)}… (${e.length} chars total, pass --full)`}function du(e){return{name:e.name,description:e.description,model:e.model??Bl,effort:e.effort,harness:e.harness??Bl,warm:e.warm??!1,interactive:e.interactive??!1,path:e.path}}Z(lu.command(`list`)).description(`list resolvable agent definitions under .agents/agents/`).option(`--dir <path>`,`project dir to search from`,process.cwd()).action(e=>{let t=ps({cwd:e.dir});G(X(e),{toon:W(`defs`,t,[{key:`name`,get:e=>e.name},{key:`model`,get:e=>e.model??`-`},{key:`harness`,get:e=>e.harness??`-`}],`${t.length} agent definitions`),json:t}),t.length===0&&K(`add a .md file under .agents/agents/ to define one`)}),Z(lu.command(`show`)).description(`show a resolved agent definition (model/effort/harness/warm/interactive + instructions)`).argument(`<name>`,`agent def name (file stem under .agents/agents/)`).option(`--dir <path>`,`project dir to search from`,process.cwd()).option(`--full`,`show the full instructions body (default: truncated)`).action((e,t)=>{let n;try{n=fs({name:e,cwd:t.dir})}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({...du(n),instructions:uu(n.instructions,t.full)}),json:{...n,instructions:t.full?n.instructions:uu(n.instructions,t.full)}})}),Z(lu.command(`resolve`)).description(`emit the full machine payload for a def — for a routing caller to compose a launch/spawn from`).argument(`[name]`,`agent def name (omit when passing --file)`).option(`--file <path>`,`read an exact def file instead of resolving by name (plugin-scoped escape hatch)`).option(`--dir <path>`,`project dir to search from`,process.cwd()).action((e,t)=>{let n;try{n=fs({name:e,file:t.file,cwd:t.dir})}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U(du(n)),json:n})}),Z(lu.command(`path`)).description(`print the resolved def file path`).argument(`<name>`,`agent def name (file stem under .agents/agents/)`).option(`--dir <path>`,`project dir to search from`,process.cwd()).action((e,t)=>{let n;try{n=fs({name:e,cwd:t.dir})}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({path:n.path}),json:{path:n.path}})});const fu=`cyberlegion init --allow-cli to add ${lc} to Claude Code's permissions.allow, so units can mail their results back`,pu=Q.command(`mux`).description(`the unit-agnostic pane layer — multiplexer detection and diagnostics`);Z(pu.command(`doctor`)).description(`probe harness, multiplexer (ancestry-discovered), hub root, and self-id`).action(e=>{let t=Y(e),n=ra(void 0,t)??`unknown`,r=Me(t.exec??M,j(t.env??process.env)),i=I(t)??`-`,a=n===`claude`?mc(dc(t.env??process.env)):`n/a`,o={harness:n,mux:r.mux,pane:r.pane,via:r.via,hubRoot:t.store.root,selfId:i};G(X(e),{toon:U({...o,permissionRule:a}),json:{...o,permissionRule:a}}),a===`missing`&&K(fu),r.mux!==`none`&&K(`export CYBER_MUX=${r.mux}${r.pane?` CYBER_MUX_PANE=${r.pane}`:``} — pin the fast-path, skip ancestry discovery on later calls`)}),Z(pu.command(`mode`)).description(`report the detected session-backend mode`).action(e=>{let t=Y(e),n=`none`;try{n=z(t.env??process.env).name}catch{}G(X(e),{toon:U({mode:n}),json:{mode:n}})}),Z(Q.command(`attach`)).description(`bind this pane as the hub's main pane (the owner's live presence); --show reads it, --clear unbinds`).option(`--clear`,`unbind the main pane (a no-op when nothing is bound)`).option(`--show`,`print the bound main pane instead of binding`).action(e=>{let t=Y(e);if(e.show){let n=t.store.getMainPane();G(X(e),{toon:U({mainPane:n??`none`}),json:{mainPane:n??null}});return}if(e.clear){t.store.setMainPane(null),G(X(e),{toon:U({mainPane:`none`}),json:{mainPane:null}});return}let n=je(j(t.env??process.env));n||q(`no multiplexer pane to bind — run this from inside a tmux or herdr pane`),t.store.setMainPane(n.pane),G(X(e),{toon:U({mainPane:n.pane}),json:{mainPane:n.pane}})}),Z(Q.command(`admin`).description(`hub-state maintenance`).command(`migrate`)).description(`merge one hub root state into another (e.g. an old project-local root into the global hub)`).requiredOption(`--from <path>`,`source hub root`).requiredOption(`--to <path>`,`destination hub root`).action(e=>{let t=jr(new vl(g(e.from)),new vl(g(e.to)));G(X(e),{toon:U({agents:t.agents,messages:t.messages,briefs:t.briefs}),json:t})}),Z(Q.command(`init`)).description(`resolve this session harness, set up the Legion surfacing hook, and advise owner binding`).option(`--agent <h>`,`claude | cursor | codex (else auto-detected)`).option(`--dir <path>`,`project dir to write config into`,process.cwd()).option(`--pin <version>`,`version the npx fallback of the cursor hook fetches (e.g. the bundled plugin version)`).option(`--allow-cli`,`add ${lc} to Claude Code's user permissions.allow (claude only)`).action(e=>{let t=Y(e),n;try{let r=ra(e.agent,t);r||q(`could not detect harness — pass --agent claude|cursor|codex`),n=r}catch(e){q(e instanceof Error?e.message:String(e))}e.allowCli&&n!==`claude`&&q(`--allow-cli applies to claude only, not ${n}`);let r;if(n===`claude`){let n=dc(t.env??process.env);try{r=e.allowCli?hc(n):mc(n)}catch(e){q(e instanceof Error?e.message:String(e))}}let i;try{i=Gs(n,e.dir,e.pin)}catch(e){q(e instanceof Error?e.message:String(e))}G(X(e),{toon:W(`hooks`,i,[{key:`event`,get:e=>e.event},{key:`status`,get:e=>e.status},{key:`file`,get:e=>e.file}],`harness ${n}, ${i.length} hooks${r?`, permission rule ${r}`:``}`),json:{harness:n,hooks:i,...r&&{permissionRule:r}}}),r===`missing`&&K(fu),F(t.store).some(e=>e.kind===`standing`)||(K(`cyberlegion unit register --standing --handle <name> to mint the durable owner inbox`),K(`cyberlegion attach to bind this pane as the owner live presence`))}),Kl(Q.command(`spawn`)),au(Q.command(`send`)),Z(Q.command(`inbox`)).description("list your mail (alias of `mail inbox`)").option(`--unread`,`only un-acked mail`).option(`--from <id>`,`filter by sender`).option(`--thread <id>`,`filter to messages carrying this thread id`).action(cu),Ll(Z(Q.command(`who`))).description("list the addressable units (alias of `unit who`)").option(`--all`,`include exited units`).option(`--reconcile`,`live-probe the current mux: cull dead-pane records and adopt unbound harness-bearing panes before listing`).action(zl),Z(Q).action(e=>{let t=Y(e);R(t);let n=I(t),r=n?N(t.store,n):void 0,i=n?H({store:t.store},{meId:n,unread:!0}).length:0,a=F(t.store).filter(e=>e.status!==`exited`).length;G(X(e),{toon:U({self:r?.handle??n??`-`,harness:r?.harness??`-`,unread:i,units:a}),json:{self:r?{id:r.id,handle:r.handle,harness:r.harness}:null,unread:i,units:a}}),n?i>0&&K(`cyberlegion mail inbox --unread`):K(`cyberlegion unit register to join`)});async function mu(e=process.argv){try{await Q.parseAsync(e)}catch(e){console.error(JSON.stringify({error:e instanceof Error?e.message:String(e)})),process.exit(1)}}await mu();export{};
|