cyberlegion 1.9.0 → 2.0.0
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 +28 -0
- package/dist/cli.mjs +408 -151
- package/dist/index.d.mts +38 -48
- package/dist/index.mjs +336 -82
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/readme.md +1 -1
- package/skills/dispatch-governance/SKILL.md +16 -3
- package/skills/dispatch-governance/scripts/cyberlegion.mjs +58 -58
- package/skills/init-cyberlegion/scripts/cyberlegion.mjs +58 -58
- package/skills/legate/SKILL.md +1 -1
- package/skills/legate/scripts/cyberlegion.mjs +58 -58
- package/skills/manage-inbox/SKILL.md +1 -1
- package/skills/manage-inbox/scripts/cyberlegion.mjs +58 -58
- package/skills/relay-governance/SKILL.md +1 -1
- package/skills/relay-governance/scripts/cyberlegion.mjs +58 -58
- package/skills/subagent-backend-governance/SKILL.md +1 -1
- package/skills/subagent-backend-governance/scripts/cyberlegion.mjs +58 -58
|
@@ -1,80 +1,80 @@
|
|
|
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":"
|
|
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
|
|
4
|
-
`)}displayWidth(e){return
|
|
2
|
+
globalThis.__SKILL_SCRIPT__ = {"package":null,"bin":null,"version":"2.0.0","entry":"skills/init-cyberlegion/scripts/cyberlegion.mjs","commands":{}};
|
|
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
|
+
`)}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(`
|
|
6
|
-
`)}},
|
|
6
|
+
`)}},ye=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\p{ID_Continue}\.\.\.[>\]]$/u.test(e),this.mandatory=!1;let n=Se(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}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}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?xe(this.name().replace(/^no-/,``)):xe(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},be=class{constructor(e){this.positiveOptions=/* @__PURE__ */ new Map,this.negativeOptions=/* @__PURE__ */ new Map,this.dualOptions=/* @__PURE__ */ new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function xe(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Se(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
7
7
|
- a short flag is a single dash and a single character
|
|
8
8
|
- either use a single dash and a single character (for a short flag)
|
|
9
9
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
|
|
10
10
|
- too many short flags`):i.test(t)?Error(`${n}
|
|
11
11
|
- too many long flags`):Error(`${n}
|
|
12
|
-
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function
|
|
13
|
-
- specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
14
|
-
Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new
|
|
15
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof
|
|
12
|
+
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function Ce(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function we(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=Ce(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var Te=class t extends v{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>b.stdout.write(e),writeErr:e=>b.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>b.stdout.isTTY?b.stdout.columns:void 0,getErrHelpWidth:()=>b.stderr.isTTY?b.stderr.columns:void 0,getOutHasColors:()=>De()??(b.stdout.isTTY&&b.stdout.hasColors?.()),getErrHasColors:()=>De()??(b.stderr.isTTY&&b.stderr.hasColors?.()),stripColor:e=>ne(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(e){return new t(e)}createHelp(){return Object.assign(new ve,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
13
|
+
- specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new ge(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
14
|
+
Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new me(e,t,n)),b.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new ye(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
15
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof ye)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{Object.hasOwn(n._optionValueSources,e)&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){b.versions?.electron&&(t.from=`electron`);let e=b.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=b.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:b.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
16
16
|
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,n,r){if(e.existsSync(t))return;let i=`'${t}' does not exist
|
|
17
17
|
- if '${r}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
18
18
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
19
|
-
- ${n?`searched for local subcommand relative to directory '${n}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(i)}_executeSubCommand(t,n){n=n.slice();let r=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function i(t,n){let i=d.resolve(t,n);if(e.existsSync(i))return i;if(r.includes(d.extname(n)))return;let a=r.find(t=>e.existsSync(`${i}${t}`));if(a)return`${i}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=t._executableFile||`${this._name}-${t._name}`,o=this._executableDir||``;if(this._scriptPath){let t;try{t=e.realpathSync(this._scriptPath)}catch{t=this._scriptPath}o=d.resolve(d.dirname(t),o)}if(o){let e=i(o,a);if(!e&&!t._executableFile&&this._scriptPath){let n=d.basename(this._scriptPath,d.extname(this._scriptPath));n!==this._name&&(e=i(o,`${n}-${t._name}`))}a=e||a}let s=r.includes(d.extname(a)),c;
|
|
20
|
-
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
21
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function
|
|
22
|
-
`).find(n);return{matched:!0,output:e,...r==null?{}:{matchedLine:r}}}async function
|
|
23
|
-
`),o.command!==void 0&&e.submit(t,n,o.command)}const
|
|
19
|
+
- ${n?`searched for local subcommand relative to directory '${n}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(i)}_executeSubCommand(t,n){n=n.slice();let r=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function i(t,n){let i=d.resolve(t,n);if(e.existsSync(i))return i;if(r.includes(d.extname(n)))return;let a=r.find(t=>e.existsSync(`${i}${t}`));if(a)return`${i}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=t._executableFile||`${this._name}-${t._name}`,o=this._executableDir||``;if(this._scriptPath){let t;try{t=e.realpathSync(this._scriptPath)}catch{t=this._scriptPath}o=d.resolve(d.dirname(t),o)}if(o){let e=i(o,a);if(!e&&!t._executableFile&&this._scriptPath){let n=d.basename(this._scriptPath,d.extname(this._scriptPath));n!==this._name&&(e=i(o,`${n}-${t._name}`))}a=e||a}let s=r.includes(d.extname(a)),c;b.platform===`win32`?(this._checkForMissingExecutable(a,o,t._name),n.unshift(a),n=Ee(b.execArgv).concat(n),c=y.spawn(b.execPath,n,{stdio:`inherit`})):s?(n.unshift(a),n=Ee(b.execArgv).concat(n),c=y.spawn(b.argv[0],n,{stdio:`inherit`})):c=y.spawn(a,n,{stdio:`inherit`}),c.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{b.on(e,()=>{c.killed===!1&&c.exitCode===null&&c.kill(e)})});let l=this._exitCallback;c.on(`close`,e=>{e??=1,l?l(new me(e,`commander.executeSubCommandAsync`,`(close)`)):b.exit(e)}),c.on(`error`,e=>{if(e.code===`ENOENT`)this._checkForMissingExecutable(a,o,t._name);else if(e.code===`EACCES`)throw Error(`'${a}' not executable`);if(!l)b.exit(1);else{let t=new me(1,`commander.executeSubCommandAsync`,`(error)`);t.nestedError=e,l(t)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)([eE][+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l)))this.emit(`option:${o.name()}`,l);else{if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in b.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,b.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new be(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=we(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=we(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>_e(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=d.basename(e,d.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(b.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
21
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function Ee(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk|-wait)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port|-wait)?)=(\[[^\]]+\]|[^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port|-wait)?)=(\[[^\]]+\]|[^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function De(){if(b.env.NO_COLOR||b.env.FORCE_COLOR===`0`||b.env.FORCE_COLOR===`false`)return!1;if(b.env.FORCE_COLOR||b.env.CLICOLOR_FORCE!==void 0)return!0}new Te;const Oe=(e,t)=>{try{let n=te(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`]}).trim();return Oe.lastError=void 0,n}catch(e){let t=e.stderr;return Oe.lastError=String(t??``).trim()||void 0,null}};function x(e,t){return e.lastError?`${t} — ${e.lastError}`:t}const ke=[`tmux`,`rmux`,`herdr`,`wezterm`,`zellij`,`cmux`,`otty`,`screen`,`none`];function Ae(e){return e!=null&&ke.includes(e)}const S={tmux:e=>e.TMUX_PANE,rmux:e=>e.RMUX_PANE,herdr:e=>e.HERDR_PANE_ID,wezterm:e=>e.WEZTERM_PANE,zellij:e=>e.ZELLIJ_PANE_ID,cmux:e=>e.CMUX_SURFACE_ID,otty:e=>e.OTTY_PANE_ID};function je(e){if(e.CYBER_MUX_PANE)return{mux:e.CYBER_MUX===`rmux`?`rmux`:e.CYBER_MUX===`herdr`?`herdr`:e.CYBER_MUX===`wezterm`?`wezterm`:e.CYBER_MUX===`zellij`?`zellij`:e.CYBER_MUX===`cmux`?`cmux`:e.CYBER_MUX===`otty`?`otty`:`tmux`,pane:e.CYBER_MUX_PANE};let t=S.rmux(e);if(t)return{mux:`rmux`,pane:t};let n=S.tmux(e);if(n)return{mux:`tmux`,pane:n};let r=S.herdr(e);if(r)return{mux:`herdr`,pane:r};let i=S.wezterm(e);if(i)return{mux:`wezterm`,pane:i};let a=S.zellij(e);if(a)return{mux:`zellij`,pane:a};let o=S.cmux(e);if(o)return{mux:`cmux`,pane:o};let s=S.otty(e);if(s)return{mux:`otty`,pane:s}}function Me(e,t,n={}){let r=n.envPrefix??`CYBER_MUX`,i=t[r],a=t[`${r}_PANE`];return Ae(i)?{mux:i,...a?{pane:a}:{},via:`env`}:n.discover===!1?{mux:`none`,via:`ancestry`}:Le(e,t)}const Ne=[{re:/^tmux(:|$)/,mux:`tmux`},{re:/^rmux(-daemon|-server)?(:|$)/,mux:`rmux`},{re:/^herdr(:|$)/,mux:`herdr`},{re:/^wezterm(-gui|-mux-server)?(:|$)/,mux:`wezterm`},{re:/^zellij(:|$)/,mux:`zellij`},{re:/^screen(:|$)/,mux:`screen`}];function Pe(e){return Object.hasOwn(S,e)}function Fe(e,t){return Pe(e)?S[e](t):void 0}function C(e,t){let n=Fe(e,t);return{mux:e,...n===void 0?{}:{pane:n},via:`ancestry`}}function Ie(e,t){let n=process.pid,r=/* @__PURE__ */ new Set;for(let i=0;i<32&&!r.has(n);i++){r.add(n);let i=e(`ps`,[`-o`,`ppid=,comm=`,`-p`,String(n)]);if(!i)break;let a=i.trim(),o=a.indexOf(` `),s=o===-1?a:a.slice(0,o),c=o===-1?``:a.slice(o+1).trim(),l=Number.parseInt(s,10);for(let e of Ne)if(e.re.test(c))return C(e.mux,t);if(!Number.isFinite(l)||l<=1)break;n=l}}function Le(e,t){return Ie(e,t)||(t.RMUX?C(`rmux`,t):t.TMUX?C(`tmux`,t):t.HERDR_ENV?C(`herdr`,t):t.WEZTERM_PANE?C(`wezterm`,t):t.ZELLIJ?C(`zellij`,t):t.CMUX_WORKSPACE_ID?C(`cmux`,t):t.OTTY_PANE_ID?C(`otty`,t):{mux:`none`,via:`ancestry`})}function Re(e){return h(e.CYBER_MUX_STATE_DIR||h(re(),`.agents`,`cyber-mux`),`jumps.json`)}function ze(e){return{read(){try{return i(e,`utf8`)}catch{return null}},write(t){r(p(e),{recursive:!0});let n=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;u(n,t,`utf8`),s(n,e)}}}function Be(e,t){let n=t=>{let[n=``,r=``]=(t??``).split(`,`);return{mux:e,home:n,run:r}};return e===`tmux`?n(t.TMUX):e===`rmux`?n(t.RMUX):e===`zellij`?{mux:e,home:t.ZELLIJ_SESSION_NAME??``,run:``}:e===`wezterm`?{mux:e,home:t.WEZTERM_UNIX_SOCKET??``,run:``}:{mux:e,home:``,run:``}}function Ve(e){let t=e.read();if(t==null)return{version:1,servers:[]};try{let e=JSON.parse(t);return e.version!==1||!Array.isArray(e.servers)?{version:1,servers:[]}:{version:1,servers:e.servers.filter(e=>e!=null&&typeof e.mux==`string`&&typeof e.home==`string`&&typeof e.run==`string`&&e.links!=null&&typeof e.links==`object`)}}catch{return{version:1,servers:[]}}}function He(e,t){e.write(`${JSON.stringify(t,null,` `)}\n`)}function Ue(e,t){e.servers=e.servers.filter(e=>e.mux!==t.mux||e.home!==t.home||e.run===t.run);let n=e.servers.find(e=>e.mux===t.mux&&e.home===t.home);return n||(n={...t,links:{}},e.servers.push(n)),n}function We(e,t,n){let r=je(n.env);if(!r||r.mux!==e||r.pane===t.id)return;let i=Ve(n.store);Ue(i,Be(e,n.env)).links[t.id]={from:r.pane,at:(n.now??Date.now)()},He(n.store,i)}const Ge=/* @__PURE__ */ new WeakMap;function Ke(e){return(Ge.get(e)??e).focus}function qe(e,t,n,r){Ke(e)(t,n);try{We(e.name,n,r)}catch{}}function Je(e){let t=Ge.get(e)??e,n={...t,focus(e,n){let r=process.env;qe(t,e,n,{env:r,store:ze(Re(r))})}};return Ge.set(n,t),n}function Ye(e){return`'${e.replace(/'/g,`'\\''`)}'`}function Xe(e){return`env ${Object.entries(e).map(([e,t])=>`${e}=${Ye(t)}`).join(` `)} `}function Ze(e,t){return e===void 0||Object.keys(e).length===0?{kind:`carried`,command:t}:t===void 0?{kind:`dropped`,variables:Object.keys(e)}:{kind:`carried`,command:`${Xe(e)}${t}`}}function Qe(e,t,n){let r=Ze(e,t),i=r.kind===`dropped`?void 0:r.command,a=n?$e(n,i):i;return r.kind===`dropped`?{kind:`dropped`,variables:r.variables,command:a}:{kind:`carried`,command:a}}function $e(e,t){let n=`cd ${Ye(e)}`;return t===void 0?n:`${n} && ${t}`}var et=class extends Error{backend;constructor(e){super(`${e} cannot open a floating pane`),this.backend=e,this.name=`FloatingPanesUnsupportedError`}};function tt(e){throw new et(e)}function nt(e,t){let n=e.read();try{return t()}finally{n!==void 0&&e.restore(n)}}function rt(e,t,n){let r=e.filter(e=>t(e)===!0);return r.length===1?n(r[0]):void 0}var it=class extends Error{backend;constructor(e){super(`${e} cannot move a pane`),this.backend=e,this.name=`PaneMoveUnsupportedError`}},at=class extends Error{backend;constructor(e){super(`${e} cannot break a pane out`),this.backend=e,this.name=`PaneBreakUnsupportedError`}};function ot(e){throw new it(e)}function st(e){throw new at(e)}function ct(e){let t=e.match!=null,n=e.regex!=null;if(t&&n)throw Error(`wait pattern must be one of match or regex — got both`);if(!t&&!n)throw Error(`wait pattern must be one of match or regex — got neither`);if(e.match!=null&&e.match===``)throw Error(`wait pattern match must not be empty`);if(e.regex!=null)try{new RegExp(e.regex)}catch(t){throw Error(`wait pattern regex is not a valid expression: ${e.regex} — ${t.message}`)}}function lt(e,t){ct(t);let n=e=>t.match==null?new RegExp(t.regex).test(e):e.includes(t.match);if(!n(e))return{matched:!1,output:e};let r=e.split(`
|
|
22
|
+
`).find(n);return{matched:!0,output:e,...r==null?{}:{matchedLine:r}}}async function ut(e,t,n,r){ct(r);let i=r.pollMs??150,a=r.now??(()=>Date.now()),o=r.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=r.lines==null?void 0:{lines:r.lines};dt(e,t,n);let c=a()+r.timeoutMs,l=``;for(;;){l=e.read(t,n,s).text;let u=lt(l,r);if(u.matched)return u;if(a()>=c)break;await o(i)}return dt(e,t,n),{matched:!1,output:l}}function dt(e,t,n){if(!e.paneExists(t,n))throw Error(`wait failed: pane ${n.id} no longer exists — the pane is gone, not quiet.`)}var ft=class extends Error{backend;constructor(e){super(`${e} cannot zoom a pane`),this.backend=e,this.name=`PaneZoomUnsupportedError`}};function pt(e){throw new ft(e)}function mt(e){let t={name:`cmux`,canBreakPanes:!0,focusOnOpen:`restored`,open(n,r){let i=r.at??`tab`;return i===`pane:float`&&tt(t.name),nt({read:()=>rt(yt(n),e=>e.focused,e=>e.id),restore:e=>t.focus(n,{id:e})},()=>{if(i===`workspace`){let e=[`--json`,`workspace`,`create`];r.cwd&&e.push(`--cwd`,r.cwd),r.label&&e.push(`--name`,r.label);let i=n(`cmux`,e);if(!i)throw Error(x(n,`cmux workspace create failed`));let a=ht(i);if(!a.workspace_ref)throw Error(`cmux workspace create did not report the workspace ref`);let o=a.surface_ref;if(!o)throw Error(`cmux workspace create did not report the initial surface ref`);let s=xt(o,a.pane_ref,a.workspace_ref);return r.workspaceGroup!=null&&t.group(n,{id:s.tab},r.workspaceGroup),St(t,n,s,r.env,r.launch),s}if(i===`tab`){let i=[`--json`,`new-surface`];r.within&&i.push(`--pane`,r.within),r.cwd&&i.push(`--cwd`,r.cwd);let a=n(`cmux`,i);if(!a)throw Error(x(n,`cmux new-surface failed`));let o=ht(a),s=o.surface_ref;if(!s)throw Error(`cmux new-surface did not report the surface ref`);let c=xt(s,o.pane_ref,e.workspace);return r.label&&t.rename(n,c,`tab`,r.label),St(t,n,c,r.env,r.launch),c}r.from&&t.focus(n,r.from);let a=n(`cmux`,[`--json`,`new-pane`,`--direction`,i===`pane:down`?`down`:`right`]);if(!a)throw Error(x(n,`cmux new-pane failed`));let o=ht(a),s=o.surface_ref;if(!s)throw Error(`cmux new-pane did not report the surface ref`);let c=xt(s,o.pane_ref,e.workspace);return r.label&&t.rename(n,c,`pane`,r.label),St(t,n,c,r.env,r.launch,r.cwd),c})},rename(e,t,n,r){let i=bt(e,t.id);if(!i)throw Error(x(e,`cmux could not resolve a surface to rename for ${t.id}`));e(`cmux`,[`rename-tab`,`--surface`,i,`--title`,r])},group(e,t,n){let r=_t(e,t.id);if(!r)throw Error(x(e,`cmux could not resolve the workspace holding ${t.id}`));let i=e(`cmux`,[`--json`,`workspace-group`,`create`,`--name`,n,`--idempotency-key`,n]);if(!i)throw Error(x(e,`cmux workspace-group create failed`));let a=gt(i);if(!a)throw Error(`cmux workspace-group create did not report the group ref`);e(`cmux`,[`workspace-group`,`add`,`--group`,a,`--workspace`,r])},sendText(e,t,n){e(`cmux`,[`send`,`--surface`,t.id,n])},sendKeys(e,t,n){for(let r of n)e(`cmux`,[`send-key`,`--surface`,t.id,wt(r)])},submit(e,n,r){r&&t.sendText(e,n,r),t.sendKeys(e,n,[`Enter`])},read(e,t,n){let r=[`read-screen`,`--surface`,t.id];return n?.lines!=null&&r.push(`--lines`,String(n.lines)),{text:e(`cmux`,r)??``}},waitForOutput(e,n,r){return ut(t,e,n,r)},focus(e,t){e(`cmux`,[`focus-panel`,`--panel`,t.id])},teardown(t,n){let r=[`close-surface`,`--surface`,n.id];e.workspace&&r.push(`--workspace`,e.workspace),t(`cmux`,r)},paneExists(e,t){return yt(e).some(e=>e.id===t.id)},isPaneFocused(e,t){let n=yt(e).find(e=>e.id===t.id);if(n)return typeof n.focused==`boolean`?n.focused:void 0},setPaneZoom(){pt(`cmux`)},isPaneZoomed(){},movePane(){ot(`cmux`)},breakPane(t,n,r){let i=[`--json`,`break-pane`,`--surface`,n.id,`--focus`,`false`];e.workspace&&i.push(`--workspace`,e.workspace);let a=t(`cmux`,i);if(!a)throw Error(x(t,`cmux could not break out surface ${n.id} into its own ${r}`));let o=ht(a);if(!o.surface_ref)throw Error(`cmux break-pane did not report the surface ref`);return xt(o.surface_ref,o.pane_ref,o.workspace_ref)},listPanes(e){return yt(e).map(e=>{let t={id:e.id,mux:`cmux`,floating:!1};return e.title&&(t.label=e.title),t})}};return Je(t)}mt({});function ht(e){try{return JSON.parse(e)}catch{return{}}}function gt(e){let t;try{t=JSON.parse(e)}catch{return}if(!t||typeof t!=`object`)return;let n=t.group;return n?.ref??n?.id}function _t(e,t){return vt(e,{pane_id:t},t)??vt(e,{surface_id:t},t)}function vt(e,t,n){let r=e(`cmux`,[`rpc`,`surface.list`,JSON.stringify(t)]);if(!r)return;let i;try{i=JSON.parse(r)}catch{return}if(!i||typeof i!=`object`)return;let a=i,o=a.workspace_ref??a.workspace_id;if(o)return(Array.isArray(a.surfaces)?a.surfaces:[]).some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return t.ref===n||t.id===n||t.pane_ref===n||t.pane_id===n})?o:void 0}function yt(e){let t=e(`cmux`,[`--json`,`list-panels`]);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return[]}if(!n||typeof n!=`object`)return[];let r=n.surfaces;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(!e||typeof e!=`object`)continue;let t=e,n=t.ref??t.id;if(!n)continue;let r={id:n};t.title&&(r.title=t.title),typeof t.focused==`boolean`&&(r.focused=t.focused);let a=t.pane_ref??t.pane_id;a&&(r.pane=a),t.selected_in_pane===!0&&(r.selected=!0),i.push(r)}return i}function bt(e,t){let n=yt(e);if(n.some(e=>e.id===t))return t;let r=n.filter(e=>e.pane===t);if(r.length!==0)return(r.find(e=>e.selected)??r[0])?.id}function xt(e,t,n){let r={id:e,tab:t??e};return n&&(r.workspace=n),r}function St(e,t,n,r,i,a){let o=Qe(r,i,a);o.kind===`dropped`&&process.stderr.write(`env (${o.variables.join(`, `)}) could not be set on this cmux surface — cmux has no --env flag on new-pane/new-surface, and its workspace --env is not adopted yet
|
|
23
|
+
`),o.command!==void 0&&e.submit(t,n,o.command)}const Ct={Enter:`enter`,Tab:`tab`,Escape:`escape`,Backspace:`backspace`,Space:`space`,Up:`up`,Down:`down`,Left:`left`,Right:`right`,"C-c":`ctrl+c`};function wt(e){return Ct[e]??e.toLowerCase()}function w(e){if(!Number.isFinite(e)||e<=0||e>=1)throw Error(`ratio must be strictly between 0 and 1 — got ${e}`)}function Tt(e){return e===``?0:(e.endsWith(`
|
|
24
24
|
`)?e.slice(0,-1):e).split(`
|
|
25
|
-
`).length}function
|
|
26
|
-
`):i.command!==void 0&&
|
|
27
|
-
`),o.command!==void 0&&e.submit(t,n,o.command)}const
|
|
25
|
+
`).length}function Et(e,t){return Tt(t)>Tt(e)}const Dt=1e6,Ot=e=>e.x+e.width,kt=e=>e.y+e.height,At={direction:`right`,start:e=>e.x,end:Ot},jt={direction:`down`,start:e=>e.y,end:kt};function Mt(e,t){let n=[...new Set(e.map(e=>t.start(e.rect)))].sort((e,t)=>e-t);for(let r of n){let n=e.filter(e=>t.end(e.rect)<=r),i=e.filter(e=>t.start(e.rect)>=r);if(n.length!==0&&i.length!==0&&n.length+i.length===e.length)return{direction:t.direction,ratio:Nt(e,i,t),first:n,second:i}}}function Nt(e,t,n){let r=Pt(e,n);return r<=0?.5:1-Pt(t,n)/r}function Pt(e,t){let n=e.map(e=>t.start(e.rect)),r=e.map(e=>t.end(e.rect));return Math.max(...r)-Math.min(...n)}function Ft(e){if(e.length===1)return{type:`pane`,pane:e[0]};let t=Mt(e,At)??Mt(e,jt);if(!t)throw Error(`this region's panes do not form a splittable tree (${e.length} panes: ${e.map(e=>e.id).join(`, `)}) — export can only capture a region built by splitting`);return{type:`split`,direction:t.direction,ratio:t.ratio,first:Ft(t.first),second:Ft(t.second)}}function It(e,t){if(!e.some(e=>e.id===t))throw Error(`pane ${t} is not in the region described (${e.map(e=>e.id).join(`, `)})`);let n=Ft(e);for(;n.type===`split`;){let e=n,r=Lt(e.first,t),i=r?e.first:e.second,a=r?e.second:e.first;if(i.type!==`pane`){n=i;continue}let o=e.direction===`right`?At:jt;return{direction:e.direction,targetIsFirst:r,firstRatio:e.ratio,extent:Pt(Rt(e),o),targetExtent:Pt([i.pane],o),otherExtent:Pt(Rt(a),o)}}}function Lt(e,t){return Rt(e).some(e=>e.id===t)}function Rt(e){return e.type===`pane`?[e.pane]:[...Rt(e.first),...Rt(e.second)]}function zt(e){try{return o.native(e)}catch{return g(e)}}const T=Je({name:`herdr`,canSizeSplits:!0,canZoomPanes:!0,canMovePanes:!0,canBreakPanes:!0,focusOnOpen:`preserved`,open(e,t){let n=t.at??`tab`,r=t.label?[`--label`,t.label]:[],i=Gt(t.env),a;if(n===`workspace`){let n=e(`herdr`,[`workspace`,`create`,`--cwd`,t.cwd,...r,...i,`--no-focus`]);if(!n)throw Error(x(e,`herdr workspace create failed`));a=an(n,`herdr workspace create`)}else if(n===`tab`){let n=e(`herdr`,[`tab`,`create`,...t.within?[`--workspace`,t.within]:[],`--cwd`,t.cwd,...r,...i,`--no-focus`]);if(!n)throw Error(x(e,`herdr tab create failed`));a=an(n,`herdr tab create`)}else if(n===`pane:float`)tt(T.name);else{let r=n===`pane:down`?`down`:`right`,o=t.from?[t.from.id]:[`--current`],s=t.ratio==null?[]:[`--ratio`,Jt(t.ratio)],c=e(`herdr`,[`pane`,`split`,...o,`--direction`,r,`--cwd`,t.cwd,...s,...i,`--no-focus`]);if(!c)throw Error(x(e,`herdr pane split failed`));a=Xt(c),t.label&&T.rename(e,a,`pane`,t.label)}return t.launch&&T.submit(e,a,t.launch),a},rename(e,t,n,r){e(`herdr`,[n,`rename`,t.id,r])},group(){},worktree:rn(),sendText(e,t,n){e(`herdr`,[`pane`,`send-text`,t.id,n])},sendKeys(e,t,n){e(`herdr`,[`pane`,`send-keys`,t.id,...n])},submit(e,t,n){n?e(`herdr`,[`pane`,`run`,t.id,n]):e(`herdr`,[`pane`,`send-keys`,t.id,`Enter`])},read(e,t,n){if(n?.lines===`all`){let r=dn(e,t,`recent`,Dt);return n.truncation?{text:r,truncated:!1}:{text:r}}let r=dn(e,t,`visible`,n?.lines);return n?.truncation?{text:r,truncated:Et(r,dn(e,t,`recent`,Tt(r)+1))}:{text:r}},async waitForOutput(e,t,n){ct(n);let r=n.now??(()=>Date.now()),i=n.match==null?[`--regex`,n.regex]:[`--match`,n.match],a=[`pane`,`wait-output`,t.id,`--source`,`visible`,`--timeout`,String(n.timeoutMs)];a.push(...i),n.lines!=null&&a.push(`--lines`,String(n.lines));let o=r(),s=e(`herdr`,a);if(s==null){if(!$t(e,t,n.timeoutMs,r()-o))throw Error(x(e,`herdr pane wait-output failed for pane ${t.id}`));let i=n.lines==null?void 0:{lines:n.lines};return{matched:!1,output:T.read(e,t,i).text}}return tn(s)},focus(e,t){let{workspaceId:n,tabId:r}=nn(e(`herdr`,[`pane`,`get`,t.id]),t.id);e(`herdr`,[`workspace`,`focus`,n]),e(`herdr`,[`tab`,`focus`,r])},teardown(e,t){e(`herdr`,[`pane`,`close`,t.id])},paneExists(e,t){return e(`herdr`,[`pane`,`read`,t.id,`--source`,`visible`])!==null},isPaneFocused(e,t){let n=e(`herdr`,[`pane`,`get`,t.id]);if(n!=null)try{let e=JSON.parse(n)?.result?.pane?.focused;return typeof e==`boolean`?e:void 0}catch{return}},setPaneZoom(e,t,n){if(T.isPaneZoomed(e,t)!==n&&e(`herdr`,[`pane`,`zoom`,t.id,n?`--on`:`--off`])==null)throw Error(x(e,`herdr could not ${n?`zoom`:`unzoom`} pane ${t.id}`))},isPaneZoomed(e,t){let n=e(`herdr`,[`pane`,`layout`,`--pane`,t.id]);if(n!=null)try{let e=JSON.parse(n)?.result?.layout;return typeof e?.zoomed==`boolean`?e.zoomed===!0&&e.focused_pane_id===t.id:void 0}catch{return}},movePane(e,t,n,r){let{tabId:i}=Zt(e(`herdr`,[`pane`,`get`,n.id]));if(!i)throw Error(`herdr could not resolve the tab of destination pane ${n.id}`);let a=e(`herdr`,[`pane`,`move`,t.id,`--tab`,i,`--split`,r,`--target-pane`,n.id,`--no-focus`]);if(!a)throw Error(x(e,`herdr could not move pane ${t.id} to ${n.id}`));return cn(a,`herdr pane move`)},breakPane(e,t,n){let r=e(`herdr`,[`pane`,`move`,t.id,n===`workspace`?`--new-workspace`:`--new-tab`,`--no-focus`]);if(!r)throw Error(x(e,`herdr could not break out pane ${t.id} into its own ${n}`));return cn(r,`herdr pane move`)},listPanes(e){let t=e(`herdr`,[`pane`,`list`]);if(!t)return[];let n;try{n=JSON.parse(t)?.result?.panes}catch{return[]}return Array.isArray(n)?n.filter(e=>typeof e?.pane_id==`string`).map(e=>{let t=e.agent||void 0,n=e.label||void 0,r=Vt(e.agent_status);return{id:e.pane_id,mux:`herdr`,floating:!1,...t===void 0?{}:{harness:t},...r===void 0?{}:{agentStatus:r},...e.cwd===void 0?{}:{cwd:e.cwd},...n===void 0?{}:{label:n}}}):[]},regions:{describeRegion(e,t){return Ut(e,t.id,Wt(e))},resizePane(e,t,n){let r=It(Ut(e,t.id,Wt(e)),t.id);if(!r)throw Error(`herdr pane ${t.id} is the only pane in its region — there is no split to resize`);let i=Kt(r,n);if(i===0)return;let a=qt(r.direction,i);if(e(`herdr`,[`pane`,`resize`,`--pane`,t.id,`--direction`,a,`--amount`,String(Math.abs(i))])===null)throw Error(x(e,`herdr could not resize pane ${t.id}`))},describeWorkspace(e,t){let{workspaceId:n}=Zt(e(`herdr`,[`pane`,`get`,t.id]));if(!n)throw Error(x(e,`herdr could not resolve the workspace around pane ${t.id}`));let r=e(`herdr`,[`tab`,`list`,`--workspace`,n]);if(!r)throw Error(x(e,`herdr could not enumerate the tabs of workspace ${n}`));let i;try{i=JSON.parse(r)?.result?.tabs}catch{throw Error(`herdr tab list returned unparseable output: ${r.slice(0,200)}`)}if(!Array.isArray(i)||i.length===0)throw Error(`herdr reported no tabs in workspace ${n}: ${r.slice(0,200)}`);let a=Wt(e,n),o=[];for(let t of i){if(typeof t?.tab_id!=`string`)continue;let r=t.tab_id,i=[...a].find(([,e])=>e.tab===r)?.[0];if(!i)throw Error(`herdr reported no panes in tab ${r} of workspace ${n}`);let s={id:r,panes:Ut(e,i,a)};typeof t.label==`string`&&t.label!==``&&(s.label=t.label),o.push(s)}if(o.length===0)throw Error(`herdr reported no usable tabs in workspace ${n}: ${r.slice(0,200)}`);return o}},agentLifecycle:{waitForState(e,t,n){let r=n.until??[],i=Ht(e(`herdr`,[`agent`,`wait`,t.id,...r.flatMap(e=>[`--until`,e]),...n.timeoutMs==null?[]:[`--timeout`,String(n.timeoutMs)]]));if(!i)throw Error(x(e,`herdr agent wait reported no reached agent_status for pane ${t.id}`));return i}}}),Bt=[`idle`,`working`,`blocked`,`done`,`unknown`];function Vt(e){return typeof e==`string`&&Bt.includes(e)?e:void 0}function Ht(e){if(e!=null)try{return Vt(JSON.parse(e)?.result?.agent?.agent_status)}catch{return}}function Ut(e,t,n){let r=e(`herdr`,[`pane`,`layout`,`--pane`,t]);if(!r)throw Error(x(e,`herdr could not describe the region around pane ${t}`));let i;try{i=JSON.parse(r)?.result?.layout?.panes}catch{throw Error(`herdr pane layout returned unparseable output: ${r.slice(0,200)}`)}if(!Array.isArray(i)||i.length===0)throw Error(`herdr pane layout reported no panes for ${t}: ${r.slice(0,200)}`);return i.filter(e=>typeof e?.pane_id==`string`).map(e=>{let t=n.get(e.pane_id),r={id:e.pane_id,rect:{x:e.rect?.x??0,y:e.rect?.y??0,width:e.rect?.width??0,height:e.rect?.height??0}};return t?.cwd&&(r.cwd=t.cwd),t?.label&&(r.label=t.label),r})}function Wt(e,t){let n=/* @__PURE__ */ new Map,r=e(`herdr`,[`pane`,`list`,...t?[`--workspace`,t]:[]]);if(!r)return n;let i;try{i=JSON.parse(r)?.result?.panes}catch{return n}if(!Array.isArray(i))return n;for(let e of i)typeof e?.pane_id==`string`&&n.set(e.pane_id,{cwd:e.cwd,label:e.label,tab:e.tab_id});return n}function Gt(e){return e?Object.entries(e).flatMap(([e,t])=>[`--env`,`${e}=${t}`]):[]}function Kt(e,t){w(t);let n=(e.targetIsFirst?t:1-t)-e.firstRatio;return Math.round(n*1e6)/1e6}function qt(e,t){return e===`right`?t>0?`right`:`left`:t>0?`down`:`up`}function Jt(e){return w(e),String(e)}function Yt(e,t,n,r){let i=Ze(n,r);i.kind===`dropped`?process.stderr.write(`env (${i.variables.join(`, `)}) could not be set on this worktree's workspace and no command was given to carry it — herdr worktree create/open take no env parameter
|
|
26
|
+
`):i.command!==void 0&&T.submit(e,t,i.command)}function Xt(e){return on(e,`herdr pane split`,`pane`)}function Zt(e){if(e==null)return{};try{let t=JSON.parse(e)?.result?.pane;return{workspaceId:Qt(t?.workspace_id),tabId:Qt(t?.tab_id)}}catch{return{}}}function Qt(e){return typeof e==`string`&&e!==``?e:void 0}function $t(e,t,n,r){let i=en(e.lastError);return i==null?r<n*.9?!1:T.paneExists(e,t):i===`timeout`}function en(e){if(e)try{return Qt(JSON.parse(e)?.error?.code)}catch{return}}function tn(e){let t,n;try{let r=JSON.parse(e)?.result;t=Qt(r?.read?.text),n=Qt(r?.matched_line)}catch{}return{matched:!0,output:t??``,...n==null?{}:{matchedLine:n}}}function nn(e,t){let{workspaceId:n,tabId:r}=Zt(e);if(!n||!r)throw Error(`peer's pane ${t} could not be resolved to beam to`);return{workspaceId:n,tabId:r}}function rn(){return{createInWorkspace(e,t){let n=[`worktree`,`create`,`--cwd`,t.primaryRoot,`--branch`,t.branch,`--path`,t.path];t.base&&n.push(`--base`,t.base),t.label&&n.push(`--label`,t.label),n.push(`--no-focus`);let r=e(`herdr`,n);if(!r)throw Error(x(e,`herdr worktree create failed`));let i=ln(r,`herdr worktree create`);return Yt(e,i.target,t.env,t.launch),i},openInWorkspace(e,t){let n=[`worktree`,`open`,`--cwd`,t.primaryRoot,`--path`,t.path];t.label&&n.push(`--label`,t.label),n.push(`--no-focus`);let r=e(`herdr`,n);if(!r)throw Error(x(e,`herdr worktree open failed`));let i=ln(r,`herdr worktree open`);return Yt(e,i.target,t.env,t.launch),i},bindings(e,t){return un(e(`herdr`,[`worktree`,`list`,`--cwd`,t.primaryRoot]))},releaseWorkspace(e,t,n){(n?.group===!1||e(`herdr`,[`workspace`,`close`,t,`--group`])===null)&&e(`herdr`,[`workspace`,`close`,t])}}}function an(e,t){return on(e,t,`root_pane`)}function on(e,t,n){let r;try{r=JSON.parse(e)?.result?.[n]}catch{throw Error(`${t} returned unparseable output: ${e.slice(0,200)}`)}return sn(r,e,t,n)}function sn(e,t,n,r){let i=e?.pane_id;if(typeof i!=`string`||i===``)throw Error(`${n} output had no result.${r}.pane_id: ${t.slice(0,200)}`);let a=e?.tab_id;if(typeof a!=`string`||a===``)throw Error(`${n} output had no result.${r}.tab_id: ${t.slice(0,200)}`);let o=e?.workspace_id;return typeof o==`string`&&o!==``?{id:i,tab:a,workspace:o}:{id:i,tab:a}}function cn(e,t){let n;try{n=JSON.parse(e)?.result?.move_result?.pane}catch{throw Error(`${t} returned unparseable output: ${e.slice(0,200)}`)}return sn(n,e,t,`move_result.pane`)}function ln(e,t){let n;try{n=JSON.parse(e)}catch{throw Error(`${t} returned unparseable output: ${e.slice(0,200)}`)}let r=n?.result,i=on(e,t,`root_pane`),a=r?.workspace?.workspace_id,o=r?.worktree?.path,s=r?.worktree?.branch;if(typeof o!=`string`||o===``||typeof s!=`string`||s===``)throw Error(`${t} output had no result.worktree.{path,branch}: ${e.slice(0,200)}`);if(typeof a!=`string`||a===``)throw Error(`${t} output had no result.workspace.workspace_id: ${e.slice(0,200)}`);return{target:i,worktree:{root:g(o),branch:s},workspace:a}}function un(e){let t=/* @__PURE__ */ new Map;if(!e)return t;let n;try{n=JSON.parse(e)}catch{return t}let r=n?.result?.worktrees??[];if(!Array.isArray(r))return t;for(let e of r){let n=e?.path,r=e?.open_workspace_id;typeof n==`string`&&n!==``&&typeof r==`string`&&r!==``&&t.set(zt(n),r)}return t}function dn(e,t,n,r){let i=[`pane`,`read`,t.id,`--source`,n];return r!=null&&i.push(`--lines`,String(r)),e(`herdr`,i)??``}var fn=class extends Error{backend;requested;supported;constructor(e,t,n){super(`${e} can only end an agent wait on ${n.join(`, `)} — asked for ${t.join(`, `)}`),this.backend=e,this.requested=t,this.supported=n,this.name=`AgentWaitStatesUnsupportedError`}};function pn(e,t,n){throw new fn(e,t,n)}function mn(e,t){return!e||e.length===0||e.every(e=>t.includes(e))}function hn(e){let t={name:`otty`,canSizeSplits:!0,focusOnOpen:`restored`,open(n,r){let i=r.at??`tab`;return i===`pane:float`&&tt(t.name),r.ratio!=null&&w(r.ratio),nt({read:()=>rt(_n(n),e=>e.is_focused,e=>e.id),restore:e=>t.focus(n,{id:e})},()=>{if(i===`workspace`){let e=[`open`];r.label&&e.push(`--title`,r.label),r.cwd&&e.push(r.cwd);let i=n(`otty`,e);if(!i)throw Error(x(n,`otty open failed`));let a=gn(i);if(!a.window_id)throw Error(`otty open did not report the window id`);let o=a.pane_id;if(!o)throw Error(`otty open did not report the initial pane id`);let s=vn(o,a.tab_id,a.window_id);return yn(t,n,s,r.env,r.launch),s}if(i===`tab`){let i=[`tab`,`new`];r.label&&i.push(`--title`,r.label);let a=n(`otty`,i);if(!a)throw Error(x(n,`otty tab new failed`));let o=gn(a),s=o.pane_id;if(!s)throw Error(`otty tab new did not report the pane id`);let c=vn(s,o.tab_id,e.window);return yn(t,n,c,r.env,r.launch,r.cwd),c}r.from&&t.focus(n,r.from);let a=[`pane`,`split`,`--direction`,i===`pane:down`?`down`:`right`];if(r.cwd&&a.push(`--cwd`,r.cwd),r.ratio!=null){let{size:e,requested:t}=Sn(r.ratio);e!==t&&process.stderr.write(`otty sizes a split between 10% and 90% — ratio ${r.ratio} asked for a ${t}% new pane, so ${e}% was used instead\n`),a.push(`--size`,String(e))}let o=n(`otty`,a);if(!o)throw Error(x(n,`otty pane split failed`));let s=gn(o),c=s.pane_id;if(!c)throw Error(`otty pane split did not report the pane id`);let l=vn(c,s.tab_id,e.window);return r.label&&process.stderr.write(`otty cannot name a pane — "${r.label}" was not set on pane ${l.id}\n`),yn(t,n,l,r.env,r.launch),l})},rename(e,t,n,r){if(n===`tab`)e(`otty`,[`tab`,`rename`,`--tab`,t.id,`--title`,r]);else throw Error(`otty cannot name a pane (only a window or tab) — asked to rename ${t.id}`)},group(){},sendText(e,t,n){e(`otty`,[`pane`,`send-keys`,`--pane`,t.id,`--`,n])},sendKeys(e,t,n){let r=n.map(e=>`key:${wn(e)}`);e(`otty`,[`pane`,`send-keys`,`--pane`,t.id,`--`,...r])},submit(e,n,r){r?e(`otty`,[`pane`,`send-keys`,`--pane`,n.id,`--`,r,`key:Enter`]):t.sendKeys(e,n,[`Enter`])},read(e,t,n){let r=[`pane`,`capture`,`--pane`,t.id];return n?.lines!=null&&r.push(`--lines`,String(n.lines)),{text:e(`otty`,r)??``}},waitForOutput(e,n,r){return ut(t,e,n,r)},focus(e,t){e(`otty`,[`pane`,`focus`,`--pane`,t.id])},teardown(e,t){e(`otty`,[`pane`,`close`,`--pane`,t.id])},paneExists(e,t){return _n(e).some(e=>e.id===t.id)},isPaneFocused(e,t){let n=_n(e).find(e=>e.id===t.id);if(n)return typeof n.is_focused==`boolean`?n.is_focused:void 0},setPaneZoom(){pt(`otty`)},isPaneZoomed(){},movePane(){ot(`otty`)},breakPane(){st(`otty`)},listPanes(e){return _n(e).map(e=>{let t={id:e.id,mux:`otty`,floating:!1};return e.cwd&&(t.cwd=e.cwd),e.title&&(t.label=e.title),t})},agentLifecycle:{waitForState(e,n,r){mn(r.until,bn)||pn(t.name,r.until??[],bn);let i=[`pane`,`wait`,`--pane`,n.id];if(r.timeoutMs!=null&&i.push(`--timeout-secs`,String(xn(r.timeoutMs))),e(`otty`,i)===null)throw Error(x(e,`otty pane wait did not reach idle for pane ${n.id}`));return`idle`}}};return Je(t)}hn({});function gn(e){try{return JSON.parse(e)}catch{return{}}}function _n(e){let t=e(`otty`,[`panes`,`--json`]);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return[]}if(!Array.isArray(n))return[];let r=[];for(let e of n)e?.pane_id&&r.push({id:e.pane_id,title:e.title,cwd:e.cwd,is_focused:e.is_focused});return r}function vn(e,t,n){let r={id:e,tab:t??e};return n&&(r.workspace=n),r}function yn(e,t,n,r,i,a){let o=Qe(r,i,a);o.kind===`dropped`&&process.stderr.write(`env (${o.variables.join(`, `)}) could not be set on this otty pane — otty has no --env flag on pane split/tab new/open
|
|
27
|
+
`),o.command!==void 0&&e.submit(t,n,o.command)}const bn=[`idle`];function xn(e){return Math.max(1,Math.ceil(e/1e3))}function Sn(e){w(e);let t=Math.round((1-e)*100);return{requested:t,size:Math.min(90,Math.max(10,t))}}const Cn={"C-c":`Ctrl+c`};function wn(e){return Cn[e]??e}const Tn=`@cm_ws`,En=`@cm_tab`,Dn=Je({name:`rmux`,canSizeSplits:!0,canZoomPanes:!0,canMovePanes:!0,canBreakPanes:!0,focusOnOpen:`preserved`,open(e,t){let n=t.at??`tab`,r=n===`workspace`||n===`tab`;n===`pane:float`&&tt(Dn.name);let i=t.env?Object.entries(t.env).flatMap(([e,t])=>[`-e`,`${e}=${t}`]):[],a=r&&t.workspaceGroup!=null,o=`#{pane_id} #{window_id}`,s;if(r)s=[`new-window`,`-d`,...i,`-c`,t.cwd,`-P`,`-F`,o];else{let e=t.from?[`-t`,t.from.id]:[],r=t.ratio==null?[]:[`-l`,Pn(t.ratio)];s=[`split-window`,`-d`,n===`pane:down`?`-v`:`-h`,...e,...r,...i,`-c`,t.cwd,`-P`,`-F`,o]}r&&t.label&&s.splice(1,0,`-n`,t.label);let c=e(`rmux`,s);if(!c)throw Error(x(e,`rmux ${s[0]} failed`));let[l,u]=jn(c,s[0]),d={id:l,tab:u};return a&&u&&Dn.group(e,{id:u},t.workspaceGroup),!r&&t.label&&Dn.rename(e,d,`pane`,t.label),t.launch&&Dn.submit(e,d,t.launch),d},rename(e,t,n,r){n===`tab`?e(`rmux`,[`rename-window`,`-t`,t.id,r]):e(`rmux`,[`select-pane`,`-t`,t.id,`-T`,r])},group(e,t,n,r){e(`rmux`,[`set-option`,`-w`,`-t`,t.id,Tn,n]),r!==void 0&&e(`rmux`,[`set-option`,`-w`,`-t`,t.id,En,r])},sendText(e,t,n){e(`rmux`,[`send-keys`,`-t`,t.id,`-l`,n])},sendKeys(e,t,n){e(`rmux`,[`send-keys`,`-t`,t.id,...n.map(Ln)])},submit(e,t,n){n&&Dn.sendText(e,t,n),e(`rmux`,[`send-keys`,`-t`,t.id,`Enter`])},read(e,t,n){let r=In(e,t,n?.lines);return n?.truncation?n.lines===`all`?{text:r,truncated:!1}:{text:r,truncated:Et(r,In(e,t,(n.lines??0)+1))}:{text:r}},waitForOutput(e,t,n){return ut(Dn,e,t,n)},focus(e,t){let{sessionName:n,windowId:r}=Rn(e(`rmux`,[`list-panes`,`-a`,`-F`,`#{pane_id} #{session_name} #{window_id}`]),t.id);e(`rmux`,[`switch-client`,`-t`,n]),e(`rmux`,[`select-window`,`-t`,r]),e(`rmux`,[`select-pane`,`-t`,t.id])},teardown(e,t){e(`rmux`,[`kill-pane`,`-t`,t.id])},paneExists(e,t){return e(`rmux`,[`has-session`,`-t`,t.id])!==null||(e(`rmux`,[`list-panes`,`-a`,`-F`,`#{pane_id}`])??``).split(`
|
|
28
28
|
`).includes(t.id)},isPaneFocused(e,t){let n=e(`rmux`,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_active} #{window_active} #{session_attached}`]);if(!n)return;let r=n.split(`
|
|
29
|
-
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a,o]=r.split(` `);if(i!==void 0&&a!==void 0&&o!==void 0)return i===`1`&&a===`1`&&o!==`0`},setPaneZoom(e,t,n){if(
|
|
30
|
-
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a]=r.split(` `);return i===`1`&&a===`1`},movePane(e,t,n,r){if(e(`rmux`,[`move-pane`,`-d`,r===`down`?`-v`:`-h`,`-s`,t.id,`-t`,n.id])===null)throw Error(
|
|
31
|
-
`).filter(Boolean).map(e=>{let[t,,n,r,i]=e.split(` `),a={id:t??``,mux:`rmux`,floating:!1};n&&(a.cwd=n);let o=
|
|
32
|
-
`)[0].split(` `);if(!r)throw Error(`rmux did not report the window around pane ${t.id}`);if(!i)return[
|
|
33
|
-
`).filter(Boolean).map(e=>e.split(` `)).filter(([e])=>!!e).map(([t,n,...r])=>
|
|
34
|
-
`).filter(Boolean)){let[t,n,i,a,o,s,c,l]=e.split(` `);if(!t)continue;let u={id:t,rect:{x:Number(n),y:Number(i),width:Number(a),height:Number(o)}};s&&(u.cwd=s);let d=
|
|
35
|
-
`).find(e=>e.split(` `)[0]===t);if(!r)throw Error(`rmux could not resolve pane ${t} after the ${n}`);let[,i]=r.split(` `);if(!i)throw Error(`rmux did not report a window for pane ${t} after the ${n}`);return{id:t,tab:i}}function
|
|
36
|
-
`).find(e=>e.split(` `)[0]===t);if(!n)throw Error(`peer's pane ${t} could not be resolved to beam to`);let[,r,i]=n.split(` `);return{sessionName:r,windowId:i}}const
|
|
37
|
-
`).includes(t.id)},isPaneFocused(e,t){let n=
|
|
38
|
-
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a,o]=r.split(` `);if(i!==void 0&&a!==void 0&&o!==void 0)return i===`1`&&a===`1`&&o!==`0`},setPaneZoom(e,t,n){if(
|
|
39
|
-
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a]=r.split(` `);return i===`1`&&a===`1`},movePane(e,t,n,r){if(
|
|
40
|
-
`).filter(Boolean).map(e=>{let[t,,n,r,i,a]=e.split(` `),o={id:t??``,mux:`tmux`,floating:a===`1`};n&&(o.cwd=n);let s=
|
|
41
|
-
`)[0].split(` `);if(!r)throw Error(`tmux did not report the window around pane ${t.id}`);if(!i)return[
|
|
42
|
-
`).filter(Boolean).map(e=>e.split(` `)).filter(([e])=>!!e).map(([t,n,...r])=>
|
|
43
|
-
`).filter(Boolean)){let[t,n,i,a,o,s,c,l]=e.split(` `);if(!t)continue;let u={id:t,rect:{x:Number(n),y:Number(i),width:Number(a),height:Number(o)}};s&&(u.cwd=s);let d=
|
|
44
|
-
`).find(e=>e.split(` `)[0]===t);if(!r)throw Error(`tmux could not resolve pane ${t} after the ${n}`);let[,i]=r.split(` `);if(!i)throw Error(`tmux did not report a window for pane ${t} after the ${n}`);return{id:t,tab:i}}function
|
|
45
|
-
`).find(e=>e.split(` `)[0]===t);if(!n)throw Error(`peer's pane ${t} could not be resolved to beam to`);let[,r,i]=n.split(` `);return{sessionName:r,windowId:i}}const
|
|
46
|
-
`):a.command!==void 0&&e.submit(t,n,a.command)}function
|
|
47
|
-
`)[1];if(n===void 0)return;let r=n.trim().split(/\s+/)[1];if(r)return r}}function
|
|
48
|
-
`):a.command!==void 0&&e.submit(t,n,a.command)}const
|
|
29
|
+
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a,o]=r.split(` `);if(i!==void 0&&a!==void 0&&o!==void 0)return i===`1`&&a===`1`&&o!==`0`},setPaneZoom(e,t,n){if(Dn.isPaneZoomed(e,t)!==n){if(n&&e(`rmux`,[`select-pane`,`-t`,t.id])===null)throw Error(x(e,`rmux could not select pane ${t.id}`));if(e(`rmux`,[`resize-pane`,`-Z`,`-t`,t.id])===null)throw Error(x(e,`rmux could not ${n?`zoom`:`unzoom`} pane ${t.id}`))}},isPaneZoomed(e,t){let n=e(`rmux`,[`list-panes`,`-a`,`-F`,`#{pane_id} #{window_zoomed_flag} #{pane_active}`]);if(!n)return;let r=n.split(`
|
|
30
|
+
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a]=r.split(` `);return i===`1`&&a===`1`},movePane(e,t,n,r){if(e(`rmux`,[`move-pane`,`-d`,r===`down`?`-v`:`-h`,`-s`,t.id,`-t`,n.id])===null)throw Error(x(e,`rmux could not move pane ${t.id} to ${n.id}`));return Mn(e,t.id,`move`)},breakPane(e,t,n){let r=e(`rmux`,[`break-pane`,`-d`,`-s`,t.id,`-P`,`-F`,`#{pane_id} #{window_id}`]);if(!r)throw Error(x(e,`rmux could not break out pane ${t.id}`));let[i,a]=r.trim().split(` `);if(!i||!a)throw Error(`rmux break-pane did not report the pane and window of ${t.id}`);return{id:i,tab:a}},listPanes(e){let t=e(`rmux`,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_current_command} #{pane_current_path} #{pane_title} #{host}`]);return t?t.split(`
|
|
31
|
+
`).filter(Boolean).map(e=>{let[t,,n,r,i]=e.split(` `),a={id:t??``,mux:`rmux`,floating:!1};n&&(a.cwd=n);let o=An(r,i);return o&&(a.label=o),a}).filter(e=>e.id!==``):[]},regions:{describeRegion(e,t){return kn(e,t.id)},resizePane(e,t,n){let r=It(kn(e,t.id),t.id);if(!r)throw Error(`rmux pane ${t.id} is the only pane in its region — there is no split to resize`);let i=r.direction===`right`?`-x`:`-y`;if(e(`rmux`,[`resize-pane`,`-t`,t.id,i,String(Nn(r,n))])===null)throw Error(x(e,`rmux could not resize pane ${t.id}`))},describeWorkspace(e,t){let n=e(`rmux`,[`display-message`,`-p`,`-t`,t.id,`#{window_id}\t#{${Tn}}\t#{${En}}\t#{window_name}`]);if(!n)throw Error(x(e,`rmux could not resolve the workspace around pane ${t.id}`));let[r,i,a,...o]=n.split(`
|
|
32
|
+
`)[0].split(` `);if(!r)throw Error(`rmux did not report the window around pane ${t.id}`);if(!i)return[On(e,r,a,o.join(` `))];let s=e(`rmux`,[`list-windows`,`-a`,`-F`,`#{window_id}\t#{${En}}\t#{window_name}`,`-f`,`#{==:#{${Tn}},${i}}`]);if(!s)throw Error(x(e,`rmux could not enumerate the windows grouped as ${i}`));let c=s.split(`
|
|
33
|
+
`).filter(Boolean).map(e=>e.split(` `)).filter(([e])=>!!e).map(([t,n,...r])=>On(e,t,n,r.join(` `)));if(c.length===0)throw Error(`rmux reported no windows grouped as ${i}`);return c}}});function On(e,t,n,r){let i={id:t,panes:kn(e,t)},a=n||r;return a&&(i.label=a),i}function kn(e,t){let n=e(`rmux`,[`list-panes`,`-t`,t,`-F`,`#{pane_id} #{pane_left} #{pane_top} #{pane_width} #{pane_height} #{pane_current_path} #{pane_title} #{host}`]);if(!n)throw Error(x(e,`rmux could not describe the region around pane ${t}`));let r=[];for(let e of n.split(`
|
|
34
|
+
`).filter(Boolean)){let[t,n,i,a,o,s,c,l]=e.split(` `);if(!t)continue;let u={id:t,rect:{x:Number(n),y:Number(i),width:Number(a),height:Number(o)}};s&&(u.cwd=s);let d=An(c,l);d&&(u.label=d),r.push(u)}if(r.length===0)throw Error(`rmux reported no panes in the region around pane ${t}`);return r}function An(e,t){return e&&e!==t?e:void 0}function jn(e,t){let[n,r]=e.split(` `);if(!n||!r)throw Error(`rmux ${t} did not report the new pane's id and window id`);return[n,r]}function Mn(e,t,n){let r=(e(`rmux`,[`list-panes`,`-a`,`-F`,`#{pane_id} #{window_id}`])??``).split(`
|
|
35
|
+
`).find(e=>e.split(` `)[0]===t);if(!r)throw Error(`rmux could not resolve pane ${t} after the ${n}`);let[,i]=r.split(` `);if(!i)throw Error(`rmux did not report a window for pane ${t} after the ${n}`);return{id:t,tab:i}}function Nn(e,t){w(t);let n=Math.round((e.targetIsFirst?1-t:t)*e.extent);if(!e.targetIsFirst)return n;let r=e.extent-e.targetExtent-e.otherExtent;return e.extent-r-n}function Pn(e){return w(e),`${Math.round((1-e)*100)}%`}const Fn={Backspace:`BSpace`};function In(e,t,n){let r=[`capture-pane`,`-p`,`-t`,t.id];return n===`all`?r.push(`-S`,`-`):n!=null&&r.push(`-S`,`-${n}`),e(`rmux`,r)??``}function Ln(e){return Fn[e]??e}function Rn(e,t){let n=(e??``).split(`
|
|
36
|
+
`).find(e=>e.split(` `)[0]===t);if(!n)throw Error(`peer's pane ${t} could not be resolved to beam to`);let[,r,i]=n.split(` `);return{sessionName:r,windowId:i}}const zn=`@cm_ws`,Bn=`@cm_tab`;function E(e,t){return e(`tmux`,[`-u`,...t])}const D=Je({name:`tmux`,canSizeSplits:!0,canFloatPanes:!0,canZoomPanes:!0,canMovePanes:!0,canBreakPanes:!0,focusOnOpen:`preserved`,open(e,t){let n=t.at??`tab`,r=n===`workspace`||n===`tab`,i=t.env?Object.entries(t.env).flatMap(([e,t])=>[`-e`,`${e}=${t}`]):[],a=r&&t.workspaceGroup!=null,o=`#{pane_id} #{window_id}`,s;if(n===`pane:float`)s=[`new-pane`,`-d`,...t.from?[`-t`,t.from.id]:[],...i,`-c`,t.cwd,`-P`,`-F`,o];else if(r)s=[`new-window`,`-d`,...i,`-c`,t.cwd,`-P`,`-F`,o];else{let e=t.from?[`-t`,t.from.id]:[],r=t.ratio==null?[]:[`-l`,qn(t.ratio)];s=[`split-window`,`-d`,n===`pane:down`?`-v`:`-h`,...e,...r,...i,`-c`,t.cwd,`-P`,`-F`,o]}r&&t.label&&s.splice(1,0,`-n`,t.label);let c=E(e,s);if(!c)throw Error(x(e,`tmux ${s[0]} failed`));let[l,u]=Wn(c,s[0]),d={id:l,tab:u};return a&&u&&D.group(e,{id:u},t.workspaceGroup),!r&&t.label&&D.rename(e,d,`pane`,t.label),t.launch&&D.submit(e,d,t.launch),d},rename(e,t,n,r){n===`tab`?E(e,[`rename-window`,`-t`,t.id,r]):E(e,[`select-pane`,`-t`,t.id,`-T`,r])},group(e,t,n,r){E(e,[`set-option`,`-w`,`-t`,t.id,zn,n]),r!==void 0&&E(e,[`set-option`,`-w`,`-t`,t.id,Bn,r])},sendText(e,t,n){E(e,[`send-keys`,`-t`,t.id,`-l`,n])},sendKeys(e,t,n){E(e,[`send-keys`,`-t`,t.id,...n.map(Xn)])},submit(e,t,n){n&&D.sendText(e,t,n),E(e,[`send-keys`,`-t`,t.id,`Enter`])},read(e,t,n){let r=Yn(e,t,n?.lines);return n?.truncation?n.lines===`all`?{text:r,truncated:!1}:{text:r,truncated:Et(r,Yn(e,t,(n.lines??0)+1))}:{text:r}},waitForOutput(e,t,n){return ut(D,e,t,n)},focus(e,t){let{sessionName:n,windowId:r}=Zn(E(e,[`list-panes`,`-a`,`-F`,`#{pane_id} #{session_name} #{window_id}`]),t.id);E(e,[`switch-client`,`-t`,n]),E(e,[`select-window`,`-t`,r]),E(e,[`select-pane`,`-t`,t.id])},teardown(e,t){E(e,[`kill-pane`,`-t`,t.id])},paneExists(e,t){return E(e,[`has-session`,`-t`,t.id])!==null||(E(e,[`list-panes`,`-a`,`-F`,`#{pane_id}`])??``).split(`
|
|
37
|
+
`).includes(t.id)},isPaneFocused(e,t){let n=E(e,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_active} #{window_active} #{session_attached}`]);if(!n)return;let r=n.split(`
|
|
38
|
+
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a,o]=r.split(` `);if(i!==void 0&&a!==void 0&&o!==void 0)return i===`1`&&a===`1`&&o!==`0`},setPaneZoom(e,t,n){if(D.isPaneZoomed(e,t)!==n){if(n&&E(e,[`select-pane`,`-t`,t.id])===null)throw Error(x(e,`tmux could not select pane ${t.id}`));if(E(e,[`resize-pane`,`-Z`,`-t`,t.id])===null)throw Error(x(e,`tmux could not ${n?`zoom`:`unzoom`} pane ${t.id}`))}},isPaneZoomed(e,t){let n=E(e,[`list-panes`,`-a`,`-F`,`#{pane_id} #{window_zoomed_flag} #{pane_active}`]);if(!n)return;let r=n.split(`
|
|
39
|
+
`).find(e=>e.split(` `)[0]===t.id);if(!r)return;let[,i,a]=r.split(` `);return i===`1`&&a===`1`},movePane(e,t,n,r){if(E(e,[`move-pane`,`-d`,r===`down`?`-v`:`-h`,`-s`,t.id,`-t`,n.id])===null)throw Error(x(e,`tmux could not move pane ${t.id} to ${n.id}`));return Gn(e,t.id,`move`)},breakPane(e,t,n){let r=E(e,[`break-pane`,`-d`,`-s`,t.id,`-P`,`-F`,`#{pane_id} #{window_id}`]);if(!r)throw Error(x(e,`tmux could not break out pane ${t.id}`));let[i,a]=r.trim().split(` `);if(!i||!a)throw Error(`tmux break-pane did not report the pane and window of ${t.id}`);return{id:i,tab:a}},listPanes(e){let t=E(e,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_current_command} #{pane_current_path} #{pane_title} #{host} #{pane_floating_flag}`]);return t?t.split(`
|
|
40
|
+
`).filter(Boolean).map(e=>{let[t,,n,r,i,a]=e.split(` `),o={id:t??``,mux:`tmux`,floating:a===`1`};n&&(o.cwd=n);let s=Un(r,i);return s&&(o.label=s),o}).filter(e=>e.id!==``):[]},regions:{describeRegion(e,t){return Hn(e,t.id)},resizePane(e,t,n){let r=It(Hn(e,t.id),t.id);if(!r)throw Error(`tmux pane ${t.id} is the only pane in its region — there is no split to resize`);let i=r.direction===`right`?`-x`:`-y`,a=Kn(r,n);if(E(e,[`resize-pane`,`-t`,t.id,i,String(a)])===null)throw Error(x(e,`tmux could not resize pane ${t.id}`))},describeWorkspace(e,t){let n=E(e,[`display-message`,`-p`,`-t`,t.id,`#{window_id}\t#{${zn}}\t#{${Bn}}\t#{window_name}`]);if(!n)throw Error(x(e,`tmux could not resolve the workspace around pane ${t.id}`));let[r,i,a,...o]=n.split(`
|
|
41
|
+
`)[0].split(` `);if(!r)throw Error(`tmux did not report the window around pane ${t.id}`);if(!i)return[Vn(e,r,a,o.join(` `))];let s=E(e,[`list-windows`,`-a`,`-F`,`#{window_id}\t#{${Bn}}\t#{window_name}`,`-f`,`#{==:#{${zn}},${i}}`]);if(!s)throw Error(x(e,`tmux could not enumerate the windows grouped as ${i}`));let c=s.split(`
|
|
42
|
+
`).filter(Boolean).map(e=>e.split(` `)).filter(([e])=>!!e).map(([t,n,...r])=>Vn(e,t,n,r.join(` `)));if(c.length===0)throw Error(`tmux reported no windows grouped as ${i}`);return c}}});function Vn(e,t,n,r){let i={id:t,panes:Hn(e,t)},a=n||r;return a&&(i.label=a),i}function Hn(e,t){let n=E(e,[`list-panes`,`-t`,t,`-F`,`#{pane_id} #{pane_left} #{pane_top} #{pane_width} #{pane_height} #{pane_current_path} #{pane_title} #{host}`]);if(!n)throw Error(x(e,`tmux could not describe the region around pane ${t}`));let r=[];for(let e of n.split(`
|
|
43
|
+
`).filter(Boolean)){let[t,n,i,a,o,s,c,l]=e.split(` `);if(!t)continue;let u={id:t,rect:{x:Number(n),y:Number(i),width:Number(a),height:Number(o)}};s&&(u.cwd=s);let d=Un(c,l);d&&(u.label=d),r.push(u)}if(r.length===0)throw Error(`tmux reported no panes in the region around pane ${t}`);return r}function Un(e,t){return e&&e!==t?e:void 0}function Wn(e,t){let[n,r]=e.split(` `);if(!n||!r)throw Error(`tmux ${t} did not report the new pane's id and window id`);return[n,r]}function Gn(e,t,n){let r=(E(e,[`list-panes`,`-a`,`-F`,`#{pane_id} #{window_id}`])??``).split(`
|
|
44
|
+
`).find(e=>e.split(` `)[0]===t);if(!r)throw Error(`tmux could not resolve pane ${t} after the ${n}`);let[,i]=r.split(` `);if(!i)throw Error(`tmux did not report a window for pane ${t} after the ${n}`);return{id:t,tab:i}}function Kn(e,t){w(t);let n=Math.round((e.targetIsFirst?1-t:t)*e.extent);if(!e.targetIsFirst)return n;let r=e.extent-e.targetExtent-e.otherExtent;return e.extent-r-n}function qn(e){return w(e),`${Math.round((1-e)*100)}%`}const Jn={Backspace:`BSpace`};function Yn(e,t,n){let r=[`capture-pane`,`-p`,`-t`,t.id];return n===`all`?r.push(`-S`,`-`):n!=null&&r.push(`-S`,`-${n}`),E(e,r)??``}function Xn(e){return Jn[e]??e}function Zn(e,t){let n=(e??``).split(`
|
|
45
|
+
`).find(e=>e.split(` `)[0]===t);if(!n)throw Error(`peer's pane ${t} could not be resolved to beam to`);let[,r,i]=n.split(` `);return{sessionName:r,windowId:i}}const Qn=()=>oe();function $n(e){let t={name:`wezterm`,canSizeSplits:!0,focusOnOpen:`restored`,canZoomPanes:!0,canMovePanes:!0,canBreakPanes:!0,open(n,r){let i=r.at??`tab`;return i===`pane:float`&&tt(t.name),r.ratio!=null&&w(r.ratio),nt({read:()=>ar(n),restore:e=>t.focus(n,{id:e})},()=>{if(i===`workspace`){let i=r.label??`cyber-mux-${e.newId().slice(0,8)}`,a=n(`wezterm`,[`cli`,`spawn`,`--new-window`,`--workspace`,i,`--cwd`,r.cwd]);if(!a)throw Error(x(n,`wezterm cli spawn --new-window failed`));let o=a.trim();if(!o)throw Error(`wezterm cli spawn --new-window did not report the new pane id`);let s={id:o,tab:er(n,o),workspace:i};return rr(t,n,s,r.env,r.launch),s}if(i===`tab`){let e=n(`wezterm`,[`cli`,`spawn`,...r.within?[`--window-id`,tr(n,r.within)]:[],`--cwd`,r.cwd]);if(!e)throw Error(x(n,`wezterm cli spawn failed`));let i=e.trim();if(!i)throw Error(`wezterm cli spawn did not report the new pane id`);let a=nr(n,i);return r.label&&t.rename(n,{id:a.tab},`tab`,r.label),rr(t,n,a,r.env,r.launch),a}let a=i===`pane:down`?[`--bottom`]:[`--right`],o=r.from?[`--pane-id`,r.from.id]:[],s=r.ratio==null?[]:[`--percent`,cr(r.ratio)],c=n(`wezterm`,[`cli`,`split-pane`,...a,...o,...s,`--cwd`,r.cwd]);if(!c)throw Error(x(n,`wezterm cli split-pane failed`));let l=c.trim();if(!l)throw Error(`wezterm cli split-pane did not report the new pane id`);let u=nr(n,l);return r.label&&process.stderr.write(`wezterm cannot name a pane — "${r.label}" was not set on pane ${u.id}\n`),rr(t,n,u,r.env,r.launch),u})},rename(e,t,n,r){if(n===`tab`)e(`wezterm`,[`cli`,`set-tab-title`,`--tab-id`,t.id,r]);else throw Error(`wezterm cannot name a pane (only a tab or window) — asked to rename ${t.id}`)},group(){},sendText(e,t,n){e(`wezterm`,[`cli`,`send-text`,`--pane-id`,t.id,n])},sendKeys(e,t,n){let r=n.map(e=>lr[e]??e).join(``);e(`wezterm`,[`cli`,`send-text`,`--pane-id`,t.id,`--no-paste`,r])},submit(e,n,r){r&&t.sendText(e,n,r),t.sendKeys(e,n,[`Enter`])},read(e,t,n){let r=ur(e,t,n?.lines);return n?.truncation?n.lines===`all`?{text:r,truncated:!1}:{text:r,truncated:Et(r,ur(e,t,(n.lines??0)+1))}:{text:r}},waitForOutput(e,n,r){return ut(t,e,n,r)},focus(e,t){e(`wezterm`,[`cli`,`activate-pane`,`--pane-id`,t.id])},teardown(e,t){e(`wezterm`,[`cli`,`kill-pane`,`--pane-id`,t.id])},paneExists(e,t){return ir(e).some(e=>String(e.pane_id)===t.id)},isPaneFocused(e,t){if(!ir(e).some(e=>String(e.pane_id)===t.id))return;let n=or(e);if(n!==void 0&&n.length!==0)return n.some(e=>e.focused_pane_id!=null&&String(e.focused_pane_id)===t.id)},setPaneZoom(e,n,r){if(t.isPaneZoomed(e,n)!==r&&e(`wezterm`,[`cli`,`zoom-pane`,`--pane-id`,n.id,r?`--zoom`:`--unzoom`])===null)throw Error(`wezterm could not ${r?`zoom`:`unzoom`} pane ${n.id}`)},isPaneZoomed(e,t){let n=ir(e).find(e=>String(e.pane_id)===t.id);if(n)return n.is_zoomed===!0},movePane(e,t,n,r){if(e(`wezterm`,[`cli`,`split-pane`,`--pane-id`,n.id,r===`down`?`--bottom`:`--right`,`--move-pane-id`,t.id])===null)throw Error(`wezterm could not move pane ${t.id} to ${n.id}`);return nr(e,t.id)},breakPane(t,n,r){let i=[`cli`,`move-pane-to-new-tab`,`--pane-id`,n.id];if(r===`workspace`&&i.push(`--new-window`,`--workspace`,`cyber-mux-${e.newId().slice(0,8)}`),t(`wezterm`,i)===null)throw Error(`wezterm could not break out pane ${n.id} into its own ${r}`);return nr(t,n.id)},listPanes(e){return ir(e).map(e=>{let t={id:String(e.pane_id),mux:`wezterm`,floating:!1},n=sr(e.cwd);return n&&(t.cwd=n),t})}};return Je(t)}$n({newId:Qn});function er(e,t){let n=ir(e).find(e=>String(e.pane_id)===t);if(!n)throw Error(`wezterm did not report a tab for the new pane ${t}`);return String(n.tab_id)}function tr(e,t){let n=ir(e).find(e=>e.workspace===t);if(!n)throw Error(`wezterm reported no window in workspace ${t} to open a tab in`);return String(n.window_id)}function nr(e,t){let n=ir(e).find(e=>String(e.pane_id)===t);if(!n)throw Error(`wezterm did not report a tab for the new pane ${t}`);return{id:t,tab:String(n.tab_id),workspace:n.workspace}}function rr(e,t,n,r,i){let a=Ze(r,i);a.kind===`dropped`?process.stderr.write(`env (${a.variables.join(`, `)}) could not be set on this wezterm pane — wezterm has no --env flag on any space-creating command
|
|
46
|
+
`):a.command!==void 0&&e.submit(t,n,a.command)}function ir(e){let t=e(`wezterm`,[`cli`,`list`,`--format`,`json`]);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return[]}return Array.isArray(n)?n.filter(e=>e!=null&&e.pane_id!=null&&e.tab_id!=null&&e.window_id!=null):[]}function ar(e){let t=or(e)?.[0]?.focused_pane_id;return t==null?void 0:String(t)}function or(e){let t=e(`wezterm`,[`cli`,`list-clients`,`--format`,`json`]);if(t===null)return;let n;try{n=JSON.parse(t)}catch{return}if(Array.isArray(n))return n.filter(e=>typeof e==`object`&&!!e)}function sr(e){if(!e)return;let t=/^file:\/\/[^/]*(\/.*)$/.exec(e);return t?decodeURIComponent(t[1]):e}function cr(e){return w(e),String(Math.round((1-e)*100))}const lr={Up:`\x1B[A`,Down:`\x1B[B`,Right:`\x1B[C`,Left:`\x1B[D`,Enter:`\r`,Escape:`\x1B`,Tab:` `,Space:` `,Backspace:`\u007F`,"C-c":`\u0003`,F1:`\x1BOP`,F2:`\x1BOQ`,F3:`\x1BOR`,F4:`\x1BOS`,F5:`\x1B[15~`,F6:`\x1B[17~`,F7:`\x1B[18~`,F8:`\x1B[19~`,F9:`\x1B[20~`,F10:`\x1B[21~`,F11:`\x1B[23~`,F12:`\x1B[24~`,Home:`\x1B[H`,End:`\x1B[F`,Delete:`\x1B[3~`,Insert:`\x1B[2~`,PageUp:`\x1B[5~`,PageDown:`\x1B[6~`};function ur(e,t,n){let r=[`cli`,`get-text`,`--pane-id`,t.id],i=n===`all`?Dt:n;return i!=null&&r.push(`--start-line`,String(-i)),e(`wezterm`,r)??``}function dr(e){let t={name:`zellij`,canFloatPanes:!0,canZoomPanes:!0,focusOnOpen:`restored`,open(n,r){let i=r.at??`tab`;if(i===`tab`||i===`workspace`){let i=[`action`,`new-tab`,`--no-focus`,`--cwd`,r.cwd];r.label&&i.push(`--name`,r.label);let a=hr(n),o=n(`zellij`,i);if(o===null)throw Error(x(n,`zellij action new-tab failed`));let s=br(n,o.trim(),a,e.session);return Sr(t,n,s,r.env,r.launch),s}let a=hr(n),o=r.from?gr(n):void 0;r.from&&_r(n,r.from.id);let s=i===`pane:float`?[`--floating`]:[`--direction`,i===`pane:down`?`down`:`right`],c=r.from?[]:[`--no-focus`],l=[`action`,`new-pane`,...s,...c,`--cwd`,r.cwd];r.label&&l.push(`--name`,r.label);let u=n(`zellij`,l);if(u===null)throw Error(x(n,`zellij action new-pane failed`));let d=yr(n,u.trim(),a,e.session);return o&&_r(n,o),Sr(t,n,d,r.env,r.launch),d},rename(e,t,n,r){n===`tab`?O(e,[`action`,`rename-tab-by-id`,t.id,r]):O(e,[`action`,`rename-pane`,`--pane-id`,t.id,r])},group(){},sendText(e,t,n){O(e,[`action`,`write-chars`,`--pane-id`,t.id,n])},sendKeys(e,t,n){O(e,[`action`,`send-keys`,`--pane-id`,t.id,...n.map(wr)])},submit(e,n,r){r&&t.sendText(e,n,r),t.sendKeys(e,n,[`Enter`])},read(e,t,n){if(n?.lines===`all`){let r=O(e,[`action`,`dump-screen`,`--pane-id`,t.id,`--full`])??``;return n.truncation?{text:r,truncated:!1}:{text:r}}if(n?.lines!=null){let r=O(e,[`action`,`dump-screen`,`--pane-id`,t.id,`--full`])??``,i=Or(r,n.lines);return n.truncation?{text:i,truncated:Et(i,r)}:{text:i}}let r=O(e,[`action`,`dump-screen`,`--pane-id`,t.id])??``;return n?.truncation?{text:r,truncated:Et(r,O(e,[`action`,`dump-screen`,`--pane-id`,t.id,`--full`])??``)}:{text:r}},waitForOutput(e,n,r){return ut(t,e,n,r)},focus(e,t){O(e,[`action`,`focus-pane-id`,t.id])},teardown(e,t){O(e,[`action`,`close-pane`,`--pane-id`,t.id])},paneExists(e,t){return mr(e).some(e=>Dr(e.id,t.id))},isPaneFocused(e,t){if(!mr(e).find(e=>Dr(e.id,t.id)))return;let n=gr(e);if(n!==void 0)return Dr(n,t.id)},setPaneZoom(e,n,r){if(t.isPaneZoomed(e,n)!==r&&(r&&_r(e,n.id),O(e,[`action`,`toggle-fullscreen`,`-p`,n.id])===null))throw Error(`zellij could not ${r?`zoom`:`unzoom`} pane ${n.id}`)},isPaneZoomed(e,t){let n=mr(e).find(e=>Dr(e.id,t.id));if(n)return n.is_fullscreen===!0},movePane(){ot(`zellij`)},breakPane(){st(`zellij`)},listPanes(e){return mr(e).map(e=>{let t={id:e.id,mux:`zellij`,floating:e.is_floating===!0};e.pane_cwd&&(t.cwd=e.pane_cwd);let n=Tr(e.title,e.terminal_command);return n&&(t.label=n),t})}};return Je(t)}dr({});function O(e,t){for(let n=1;n<=3;n++){let n=e(`zellij`,t);if(n!==null)return n}return null}function fr(e){let t=e(`zellij`,[`action`,`list-panes`,`--json`]);if(!t)return;let n;try{n=JSON.parse(t)}catch{return}if(Array.isArray(n))return n.filter(e=>e!=null&&e.id!=null).map(e=>({...e,id:pr(e.id,e.is_plugin)}))}function pr(e,t){let n=String(e);return/^\d+$/.test(n)?t===!0?`plugin_${n}`:`terminal_${n}`:n}function mr(e){for(let t=1;t<=3;t++){let t=fr(e);if(t)return t}return[]}function hr(e){return new Set(mr(e).map(e=>Er(e.id)))}function gr(e){for(let t=1;t<=3;t++){let t=e(`zellij`,[`action`,`list-clients`]);if(t===null||!/^CLIENT_ID\b/.test(t))continue;let n=t.split(`
|
|
47
|
+
`)[1];if(n===void 0)return;let r=n.trim().split(/\s+/)[1];if(r)return r}}function _r(e,t){for(let n=1;n<=3;n++){O(e,[`action`,`focus-pane-id`,t]);let n=gr(e);if(n===void 0||Dr(n,t))return}}function vr(e,t){return mr(e).filter(e=>e.is_plugin!==!0&&!t.has(Er(e.id)))}function yr(e,t,n,r){for(let i=1;i<=10;i++){let a=vr(e,n),o=t?a.find(e=>Dr(e.id,t)):void 0;if(o?.tab_id!=null)return xr(t,String(o.tab_id),r);let s=a.length===1?a[0]:void 0;if((i>1||!t)&&s?.tab_id!=null)return xr(s.id,String(s.tab_id),r)}throw Error(t?`zellij did not report a tab for the new pane ${t}`:`zellij action new-pane did not report the new pane id, and no new pane appeared`)}function br(e,t,n,r){for(let i=1;i<=10;i++){let a=vr(e,n),o=t?a.find(e=>e.tab_id!=null&&String(e.tab_id)===t):void 0;if(o)return xr(o.id,t,r);let s=a.length===1?a[0]:void 0;if((i>1||!t)&&s?.tab_id!=null)return xr(s.id,String(s.tab_id),r)}throw Error(t?`zellij did not report a pane in the new tab ${t}`:`zellij action new-tab did not report the new tab id, and no new pane appeared`)}function xr(e,t,n){let r={id:e,tab:t};return n&&(r.workspace=n),r}function Sr(e,t,n,r,i){let a=Ze(r,i);a.kind===`dropped`?process.stderr.write(`env (${a.variables.join(`, `)}) could not be set on this zellij pane — zellij has no --env flag on new-pane/new-tab
|
|
48
|
+
`):a.command!==void 0&&e.submit(t,n,a.command)}const Cr={Escape:`Esc`,"C-c":`Ctrl c`};function wr(e){return Cr[e]??e}function Tr(e,t){return e&&e!==t?e:void 0}function Er(e){return/^\d+$/.test(e)?`terminal_${e}`:e}function Dr(e,t){return Er(e)===Er(t)}function Or(e,t){let n=e.split(`
|
|
49
49
|
`);return n.slice(Math.max(0,n.length-t)).join(`
|
|
50
|
-
`)}function
|
|
51
|
-
`).filter(e=>e.trim()!==``).slice(-5).join(` `).replace(/\s+/g,` `).trim().includes(n)}function
|
|
52
|
-
`).map(e=>e.trim()).filter(Boolean))}async function
|
|
53
|
-
`)){let t=e.indexOf(` `);t!==-1&&e.slice(t+1).trim()===`[gone]`&&r.add(e.slice(0,t))}return r}async function
|
|
54
|
-
`).some(e=>e.startsWith(`-`))??!1:!1}async function
|
|
50
|
+
`)}function kr(e,t){if(!e)return!0;let n=t.replace(/\s+/g,` `).trim().slice(0,40);return n===``||e.split(`
|
|
51
|
+
`).filter(e=>e.trim()!==``).slice(-5).join(` `).replace(/\s+/g,` `).trim().includes(n)}function Ar(e,t){let n=je(t);return n&&n.mux===e.name?{id:n.pane}:void 0}function jr(e,t){let n=0,r=0,i=0;t.ensureMarker();for(let a of e.listAgents()){t.getAgent(a.id)||(t.putAgent(a),n++);let o=e.listInbox(a.id);for(let e of[...o.unread,...o.read])t.putMessage(a.id,e),r++;let s=e.readBrief(a.id);s!=null&&(t.writeBrief(a.id,s),i++)}return{agents:n,messages:r,briefs:i}}async function Mr(e,t){let n=[`-C`,e,`status`,`--porcelain`,`--untracked-files=all`];t.ignore?.length&&n.push(`--`,`.`,...t.ignore.map(e=>`:(exclude)${e}`));let r=await t.exec(`git`,n);return r===null?void 0:r.length>0}const Nr=(e,t)=>new Promise(n=>{ee(e,[...t],{encoding:`utf8`,maxBuffer:67108864},(e,t)=>{n(e?null:t.trim())})});async function Pr(e,t,n){return await e(`git`,[`-C`,t,`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`])||n}async function Fr(e,t,n,r){let[i,a]=await Promise.all([Lr(e,t,n),Rr(e,t)]);return{exec:e,primaryRoot:t,target:n,merged:i,goneUpstream:a,forge:r}}async function Ir(e,t){if(!e)return{};if(t.merged?.has(e))return{merged:!0,signal:`ancestor`};let n=t.merged?{merged:!1}:{};return t.goneUpstream?.has(e)?{merged:!0,signal:`upstream-gone`}:t.target&&await zr(t.exec,t.primaryRoot,t.target,e)?{merged:!0,signal:`squash-patch`}:await t.forge?.(e)===!0?{merged:!0,signal:`forge`}:n}async function Lr(e,t,n){if(!n)return;let r=await e(`git`,[`-C`,t,`branch`,`--format=%(refname:short)`,`--merged`,n]);if(r!==null)return new Set(r.split(`
|
|
52
|
+
`).map(e=>e.trim()).filter(Boolean))}async function Rr(e,t){let n=await e(`git`,[`-C`,t,`for-each-ref`,`--format=%(refname:short) %(upstream:track)`,`refs/heads/`]);if(n===null)return;let r=/* @__PURE__ */ new Set;for(let e of n.split(`
|
|
53
|
+
`)){let t=e.indexOf(` `);t!==-1&&e.slice(t+1).trim()===`[gone]`&&r.add(e.slice(0,t))}return r}async function zr(e,t,n,r){let i=await e(`git`,[`-C`,t,`merge-base`,n,r]);if(!i)return!1;let a=await e(`git`,[`-c`,`user.name=agent-harness`,`-c`,`user.email=probe@agent-harness.invalid`,`-C`,t,`commit-tree`,`${r}^{tree}`,`-p`,i,`-m`,`agent-harness squash probe`]);return a?(await e(`git`,[`-C`,t,`cherry`,n,a]))?.split(`
|
|
54
|
+
`).some(e=>e.startsWith(`-`))??!1:!1}async function Br(e={}){let t=await(e.exec??Nr)(`git`,[`-C`,e.from??`.`,`rev-parse`,`--path-format=absolute`,`--git-common-dir`]);if(!t)throw Error(`not inside a git repository: ${g(e.from??`.`)}`);return p(t)}async function Vr(e){try{return await de(e)}catch{return g(e)}}async function Hr(e){let t=e.exec??Nr,n=await t(`git`,[`-C`,e.primaryRoot,`worktree`,`list`,`--porcelain`]);if(!n)return[];let r=await Vr(e.primaryRoot),i=await Promise.all(n.split(`
|
|
55
55
|
|
|
56
|
-
`).map(e=>e.trim()).filter(e=>e.startsWith(`worktree `)).map(e=>
|
|
57
|
-
`),r=await
|
|
58
|
-
`,r:`\r`,t:` `,v:`\v`};function Wr(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(Ur[i]??i))}return Buffer.from(t).toString(`utf8`)}function Gr(e){return h(p(e),`${f(e)}.worktrees`)}function Kr(e,t){return h(Gr(e),`${f(e)}-${t}`)}function qr(e,t){if(p(t)!==Gr(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 Jr(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 Yr(e,t){return Jr(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&&qr(t.primaryRoot,e.root)!==void 0?{owner:`self`,research:[]}:Xr(e.root,`${t.primaryRoot}${_}.claude${_}worktrees`)?{owner:`claude-code`,research:[`E-CC-W1`]}:t.codexHome&&Xr(e.root,`${t.codexHome}${_}worktrees`)?{owner:`codex`,research:[`E-CODEX-W1`]}:{owner:`unknown`,research:[]}:{owner:`user`,research:[]}}function Xr(e,t){return e.startsWith(`${t}${_}`)}const Zr={async createExclusive(e,t){try{return await fe(e,t,{flag:`wx`}),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}},async readText(e){try{return await se(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}},async remove(e){try{await de(e)}catch(e){if(e.code!==`ENOENT`)throw e}}};async function Qr(e,t=Mr,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 $r(e,n);return i?h(i,`locked`):void 0}async function $r(e,t){let n=h(t,`worktrees`),r=await ei(e),i;try{i=await ce(n)}catch{return}for(let e of i){let t;try{t=(await se(h(n,e,`gitdir`),`utf8`)).trim()}catch{continue}if(await ei(p(t))===r)return h(n,e)}}async function ei(e){return h(await Br(p(e)),f(e),`.git`)}async function ti(e,t,n={}){let r=n.exec??Mr,i=n.fs??Zr,a=await Qr(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??ae(),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 ni(s,{exec:r,fs:i})?s:void 0}async function ni(e,t={}){let n=await Qr(e.worktree,t.exec??Mr,e.commonDir);return n?Jr(await(t.fs??Zr).readText(n))?.leaseId===e.leaseId:!1}async function ri(e,t={}){let n=t.exec??Mr,r=t.fs??Zr,i=await Qr(e.worktree,n,e.commonDir);return!i||Jr(await r.readText(i))?.leaseId!==e.leaseId?{released:!1,reason:`lost`}:(await r.remove(i),{released:!0})}function ii(e=`/proc`){return async()=>{if(e===`/proc`&&process.platform!==`linux`)return null;let t;try{t=await ce(e)}catch{return null}return(await Promise.all(t.filter(e=>/^\d+$/.test(e)).map(t=>ai(h(e,t),Number(t))))).filter(e=>e!==void 0)}}async function ai(e,t){let[n,r,i,a,o]=await Promise.all([si(h(e,`stat`)),si(h(e,`cmdline`)),ci(h(e,`exe`)),ci(h(e,`cwd`)),si(h(e,`environ`))]);if(n===void 0)return;let s={pid:t,argv:r?oi(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 oi(o)){let n=t.indexOf(`=`);n>0&&(e[t.slice(0,n)]=t.slice(n+1))}s.env=e}return s}const oi=e=>e.split(`\0`).filter(e=>e.length>0);async function si(e){try{return await se(e,`utf8`)}catch{return}}async function ci(e){try{return(await le(e)).replace(/ \(deleted\)$/,``)}catch{return}}const li=e=>e?.slice(e.lastIndexOf(`/`)+1),ui=(e,t)=>li(e.exe)===t,di=(e,t)=>e.exe!==void 0&&t.test(e.exe),fi=e=>ui(e,`node`)||li(e.argv[0])===`node`,A=(e,t)=>e.argv.some(e=>t.test(e)),pi=[{harness:`claude-code`,research:[`E-PROC-CC1`,`E-PROC-CC2`,`E-PROC-CC3`],isSession:e=>di(e,/\/claude\/versions\/[^/]+$/),link:{pid:`CLAUDE_PID`,id:`CLAUDE_CODE_SESSION_ID`}},{harness:`codex`,research:[`E-PROC-CX1`,`E-PROC-CX2`],isSession:e=>ui(e,`codex`)&&!mi(e),helper:e=>mi(e)?`session`:void 0,link:{id:`CODEX_SESSION_ID`}},{harness:`copilot-cli`,research:[`E-PROC-COP1`,`E-PROC-COP2`],isSession:e=>ui(e,`copilot`),link:{id:`COPILOT_AGENT_SESSION_ID`}},{harness:`cursor`,research:[`E-PROC-CUR1`,`E-PROC-CUR3`,`E-PROC-CUR4`],isSession:e=>hi(e)&&e.env?.AGENT_CLI_SOCKET_PATH===void 0,helper:e=>hi(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=>ui(e,`opencode`),link:{pid:`OPENCODE_PID`}},{harness:`kilo`,research:[`E-PROC-KILO1`],isSession:e=>di(e,/\/cli-linux-x64\/bin\/kilo$/)||fi(e)&&A(e,/\/@kilocode\/cli\/bin\/kilo$/),link:{pid:`KILO_PID`,id:`KILO_RUN_ID`}},{harness:`qwen-code`,research:[`E-PROC-QWEN1`],isSession:e=>fi(e)&&A(e,/\/qwen-code\/cli-entry\.js$/),link:{id:`QWEN_CODE_SESSION_ID`}},{harness:`crush`,research:[`E-PROC-CRUSH1`],isSession:e=>di(e,/\/crush\/bin\/crush$/)||fi(e)&&A(e,/\/@charmland\/crush(\/|$)/)},{harness:`gemini-cli`,research:[`E-PROC-GEM1`],isSession:e=>fi(e)&&A(e,/\/gemini-cli\/bundle\/gemini\.js$/)},{harness:`goose`,research:[`E-PROC-GOOSE1`],isSession:e=>ui(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(li(e.exe)??``)&&A(e,/\/openhands$/),helper:e=>ui(e,`tmux`)&&(e.argv.includes(`-Lopenhands`)||/-L openhands( |$)/.test(e.argv.join(` `)))?`shared`:void 0},{harness:`cline`,research:[`E-PROC-CLINE1`],isSession:e=>gi(e)&&!e.argv.includes(`--cline-hub-daemon`),helper:e=>gi(e)&&e.argv.includes(`--cline-hub-daemon`)?`shared`:void 0},{harness:`augment`,research:[`E-PROC-AUG1`],isSession:e=>fi(e)&&A(e,/\/@augmentcode\/auggie\/augment\.mjs$/)},{harness:`antigravity-cli`,research:[`E-PROC-AGY1`],isSession:e=>ui(e,`agy`),link:{id:`ANTIGRAVITY_CONVERSATION_ID`}}];function mi(e){return li(e.exe)===`codex-code-mode-host`||e.argv.some(e=>li(e)===`codex-code-mode-host`)}function hi(e){return fi(e)&&A(e,/(^|\/)cursor-agent$/)}function gi(e){return di(e,/\/cli-linux-x64\/bin\/cline$/)||fi(e)&&A(e,/\/cline\/bin\/cline$/)}async function _i(e={}){let t=await(e.source??ii())();return t===null?{verified:!1,occupancy:(e,t)=>({busy:t?.strict===!0,verified:!1,occupants:[],lingering:[],unlinked:[]})}:vi(t)}function vi(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 pi){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=pi.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 yi(e){let t=e.exec??Mr,n=await Br(e.primaryRoot??await zr({from:e.from,exec:t})),r=await Vr({primaryRoot:n,exec:t,ignore:e.ignore,forge:e.forge}),i=e.base??await Nr(t,n,r.find(e=>!e.linked)?.branch),a=e.codexHome&&await Br(e.codexHome),o=e.probe,s=[];for(let c of r){let l=Yr(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=Jr(c.locked);if(d){u.skip=`leased`,u.holder=d.holder;continue}if(c.prunable){u.skip=`prunable`;continue}o??=await _i();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 bi(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 bi(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 xi(e=Mr){return async({primaryRoot:t,path:n,base:r,branch:i})=>{let a=[`-C`,t,`worktree`,`add`,`--quiet`];if(i?await Oi(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 Si=class extends Error{code;verdicts;constructor(e,t,n){super(t),this.code=e,this.verdicts=n,this.name=`AcquireError`}};async function Ci(e){let t=[];for(let n=0;n<3;n++){let n=await yi(e);t=n.verdicts;let{primary:r,exec:i,entries:a}=n;if(!n.base)throw new Si(`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 Si(`no-base`,`base does not resolve to a commit: ${n.base}`,t);let s=t.filter(e=>e.skip===void 0).sort((e,t)=>wi(r,e)-wi(r,t));for(let t of s){let n=await Ti(t,o,e,i,r);if(n)return n}let c=a.filter(e=>e.linked&&qr(r,e.root)!==void 0);if(e.max!==void 0&&c.length>=e.max)throw new Si(`pool-full`,`all ${e.max} worktrees are in use`,t);let l=await Ei(r,o,e,i,c);if(l)return{...l,reused:!1,branch:e.branch,verified:!0,lingering:[]}}throw new Si(`contended`,`another caller took every worktree this one tried`,t)}function wi(e,t){return qr(e,t.worktree.root)??1/0}async function Ti(e,t,n,r,i){let a=e.worktree,o={exec:r,fs:n.fs},s=await ti(a.root,n.holder,{...o,leaseId:n.newLeaseId?.()});if(!s)return;let c=await r(`git`,[`-C`,a.root,`rev-parse`,`HEAD`]),l=await jr(a.root,{exec:r,ignore:n.ignore});if(c!==a.head||l!==!1||!await ni(s,o)){await ri(s,o);return}let u=(...e)=>r(`git`,[`-C`,a.root,...e]),d=async e=>{throw await ri(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 Oi(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 Ei(e,t,n,r,i){let a=new Set(i.map(t=>qr(e,t.root))),o=1;for(;a.has(o)||await ki(Kr(e,o));)o++;let s=Kr(e,o),c=n.create??xi(r),l={primaryRoot:e,path:s,base:t,branch:n.branch};try{await c(l)}catch(e){if(await ki(s))return;throw e}let u;try{u=await ti(await Br(s),n.holder,{exec:r,fs:n.fs,leaseId:n.newLeaseId?.()})}catch(e){throw await Di(n.undoCreate,l),e}return u||await Di(n.undoCreate,l),u}async function Di(e,t){try{await e?.(t)}catch{}}async function Oi(e,t,n){return await e(`git`,[`-C`,t,`rev-parse`,`--verify`,`--quiet`,`refs/heads/${n}`])!==null}async function ki(e){try{return await oe(e),!0}catch{return!1}}var Ai=class extends Error{};const ji={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 Ai(`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 Ai(`git worktree remove failed for ${t}`)}};function Mi(e){let t=e(`git`,[`rev-parse`,`--path-format=absolute`,`--git-common-dir`]);if(!t)throw new Ai(`cannot resolve the primary checkout — not inside a git repository`);return p(t)}function Ni(e,t){if(g(e)===g(t))throw new Ai(`refusing to run in the primary checkout — spawn a worktree distinct from the primary checkout`)}const Pi=`config.json`,Fi=`.agents/cyberlegion/${Pi}`;function Ii(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 Li(e={}){let t=e.env??process.env,n=e.root??e.space??t.CYBERLEGION_ROOT;if(n)return g(n);let r=ne();return h(r||Ii(e.cwd),`.agents`,`cyberlegion`)}function Ri(e){r(e,{recursive:!0});let t=h(e,Pi);n(t)||u(t,`${JSON.stringify({version:1},null,2)}\n`)}var zi=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 Bi=/[\\/\0]/;function j(e,t){if(!e||e===`.`||e===`..`||Bi.test(e))throw new zi(t,e);return e}const M={agentsDir:e=>h(e,`agents`),agentFile:(e,t)=>h(e,`agents`,`${j(t,`agent id`)}.json`),panesDir:e=>h(e,`panes`),paneFile:(e,t)=>h(e,`panes`,`${Vi(t)}.id`),inboxDir:(e,t)=>h(e,`inbox`,j(t,`agent id`)),inboxReadDir:(e,t)=>h(e,`inbox`,j(t,`agent id`),`read`),dataDir:(e,t)=>h(e,`data`,j(t,`agent id`)),briefFile:(e,t)=>h(e,`data`,j(t,`agent id`),`brief.md`),mainPaneFile:e=>h(e,`main-pane.id`),projectsDir:e=>h(e,`projects`),serviceLeaseFile:(e,t,n)=>h(e,`services`,j(t,`project id`),`${j(n,`service name`)}.json`),projectFile:(e,t)=>h(e,`projects`,`${j(t,`project id`)}.json`),messageFile:(e,t,n)=>h(M.inboxDir(e,t),`${j(n,`message id`)}.json`),messageReadFile:(e,t,n)=>h(M.inboxReadDir(e,t),`${j(n,`message id`)}.json`)};function Vi(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`)}function N(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 P=De;function Hi(e){let t=Ae(N(e));return t&&(t.mux===`tmux`||t.mux===`herdr`)?{mux:t.mux,pane:t.pane}:void 0}const Ui=e=>new Date(e.now?.()??Date.now()).toISOString();function Wi(){return ie(8).toString(`hex`)}function F(e,t){return e.getAgent(t)}function I(e,t){e.putAgent(t)}function L(e){return e.listAgents()}function Gi(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??P)(`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 R(e){let t=e.env??process.env,n=Ae(N(t));return n?e.store.resolvePaneId(n.pane):t.CYBERLEGION_AGENT_ID||void 0}function Ki(e,t){e.store.ensureMarker();let n=e.env??process.env,r=Gi(t.harness,e);if(!r)throw Error(`could not detect harness — pass --harness claude|cursor|codex`);let i=R(e),a=i?F(e.store,i):void 0,o=a?.id??i??Wi(),s=Ui(e),c=Hi(n),l=e.exec??P,u={id:o,handle:t.handle??a?.handle??o.slice(0,6),harness:r,cwd:process.cwd(),worktree:a?.worktree?$i(a.worktree,l):Zi(l),pane:c?qi(c,l,n):null,status:`active`,createdAt:a?.createdAt??s,lastSeen:s,...a?.brief?{brief:a.brief}:{},...a?.spawnedBy?{spawnedBy:a.spawnedBy}:{}};return I(e.store,u),c&&e.store.putPaneIndex(c.pane,o),u}function qi(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}}function Ji(e){return`standing-${Vi(e)}`}function Yi(e,t){e.store.ensureMarker();let n=Ji(t.handle);return e.store.withLock(`presence:${n}`,()=>Xi(e,n,t))}function Xi(e,t,n){let r=F(e.store,t),i=Ui(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),I(e.store,a),a}function Zi(e){let t=e(`git`,[`rev-parse`,`--show-toplevel`]);if(!t)return null;let n=e(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`])??void 0,r=Qi(e);return{root:t,...n===void 0?{}:{branch:n},...r===void 0?{}:{primaryRoot:r}}}function Qi(e){try{return Mi(e)}catch{return}}function $i(e,t){if(!e||e.primaryRoot!==void 0)return e;let n=Zi(t);return n?.root!==e.root||n.primaryRoot===void 0?e:{...e,primaryRoot:n.primaryRoot}}function ea(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 ta(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 na(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 ra(e,t){let n=L(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 ia(e,t){let n=F(e,t);if(n?.kind===`service`||n?.kind===`standing`)return n.id;let r=L(e);if(r.some(e=>e.handle===t&&e.kind===`standing`))return ra(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 ra(e,t)}function aa(e,t){let n=F(e,t);if(n)return n;let{live:r,exited:i}=ta(L(e),t),a=ea(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 oa(e,t){let n=ra(e.store,t);if(!F(e.store,n))throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);if(je(e.exec??P,N(e.env??process.env)).mux===`none`)throw Error(`claiming a presence needs a multiplexer to open panes`);let r=R(e);if(!r)throw Error("no identity in this session — run `cyberlegion unit register` first");return e.store.withLock(`presence:${n}`,()=>{let i=F(e.store,n);if(!i)throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return i.presence=r,I(e.store,i),i})}function sa(e,t){let n=ra(e.store,t);if(!F(e.store,n))throw Error(`no standing owner "${t}" — run 'cyberlegion unit register --standing --handle ${t}'`);return e.store.withLock(`presence:${n}`,()=>{let r=F(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,I(e.store,r)),r})}function ca(e,t){if(!t.presence)return;let n=F(e,t.presence);if(n&&n.status!==`exited`)return n}function la(e,t){let n=F(e,ra(e,t));if(n)return ca(e,n)}function ua(e,t){if(F(e,t))return t;let{live:n,exited:r}=ta(L(e),t),i=ea(t,n);if(!i)throw na(t,r,`id and handle`);return i.id}function z(e,t){let n=F(e,t);if(n)return n;let r=L(e),{live:i,exited:a}=ta(r,t),o=ea(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 na(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 da(e){return f(e.worktree?.primaryRoot??e.cwd)}function fa(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=L(e).filter(e=>e.status!==`exited`&&(r===void 0||e.worktree?.branch===r)&&(n===void 0||da(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}`:``}, ${da(e)})`).join(`, `);throw Error(`${i} matches ${a.length} units — ${e} — address one by its id`)}return o}function pa(e,t){let n=F(e.store,t);n&&(n.lastSeen=Ui(e),I(e.store,n))}function B(e){let t=R(e);t&&pa(e,t)}function ma(e){return e.kind===`standing`||e.kind===`service`}function ha(e){return!ma(e)&&e.status!==`exited`&&e.status!==`stopped`}function ga(e,t){if(t.status===`exited`||t.status===`stopped`)return!1;if(!t.pane)return!0;let n=_a[t.pane.mux].listPanes(e.exec??P);if(n.length===0)return!0;let r=t.pane.id;return n.some(e=>e.id===r)}const _a={tmux:O,herdr:E};function va(e){if(e){if(e.includes(`cursor`))return`cursor`;if(e.includes(`codex`))return`codex`;if(e.includes(`claude`))return`claude`}}function ya(e,t){let n=L(e.store),r=[];for(let i of t){if(i.mux!==`tmux`&&i.mux!==`herdr`)continue;let t=va(i.harness);if(!t)continue;let a=e.store.resolvePaneId(i.id);if(a&&F(e.store,a)||n.some(e=>e.pane?.mux===i.mux&&e.pane.id===i.id))continue;let o=Wi(),s=Ui(e),c={id:o,handle:i.cwd?Vi(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};I(e.store,c),e.store.putPaneIndex(i.id,o),r.push(c)}return r}function ba(e,t){let n=e.exec??P,r=Hi(e.env??process.env);if(!r)return[];let i=_a[r.mux].listPanes(n);if(i.length===0)return[];let a=new Set(i.map(e=>e.id)),o=[];for(let t of L(e.store))ha(t)&&t.pane&&t.pane.mux===r.mux&&(a.has(t.pane.id)||(t.status=`exited`,I(e.store,t),o.push(t)));return t?.adopt&&o.push(...ya(e,i)),o}function xa(e,t,n){let r=_a[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 Sa(e){let t=e.exec??P,n=e.now?.()??Date.now(),r=ba(e),i=/* @__PURE__ */ new Map;for(let a of L(e.store))ha(a)&&(a.pane?xa(t,a.pane,i):n-new Date(a.lastSeen).getTime()>9e5)&&(a.status=`exited`,I(e.store,a),r.push(a));return r}const Ca=/* @__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`]),wa={claude:{head:/^❯(?:[ ](.*))?$/,indent:` `,ruled:!0,placeholder:e=>/^Try ".*"$/.test(e)},codex:{head:/^›(?: (.*))?$/,indent:` `,ruled:!1,placeholder:e=>Ca.has(e)},cursor:{head:/^ {2}→(?: (.*))?$/,indent:` `,ruled:!1,placeholder:e=>e===`Plan, search, build anything`}},Ta=e=>/^─{3,}/.test(e);function Ea(e,t){for(let n=e.length-1;n>=0;n--){let r=t.head.exec(e[n]??``);if(!r||t.ruled&&!Ta(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(!Ta(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
|
|
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
|
+
`),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 Ya(e){return e!==void 0&&Ka[e]!==void 0}function Xa(e,t){let n=e.split(`
|
|
60
|
+
`),r=t&&Ka[t]?[Ka[t]]:Object.values(Ka);for(let e of r){let t=Ja(n,e);if(t.kind!==`unknown`)return t}return{kind:`unknown`}}async function Za(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 Xa(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 Qa(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 Qa(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 Qa(e,t,n,r){e.sendText(t,n,`\u0005`),await r(150),e.sendText(t,n,`\u0015`),await r(150)}function $a(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 eo(e,t,n){let r=e?Xa(e,n):{kind:`unknown`};if(r.kind===`unknown`)return{boxKnown:!1,staged:kr(e,t),outside:$a(e,t)};let i=r.kind===`draft`?$a(r.text,t):0;return{boxKnown:!0,staged:i>0,outside:$a(e,t)-i}}async function to(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&&Ya(i.harness))for(let l=0;l<a&&!eo(c,r,i.harness).boxKnown;l++)await s(o),c=e.read(t,n).text;let l=eo(c,r,i.harness).outside,u=()=>{let a=eo(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 no=`You have unread mail — check your inbox.`;function ro(e){return`Read your brief at ${e}, then begin work.`}const io=/^Readyourbriefat.+,thenbeginwork\.$/,ao=/^Yoursessionwasrestartedwithitsconversationresumed—continueyourwork\.Ifyouhavenoearlierconversation,readyourbriefat.+,thenbeginwork\.$/;function oo(e,t){let n=e=>e.replace(/\s+/g,``),r=n(e);return r===``?!1:r===n(`You have unread mail — check your inbox.`)||io.test(r)||ao.test(r)||t!==void 0&&r===n(t)}function so(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 co={attempts:20,settleMs:400};function lo(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 uo(e,t){return N(e,t)?.pane?.id??e.findPaneByAgentId(t)}async function fo(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=lo(o.handle,e)}t?(s=uo(e,t.id),c=t.harness):(s=e.getMainPane(),l=!0)}else s=uo(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===uo(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 Za(e,n,r,()=>to(e,n,r,no,{...i,harness:c}),{...a,harness:c,ownText:e=>oo(e)}),{rung:!0,pane:s}}catch(e){return{rung:!1,pane:s,warning:e instanceof Error?e.message:String(e)}}}}async function po(e,t,n,r=co,i){if(n.noWake)return{rung:!1};try{let a=e(),o=(n.resumed?so:ro)(n.briefPath);return await Za(a,t,n.target,()=>to(a,t,n.target,o,{...r,requirePosted:!0,harness:n.harness}),{...i,harness:n.harness,ownText:e=>oo(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 mo={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`}]}},ho=e=>e.replace(/\s+/g,` `);function go(e,t){let n=ho(t);return mo[e].markers.some(e=>e.every(e=>n.includes(ho(e))))}async function _o(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=>go(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 mo[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 vo(y)}for(let e=0;e<u;e++){if(!p(f()))return{state:`accepted`};await d(a)}return vo(y)}function vo(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 yo=/* @__PURE__ */ new Set([`clean`,`cleanup`,`decommission`,`delete`,`deprecate`,`disable`,`drop`,`prune`,`purge`,`remove`,`retire`,`revert`,`revoke`,`rollback`,`teardown`,`undo`,`uninstall`,`unregister`]),bo=/* @__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(`.`)),xo=/* @__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(`.`)),So=/* @__PURE__ */ new Set([`a`,`an`,`the`]);function Co(e){let t=To(wo(e.brief)),n=t[0],r=`2B-`,i=!1;n&&yo.has(n)?(r=`A2-`,i=!0):n&&bo.has(n)?(r=`9S-`,i=!0):n&&xo.has(n)&&(i=!0);let a;e.handle?a=To(e.handle):(a=i?t.slice(1):t.slice(),a[0]&&So.has(a[0])&&a.shift());let o=Eo(a,27)||e.id.slice(0,6);return`${r}${o}`}function wo(e){for(let t of e.split(`
|
|
62
|
+
`))if(t.trim()!==``)return t;return``}function To(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e!==``)}function Eo(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 Do={acquire:Ti,release:ii};function Oo(e){return async(t,n)=>e(t,[...n])}function ko(e){return`cyberlegion:${e}`}const Ao=[Li],B={claude:`claude`,cursor:`cursor-agent`,codex:`codex`},jo={claude:`/clear`,codex:`/clear`,copilot:`/clear`,cursor:`/new-chat`},Mo=/* @__PURE__ */ new Set([`gemini`]);function No(e){let t=jo[e];if(t)return t;throw Mo.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(jo).join(` | `)}) — unit clear refuses to guess a command`)}async function Po(e,t){try{return await Br({from:g(t),exec:Oo(e)})}catch{throw Error(`--repo ${t} is not inside a git repository`)}}function Fo(e,t){let n=g(t);try{return Pi((t,r)=>e(t,t===`git`?[`-C`,n,...r]:r))}catch{return}}function Io(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 Lo(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=ns(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?Fo(i,t.cwd):t.repo?await Po(i,t.repo):await Br({exec:Oo(i)}),d=t.command??B[s],f=()=>Uo(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,...Ho(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=Io(i,u,t.base);let r=Ho(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(Oo(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=ko(l),n=await Do.acquire({primaryRoot:u,holder:t,branch:e,base:y.ref,exec:Oo(i),ignore:Ao,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,ts(c,t.briefInstructions)),{agent:re,pane:te.id,launch:d,...y?{base:y}:{},...ee===void 0?{}:{reused:ee}}}async function Ro(e,t,n={}){let r=await Lo(e,t),i=await zo(e,r,n);return i.trustBlocked?{...r,...i}:{...r,...await Bo(e,r,i,n)}}async function zo(e,t,n){let r=await Vo(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 Bo(e,t,n,r){let i=e.env??process.env,a=e.exec??M,o=t.agent.brief,s=await po(()=>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 Vo(e,t,n,r=!1){let i=e.exec??M,a;try{a=z(e.env??process.env,i)}catch{return{state:`unsettled`}}return _o(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 Ho(e,t,n,r){return e===`workspace`?{label:Co({brief:n,handle:t.handle,id:r})}:{}}function Uo(e,t,n,r,i={}){let a=e.self?Yo(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?Ko(a):``}${qo(t)}`;return`${o}${s}${r}${i.fallback?` || ${s}${i.fallback}`:``}`}const Wo={claude:e=>`--resume ${V(e)}`,codex:e=>`resume ${V(e)}`};function Go(e,t,n){let r=Wo[e];if(r&&t.split(/\s+/)[0]===B[e])return`${t} ${r(n)}`}function Ko(e){return`PATH=${V(p(e))}:"$PATH" CYBERLEGION_CLI=${V(e)} `}function qo(e){return e===`tmux`?`CYBER_MUX=tmux CYBER_MUX_PANE=$TMUX_PANE `:e===`herdr`?`CYBER_MUX=herdr `:``}function Jo(){let e=process.argv[1];return[process.execPath,...process.execArgv,...e?[o(e)]:[]]}function Yo(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 Xo(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 Zo(e,t){let{agent:n,target:r}=Xo(e,t),i=e.exec??M;return z(e.env??process.env,i).focus(i,r),{agent:n,pane:r.id}}async function Qo(e,t,n={}){let{agent:r,target:i}=Xo(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 Za(s,a,i,()=>to(s,a,i,o,n.nudgeOpts),{...n.guardOpts,harness:r.harness,ownText:e=>oo(e,o)});return{agent:r,pane:i.id,message:o,resubmits:c.resubmits}}function $o(e,t,n={}){let{agent:r,target:i}=Xo(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 es(e,t,n={}){let{agent:r,target:i}=Xo(e,t),a=i.id;if(!r.harness)throw Error(`unit "${t}" has no harness on record — cannot resolve its reset command`);let o=No(r.harness),s=e.env??process.env,c=e.exec??M,l=z(s,c);return await Za(l,c,i,async()=>l.submit(c,i,o),{...n.guardOpts,harness:r.harness,ownText:e=>oo(e)}),{agent:r,pane:a,command:o}}function ts(e,t){return t?`## Agent instructions\n\n${t}\n\n## Brief\n\n${e}`:e}function ns(e,t=()=>i(0,`utf8`)){return e.briefFile?i(e.briefFile,`utf8`):e.task===`-`?t():e.task!=null&&e.task!==``?e.task:null}function rs(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
|
|
68
|
-
`)}function
|
|
69
|
-
`)}async function
|
|
70
|
-
`)}`)}let o=
|
|
64
|
+
`:` `)}i[n]=is(r)}return{fm:i,instructions:r.trim()}}function is(e){return e.length>=2&&(e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`))?e.slice(1,-1):e}function as(e){if(e!==void 0){if(e===`true`)return!0;if(e===`false`)return!1}}const os=Object.keys(B);function ss(e,t){if(e===void 0||os.includes(e))return e;throw Error(`agent def "${t}" has unknown harness "${e}" — expected one of ${os.join(`, `)}`)}function cs(e,t,n){let{fm:r,instructions:i}=rs(t);return{name:r.name??n,description:r.description,model:r.model,effort:r.effort,harness:ss(r.harness,e),warm:as(r.warm),interactive:as(r.interactive),instructions:i,path:e}}function ls(e){return h(Ri(e),`.agents`,`agents`)}function us(e){if(e.file){let t=g(e.file);if(!n(t))throw Error(`agent def file "${e.file}" does not exist`);return cs(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??[],ls(e.cwd)];for(let r of t){let t=h(r,`${e.name}.md`);if(n(t))return cs(t,i(t,`utf8`),e.name)}throw Error(`no agent definition named "${e.name}" found under .agents/agents/`)}function ds(e={}){let t=[...e.searchRoots??[],ls(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(cs(n,i(n,`utf8`),t.replace(/\.md$/,``))))}return o}function fs(e){return`'${e.replace(/'/g,`'\\''`)}'`}function ps(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 ms(e,t,n){let r=t?[`--model`,fs(t)]:[];return!n||e===`cursor`?r:e===`codex`?[...r,`-c`,fs(`model_reasoning_effort="${n}"`)]:[...r,`--effort`,fs(n)]}function hs(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function gs(e,t){return!t||e===`cursor`?[]:e===`claude`?[`--append-system-prompt`,fs(t)]:[`-c`,fs(`developer_instructions=${hs(t)}`)]}function _s(e,t={}){let n=t.harness??e.harness??`claude`,r=t.effort??e.effort,i=t.model??e.model,a=n===`cursor`?ps(i,r,t.listCursorModels):void 0,o=a?a.model:i,s=[B[n],...ms(n,o,r),...gs(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 vs(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}:_s({name:e.harness,instructions:``,path:``},t):_s(us({name:e.agent,file:e.agentFile,...e.cwd?{cwd:e.cwd}:{},...e.searchRoots?{searchRoots:e.searchRoots}:{}}),t)}function ys(e,t){let{harness:n,command:r,model:i,effort:a,effortNotApplied:o,briefInstructions:s}=vs({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 bs(e,t){return e===`json`?JSON.stringify(t,null,2):t.output}function xs(e){return ne(e).split(`
|
|
65
|
+
`).map(e=>e.trim().replace(/^[-*•]\s+/,``).split(/\s+/)[0]??``).filter(e=>e!==``)}function Ss(){try{return xs(te(`cursor-agent`,[`models`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:15e3}))}catch{return[]}}function Cs(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 ws(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 Ts(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 Es(e,t,n){let r=e.store.listInbox(t);return[...r.unread,...r.read].find(e=>e.id===n)}function Ds(e,t,n){return e.store.ackMessage(t,n)}function Os(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 ks(e,t,n){e.store.removeMessage(t,n)}function As(e,t){e.removeMailbox(t)}async function js(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 Ms(i,o):r.worktree?.primaryRoot,l=r.worktree?.lease,u=Ua(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&&Ns(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 Do.release({worktree:o,...l},{exec:Oo(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),As(e.store,t.id),{agent:r,worktreeRoot:o,retainedWorktree:s&&!u&&(t.keepWorktree||l)?o:void 0,...p?{lease:p}:{},pane:f}}async function Ms(e,t){try{return await Br({from:t,exec:Oo(e)})}catch{throw Error(`cannot resolve the repository of worktree ${t} — git does not know it`)}}function Ns(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 Ps=/^[0-9A-Za-z][0-9A-Za-z._+-]*$/;function Fs(e){if(!Ps.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 Is=(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`,Ls=[/^(?: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 Rs(e){for(let t of Ls){let n=e.match(t)?.[1];if(n)return n}}const zs={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}},Bs=[`PostToolUse`];function Vs(e){if(!n(e))return{};try{return JSON.parse(i(e,`utf8`))}catch{return{}}}function Hs(e,t){r(p(e),{recursive:!0}),u(e,`${JSON.stringify(t,null,2)}\n`)}function Us(e,t=process.cwd(),n){let r=zs[e];if(!r)throw Error(`unknown harness "${e}" (expected claude | cursor | codex)`);n!==void 0&&Fs(n);let i=h(t,r.file),a=Vs(i),o=[],s=!1;for(let[t,c]of Object.entries(r.events)){let l;if(r.pluginHook){let e=r.shape===`claude`?qs(a,c,t):Js(a,c,t);l=e?`removed project hook`:`provided by plugin`,s||=e}else{let e=Is(t,n);l=r.shape===`claude`?Ws(a,c,e):Gs(a,c,e),s=!0}o.push({harness:e,event:t,vendorEvent:c,file:i,status:l})}if(r.pluginHook)for(let t of Bs)(r.shape===`claude`?qs(a,t,t):Js(a,t,t))&&(s=!0,o.push({harness:e,event:t,vendorEvent:t,file:i,status:`removed project hook`}));return s&&Hs(i,a),o}function Ws(e,t,n){let r=e.hooks??={},i=r[t]??=[],a=Rs(n);for(let e of i)for(let t of e.hooks??[]){if(t.command===n)return`already present`;if(a&&Rs(t.command)===a)return t.command=n,`already present`}return i.push({hooks:[{type:`command`,command:n}]}),`registered`}function Gs(e,t,n){e.version??=1;let r=e.hooks??={},i=r[t]??=[],a=Rs(n);for(let e of i){if(e.command===n)return`already present`;if(a&&Rs(e.command)===a)return e.command=n,`already present`}return i.push({command:n}),`registered`}const Ks=(e,t)=>e!==void 0&&Rs(e)===t;function qs(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=>!Ks(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 Js(e,t,n){let r=e.hooks,i=r?.[t];if(!r||!i)return!1;let a=i.filter(e=>!Ks(e.command,n));return a.length!==i.length&&(a.length>0?r[t]=a:delete r[t],!0)}function Ys(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=>Ys(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 Xs=`cyberlegion:unit/`;function Zs(e){return`cyberlegion:hub/${ie(`sha256`).update(e).digest(`hex`).slice(0,16)}`}function Qs(e){return`${Xs}${e}`}function $s(e){return e.kind===void 0||e.kind===`session`}function ec(e,t){let n={registered:[],retired:[],renamed:[]},r=e.registerParticipant({key:Zs(t.root),kind:`service`,name:`cyberlegion`}).participant.id,i=/* @__PURE__ */ new Map;for(let t of e.participants({registeredBy:r}))t.key?.startsWith(Xs)&&i.set(t.key.slice(17),t);let a=new Map(t.listAgents().filter($s).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:Qs(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 tc(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 nc(e,t,n,r=process.env,i=rc){let a;try{if(a=await ic(r,i),!a)return;let o=t.subject;if(!o){if(o=tc(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 rc=async()=>{let{silenceSqliteWarning:e}=await import(`cynapse/sqlite-warning`);return e(),await import(`cynapse`)};async function ic(e=process.env,t=rc){let n;try{n=await t()}catch{return}return n.openStore({path:n.resolveDbPath(e)})}async function ac(e,t=process.env,n=rc){let r;try{if(r=await ic(t,n),!r)return;let i=r;return e.withLock(`cynapse-participants`,()=>ec(i,e))}catch(e){console.error(`cynapse: participant sync skipped — ${e instanceof Error?e.message:String(e)}`);return}finally{r?.close()}}const oc=`Bash(cyberlegion *)`,sc=/^Bash(?:\((?:\*|cyberlegion(?: \*|:\*|\*))\))?$/;function cc(e=process.env){return h(e.CLAUDE_CONFIG_DIR||h(re(),`.claude`),`settings.json`)}function lc(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 uc=e=>e.some(e=>typeof e==`string`&&sc.test(e));function dc(e){try{return uc(lc(e).allow)?`present`:`missing`}catch{return`unreadable`}}function fc(e){let{settings:t,allow:n}=lc(e);return uc(n)?`present`:(t.permissions={...t.permissions??{},allow:[...n,oc]},r(p(e),{recursive:!0}),u(e,`${JSON.stringify(t,null,2)}\n`),`added`)}function pc(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 mc(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=vs({agent:r.agent,harness:r.harness,cwd:r.dir}),s=await Lo(e,{harness:o.harness,command:o.command,briefInstructions:o.briefInstructions,task:pc(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 zo(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 Bo(e,a,o,n);return{kind:`spawned`,presence:a.agent,pane:a.pane,unbound:s,...c}}function hc(e,t){let n=e(`git`,[`-C`,t,`rev-parse`,`--path-format=absolute`,`--git-common-dir`]);if(n)return _c(n)}function gc(e){return`prj-${ie(`sha256`).update(e).digest(`hex`).slice(0,16)}`}function _c(e){try{return o(e)}catch{return g(e)}}function vc(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&&_c(r)===n?{root:_c(i),exact:!0}:{root:p(n),exact:!1}}function yc(e,t={}){let n=e.exec??M,r=g(t.dir??process.cwd()),i=hc(n,r);if(!i)throw Error(`cannot register a project at "${r}" — not inside a git repository`);e.store.ensureMarker();let a=gc(i),o=e.store.getProject(a),s=vc(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 bc(e){return e.listProjects()}function xc(e){return m(e)||e.startsWith(`.`)||e.includes(_)||e.includes(`/`)}function Sc(e){return n(e)&&l(e).isDirectory()}function Cc(e,t){let n=e.store.getProject(t);if(n)return n;let r=g(t);if(xc(t)&&Sc(r))return wc(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(Sc(r))return wc(e,r);throw Error(`no registered project "${t}" (tried id, path, and name) — pass a path inside the repository to register it`)}function wc(e,t){let n=hc(e.exec??M,t);if(!n)throw Error(`"${t}" is not inside a git repository`);return e.store.getProject(gc(n))??yc(e,{dir:t})}const Tc=[`SessionStart`];function Ec(e,t){if(!Tc.includes(t))throw Error(`unsupported --event "${t}" (expected ${Tc.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
|
+
`)}`)}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 cc=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`ServiceOwnershipError`}};const lc=/^[a-z0-9][a-z0-9_-]{0,62}$/;function uc(e){if(!lc.test(e))throw Error(`invalid service name "${e}" — use lowercase letters, digits, "-" or "_" (max 63)`)}function dc(e,t){return`svc-${e}-${t}`}const fc=e=>e.now?.()??Date.now(),pc=e=>new Date(e).toISOString();function mc(e,t){return`service-${e}-${t}`}function hc(e,t){return t.status===`exited`?!1:e.isLive?e.isLive(t):ga(e,t)}function gc(e,t,n){let r=dc(t.id,n),i=F(e.store,r);if(i)return i;e.store.ensureMarker();let a=pc(fc(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 I(e.store,o),o}function _c(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=fc(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?F(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 hc(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 vc(e,t,n){return{project:t,service:n,endpoint:dc(t,n),generation:0,state:`vacant`,updatedAt:pc(fc(e))}}function yc(e,t,n,r){uc(n);let i=ic(e,t),a=e.store.getServiceLease(i.id,n),o=F(e.store,dc(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:gc(e,i,n),lease:a??vc(e,i.id,n)}}function bc(e,t,n,r,i){uc(n);let a=ic(e,t);return e.store.withLock(mc(a.id,n),()=>i(yc(e,a.id,n,r)))}function xc(e,t){let n={...t,updatedAt:pc(fc(e))};return e.store.putServiceLease(n),n}function Sc(e){return new cc(`stale`,e)}function Cc(e,t,n){let{project:r,endpoint:i,lease:a}=yc(e,t,n,!1);return _c(e,r,i,a)}function wc(e,t,n,r={}){return bc(e,t,n,!0,({project:t,endpoint:i,lease:a})=>{let o=_c(e,t,i,a);if(r.force){if(r.force.generation!==a.generation)throw Sc(`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=fc(e),c=ie(8).toString(`hex`),l=xc(e,{project:t.id,service:n,endpoint:i.id,generation:a.generation+1,state:`reserved`,reservation:{token:c,...r.by?{by:r.by}:{},at:pc(s),expiresAt:pc(s+(r.ttlMs??3e5)),...r.force?{forced:!0}:{}},updatedAt:pc(s)});return{outcome:`reserved`,lease:l,view:_c(e,t,i,l),token:c}})}function Tc(e,t){let n=F(e.store,t);if(!n)throw new cc(`unknown-unit`,`no unit "${t}"`);if(!hc(e,n))throw new cc(`unit-not-live`,`unit "${t}" has no live session`);return n}function Ec(e,t,n,r){return bc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(i.state!==`reserved`||i.generation!==r.generation||i.reservation?.token!==r.token)throw Sc(`reservation for generation ${r.generation} is no longer current (now ${i.state} at ${i.generation})`);return Tc(e,r.unit),_c(e,t,n,xc(e,{project:i.project,service:i.service,endpoint:i.endpoint,generation:i.generation,state:`active`,holder:r.unit,updatedAt:i.updatedAt}))})}function Dc(e,t,n,r){return bc(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 Sc(`nothing to release at generation ${r.generation} (now ${i.state} at ${i.generation})`);return _c(e,t,n,xc(e,{project:i.project,service:i.service,endpoint:i.endpoint,generation:i.generation,state:`vacant`,updatedAt:i.updatedAt}))})}function Oc(e,t,n,r){return bc(e,t,n,!1,({project:t,endpoint:n,lease:i})=>{if(i.state!==`active`||i.generation!==r.generation||i.holder!==r.from)throw Sc(`"${r.from}" is not the owner at generation ${r.generation}`);return Tc(e,r.to),_c(e,t,n,xc(e,{...i,generation:i.generation+1,holder:r.to}))})}function kc(e,t,n,r){let{project:i,endpoint:a,lease:o}=yc(e,t,n,!1);if(o.state!==`active`||o.holder!==r.unit||o.generation!==r.generation)throw Sc(`"${r.unit}" at generation ${r.generation} is not the owner (now ${o.state}${o.holder?` by ${o.holder}`:``} at ${o.generation})`);return _c(e,i,a,o)}async function Ac(e,t,n,r){let i=wc(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{Dc(e,t,n,{generation:a,token:i.token})}catch{}throw r}try{return{outcome:`started`,view:Ec(e,t,n,{generation:a,token:i.token,unit:s.unit}),launched:s}}catch(e){throw e instanceof cc?new cc(e.code,`launched unit "${s.unit}" could not become the owner — ${e.message}; stop it`):e}}function jc(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 H))throw Error(`unrecognized --harness "${t.harness}" (${Object.keys(H).join(` | `)})`);i={harness:t.harness}}else{let e=t.agent;try{Uo({name:e,cwd:r})}catch{throw Error(`the agent definition "${e}" does not resolve from the home ${r}`)}i={agent:e}}let a=po(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 Mc=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 Nc(e){if(e===process.pid)return`alive`;try{return process.kill(e,0),`alive`}catch(e){return e.code===`ESRCH`?`dead`:`unknown`}}var Pc=class extends Error{name;constructor(e){super(`timed out waiting for lock "${e}"`),this.name=e,this.name=`LockTimeoutError`}};function Fc(e){return h(e,`locks`)}function Ic(e,t){return h(Fc(e),`${t}.lock`)}function Lc(e){try{return JSON.parse(i(h(e,`holder.json`),`utf8`))}catch{return}}function Rc(e){return Nc(e)!==`dead`}function zc(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Bc(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=Lc(t);if(n&&Rc(n.pid)){try{s(t,e)}catch{c(t,{recursive:!0,force:!0})}return!1}return c(t,{recursive:!0,force:!0}),!0}function Vc(e,t,n={}){let i=n.retryDelayMs??20,a=n.timeoutMs??5e3,o=Ic(e,t);r(Fc(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=Lc(o);if(n&&!Rc(n.pid)&&Bc(o))continue;if(Date.now()>s)throw new Pc(t);zc(i)}}function Hc(e,t,n,r){let i=Vc(e,t,r);try{return n()}finally{i.release()}}async function Uc(e,t,n,r){let i=Vc(e,t,r);try{return await n()}finally{i.release()}}function Wc(e){let t=i(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Mc(e,t)}}function Gc(e){return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>Wc(h(e,t))):[]}let Kc=0;function qc(e,t){r(p(e),{recursive:!0});let n=`${e}.${process.pid}.${Kc++}.tmp`;u(n,t),s(n,e)}function Jc(e,t){qc(e,`${JSON.stringify(t,null,2)}\n`)}function Yc(e,t){qc(e,t)}function q(e){try{return e()}catch(e){if(e instanceof zi)return;throw e}}var Xc=class{root;constructor(e){this.root=e}ensureMarker(){Ri(this.root)}putMessage(e,t){qc(M.messageFile(this.root,e,t.id),`${JSON.stringify(t,null,2)}\n`)}listInbox(e){let t=q(()=>M.inboxDir(this.root,e)),n=q(()=>M.inboxReadDir(this.root,e));return{unread:t?Gc(t):[],read:n?Gc(n):[]}}hasMailbox(e){let t=q(()=>M.inboxDir(this.root,e));return t!==void 0&&n(t)}ackMessage(e,t){let i=q(()=>M.messageFile(this.root,e,t));if(!i||!n(i))throw Error(`"${t}" is not an unread message in this inbox`);let a=Wc(i),o=M.messageReadFile(this.root,e,t);return r(p(o),{recursive:!0}),s(i,o),a}removeMessage(e,t){let r=q(()=>M.messageFile(this.root,e,t));if(r&&n(r)){c(r);return}let i=q(()=>M.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(M.inboxDir(this.root,e),{recursive:!0,force:!0})}putAgent(e){Jc(M.agentFile(this.root,e.id),e)}getAgent(e){let t=q(()=>M.agentFile(this.root,e));if(t&&n(t))return Wc(t)}listAgents(){let e=M.agentsDir(this.root);return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>Wc(h(e,t))).sort((e,t)=>e.createdAt.localeCompare(t.createdAt)):[]}removeAgent(e){c(M.agentFile(this.root,e),{force:!0})}removeAgentData(e){c(M.dataDir(this.root,e),{recursive:!0,force:!0})}putProject(e){Jc(M.projectFile(this.root,e.id),e)}getProject(e){let t=q(()=>M.projectFile(this.root,e));if(t&&n(t))return Wc(t)}listProjects(){let e=M.projectsDir(this.root);return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>Wc(h(e,t))).sort((e,t)=>e.registeredAt.localeCompare(t.registeredAt)):[]}putServiceLease(e){Jc(M.serviceLeaseFile(this.root,e.project,e.service),e)}getServiceLease(e,t){let r=q(()=>M.serviceLeaseFile(this.root,e,t));if(r&&n(r))return Wc(r)}putPaneIndex(e,t){Yc(M.paneFile(this.root,e),t)}resolvePaneId(e){let t=M.paneFile(this.root,e);return n(t)?i(t,`utf8`).trim():void 0}findPaneByAgentId(e){let t=M.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(M.paneFile(this.root,e),{force:!0})}writeBrief(e,t){Yc(M.briefFile(this.root,e),t)}readBrief(e){let t=q(()=>M.briefFile(this.root,e));return t&&n(t)?i(t,`utf8`):void 0}setMainPane(e){Hc(this.root,`main-pane`,()=>{let t=M.mainPaneFile(this.root);e?Yc(t,e):c(t,{force:!0})})}getMainPane(){let e=M.mainPaneFile(this.root);return n(e)?i(e,`utf8`).trim():void 0}withLock(e,t){return Hc(this.root,e,t)}withLockAsync(e,t){return Uc(this.root,e,t)}};function Zc(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 Qc(e,t,n){if(R(e)===t.id)throw Error(`a unit cannot ${n} its own session — run unit ${n} ${t.handle} from another session`)}function $c(e,t){return t.pane?.id??e.store.findPaneByAgentId(t.id)}function el(e,t){if(e.adapter)return e.adapter;if(t.pane?.mux===`tmux`)return O;if(t.pane?.mux===`herdr`)return E;try{return V(e.env??process.env,e.exec??P)}catch{return}}function tl(e,t,n){let r={...t,status:`stopped`,pane:null};return I(e.store,r),n&&e.store.removePaneIndex(n),r}function nl(e,t){let n=$c(e,t);if(!n)return{agent:tl(e,t,void 0),verified:!1};let r=e.exec??P,i=el(e,t);if(!i)return{agent:tl(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:tl(e,t,n),pane:n,verified:a.length>0}}function rl(e,t){let n=z(e.store,t);return Zc(n,t),Qc(e,n,`stop`),n.status===`stopped`?{agent:n,verified:!0,alreadyStopped:!0}:{...nl(e,n),alreadyStopped:!1}}async function il(e,t,r={}){let i=z(e.store,t);Zc(i,t),Qc(e,i,`restart`);let a=i.harness;if(!a||!(a in H))throw Error(`unit "${i.handle}" has harness "${i.harness??``}", not in the launch map (${Object.keys(H).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=nl(e,i);o=t.agent,s=t.pane}let c=e.env??process.env,l=e.exec??P,u=o.launch??H[a],d=o.conversation&&!r.fresh?Co(a,u,o.conversation):void 0,f=o.worktree?`workspace`:`tab`,p,m;try{m=e.adapter??V(c,l);let t=f===`workspace`?{label:eo({brief:e.store.readBrief(i.id)??``,handle:i.handle,id:i.id})}:{};p=m.open(l,{cwd:o.cwd,launch:d?xo(e,m.name,i.id,d,{bindSelf:!0,fallback:u}):xo(e,m.name,i.id,u,{bindSelf:!0}),at:f,from:kr(m,N(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:h===`tmux`||h===`herdr`?{mux:h,id:p.id}:null,lastSeen:new Date(e.now?.()??Date.now()).toISOString()};I(e.store,g),e.store.putPaneIndex(p.id,i.id);let _=g.brief,v=await Wa(()=>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 al(e,t){if(t.kind===`standing`||t.kind===`service`)return`none`;if(t.status===`stopped`)return`stopped`;if(t.status===`exited`)return`exited`;let n=$c(e,t),r=n?el(e,t):void 0;if(!n||!r)return`unknown`;let i=r.listPanes(e.exec??P);return i.length===0?`unknown`:i.some(e=>e.id===n)?`live`:`gone`}function ol(e,t){let n=z(e.store,t);Zc(n,t);let r=Hi(e.env??process.env);if(!r)throw Error(`unit rebind needs to run inside a tmux or herdr pane — there is no pane to bind`);let i=$c(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?F(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=al(e,n);if(i&&i!==r.pane&&(s===`live`||s===`unknown`))throw Error(`unit "${n.handle}" may still be running in pane ${i} — stop it first (unit stop ${n.handle})`);let c={...n,status:`active`,pane:{mux:r.mux,id:r.pane},lastSeen:new Date(e.now?.()??Date.now()).toISOString()};return I(e.store,c),i&&i!==r.pane&&e.store.removePaneIndex(i),e.store.putPaneIndex(r.pane,n.id),c}function sl(e){if(!e)return!1;try{return uo(e),!0}catch{return!1}}function cl(e,t,r){if(r===`none`)return[];let i=[];return r===`live`&&(i.push(`focus`,`nudge`,`read`),sl(t.harness)&&i.push(`clear`)),$c(e,t)!==void 0&&(r===`live`||r===`gone`||r===`unknown`)&&i.push(`stop`),t.harness&&t.harness in H&&n(t.cwd)&&i.push(`restart`),(r===`stopped`||r===`exited`||r===`gone`)&&i.push(`rebind`),i.push(`close`),i}function ll(e,t){let n=z(e.store,t),r=al(e,n),i=$c(e,n),a=n.pane?.mux??(i?el(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,lastSeen:n.lastSeen,controls:cl(e,n,r)}}function ul(e,t){let n;try{n=JSON.parse(t)?.session_id}catch{return}if(typeof n!=`string`||n===``)return;let r=R(e),i=r?F(e.store,r):void 0;i&&i.kind!==`standing`&&i.kind!==`service`&&i.conversation!==n&&I(e.store,{...i,conversation:n})}async function dl(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=is(e,{meId:t.meId,unread:!0,thread:t.thread,from:t.from});if(r.length>0){let n=r[0];return ss(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 fl(e,t,n,r={}){let i=r.sleep??(e=>new Promise(t=>setTimeout(t,e))),a=/* @__PURE__ */ new Set;for(let n of is(e,{meId:t.meId,thread:t.thread,from:t.from}))a.add(n.id);let o=0;for(;;){let s=is(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 pl=globalThis.__SKILL_SCRIPT__?.version??JSON.parse(i(new URL(`../package.json`,import.meta.url),`utf8`)).version;function J(e){return{store:new Xc(Li({space:e.space})),env:process.env,self:Eo()}}function Y(e){return e.format===`json`?`json`:`toon`}function ml(e){let t=R(e);return t||K("no identity in this session — run `cyberlegion unit register` first"),pa(e,t),t}function X(e){return e.option(`--space <path>`,`isolate the hub root (overrides the global hub / $CYBERLEGION_ROOT)`).addOption(new ve(`--format <format>`,`output format`).choices([`toon`,`json`]).default(`toon`))}function hl(e){return e.hook(`postAction`,async(e,t)=>{let n=t.opts();(t.name()!==`who`||n.reconcile)&&await Bs(J(n).store)})}const Z=new we;Z.name(`cyberlegion`).description(`Harness-agnostic agent session spawning and messaging over the filesystem`).version(pl).enablePositionalOptions();const Q=Z.command(`unit`).description(`legion units — register, discover, spawn, and reap`);function gl(e,t,n){if(!t.handle){let n=L(e.store).filter(e=>e.kind===`standing`);W(Y(t),{toon:As(`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=L(e.store).find(e=>e.handle===t.handle&&e.kind!==`standing`&&e.status!==`exited`),i=Yi(e,{handle:t.handle,home:n});r&&console.error(`a live session already claims handle "${t.handle}"`),W(Y(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})}hl(X(Q.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=J(e),n;try{n=jc(t.exec??P,e)}catch(e){K(e instanceof Error?e.message:String(e))}if(e.standing){gl(t,e,n);return}let r=Ki(t,{handle:e.handle,harness:e.harness});W(Y(e),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status}),json:r})}),X(Q.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=J(t);if(t.show){let r;try{r=la(n.store,e)}catch(e){K(e instanceof Error?e.message:String(e))}W(Y(t),{toon:U({presence:r?.id??`none`}),json:{presence:r?.id??null}});return}if(t.clear){try{sa(n,e)}catch(e){K(e instanceof Error?e.message:String(e))}W(Y(t),{toon:U({presence:`none`}),json:{presence:null}});return}let r;try{r=oa(n,e)}catch(e){K(e instanceof Error?e.message:String(e))}W(Y(t),{toon:U({owner:r.handle,presence:r.presence}),json:{owner:r.handle,presence:r.presence}})}),X(Q.command(`whoami`)).description(`print this session own identity`).action(e=>{let t=J(e),n=R(t);n||K("no identity in this session — run `cyberlegion unit register` first");let r=F(t.store,n);r||K(`registered self id "${n}" has no agent record`),W(Y(e),{toon:U({id:r.id,handle:r.handle,harness:r.harness??`-`,status:r.status}),json:r})});function _l(e){let t=J(e);B(t),e.reconcile&&ba(t,{adopt:!0});let n=L(t.store).filter(t=>e.all||t.status!==`exited`);W(Y(e),{toon:As(`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??`-`}],`${n.length} units`),json:n}),n.length===0&&G(`cyberlegion unit register to join`)}hl(X(Q.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(_l),hl(X(Q.command(`prune`))).description(`mark dead units exited and sweep`).action(e=>{let t=J(e);B(t);let n=Sa(t);W(Y(e),{toon:As(`pruned`,n,[{key:`id`,get:e=>e.id},{key:`handle`,get:e=>e.handle}],`${n.length} pruned`),json:n})});const vl=`(harness default)`;function yl(e){return e.effortNotApplied?`${e.effortNotApplied} (not applied)`:e.effort??vl}function bl(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 xl(e){return X(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 ve(`--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 Sl(e){if(e.trustBlocked){if(console.error(e.trustBlocked),e.agent.brief){let t=Fa(e.agent.brief).replaceAll(`'`,`'\\''`);console.error(`then: cyberlegion unit nudge ${e.agent.handle} --message '${t}'`)}process.exitCode=1}}function Cl(e){e.base?.fallback&&console.error(`base: fell back to local HEAD — ${e.base.fallback}`)}function wl(e){return hl(xl(e)).description(`launch a new peer session in its own git worktree (tmux or herdr)`).action(async e=>{let t=J(e);B(t);let n;try{n=Qo(e,ts)}catch(e){K(e instanceof Error?e.message:String(e))}bl(n);let r=await go(t,n.input,{noWake:n.noWake});r.warning&&console.error(`first-turn doorbell not confirmed (peer still spawned; nudge it manually): ${r.warning}`),Sl(r),Cl(r),W(Y(e),{toon:U({spawned:r.agent.id,handle:r.agent.handle,harness:r.agent.harness,model:n.launched.model??vl,effort:yl(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??vl,effort:yl(n.launched),rung:r.rung,trust:r.trust}}),G(`cyberlegion unit read ${r.agent.id}`)})}wl(Q.command(`spawn`)),hl(X(Q.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=J(t);B(n);let r=z(n.store,e),i=await ds(n,{id:r.id,force:t.force,keepWorktree:t.keepWorktree});W(Y(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})}),X(Q.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=J(t);B(n);let r=rl(n,e);W(Y(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||G(`cyberlegion unit restart ${r.agent.handle}`)}),X(Q.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=J(t);B(n);let r=await il(n,e,{noWake:t.wake===!1,fresh:t.fresh===!0});W(Y(t),{toon:U({restarted:r.agent.id,previous:r.previousPane??`-`,pane:r.pane,resumed:r.resumed,rung:r.rung}),json:r}),r.warning&&G(`warning: ${r.warning}`)}),X(Q.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(J(t),e);W(Y(t),{toon:U({rebound:n.id,pane:n.pane?.id??`-`}),json:{rebound:n.id,pane:n.pane}})}),X(Q.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=J(t);B(n);let r=ll(n,e);W(Y(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??`-`,lastSeen:r.lastSeen,controls:r.controls.join(`,`)||`-`}),json:r})}),X(Q.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)&&K(`a ref and --repo/--branch cannot be combined — pass one or the other`);let r=J(t);B(r);let{agent:i,pane:a}=Ao(r,e??n),o=e??i.id;W(Y(t),{toon:U({focused:o,pane:a}),json:{ref:o,pane:a}})}),X(Q.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`,Pa).action(async(e,t)=>{let n=J(t);B(n);let{pane:r,message:i,resubmits:a}=await jo(n,e,{message:t.message});W(Y(t),{toon:U({nudged:e,pane:r}),json:{ref:e,pane:r,message:i,resubmits:a}})}),X(Q.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=J(t);B(n);let{pane:r,output:i}=Mo(n,e,{lines:t.lines});console.log($o(Y(t),{ref:e,pane:r,output:i}))}),X(Q.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=J(t);B(n);let r;try{r=await No(n,e)}catch(e){K(e instanceof Error?e.message:String(e))}W(Y(t),{toon:U({cleared:e,pane:r.pane,command:r.command}),json:{cleared:e,pane:r.pane,command:r.command}})});const Tl=Z.command(`project`).description(`register and resolve projects (one per git repository)`);function El(e){return{id:e.id,name:e.name,root:e.root}}async function Dl(e,t,n){let r=await Ls(e.store,n,e.exec??P),i=r?{...n,subject:r.subject}:n;W(Y(t),{toon:U({...El(i),...r?{channel:r.channel?.handle??`none`}:{}}),json:r?{...i,...r.channel?{channel:r.channel}:{}}:i})}X(Tl.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=J(e),n;try{n=ec({store:t.store},{dir:e.dir})}catch(e){K(e instanceof Error?e.message:String(e))}await Dl(t,e,n)}),X(Tl.command(`list`)).description(`list the registered projects`).action(e=>{let t=tc(J(e).store);W(Y(e),{toon:As(`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&&G(`cyberlegion project register to add the current repository`)}),X(Tl.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=J(t),r;try{r=ic({store:n.store},e)}catch(e){K(e instanceof Error?e.message:String(e))}await Dl(n,t,r)});const Ol=Z.command(`service`).description(`project services — one authoritative owner each, fenced by generation`);function kl(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 Al(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t??`-`]))}function jl(e,t){W(Y(e),{toon:U(Al(t)),json:t})}function Ml(e){try{return e()}catch(e){K(e instanceof Error?e.message:String(e))}}const Nl=e=>Number.parseInt(e,10);function Pl(e,t){return t===void 0?[`.`,e]:[e,t]}function Fl(e,t){return t?Ml(()=>z(e.store,t)).id:ml(e)}X(Ol.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]=Pl(e,t),a=J(n);jl(n,kl(Ml(()=>Cc(a,r,i))))}),X(Ol.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`,Nl).option(`--force-generation <n>`,`reserve even over a healthy owner — must name the current generation`,Nl).action((e,t,n)=>{let[r,i]=Pl(e,t),a=J(n),o=Ml(()=>wc(a,r,i,{by:R(a),ttlMs:n.ttl,...n.forceGeneration===void 0?{}:{force:{generation:n.forceGeneration}}}));jl(n,{outcome:o.outcome,...kl(o.view),...o.outcome===`reserved`?{token:o.token,expiresAt:o.lease.reservation?.expiresAt}:{}}),o.outcome===`reserved`?G(`start the runtime, then: cyberlegion service bind ${r} ${i} --generation ${o.lease.generation} --token ${o.token}`):o.outcome===`starting`&&G(`another caller is starting it — re-run to resolve: cyberlegion service resolve ${r} ${i}`)}),X(Ol.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`,Nl).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]=Pl(e,t),a=J(n),o=Fl(a,n.unit);jl(n,kl(Ml(()=>Ec(a,r,i,{generation:n.generation,token:n.token,unit:o}))))}),X(Ol.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`,Nl).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]=Pl(e,t),a=J(n),o=n.token?{generation:n.generation,token:n.token}:{generation:n.generation,unit:Fl(a,n.unit)};jl(n,kl(Ml(()=>Dc(a,r,i,o))))}),X(Ol.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`,Nl).requiredOption(`--to <ref>`,`the unit taking over`).option(`--from <ref>`,`the current owner (default: this session)`).action((e,t,n)=>{let[r,i]=Pl(e,t),a=J(n),o=Fl(a,n.from),s=Ml(()=>z(a.store,n.to)).id;jl(n,kl(Ml(()=>Oc(a,r,i,{generation:n.generation,from:o,to:s}))))}),X(Ol.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`,Nl).option(`--unit <ref>`,`the unit to check (default: this session)`).action((e,t,n)=>{let[r,i]=Pl(e,t),a=J(n),o=Fl(a,n.unit);jl(n,kl(Ml(()=>kc(a,r,i,{unit:o,generation:n.generation}))))}),hl(xl(Ol.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`,Nl).action(async(e,t,n)=>{let[r,i]=Pl(e,t),a=J(n);B(a);let o;try{o=Qo(n,ts)}catch(e){K(e instanceof Error?e.message:String(e))}bl(o);let s,c;try{c=await Ac(a,r,i,{by:R(a),ttlMs:n.ttl,launch:async()=>{let e=await go(a,o.input,{noWake:o.noWake});return s=e.warning,Sl(e),Cl(e),{unit:e.agent.id,pane:e.pane}}})}catch(e){K(e instanceof Error?e.message:String(e))}s&&console.error(`first-turn doorbell not confirmed (peer still spawned; nudge it manually): ${s}`),jl(n,{outcome:c.outcome,...kl(c.view)}),c.outcome===`starting`&&G(`another caller is starting it — re-run to resolve: cyberlegion service resolve ${r} ${i}`)});const $=Z.command(`mail`).description(`durable inter-agent messaging`);function Il(e){return X(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=J(e),n=e.from??ml(t),r=rs(e.body,e.bodyFile),i=ns({store:t.store},{fromId:n,to:e.to,subject:e.subject,body:r,thread:e.thread,replyTo:e.replyTo}),a=await Ua(t.store,()=>V(t.env??process.env),P,{toId:i.to,fromId:n,noNudge:e.nudge===!1,spawnHome:e=>Ys(t,e)});a.warning&&console.error(`delivery doorbell not confirmed (message still delivered): ${a.warning}`),W(Y(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}:{}}})})}Il($.command(`send`));function Ll(e,t,n,r){let i=is({store:e.store},{meId:n,unread:t.unread,from:t.from,thread:t.thread}),a=i.filter(e=>!e.read).length;W(Y(t),{toon:As(`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&&G(`${r} ${o.id}`)}function Rl(e,t,n){let r;try{r=aa(e.store,n)}catch(e){K(e instanceof Error?e.message:String(e))}let i=as({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)`;W(Y(t),{toon:[U({unit:r.id,handle:r.handle,mailbox:i.mailbox}),As(`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 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 au(e){let t=Y(e);R(t),e.unit?iu(t,e,e.unit):ru(t,e,e.owner?Sa(t.store,e.owner):Nl(t),`cyberlegion mail read`)}Z(tu.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(au),Z(tu.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):Nl(n);if(t.ack){let{msg:i,acked:a}=Os({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=Es({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(tu.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):Nl(n),i=Ds({store:n.store},r,e);G(X(t),{toon:U({acked:i.id,from:i.fromHandle,subject:i.subject}),json:i})}),Z(tu.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=Nl(n);ks({store:n.store},r,e),G(X(t),{toon:U({deleted:e}),json:{deleted:e}})}),Z(tu.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=
|
|
80
|
+
`).action(async e=>{let t=Y(e),n=Nl(t),r=await Al({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(tu.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=Nl(t);await jl({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(tu.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{kl(t,i(0,`utf8`))}catch{}let n=Ec(t,e.event);n&&console.log(JSON.stringify(n))});const ou=Q.command(`agent`).description(`resolve reusable agent definitions`);function su(e,t){return t||e.length<=200?e:`${e.slice(0,200)}… (${e.length} chars total, pass --full)`}function cu(e){return{name:e.name,description:e.description,model:e.model??Ll,effort:e.effort,harness:e.harness??Ll,warm:e.warm??!1,interactive:e.interactive??!1,path:e.path}}Z(ou.command(`list`)).description(`list resolvable agent definitions under .agents/agents/`).option(`--dir <path>`,`project dir to search from`,process.cwd()).action(e=>{let t=ds({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(ou.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=us({name:e,cwd:t.dir})}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U({...cu(n),instructions:su(n.instructions,t.full)}),json:{...n,instructions:t.full?n.instructions:su(n.instructions,t.full)}})}),Z(ou.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=us({name:e,file:t.file,cwd:t.dir})}catch(e){q(e instanceof Error?e.message:String(e))}G(X(t),{toon:U(cu(n)),json:n})}),Z(ou.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=us({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 lu=`cyberlegion init --allow-cli to add ${oc} to Claude Code's permissions.allow, so units can mail their results back`,uu=Q.command(`mux`).description(`the unit-agnostic pane layer — multiplexer detection and diagnostics`);Z(uu.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`?dc(cc(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(lu),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(uu.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 hl(g(e.from)),new hl(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 ${oc} 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=cc(t.env??process.env);try{r=e.allowCli?fc(n):dc(n)}catch(e){q(e instanceof Error?e.message:String(e))}}let i;try{i=Us(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(lu),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`))}),Ul(Q.command(`spawn`)),nu(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(au),Pl(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(Il),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 du(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 du();export{};
|