@robota-sdk/agent-command 3.0.0-beta.81 → 3.0.0-beta.82

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.
@@ -16,7 +16,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
16
16
  `)||`Context reference not found: ${r}`,data:{diagnostics:i.diagnostics}}}function We(t,n){let r=n.join(` `).trim();if(!r)return{success:!1,message:T};let i=(0,e.removeCommandContextReference)(t,r);return i.removed?{success:!0,message:`Context reference removed: ${w(i.removed)}.`,data:{removed:i.removed}}:{success:!1,message:`Context reference not found: ${r}`}}function Ge(t,n,r){let i=(0,e.writeAutoCompactThresholdSetting)(t,n),a=i?`settings`:`session`;return(0,e.setCommandAutoCompactThreshold)(t,n,a),{success:!0,message:Ke(r,n,i),data:{autoCompactThreshold:n,autoCompactThresholdSource:a,persisted:i}}}function Ke(e,t,n){let r=ze(n);return e===`disabled`?`Auto compact disabled (${r}).`:e===`enabled`?`Auto compact enabled at ${S(t)} (${r}).`:`Auto compact threshold set to ${S(t)} (${r}).`}function qe(e){if(e.endsWith(`%`)){let t=Number(e.slice(0,-1));return!Number.isFinite(t)||t<=0||t>100?{success:!1,message:`Auto compact percentage must be greater than 0% and at most 100%.`}:{success:!0,threshold:t/100}}if(e.includes(`.`)){let t=Number(e);return!Number.isFinite(t)||t<=0||t>1?{success:!1,message:`Auto compact fraction must be greater than 0 and at most 1.`}:{success:!0,threshold:t}}return{success:!1,message:`Use a percentage such as 85% or a fraction such as 0.85.`}}function Je(e){return`References: ${e.filter(e=>e.status===`active`).length} active, ${e.filter(e=>e.status===`observed`).length} observed`}function E(e,t){return{name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description,...e.example===void 0?{}:{example:e.example},...e.modelInvocable===void 0?{}:{modelInvocable:e.modelInvocable},...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},...e.userInvocable===void 0?{}:{userInvocable:e.userInvocable},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.safety===void 0?{}:{safety:e.safety},...e.subcommands===void 0?{}:{subcommands:e.subcommands},...t.semanticRole===void 0?{}:{semanticRole:t.semanticRole},lifecycle:t.lifecycle,requiresPermission:t.requiresPermission,execute:t.execute}}function Ye(){return{name:`context`,displayName:`Context References`,description:`Context window info, reference inventory, and auto-compact controls`,modelDescription:"Inspect the context window. Use it before a large task or before deciding to compact, or to see which files the user pinned into context. Bare returns used/max tokens and percentage, the auto-compact threshold, the pinned-reference summary and the turn count; `list` returns the per-category token breakdown and every pinned reference.",source:`context`,modelInvocable:!0,userInvocable:!0,argumentHint:`list | add <path> | remove <path> | clear | auto ...`,subcommands:[{name:`list`,description:`List loaded context references`,source:`context`,modelInvocable:!0},{name:`add`,description:`Add a file to active context references`,source:`context`,modelInvocable:!1},{name:`remove`,description:`Remove a context reference`,source:`context`,modelInvocable:!1},{name:`clear`,description:`Clear context references`,source:`context`,modelInvocable:!1},{name:`auto`,description:`Inspect or change auto-compact policy`,source:`context`,modelInvocable:!1}]}}function Xe(){return E(Ye(),{requiresPermission:!1,lifecycle:`inline`,execute:Be})}var Ze=class{name=`context`;getCommands(){return[Ye()]}};function Qe(){return{name:`agent-command-context`,commandSources:[new Ze],systemCommands:[Xe()]}}function $e(){return{name:`devices`,displayName:`Devices`,description:`Manage this device's identity among the user's devices: list the roster, create the identity and its recovery phrase, revoke a device, or rotate the signing key from the phrase. Operator-only; the phrase is handled on the terminal and results carry only device ids and names.`,source:`devices`,modelInvocable:!1,userInvocable:!0,argumentHint:`[list|init [name]|revoke <device-id>|recover]`,subcommands:[{name:`list`,description:`List your devices`,source:`devices`},{name:`init`,description:`Create your device identity and recovery phrase`,source:`devices`,argumentHint:`[name]`},{name:`revoke`,description:`Revoke a device with the signing key`,source:`devices`,argumentHint:`<device-id>`},{name:`recover`,description:`Rotate the signing key from your recovery phrase`,source:`devices`}]}}const et={"no-terminal":`This needs an interactive terminal; the recovery phrase is never shown or read anywhere else.`,"not-initialized":"This device has no identity yet. Run `/devices init` first.","already-initialized":"This device already has an identity. Use `/devices recover` to rotate its signing key.",cancelled:`Cancelled. Nothing was changed.`,"confirmation-failed":`The confirmation did not match. Nothing was changed.`,"phrase-invalid":`That is not a valid recovery phrase. Nothing was changed.`,"phrase-mismatch":`That phrase (with that passphrase) belongs to a different identity than this device. Nothing was changed.`,"no-signing-key":"This device does not hold the signing key. Revoke from a device that does, or `/devices recover`.","signing-key-expired":"The signing key on this device has expired. Run `/devices recover` to issue a new one.","unknown-device":`No device in the roster has that id.`,"ambiguous-device":`More than one device starts with that id; give more of it.`,"self-revocation":"This device cannot revoke itself. Revoke it from another device, or `/devices recover`.","changed-concurrently":`The device identity changed in another session while this was waiting. Nothing was changed; try again.`};function D(e){return e.slice(0,10)}function tt(e){return new Date(e).toISOString().slice(0,10)}function nt(e){return{success:!1,message:et[e]}}function rt(e){if(e===void 0)return{success:!0,message:et[`not-initialized`]};let t=e.devices.map(e=>{let t=[...e.thisDevice?[`this device`]:[],...e.holdsSigningKey?[`holds the signing key`]:[]],n=t.length>0?` (${t.join(`, `)})`:``;return` ${D(e.deviceId)} ${e.name}${n} certificate expires ${tt(e.certificateExpiresAt)}`});return{success:!0,message:[`Devices of user ${D(e.userId)}:`,...t,`${e.revokedDeviceCount} revoked. Roster and revocation list valid until ${new Date(e.listsExpireAt).toISOString()}.`].join(`
17
17
  `)}}function it(e){return e.getCommandInvocationSource()===`user`}async function at(e,t,n){if(!e.canHandoffTerminal())return nt(`no-terminal`);try{let r=await e.runWithTerminal(t);return r.ok?{success:!0,message:n(r.value)}:nt(r.reason)}catch(e){return{success:!1,message:`Device identity operation failed: ${e instanceof Error?e.message:`unknown error`}`}}}async function ot(e,t,n){if(!it(t))return{success:!1,message:"`/devices` runs only for the operator at this terminal, never from a remote surface or the model."};let r=n.trim(),i=r.indexOf(` `),a=(i===-1?r:r.slice(0,i)).toLowerCase(),o=i===-1?``:r.slice(i+1).trim();switch(a){case``:case`list`:try{return rt(await e.list())}catch(e){return{success:!1,message:`Device identity could not be read: ${e instanceof Error?e.message:`unknown error`}`}}case`init`:return at(t,()=>e.init(o.length>0?{name:o}:{}),e=>[`Device identity created. This device: ${D(e.deviceId)}; user ${D(e.userId)}.`,`It holds signing key ${D(e.signingKeyId)}.`,...e.keyStorage===void 0?[]:[`Private keys are kept in: ${e.keyStorage}.`],`Keep the recovery phrase offline; it is the only way to recover this identity.`].join(`
18
18
  `));case`recover`:return at(t,()=>e.recover(),e=>[`Recovered. New signing key ${D(e.signingKeyId)}; ${e.revokedSigningKeyCount} old signing key(s) revoked.`,`This device (${D(e.deviceId)}) is certified again.`,...e.droppedDeviceCount>0?[`${e.droppedDeviceCount} other device(s) were certified by a retired signing key and must enrol again.`]:[]].join(`
19
- `));case`revoke`:return o.length===0?{success:!1,message:`Usage: /devices revoke <device-id>`}:at(t,()=>e.revoke(o),e=>`Revoked ${e.name} (${D(e.deviceId)}). A new roster and revocation list were issued.`);case`add`:case`join`:return{success:!1,message:`\`/devices ${a}\` is not available yet: enrolling another device needs the device connection, which is not built yet.`};default:return{success:!1,message:`Unknown argument "${a}". Usage: /devices [list|init [name]|revoke <device-id>|recover]`}}}var st=class{name=`devices`;getCommands(){return[$e()]}};function ct(e){let t=E($e(),{requiresPermission:!1,lifecycle:`inline`,execute:(t,n)=>ot(e,t,n)});return{name:`agent-command-devices`,commandSources:[new st],systemCommands:[t]}}const lt=3e3;function ut(e,t){return new Promise(n=>{let i=Date.now(),a=(0,r.createConnection)({host:e,port:t}),o=setTimeout(()=>{a.destroy(),n({reachable:!1,error:`timeout (${lt/1e3}s)`})},lt);a.on(`connect`,()=>{clearTimeout(o),a.destroy(),n({reachable:!0,elapsedMs:Date.now()-i})}),a.on(`error`,e=>{clearTimeout(o),n({reachable:!1,error:e.message})})})}function dt(e){if(!(0,n.existsSync)(e))return{exists:!1,isDirectory:!1,writable:!1};let t=!1,r;try{let i=(0,n.statSync)(e);t=i.isDirectory(),r=i.mode&511}catch{return{exists:!0,isDirectory:!1,writable:!1}}let i=!1;try{(0,n.accessSync)(e,n.constants.W_OK),i=!0}catch{i=!1}return{exists:!0,isDirectory:t,writable:i,...r===void 0?{}:{mode:r}}}function ft(e,t=process.env){let r=e.trim().split(/\s+/)[0];if(r===void 0||r.length===0)return!1;if((0,i.isAbsolute)(r)||r.includes(`/`))return(0,n.existsSync)(r);let a=process.platform===`win32`?[``,`.exe`,`.cmd`,`.bat`]:[``];return(t.PATH??``).split(i.delimiter).filter(e=>e.length>0).some(e=>a.some(t=>(0,n.existsSync)((0,i.join)(e,r+t))))}function pt(e=process.env){return{probeEndpoint:ut,inspectPath:dt,resolveCommand:t=>ft(t,e),ownerOnlyGuarantee:()=>(0,a.ownerOnlyGuarantee)()}}const mt={ok:`✓`,warn:`⚠`,fail:`✗`,"not-configured":`○`,"not-probed":`–`};function ht(e,t){let n=[` ${mt[e.status]} ${e.label} [${e.id}] ${e.status}${e.cause===void 0?``:`: ${e.cause}`}`];e.path!==void 0&&n.push(` path: ${e.path}`);for(let t of e.detail??[])n.push(` ${t}`);if(e.repair!==void 0){let r=t.formatRepairCommand?.(e.repair);n.push(` repair: ${r??`request repair for ${e.repair} through your host`}`)}return n}function gt(e,t){let n=t.productName?.trim();return e.failCount===0&&e.warnCount===0?n?`✓ All checks passed. ${n} is ready to use.`:`✓ All checks passed.`:e.failCount>0?n?`✗ ${e.failCount} issue(s) found. Fix the items above to use ${n}.`:`✗ ${e.failCount} issue(s) found. Fix the items above before use.`:n?`⚠ ${e.warnCount} warning(s). ${n} may work but check the items above.`:`⚠ ${e.warnCount} warning(s). Check the items above.`}function _t(e,t=`Doctor`,n={}){let r=[``,t,``,...e.checks.flatMap(e=>ht(e,n)),``,gt(e,n)];return e.repairable.length>0&&r.push(` repairable: ${e.repairable.join(`, `)} — ${n.repairOffer??`ask your host to apply a repair`}`),r.push(``),r}const O=`[redacted]`,vt=/(\b[a-z][a-z0-9+.-]{0,31}:\/\/)([^\s/@]+)@/gi,yt=/\b(bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi,bt=/\b(?:sk-[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{20,}|ghp_[A-Za-z0-9]{20,}|xox[abprs]-[A-Za-z0-9-]{10,})\b/g,xt=/\.\.\."[^"]*"\.\.\./g;function St(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ct(e,t=[]){let n=e,r=new Set;for(let e of t)typeof e!=`string`||e.length<4||r.has(e)||(r.add(e),n=n.replace(new RegExp(St(e),`g`),O));return n=n.replace(vt,`$1${O}@`),n=n.replace(yt,`$1 ${O}`),n=n.replace(bt,O),n}function wt(t){return t instanceof e.SettingsParseError?`${t.name}: ${t.filePath} is not valid JSON (see the settings check)`:`${t.name}: ${t.message.replace(xt,`…`)}`}function Tt(e,t){let n=new Set,r=e=>{if(e!==void 0){if(e.startsWith(`$ENV:`)){let r=t[e.slice(5).trim()];r!==void 0&&n.add(r);return}n.add(e)}};for(let t of e)if(t!==void 0){r(t.provider?.apiKey);for(let e of Object.values(t.providers??{}))r(e.apiKey);for(let e of Object.values(t.env??{}))n.add(e)}return[...n]}function Et(e){let t=(0,i.basename)((0,i.dirname)(e.kind===`host`?e.path:e.relativePath)).replace(/^\./,``);return`settings.${e.scope}.${t}`}function Dt(e){let t=e.settingsSources.find(t=>t.kind===`host`&&t.path===e.userSettingsPath);return t===void 0?void 0:Et(t)}function Ot(e){let t=e.cause;if(t===void 0)return e.state;switch(t.state){case`unreadable`:return t.errno===void 0?`unreadable`:`unreadable (${t.errno})`;case`invalid-json`:return t.offset===void 0?`invalid-json`:`invalid-json at offset ${t.offset}`;case`schema-invalid`:return`schema-invalid: ${(t.issues??[]).map(e=>`${e.path} (${e.code})`).join(`, `)}`;default:return t.state}}function kt(e,t){return e.source.kind===`host`&&e.source.path===t.userSettingsPath&&e.state===`empty`}function At(e,t){let n=Et(e.source),r=e.source.kind===`host`?e.source.path:e.source.relativePath;if(e.state===`absent`)return{id:n,label:`Settings layer`,status:`not-configured`,path:r,cause:`absent`};if(e.state===`ok`)return{id:n,label:`Settings layer`,status:`ok`,path:r,cause:`ok`};let i=kt(e,t);return{id:n,label:`Settings layer`,status:`fail`,path:r,cause:Ot(e),detail:i?[`The file exists but holds nothing; rewriting it as {} loses no content.`]:[`Session start will refuse this configuration. Fix the file at the named path.`],...i?{repair:n}:{}}}function jt(e){let t=[...e.provenance.map(e=>`${e.key}: ${e.rule} ← ${e.contributors.join(` → `)}`),...e.hookSources.map((e,t)=>`settings hook ${t+1}: ${e.event}/${e.type} ← ${e.source}`)];return e.partial?{id:`settings.merge`,label:`Merged settings`,status:`warn`,cause:`partial — a present layer is broken; session start will refuse this configuration`,detail:t.length===0?[`(no key declared by a healthy layer)`]:t}:{id:`settings.merge`,label:`Merged settings`,status:`ok`,cause:`${e.provenance.length} key(s) from ${e.layers.filter(e=>e.state===`ok`).length} layer(s)`,detail:t.length===0?[`(no settings declared)`]:t}}function Mt(t){let n=(0,e.inspectSettingsLayers)(t.settingsSources);return{inspection:n,checks:[...n.layers.map(e=>At(e,t)),jt(n)]}}function Nt(e){let t=e.source===`env-default`?`env-default via ${e.sourceEnvVar??`environment`}`:`settings profile`;return{id:`provider.resolution`,label:`Provider`,status:`ok`,cause:`${e.name} (${e.model}) — ${t}`}}function Pt(e,n){let r=(0,t.findProviderDefinition)(n.providerDefinitions,e.name),i=e.baseURL??r?.defaults?.baseURL;if(i!==void 0)try{let t=new URL(i),n=t.port===``?t.protocol===`http:`?80:443:Number(t.port);return{host:t.hostname,port:n,origin:e.baseURL===void 0?`definition defaults.baseURL`:`profile baseURL`}}catch{return}let a=r?.endpoint;return a===void 0?void 0:{...a,origin:`definition endpoint`}}async function Ft(e,t,n){let r=Pt(e,t);if(r===void 0)return{id:`provider.reachability`,label:`Provider reachability`,status:`warn`,cause:`not checked: ${e.name} declares no endpoint (no profile baseURL, defaults.baseURL or definition endpoint)`};let i=await n.probeEndpoint(r.host,r.port),a=`${r.host}:${r.port} (${r.origin})`;return i.reachable?{id:`provider.reachability`,label:`Provider reachability`,status:`ok`,cause:`${a} reachable in ${i.elapsedMs??0}ms`}:{id:`provider.reachability`,label:`Provider reachability`,status:`warn`,cause:`${a} unreachable: ${i.error??`connection failed`}`,detail:[`Check proxy settings, firewall, or the profile baseURL.`]}}async function It(t,n){let r;try{r=(0,e.readProviderSettings)(t.settingsSources,{providerDefinitions:t.providerDefinitions,env:{...t.env}})}catch(e){return{checks:[{id:`provider.resolution`,label:`Provider`,status:`fail`,cause:wt(e instanceof Error?e:Error(String(e))),detail:[t.diagnosticGuidance?.providerResolution??`Configure a provider or set its API key environment variable.`]}]}}return{checks:[Nt(r),await Ft(r,t,n)],...r.apiKey===void 0?{}:{resolvedApiKey:r.apiKey}}}function Lt(e,t){let{root:n,sessions:r}=e.userStorage,i=[t.inspectPath(n),t.inspectPath(r)];return i.some(e=>!e.exists)?`missing`:i.some(e=>!e.isDirectory||!e.writable)?`unwritable`:t.ownerOnlyGuarantee()===`posix-mode`?i.some(e=>e.mode!==void 0&&(e.mode&63)!=0)?`too-open`:`ok`:`mode-not-probed`}function Rt(e,t){let{root:n,sessions:r}=e.userStorage,i={id:`storage.user`,label:`User storage`,path:n};switch(Lt(e,t)){case`missing`:return{...i,status:`warn`,cause:`not initialized (created on first write)`,detail:[n,r],repair:`storage.user`};case`unwritable`:return{...i,status:`fail`,cause:`exists but is not a writable directory`,detail:[n,r]};case`too-open`:return{...i,status:`warn`,cause:`not owner-only (mode allows group/other access)`,detail:[n,r],repair:`storage.user`};case`mode-not-probed`:return{...i,status:`not-probed`,cause:`owner-only mode is not asserted on this platform (windows-acl)`};default:return{...i,status:`ok`,cause:`writable, owner-only`}}}function zt(e,t){if(e.projectAccess.status!==`trusted`)return{id:`storage.project`,label:`Project storage`,status:`not-configured`,cause:`project sources are disabled in an untrusted workspace`};let n=e.projectStorageRoot;if(n===void 0)return{id:`storage.project`,label:`Project storage`,status:`not-configured`,cause:`the host names no project state root`};let r=t.inspectPath(n);return r.exists?r.isDirectory&&r.writable?{id:`storage.project`,label:`Project storage`,status:`ok`,path:n,cause:`writable`}:{id:`storage.project`,label:`Project storage`,status:`fail`,path:n,cause:`exists but is not a writable directory`}:{id:`storage.project`,label:`Project storage`,status:`not-configured`,path:n,cause:`absent (created on first write)`}}function Bt(e){let t=e.projectAccess;if(t.status===`trusted`)return{id:`workspace.trust`,label:`Workspace trust`,status:`ok`,path:t.identity.displayPath,cause:`trusted`};let n=t.cause===void 0?t.trustState:`${t.trustState}: ${t.cause.name}: ${t.cause.message}`;return{id:`workspace.trust`,label:`Workspace trust`,status:t.trustState===`store-unavailable`||t.trustState===`identity-unavailable`?`fail`:`warn`,...t.displayPath===void 0?{}:{path:t.displayPath},cause:n,detail:[e.diagnosticGuidance?.projectTrust??`Project sources are disabled. Approve this workspace with the host.`]}}function Vt(e){let t=new Map,n=!1;for(let r of e.layers)for(let[e,i]of Object.entries(r.settings?.providers??{})){let r=t.get(e);r?.apiKey!==void 0&&i.baseURL!==void 0&&i.baseURL!==r.baseURL&&i.apiKey===void 0&&(n=!0),t.set(e,{baseURL:i.baseURL??r?.baseURL,apiKey:i.apiKey??r?.apiKey})}return n?{id:`provider.security`,label:`Provider security`,status:`warn`,cause:`provider endpoint quarantined; inherited credential removed (credential redacted)`}:void 0}function Ht(e,t,n){let r=Vt(n);return[Bt(e),Rt(e,t),zt(e,t),...r===void 0?[]:[r]]}const Ut=`storage.user`;function Wt(e){let t=Dt(e);return t===void 0?[Ut]:[t,Ut]}function Gt(e,t){return Wt(t).includes(e)}function Kt(t,n){let r=(0,e.inspectSettingsLayers)(n.settingsSources).layers.find(e=>Et(e.source)===t);return r===void 0||r.source.kind!==`host`?{ok:!1,reason:`${t}: no user settings layer in this composition`}:kt(r,n)?{ok:!0,plan:{id:t,description:`rewrite the empty user settings file as {}`,path:r.source.path}}:{ok:!1,reason:`${t}: state is ${r.state}; only an empty file is rewritten`}}function qt(e,t){let n=Lt(e,t),{root:r}=e.userStorage;return n!==`missing`&&n!==`too-open`?{ok:!1,reason:`storage.user: state is ${n}; only a missing or too-open directory is repaired`}:{ok:!0,plan:{id:`storage.user`,description:`create the user store root and its sessions directory as owner-only directories`,path:r}}}function Jt(e,t,n){return Gt(e,t)?e===`storage.user`?qt(t,n):Kt(e,t):{ok:!1,reason:`${e}: not a repairable check (allowlist: ${Wt(t).join(`, `)})`}}async function Yt(t,n,r,i){let o=Jt(t,n,r);if(!o.ok)return{applied:!1,reason:o.reason};if(!await i(o.plan))return{applied:!1,reason:`${t}: repair not confirmed; nothing written`};let s=Jt(t,n,r);if(!s.ok)return{applied:!1,reason:`${s.reason} (state changed before the write)`};if(s.plan.id===`storage.user`){let{root:e,sessions:t}=n.userStorage;(0,a.ensureOwnerOnlyDirectory)(t,{withinRoot:e})}else(0,e.writeSettings)(s.plan.path,{});return{applied:!0,plan:s.plan}}const Xt={"manifest-unreadable":`manifest could not be parsed`,"manifest-invalid":`manifest is not a valid plugin.json (name, version, description required)`,"load-failed":`plugin assets could not be loaded`};function Zt(e){let t=[],n=e.reduce((e,t)=>e+t.loaded.length,0),r=e.filter(e=>e.cacheDirPresent);t.push(r.length===0?{id:`plugins`,label:`Plugins`,status:`not-configured`,cause:`no plugin cache directory`,detail:e.map(e=>e.pluginsDir)}:{id:`plugins`,label:`Plugins`,status:`ok`,cause:`${n} plugin(s) loaded`,detail:r.map(e=>`${e.pluginsDir}: ${e.loaded.length} loaded, ${e.skipped.length} skipped`)});for(let n of e){for(let e of n.skipped)e.reason!==`disabled`&&t.push({id:`plugin.${e.pluginId}`,label:`Plugin`,status:`fail`,path:e.manifestPath,cause:Xt[e.reason]??e.reason,...e.detail===void 0?{}:{detail:[e.detail]}});for(let e of n.hookIssues)t.push({id:`plugin.${e.pluginId}.hooks`,label:`Plugin hooks`,status:`warn`,path:e.hooksPath,cause:`hooks.json fails the hooks schema: ${e.issues.map(e=>`${e.path} (${e.code})`).join(`, `)}`,detail:[`Report-only: the plugin still loads; these hooks may not run.`]})}return t}function Qt(t){let n=(0,e.inspectSkillSources)(t.contributionSources,t.skillRoots).roots.filter(e=>e.present),r=n.reduce((e,t)=>e+t.discovered.length,0),i=[n.length===0?{id:`skills`,label:`Skills and commands`,status:`not-configured`,cause:`no skill or command root present`}:{id:`skills`,label:`Skills and commands`,status:`ok`,cause:`${r} discovered`,detail:n.map(e=>`${e.sourceDisplayName}: ${e.root} (${e.discovered.length})`)}];for(let e of n)for(let t of e.skipped)i.push({id:`skill.${t.path}`,label:`Skill definition`,status:t.reason===`frontmatter-invalid`?`fail`:`warn`,path:`${e.sourceDisplayName}: ${t.path}`,cause:t.reason,...t.detail===void 0?{}:{detail:[t.detail]}});return i}function $t(e,t){let n=[],r=e=>{if(e!==void 0)for(let t of Object.values(e))for(let e of t??[])for(let t of e.hooks??[])t.type===`command`&&typeof t.command==`string`&&n.push(t.command)};r(e.merged.hooks);for(let e of t)for(let t of e.loaded)r(t.hooks);return n}function en(e,t,n){let r=$t(e,t),i=r.filter(e=>!n.resolveCommand(e));return[r.length===0?{id:`hooks`,label:`Hooks`,status:`not-configured`,cause:`no command hooks configured`}:i.length===0?{id:`hooks`,label:`Hooks`,status:`ok`,cause:`${r.length} command hook(s); every executable resolves`}:{id:`hooks`,label:`Hooks`,status:`warn`,cause:`${i.length} command hook executable(s) not found on PATH`,detail:i.map(e=>e.split(/\s+/)[0]??e)},{id:`hooks.execution`,label:`Hook execution`,status:`not-probed`,cause:`the doctor does not run hooks`}]}function tn(e,t){let n=`mcp.plugin.${e.pluginId}.${e.name}`;if(e.transport===`stdio`&&e.command!==void 0)return t.resolveCommand(e.command)?{id:n,label:`MCP server (plugin)`,status:`ok`,path:e.mcpPath,cause:`stdio command ${e.command} resolves`}:{id:n,label:`MCP server (plugin)`,status:`warn`,path:e.mcpPath,cause:`stdio command ${e.command} not found on PATH`,detail:e.envKeys.length===0?[]:[`env keys: ${e.envKeys.join(`, `)}`]};if(e.transport===`http`&&e.url!==void 0)try{return new URL(e.url),{id:n,label:`MCP server (plugin)`,status:`ok`,path:e.mcpPath,cause:`url ${e.url}`}}catch{return{id:n,label:`MCP server (plugin)`,status:`warn`,path:e.mcpPath,cause:`url is not parseable`}}return{id:n,label:`MCP server (plugin)`,status:`warn`,path:e.mcpPath,cause:`neither command nor url declared`}}function nn(e,t,n){let r=[];if(e.mcpActivation===void 0)r.push({id:`mcp.activation`,label:`MCP activation`,status:`not-configured`,cause:`this CLI composes no MCP activation adapter`});else{let t=e.mcpActivation.list();r.push({id:`mcp.activation`,label:`MCP activation`,status:`ok`,cause:`${t.length} server(s) known`});for(let e of t)r.push({id:`mcp.${e.serverId}`,label:`MCP server`,status:e.allowed?`ok`:`warn`,cause:`${e.status} (${e.source}): ${e.reason}`})}for(let e of t){for(let t of e.mcpServers)r.push(tn(t,n));for(let t of e.mcpFaults)r.push({id:`mcp.plugin.${t.pluginId}`,label:`MCP declaration (plugin)`,status:`warn`,path:t.mcpPath,cause:`.mcp.json ${t.reason}`})}return r.push({id:`mcp.connection`,label:`MCP connection`,status:`not-probed`,cause:`the doctor does not connect to MCP servers`}),r}function rn(t,n,r){let i=(0,e.loadHostBundlePluginInspectionFromScopes)(t.pluginsDirs,{settingsPath:t.userSettingsPath});return[...Zt(i),...Qt(t),...en(r,i,n),...nn(t,i,n)]}function an(e,t,n){return{id:e,label:t,status:`fail`,cause:wt(n)}}async function on(e,t,n,r){try{return r(await n())}catch(n){return[an(e,t,n instanceof Error?n:Error(String(n)))]}}function sn(e,t){let n=e=>Ct(e,t);return{...e,label:n(e.label),...e.path===void 0?{}:{path:n(e.path)},...e.cause===void 0?{}:{cause:n(e.cause)},...e.detail===void 0?{}:{detail:e.detail.map(n)}}}function cn(e){let t=e.filter(e=>e.status===`fail`).length;return{checks:e,failCount:t,warnCount:e.filter(e=>e.status===`warn`).length,repairable:e.flatMap(e=>e.repair===void 0?[]:[e.repair]),exitCode:t===0?0:1}}function ln(e){try{let t=Mt(e);return{checks:t.checks,result:t}}catch(e){return{checks:[an(`settings`,`Settings`,e instanceof Error?e:Error(String(e)))]}}}async function un(e,t){let n=[...e.hostChecks];e.compositionFailure!==void 0&&n.push(e.compositionFailure);let r=ln(e);n.push(...r.checks);let i=r.result?.inspection,a=Tt((i?.layers??[]).map(e=>e.settings),e.env);return n.push(...await on(`provider`,`Provider`,()=>It(e,t),e=>(e.resolvedApiKey!==void 0&&a.push(e.resolvedApiKey),e.checks))),i!==void 0&&(n.push(...await on(`storage`,`Storage`,()=>Ht(e,t,i),e=>e)),n.push(...await on(`extensions`,`Extensions`,()=>rn(e,t,i),e=>e))),cn(n.map(e=>sn(e,a)))}function dn(){return{name:`doctor`,displayName:`Doctor`,description:"Diagnose configuration and runtime readiness; `repair <check-id>` applies an allowlisted fix",source:`doctor`,modelInvocable:!1,userInvocable:!0,argumentHint:`[repair <check-id>]`}}var fn=class{name=`doctor`;getCommands(){return[dn()]}};async function pn(e,n){let r=e.getUserInteraction();if(r===void 0)return!1;let i=await r.ask((0,t.confirmAction)(`doctor-repair:${n.id}`,`Repair ${n.id}?`,{description:`${n.description} (${n.path})`,defaultYes:!1}));return i.type===`answer`&&i.values[0]===`yes`}async function mn(e,t,n,r,i){let a=await Yt(e,t,n,e=>pn(r,e));if(!a.applied)return{success:!1,message:a.reason,data:{repair:e,applied:!1}};let o=await un(t,n),s=o.checks.find(t=>t.id===e);return{success:!0,message:[`Repaired ${e}: ${a.plan.description}.`,..._t(o,`${i.title??`Doctor`} (after repair)`,i)].join(`
19
+ `));case`revoke`:return o.length===0?{success:!1,message:`Usage: /devices revoke <device-id>`}:at(t,()=>e.revoke(o),e=>`Revoked ${e.name} (${D(e.deviceId)}). A new roster and revocation list were issued.`);case`add`:case`join`:return{success:!1,message:`\`/devices ${a}\` is not available yet: enrolling another device over the device connection is not built yet.`};default:return{success:!1,message:`Unknown argument "${a}". Usage: /devices [list|init [name]|revoke <device-id>|recover]`}}}var st=class{name=`devices`;getCommands(){return[$e()]}};function ct(e){let t=E($e(),{requiresPermission:!1,lifecycle:`inline`,execute:(t,n)=>ot(e,t,n)});return{name:`agent-command-devices`,commandSources:[new st],systemCommands:[t]}}const lt=3e3;function ut(e,t){return new Promise(n=>{let i=Date.now(),a=(0,r.createConnection)({host:e,port:t}),o=setTimeout(()=>{a.destroy(),n({reachable:!1,error:`timeout (${lt/1e3}s)`})},lt);a.on(`connect`,()=>{clearTimeout(o),a.destroy(),n({reachable:!0,elapsedMs:Date.now()-i})}),a.on(`error`,e=>{clearTimeout(o),n({reachable:!1,error:e.message})})})}function dt(e){if(!(0,n.existsSync)(e))return{exists:!1,isDirectory:!1,writable:!1};let t=!1,r;try{let i=(0,n.statSync)(e);t=i.isDirectory(),r=i.mode&511}catch{return{exists:!0,isDirectory:!1,writable:!1}}let i=!1;try{(0,n.accessSync)(e,n.constants.W_OK),i=!0}catch{i=!1}return{exists:!0,isDirectory:t,writable:i,...r===void 0?{}:{mode:r}}}function ft(e,t=process.env){let r=e.trim().split(/\s+/)[0];if(r===void 0||r.length===0)return!1;if((0,i.isAbsolute)(r)||r.includes(`/`))return(0,n.existsSync)(r);let a=process.platform===`win32`?[``,`.exe`,`.cmd`,`.bat`]:[``];return(t.PATH??``).split(i.delimiter).filter(e=>e.length>0).some(e=>a.some(t=>(0,n.existsSync)((0,i.join)(e,r+t))))}function pt(e=process.env){return{probeEndpoint:ut,inspectPath:dt,resolveCommand:t=>ft(t,e),ownerOnlyGuarantee:()=>(0,a.ownerOnlyGuarantee)()}}const mt={ok:`✓`,warn:`⚠`,fail:`✗`,"not-configured":`○`,"not-probed":`–`};function ht(e,t){let n=[` ${mt[e.status]} ${e.label} [${e.id}] ${e.status}${e.cause===void 0?``:`: ${e.cause}`}`];e.path!==void 0&&n.push(` path: ${e.path}`);for(let t of e.detail??[])n.push(` ${t}`);if(e.repair!==void 0){let r=t.formatRepairCommand?.(e.repair);n.push(` repair: ${r??`request repair for ${e.repair} through your host`}`)}return n}function gt(e,t){let n=t.productName?.trim();return e.failCount===0&&e.warnCount===0?n?`✓ All checks passed. ${n} is ready to use.`:`✓ All checks passed.`:e.failCount>0?n?`✗ ${e.failCount} issue(s) found. Fix the items above to use ${n}.`:`✗ ${e.failCount} issue(s) found. Fix the items above before use.`:n?`⚠ ${e.warnCount} warning(s). ${n} may work but check the items above.`:`⚠ ${e.warnCount} warning(s). Check the items above.`}function _t(e,t=`Doctor`,n={}){let r=[``,t,``,...e.checks.flatMap(e=>ht(e,n)),``,gt(e,n)];return e.repairable.length>0&&r.push(` repairable: ${e.repairable.join(`, `)} — ${n.repairOffer??`ask your host to apply a repair`}`),r.push(``),r}const O=`[redacted]`,vt=/(\b[a-z][a-z0-9+.-]{0,31}:\/\/)([^\s/@]+)@/gi,yt=/\b(bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi,bt=/\b(?:sk-[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{20,}|ghp_[A-Za-z0-9]{20,}|xox[abprs]-[A-Za-z0-9-]{10,})\b/g,xt=/\.\.\."[^"]*"\.\.\./g;function St(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ct(e,t=[]){let n=e,r=new Set;for(let e of t)typeof e!=`string`||e.length<4||r.has(e)||(r.add(e),n=n.replace(new RegExp(St(e),`g`),O));return n=n.replace(vt,`$1${O}@`),n=n.replace(yt,`$1 ${O}`),n=n.replace(bt,O),n}function wt(t){return t instanceof e.SettingsParseError?`${t.name}: ${t.filePath} is not valid JSON (see the settings check)`:`${t.name}: ${t.message.replace(xt,`…`)}`}function Tt(e,t){let n=new Set,r=e=>{if(e!==void 0){if(e.startsWith(`$ENV:`)){let r=t[e.slice(5).trim()];r!==void 0&&n.add(r);return}n.add(e)}};for(let t of e)if(t!==void 0){r(t.provider?.apiKey);for(let e of Object.values(t.providers??{}))r(e.apiKey);for(let e of Object.values(t.env??{}))n.add(e)}return[...n]}function Et(e){let t=(0,i.basename)((0,i.dirname)(e.kind===`host`?e.path:e.relativePath)).replace(/^\./,``);return`settings.${e.scope}.${t}`}function Dt(e){let t=e.settingsSources.find(t=>t.kind===`host`&&t.path===e.userSettingsPath);return t===void 0?void 0:Et(t)}function Ot(e){let t=e.cause;if(t===void 0)return e.state;switch(t.state){case`unreadable`:return t.errno===void 0?`unreadable`:`unreadable (${t.errno})`;case`invalid-json`:return t.offset===void 0?`invalid-json`:`invalid-json at offset ${t.offset}`;case`schema-invalid`:return`schema-invalid: ${(t.issues??[]).map(e=>`${e.path} (${e.code})`).join(`, `)}`;default:return t.state}}function kt(e,t){return e.source.kind===`host`&&e.source.path===t.userSettingsPath&&e.state===`empty`}function At(e,t){let n=Et(e.source),r=e.source.kind===`host`?e.source.path:e.source.relativePath;if(e.state===`absent`)return{id:n,label:`Settings layer`,status:`not-configured`,path:r,cause:`absent`};if(e.state===`ok`)return{id:n,label:`Settings layer`,status:`ok`,path:r,cause:`ok`};let i=kt(e,t);return{id:n,label:`Settings layer`,status:`fail`,path:r,cause:Ot(e),detail:i?[`The file exists but holds nothing; rewriting it as {} loses no content.`]:[`Session start will refuse this configuration. Fix the file at the named path.`],...i?{repair:n}:{}}}function jt(e){let t=[...e.provenance.map(e=>`${e.key}: ${e.rule} ← ${e.contributors.join(` → `)}`),...e.hookSources.map((e,t)=>`settings hook ${t+1}: ${e.event}/${e.type} ← ${e.source}`)];return e.partial?{id:`settings.merge`,label:`Merged settings`,status:`warn`,cause:`partial — a present layer is broken; session start will refuse this configuration`,detail:t.length===0?[`(no key declared by a healthy layer)`]:t}:{id:`settings.merge`,label:`Merged settings`,status:`ok`,cause:`${e.provenance.length} key(s) from ${e.layers.filter(e=>e.state===`ok`).length} layer(s)`,detail:t.length===0?[`(no settings declared)`]:t}}function Mt(t){let n=(0,e.inspectSettingsLayers)(t.settingsSources);return{inspection:n,checks:[...n.layers.map(e=>At(e,t)),jt(n)]}}function Nt(e){let t=e.source===`env-default`?`env-default via ${e.sourceEnvVar??`environment`}`:`settings profile`;return{id:`provider.resolution`,label:`Provider`,status:`ok`,cause:`${e.name} (${e.model}) — ${t}`}}function Pt(e,n){let r=(0,t.findProviderDefinition)(n.providerDefinitions,e.name),i=e.baseURL??r?.defaults?.baseURL;if(i!==void 0)try{let t=new URL(i),n=t.port===``?t.protocol===`http:`?80:443:Number(t.port);return{host:t.hostname,port:n,origin:e.baseURL===void 0?`definition defaults.baseURL`:`profile baseURL`}}catch{return}let a=r?.endpoint;return a===void 0?void 0:{...a,origin:`definition endpoint`}}async function Ft(e,t,n){let r=Pt(e,t);if(r===void 0)return{id:`provider.reachability`,label:`Provider reachability`,status:`warn`,cause:`not checked: ${e.name} declares no endpoint (no profile baseURL, defaults.baseURL or definition endpoint)`};let i=await n.probeEndpoint(r.host,r.port),a=`${r.host}:${r.port} (${r.origin})`;return i.reachable?{id:`provider.reachability`,label:`Provider reachability`,status:`ok`,cause:`${a} reachable in ${i.elapsedMs??0}ms`}:{id:`provider.reachability`,label:`Provider reachability`,status:`warn`,cause:`${a} unreachable: ${i.error??`connection failed`}`,detail:[`Check proxy settings, firewall, or the profile baseURL.`]}}async function It(t,n){let r;try{r=(0,e.readProviderSettings)(t.settingsSources,{providerDefinitions:t.providerDefinitions,env:{...t.env}})}catch(e){return{checks:[{id:`provider.resolution`,label:`Provider`,status:`fail`,cause:wt(e instanceof Error?e:Error(String(e))),detail:[t.diagnosticGuidance?.providerResolution??`Configure a provider or set its API key environment variable.`]}]}}return{checks:[Nt(r),await Ft(r,t,n)],...r.apiKey===void 0?{}:{resolvedApiKey:r.apiKey}}}function Lt(e,t){let{root:n,sessions:r}=e.userStorage,i=[t.inspectPath(n),t.inspectPath(r)];return i.some(e=>!e.exists)?`missing`:i.some(e=>!e.isDirectory||!e.writable)?`unwritable`:t.ownerOnlyGuarantee()===`posix-mode`?i.some(e=>e.mode!==void 0&&(e.mode&63)!=0)?`too-open`:`ok`:`mode-not-probed`}function Rt(e,t){let{root:n,sessions:r}=e.userStorage,i={id:`storage.user`,label:`User storage`,path:n};switch(Lt(e,t)){case`missing`:return{...i,status:`warn`,cause:`not initialized (created on first write)`,detail:[n,r],repair:`storage.user`};case`unwritable`:return{...i,status:`fail`,cause:`exists but is not a writable directory`,detail:[n,r]};case`too-open`:return{...i,status:`warn`,cause:`not owner-only (mode allows group/other access)`,detail:[n,r],repair:`storage.user`};case`mode-not-probed`:return{...i,status:`not-probed`,cause:`owner-only mode is not asserted on this platform (windows-acl)`};default:return{...i,status:`ok`,cause:`writable, owner-only`}}}function zt(e,t){if(e.projectAccess.status!==`trusted`)return{id:`storage.project`,label:`Project storage`,status:`not-configured`,cause:`project sources are disabled in an untrusted workspace`};let n=e.projectStorageRoot;if(n===void 0)return{id:`storage.project`,label:`Project storage`,status:`not-configured`,cause:`the host names no project state root`};let r=t.inspectPath(n);return r.exists?r.isDirectory&&r.writable?{id:`storage.project`,label:`Project storage`,status:`ok`,path:n,cause:`writable`}:{id:`storage.project`,label:`Project storage`,status:`fail`,path:n,cause:`exists but is not a writable directory`}:{id:`storage.project`,label:`Project storage`,status:`not-configured`,path:n,cause:`absent (created on first write)`}}function Bt(e){let t=e.projectAccess;if(t.status===`trusted`)return{id:`workspace.trust`,label:`Workspace trust`,status:`ok`,path:t.identity.displayPath,cause:`trusted`};let n=t.cause===void 0?t.trustState:`${t.trustState}: ${t.cause.name}: ${t.cause.message}`;return{id:`workspace.trust`,label:`Workspace trust`,status:t.trustState===`store-unavailable`||t.trustState===`identity-unavailable`?`fail`:`warn`,...t.displayPath===void 0?{}:{path:t.displayPath},cause:n,detail:[e.diagnosticGuidance?.projectTrust??`Project sources are disabled. Approve this workspace with the host.`]}}function Vt(e){let t=new Map,n=!1;for(let r of e.layers)for(let[e,i]of Object.entries(r.settings?.providers??{})){let r=t.get(e);r?.apiKey!==void 0&&i.baseURL!==void 0&&i.baseURL!==r.baseURL&&i.apiKey===void 0&&(n=!0),t.set(e,{baseURL:i.baseURL??r?.baseURL,apiKey:i.apiKey??r?.apiKey})}return n?{id:`provider.security`,label:`Provider security`,status:`warn`,cause:`provider endpoint quarantined; inherited credential removed (credential redacted)`}:void 0}function Ht(e,t,n){let r=Vt(n);return[Bt(e),Rt(e,t),zt(e,t),...r===void 0?[]:[r]]}const Ut=`storage.user`;function Wt(e){let t=Dt(e);return t===void 0?[Ut]:[t,Ut]}function Gt(e,t){return Wt(t).includes(e)}function Kt(t,n){let r=(0,e.inspectSettingsLayers)(n.settingsSources).layers.find(e=>Et(e.source)===t);return r===void 0||r.source.kind!==`host`?{ok:!1,reason:`${t}: no user settings layer in this composition`}:kt(r,n)?{ok:!0,plan:{id:t,description:`rewrite the empty user settings file as {}`,path:r.source.path}}:{ok:!1,reason:`${t}: state is ${r.state}; only an empty file is rewritten`}}function qt(e,t){let n=Lt(e,t),{root:r}=e.userStorage;return n!==`missing`&&n!==`too-open`?{ok:!1,reason:`storage.user: state is ${n}; only a missing or too-open directory is repaired`}:{ok:!0,plan:{id:`storage.user`,description:`create the user store root and its sessions directory as owner-only directories`,path:r}}}function Jt(e,t,n){return Gt(e,t)?e===`storage.user`?qt(t,n):Kt(e,t):{ok:!1,reason:`${e}: not a repairable check (allowlist: ${Wt(t).join(`, `)})`}}async function Yt(t,n,r,i){let o=Jt(t,n,r);if(!o.ok)return{applied:!1,reason:o.reason};if(!await i(o.plan))return{applied:!1,reason:`${t}: repair not confirmed; nothing written`};let s=Jt(t,n,r);if(!s.ok)return{applied:!1,reason:`${s.reason} (state changed before the write)`};if(s.plan.id===`storage.user`){let{root:e,sessions:t}=n.userStorage;(0,a.ensureOwnerOnlyDirectory)(t,{withinRoot:e})}else(0,e.writeSettings)(s.plan.path,{});return{applied:!0,plan:s.plan}}const Xt={"manifest-unreadable":`manifest could not be parsed`,"manifest-invalid":`manifest is not a valid plugin.json (name, version, description required)`,"load-failed":`plugin assets could not be loaded`};function Zt(e){let t=[],n=e.reduce((e,t)=>e+t.loaded.length,0),r=e.filter(e=>e.cacheDirPresent);t.push(r.length===0?{id:`plugins`,label:`Plugins`,status:`not-configured`,cause:`no plugin cache directory`,detail:e.map(e=>e.pluginsDir)}:{id:`plugins`,label:`Plugins`,status:`ok`,cause:`${n} plugin(s) loaded`,detail:r.map(e=>`${e.pluginsDir}: ${e.loaded.length} loaded, ${e.skipped.length} skipped`)});for(let n of e){for(let e of n.skipped)e.reason!==`disabled`&&t.push({id:`plugin.${e.pluginId}`,label:`Plugin`,status:`fail`,path:e.manifestPath,cause:Xt[e.reason]??e.reason,...e.detail===void 0?{}:{detail:[e.detail]}});for(let e of n.hookIssues)t.push({id:`plugin.${e.pluginId}.hooks`,label:`Plugin hooks`,status:`warn`,path:e.hooksPath,cause:`hooks.json fails the hooks schema: ${e.issues.map(e=>`${e.path} (${e.code})`).join(`, `)}`,detail:[`Report-only: the plugin still loads; these hooks may not run.`]})}return t}function Qt(t){let n=(0,e.inspectSkillSources)(t.contributionSources,t.skillRoots).roots.filter(e=>e.present),r=n.reduce((e,t)=>e+t.discovered.length,0),i=[n.length===0?{id:`skills`,label:`Skills and commands`,status:`not-configured`,cause:`no skill or command root present`}:{id:`skills`,label:`Skills and commands`,status:`ok`,cause:`${r} discovered`,detail:n.map(e=>`${e.sourceDisplayName}: ${e.root} (${e.discovered.length})`)}];for(let e of n)for(let t of e.skipped)i.push({id:`skill.${t.path}`,label:`Skill definition`,status:t.reason===`frontmatter-invalid`?`fail`:`warn`,path:`${e.sourceDisplayName}: ${t.path}`,cause:t.reason,...t.detail===void 0?{}:{detail:[t.detail]}});return i}function $t(e,t){let n=[],r=e=>{if(e!==void 0)for(let t of Object.values(e))for(let e of t??[])for(let t of e.hooks??[])t.type===`command`&&typeof t.command==`string`&&n.push(t.command)};r(e.merged.hooks);for(let e of t)for(let t of e.loaded)r(t.hooks);return n}function en(e,t,n){let r=$t(e,t),i=r.filter(e=>!n.resolveCommand(e));return[r.length===0?{id:`hooks`,label:`Hooks`,status:`not-configured`,cause:`no command hooks configured`}:i.length===0?{id:`hooks`,label:`Hooks`,status:`ok`,cause:`${r.length} command hook(s); every executable resolves`}:{id:`hooks`,label:`Hooks`,status:`warn`,cause:`${i.length} command hook executable(s) not found on PATH`,detail:i.map(e=>e.split(/\s+/)[0]??e)},{id:`hooks.execution`,label:`Hook execution`,status:`not-probed`,cause:`the doctor does not run hooks`}]}function tn(e,t){let n=`mcp.plugin.${e.pluginId}.${e.name}`;if(e.transport===`stdio`&&e.command!==void 0)return t.resolveCommand(e.command)?{id:n,label:`MCP server (plugin)`,status:`ok`,path:e.mcpPath,cause:`stdio command ${e.command} resolves`}:{id:n,label:`MCP server (plugin)`,status:`warn`,path:e.mcpPath,cause:`stdio command ${e.command} not found on PATH`,detail:e.envKeys.length===0?[]:[`env keys: ${e.envKeys.join(`, `)}`]};if(e.transport===`http`&&e.url!==void 0)try{return new URL(e.url),{id:n,label:`MCP server (plugin)`,status:`ok`,path:e.mcpPath,cause:`url ${e.url}`}}catch{return{id:n,label:`MCP server (plugin)`,status:`warn`,path:e.mcpPath,cause:`url is not parseable`}}return{id:n,label:`MCP server (plugin)`,status:`warn`,path:e.mcpPath,cause:`neither command nor url declared`}}function nn(e,t,n){let r=[];if(e.mcpActivation===void 0)r.push({id:`mcp.activation`,label:`MCP activation`,status:`not-configured`,cause:`this CLI composes no MCP activation adapter`});else{let t=e.mcpActivation.list();r.push({id:`mcp.activation`,label:`MCP activation`,status:`ok`,cause:`${t.length} server(s) known`});for(let e of t)r.push({id:`mcp.${e.serverId}`,label:`MCP server`,status:e.allowed?`ok`:`warn`,cause:`${e.status} (${e.source}): ${e.reason}`})}for(let e of t){for(let t of e.mcpServers)r.push(tn(t,n));for(let t of e.mcpFaults)r.push({id:`mcp.plugin.${t.pluginId}`,label:`MCP declaration (plugin)`,status:`warn`,path:t.mcpPath,cause:`.mcp.json ${t.reason}`})}return r.push({id:`mcp.connection`,label:`MCP connection`,status:`not-probed`,cause:`the doctor does not connect to MCP servers`}),r}function rn(t,n,r){let i=(0,e.loadHostBundlePluginInspectionFromScopes)(t.pluginsDirs,{settingsPath:t.userSettingsPath});return[...Zt(i),...Qt(t),...en(r,i,n),...nn(t,i,n)]}function an(e,t,n){return{id:e,label:t,status:`fail`,cause:wt(n)}}async function on(e,t,n,r){try{return r(await n())}catch(n){return[an(e,t,n instanceof Error?n:Error(String(n)))]}}function sn(e,t){let n=e=>Ct(e,t);return{...e,label:n(e.label),...e.path===void 0?{}:{path:n(e.path)},...e.cause===void 0?{}:{cause:n(e.cause)},...e.detail===void 0?{}:{detail:e.detail.map(n)}}}function cn(e){let t=e.filter(e=>e.status===`fail`).length;return{checks:e,failCount:t,warnCount:e.filter(e=>e.status===`warn`).length,repairable:e.flatMap(e=>e.repair===void 0?[]:[e.repair]),exitCode:t===0?0:1}}function ln(e){try{let t=Mt(e);return{checks:t.checks,result:t}}catch(e){return{checks:[an(`settings`,`Settings`,e instanceof Error?e:Error(String(e)))]}}}async function un(e,t){let n=[...e.hostChecks];e.compositionFailure!==void 0&&n.push(e.compositionFailure);let r=ln(e);n.push(...r.checks);let i=r.result?.inspection,a=Tt((i?.layers??[]).map(e=>e.settings),e.env);return n.push(...await on(`provider`,`Provider`,()=>It(e,t),e=>(e.resolvedApiKey!==void 0&&a.push(e.resolvedApiKey),e.checks))),i!==void 0&&(n.push(...await on(`storage`,`Storage`,()=>Ht(e,t,i),e=>e)),n.push(...await on(`extensions`,`Extensions`,()=>rn(e,t,i),e=>e))),cn(n.map(e=>sn(e,a)))}function dn(){return{name:`doctor`,displayName:`Doctor`,description:"Diagnose configuration and runtime readiness; `repair <check-id>` applies an allowlisted fix",source:`doctor`,modelInvocable:!1,userInvocable:!0,argumentHint:`[repair <check-id>]`}}var fn=class{name=`doctor`;getCommands(){return[dn()]}};async function pn(e,n){let r=e.getUserInteraction();if(r===void 0)return!1;let i=await r.ask((0,t.confirmAction)(`doctor-repair:${n.id}`,`Repair ${n.id}?`,{description:`${n.description} (${n.path})`,defaultYes:!1}));return i.type===`answer`&&i.values[0]===`yes`}async function mn(e,t,n,r,i){let a=await Yt(e,t,n,e=>pn(r,e));if(!a.applied)return{success:!1,message:a.reason,data:{repair:e,applied:!1}};let o=await un(t,n),s=o.checks.find(t=>t.id===e);return{success:!0,message:[`Repaired ${e}: ${a.plan.description}.`,..._t(o,`${i.title??`Doctor`} (after repair)`,i)].join(`
20
20
  `),data:{repair:e,applied:!0,status:s?.status,exitCode:o.exitCode}}}async function hn(e,t,n,r,i){let[a,o]=r.trim().split(/\s+/);if(a===`repair`)return o===void 0||o.length===0?{success:!1,message:`Usage: /doctor repair <check-id>`}:mn(o,e,t,n,i);let s=await un(e,t);return{success:s.failCount===0,message:_t(s,i.title,i).join(`
21
21
  `),data:{failCount:s.failCount,warnCount:s.warnCount,repairable:[...s.repairable]}}}function gn(e,t=pt({...e.env}),n={}){let r=E(dn(),{requiresPermission:!1,lifecycle:`inline`,execute:(r,i)=>hn(e,t,r,i,n)});return{name:`agent-command-doctor`,commandSources:[new fn],systemCommands:[r]}}function _n(){let e=process.env.VISUAL?.trim(),t=process.env.EDITOR?.trim(),n=(e!==void 0&&e.length>0?e:t!==void 0&&t.length>0?t:`vi`).split(/\s+/).filter(e=>e.length>0);return{command:n[0]??`vi`,args:n.slice(1)}}function k(e,t,n){return new Promise((r,i)=>{let a=(0,s.spawn)(e,[...t],{cwd:n,stdio:`inherit`,env:process.env});a.on(`error`,i),a.on(`exit`,(e,t)=>{if(e!==null){r(e);return}if(t){let e=o.constants.signals[t];r(128+(e??0));return}r(0)})})}const vn="Compose a message in $EDITOR (optionally pre-filled with `/editor <text>`), then return it.";async function yn(e,t,r=`agent-editor-`){if(!e.canHandoffTerminal())return{message:`An editor is unavailable here (no interactive terminal).`,success:!1};let a=_n(),s=(0,n.mkdtempSync)((0,i.join)((0,o.tmpdir)(),r)),c=(0,i.join)(s,`message.md`);(0,n.writeFileSync)(c,t??``,`utf8`);try{let t=await e.runWithTerminal(async()=>k(a.command,[...a.args,c],e.getCwd()));if(t!==0)return{message:`Editor exited without saving (code ${t}).`,success:!1,data:{exitCode:t}};let r=(0,n.readFileSync)(c,`utf8`).replace(/\s+$/u,``);return r.length===0?{message:`Editor closed with empty content; nothing composed.`,success:!1}:{message:r,success:!0,data:{content:r}}}finally{(0,n.rmSync)(s,{recursive:!0,force:!0,maxRetries:3,retryDelay:20})}}function bn(){return{name:`editor`,displayName:`Editor`,description:vn,source:`editor`,modelInvocable:!1}}function xn(e){let t=bn();return{name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(t,n)=>yn(t,n,e)}}var Sn=class{name=`editor`;getCommands(){return[bn()]}};function Cn(e){return{name:`agent-command-editor`,commandSources:[new Sn],systemCommands:[xn(e)]}}const wn=`advisorModel`;function Tn(e){if(e.killSwitch)return`Advisor: disabled by the environment kill switch.`;if(e.target===void 0||!e.enabled)return`Advisor: off. Set one with /advisor <profile> or /advisor <profile>:<model>.`;let t=e.registered?`${e.sessionCalls}/${e.maxCallsPerSession} calls used this session`:`available from the next session`;return`Advisor: ${e.target} (${t}).`}async function En(e,t){let n=e.getCommandHostAdapters?.()??{},r=n.advisor;if(r===void 0)return{success:!1,message:`The advisor is not available in this environment.`};let i=t.trim();if(i.length===0){let e=r.status();return{success:!0,message:Tn(e),data:{advisor:{...e}}}}let a=r.set(i);if(!a.success||a.saved===void 0)return{success:a.success,message:a.message};let o=n.settings;if(o!==void 0&&e.getCommandInvocationSource()===`user`){let e=o.read();if(a.saved===`off`){let{[wn]:t,...n}=e;o.write(n)}else o.write({...e,[wn]:a.saved})}return{success:!0,message:a.message,data:{advisor:{...r.status()}}}}function Dn(){return{name:`advisor`,displayName:`Advisor`,description:`Show, set, or turn off the model the main model can consult for advice`,source:`advisor`,argumentHint:`<profile> | <profile>:<model> | off`,modelInvocable:!1}}function On(){let e=Dn();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,lifecycle:`inline`,execute:En}}var kn=class{name=`advisor`;getCommands(){return[Dn()]}};function An(){return{name:`agent-command-advisor`,commandSources:[new kn],systemCommands:[On()]}}const jn=[`auto`,...t.MODEL_EFFORT_VALUES];function Mn(e){return`Model effort: requested=${e.requested}, effective=${e.effective}, source=${e.source}, disposition=${e.disposition}.`}async function Nn(n){let r=n.getUserInteraction();if(r===void 0)return;let i=await r.ask((0,t.selectAction)(`effort`,`Select model effort`,jn.map(e=>({value:e,label:e}))));return(0,e.parseModelEffort)(i.type===`answer`?i.values[0]:void 0,`/effort`)}function Pn(t){let n=t.getCommandHostAdapters?.().effort;if(n!==void 0)return n.getResolution();let r=t.getSession().getModelEffort();return(0,e.resolveModelEffort)({command:r,modelDefault:r===`auto`?`high`:r})}function Fn(e){return e.getCommandHostAdapters?.()??{}}function In(e,t){let n=Fn(e).settings;if(n===void 0||t===`max`)return;let r=n.read();if(t===`auto`){let{effort:e,...t}=r;n.write(t);return}n.write({...r,effort:t})}async function Ln(t,n){let r;try{r=(0,e.parseModelEffort)(n.trim()||void 0,`/effort`),r===void 0&&(r=await Nn(t))}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let i=Pn(t);if(r===void 0)return{message:Mn(i),success:!0,data:{effort:i}};let a=Fn(t).effort,o;try{o=a===void 0?(0,e.resolveModelEffort)({command:r,modelDefault:i.effective}):await a.apply(r,t.getSession()),a===void 0&&await t.getSession().applyModelOptions({effort:r}),t.getCommandInvocationSource()===`user`&&In(t,r)}catch(e){return{message:`Model effort was not applied: ${e instanceof Error?e.message:String(e)}`,success:!1}}return{message:Mn(o),success:!0,data:{effort:o}}}const Rn=`auto | ${t.MODEL_EFFORT_VALUES.join(` | `)}`;function zn(){return{name:`effort`,displayName:`Model Effort`,description:`Show or change the model effort level`,source:`effort`,argumentHint:Rn,modelInvocable:!1}}function Bn(){let e=zn();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,lifecycle:`inline`,execute:Ln}}var Vn=class{name=`effort`;getCommands(){return[zn()]}};function Hn(){return{name:`agent-command-effort`,commandSources:[new Vn],systemCommands:[Bn()]}}async function Un(n,r){let i=n.getUserInteraction();return i&&!(0,t.isConfirmed)(await i.ask((0,t.confirmAction)(`exit`,`Exit the session?`)))?{success:!0,message:`Exit cancelled.`}:{success:!0,message:`Exit requested.`,hostActions:[(0,e.createSessionExitHostAction)()]}}function Wn(){return{name:`exit`,displayName:`Exit Session`,description:e.EXIT_COMMAND_DESCRIPTION,source:`exit`,modelInvocable:!1}}function Gn(){let e=Wn();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Un}}var Kn=class{name=`exit`;getCommands(){return[Wn()]}};function qn(){return{name:`agent-command-exit`,commandSources:[new Kn],systemCommands:[Gn()]}}const Jn=`none`,A=`--same-dir`;function Yn(e){let t=e.trim().split(/\s+/).filter(e=>e.length>0),n=t.find(e=>e.startsWith(`--`)&&e!==A);if(n!==void 0)return{error:`Unknown option: ${n}\nUsage: /fork [name] [${A}]`};let r=t.filter(e=>e!==A);return{name:r.length>0?r.join(` `):void 0,isolation:t.includes(A)?Jn:`worktree`}}function Xn(e){return e instanceof Error?e.message:String(e)}function Zn(e,t,n){return[`Forked this conversation into "${e}" (${t}), running ${n===Jn?`in this directory`:`in its own worktree`}.`,`The fork is a copy: this session keeps going, and the two are separate records.`,`See its progress with /background list. Attaching from the background panel points this`,`terminal at the copy as it was forked; the fork's own turns stay in its task transcript.`].join(`
22
22
  `)}function Qn(e,t,n){let r=n?.(e.sessionId);return`The fork "${e.name}" was written (${e.sessionId}) but its background job could not start: ${t}\n${r===void 0?`Resume the saved session through your host.`:`Resume it in a new terminal with: ${r}`}`}async function $n(e,t=``,n){let r=Yn(t);if(`error`in r)return{message:r.error,success:!1};let i=e.getAgentJobCapability();if(!i)return{message:`This session cannot start background jobs, so it cannot run a fork.`,success:!1};let a;try{a=await e.forkSession(r.name===void 0?{}:{name:r.name})}catch(e){return{message:`Could not fork this session: ${Xn(e)}`,success:!1}}try{let e=await i.spawnAgentJob({agentType:`general-purpose`,label:a.name,mode:`background`,prompt:`Continue.`,isolation:r.isolation,resumeSessionId:a.sessionId});return{message:Zn(a.name,e.id,r.isolation),success:!0,data:{sessionId:a.sessionId,name:a.name,taskId:e.id}}}catch(e){return{message:Qn(a,Xn(e),n),success:!1}}}function er(){return{name:`fork`,displayName:`Fork Session`,description:`Copy this conversation into a new background session and keep working here. The fork inherits the whole conversation and the assembled system prompt; it is a copy, so nothing it does reaches this session and it never merges back.`,source:`fork`,modelInvocable:!1,argumentHint:`[name] [--same-dir]`}}function tr(e){let t=er();return{name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,...t.argumentHint===void 0?{}:{argumentHint:t.argumentHint},execute:(t,n)=>$n(t,n,e)}}var nr=class{name=`fork`;getCommands(){return[er()]}};function rr(e){return{name:`agent-command-fork`,commandSources:[new nr],systemCommands:[tr(e)],sessionRequirements:[`agent-runtime`]}}const ir=[`GIT_DIR`,`GIT_WORK_TREE`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_COMMON_DIR`,`GIT_PREFIX`,`GIT_NAMESPACE`];function ar(e=process.env){let t={};for(let[n,r]of Object.entries(e))ir.includes(n)||(t[n]=r);return t}function j(e,t){return{kind:`failed`,reason:e,detail:t}}function or(e){return o.constants.signals[e]??0}function sr(e,t,n,r){return e===null?{kind:`exited`,stdout:t,stderr:n,exitCode:0}:r.signal?.aborted===!0||e.name===`AbortError`?j(`aborted`,`the run was aborted before git exited`):e.code===`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`?j(`output-too-large`,`git produced more than 16 MiB of output and was stopped`):e.killed===!0?j(`timeout`,`git did not exit within ${r.timeoutMs} ms and was stopped`):typeof e.code==`number`?{kind:`exited`,stdout:t,stderr:n,exitCode:e.code}:e.signal?{kind:`exited`,stdout:t,stderr:n,exitCode:128+or(e.signal)}:j(`not-found`,`${r.executable} could not be run (${String(e.code??e.message)})`)}function cr(e={}){let t=e.executable??`git`;return{run(n,r){let i=r.timeoutMs??12e4,a=ar(e.env??process.env);return new Promise(e=>{(0,s.execFile)(t,[...n],{cwd:r.cwd,env:a,shell:!1,encoding:`utf8`,timeout:i,maxBuffer:16777216,windowsHide:!0,...r.signal?{signal:r.signal}:{}},(n,a,o)=>e(sr(n,a,o,{executable:t,timeoutMs:i,signal:r.signal}))).stdin?.end()})}}}function M(e,t){if(t.kind===`failed`)return`git ${e} failed: ${t.detail}`;if(t.exitCode===0)return;let n=t.stderr.trim();return n.length>0?`git ${e} failed (exit ${t.exitCode}): ${n}`:`git ${e} failed (exit ${t.exitCode})`}const lr=[`status`,`--porcelain=v2`,`-z`,`--branch`],ur=/^1 (\S\S) \S+ \S+ \S+ \S+ \S+ \S+ ([^]*)$/,dr=/^2 (\S\S) \S+ \S+ \S+ \S+ \S+ \S+ \S+ ([^]*)$/,fr=/^u \S\S \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ ([^]*)$/;function pr(e,t,n){t[0]!==`.`&&e.staged.push(n),t[1]!==`.`&&e.unstaged.push(n)}function mr(e,t){t.startsWith(`# branch.head `)?e.branch=t.slice(14):t.startsWith(`# branch.oid `)&&(e.unborn=t.slice(13)===`(initial)`)}function hr(e,t,n){if(t.startsWith(`# `))return mr(e,t),0;if(t.startsWith(`? `))return e.untracked.push(t.slice(2)),0;if(t.startsWith(`1 `)){let n=ur.exec(t);return n&&pr(e,n[1]??`..`,n[2]??``),0}if(t.startsWith(`2 `)){let r=dr.exec(t);return r&&pr(e,r[1]??`..`,`${r[2]??``} (from ${n??``})`),1}if(t.startsWith(`u `)){let n=fr.exec(t);n&&e.conflicted.push(n[1]??``)}return 0}function gr(e){let t=e.split(`\0`),n={branch:void 0,unborn:!1,staged:[],unstaged:[],untracked:[],conflicted:[]};for(let e=0;e<t.length;e+=1){let r=t[e]??``;r.length!==0&&(e+=hr(n,r,t[e+1]))}return n}function N(e,t){return`${e} (${t.length}):${t.length>0?` ${t.join(`, `)}`:``}`}function _r(e){let t=[e.branch===void 0?`No branch information`:e.branch===`(detached)`?`HEAD detached`:`On branch ${e.branch}${e.unborn?` (no commits yet)`:``}`,N(`staged`,e.staged),N(`unstaged`,e.unstaged),N(`untracked`,e.untracked)];return e.conflicted.length>0&&t.push(N(`conflicted`,e.conflicted)),t.join(`
@@ -27,13 +27,13 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
27
27
  `)}async function Ur(e,t){let n=t.trim(),r=n.split(/\s+/)[0]?.toLowerCase()??``;if(n.length===0||r===`help`)return{message:`Usage:
28
28
  /goal <objective> assign a goal and pursue it autonomously
29
29
  /goal status show the current goal and progress
30
- /goal cancel stop the current goal`,success:!0};if(r===`status`){let t=e.getGoalState();return t?{message:Hr(t),success:!0,data:{status:t.status}}:{message:`No goal is set.`,success:!0}}if(r===`cancel`||r===`stop`){let t=e.cancelGoal();return t?{message:`Goal cancelled: ${t.objective}`,success:!0}:{message:`No active goal to cancel.`,success:!1}}let i;try{i=await e.setGoal(n)}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}return{message:`Goal set — pursuing autonomously (up to ${i.maxIterations} iterations):\n${i.objective}`,success:!0,data:{goalId:i.id}}}function Wr(){return{name:`goal`,displayName:`Autonomous Goal`,description:Vr,source:`goal`,modelInvocable:!1}}function Gr(){let e=Wr();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Ur}}var Kr=class{name=`goal`;getCommands(){return[Wr()]}};function qr(){return{name:`agent-command-goal`,commandSources:[new Kr],systemCommands:[Gr()]}}function I(e){return e.stillMine?`This session is still on this machine, and still yours to use.`:`This session now belongs to the destination. This copy is read-only.`}function Jr(e){return e.map(e=>` ${e.deviceId}${e.name?` ${e.name}`:``}`).join(`
31
- `)}function Yr(){return{success:!0,message:[`Usage:`,` /handoff list the machines this session could move to`,` /handoff <device-id> move it there, after confirming what stays behind`].join(`
30
+ /goal cancel stop the current goal`,success:!0};if(r===`status`){let t=e.getGoalState();return t?{message:Hr(t),success:!0,data:{status:t.status}}:{message:`No goal is set.`,success:!0}}if(r===`cancel`||r===`stop`){let t=e.cancelGoal();return t?{message:`Goal cancelled: ${t.objective}`,success:!0}:{message:`No active goal to cancel.`,success:!1}}let i;try{i=await e.setGoal(n)}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}return{message:`Goal set — pursuing autonomously (up to ${i.maxIterations} iterations):\n${i.objective}`,success:!0,data:{goalId:i.id}}}function Wr(){return{name:`goal`,displayName:`Autonomous Goal`,description:Vr,source:`goal`,modelInvocable:!1}}function Gr(){let e=Wr();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Ur}}var Kr=class{name=`goal`;getCommands(){return[Wr()]}};function qr(){return{name:`agent-command-goal`,commandSources:[new Kr],systemCommands:[Gr()]}}function I(e){return e.stillMine?`This session is still on this machine, and still yours to use.`:`This session now belongs to the destination, and this one ends.`}function Jr(e){return e.map(e=>` ${e.deviceId}${e.name?` ${e.name}`:``}`).join(`
31
+ `)}function Yr(){return{success:!0,message:[`Usage:`,` /handoff list where this session could move to`,` /handoff <session-id> move it there, after confirming what stays behind`].join(`
32
32
  `)}}async function Xr(e,t){let n=e.getCommandHostAdapters?.().handoff;if(n===void 0)return{success:!1,message:`This session has no hand-off carrier, so it cannot be moved to another machine. Nothing changed — the session is still here.`};let r=t.trim();if(r===``||r===`help`){let e=await n.destinations();return e.length===0?{success:!0,message:`No other machine is reachable for a hand-off right now.
33
33
  `+I(n.status())}:{success:!0,message:[`This session could move to:`,Jr(e),``,Yr().message??``].join(`
34
34
  `)}}let i=await n.destinations();if(!i.some(e=>e.deviceId===r))return{success:!1,message:`No reachable machine is called '${r}'.\n`+(i.length>0?`Reachable now:\n${Jr(i)}`:`None are reachable right now.`)+`\n${I(n.status())}`};let a=await n.staysBehind(),o=[a.uncommittedChanges?` - uncommitted changes in the working tree stay on THIS machine`:null,a.subprocesses>0?` - ${a.subprocesses} running process(es) stay on THIS machine and will not be reachable there`:null,` - the destination uses ITS OWN provider credential; credentials are never transferred`].filter(e=>e!==null),s=e.getUserInteraction?.();if(s===void 0)return{success:!1,message:`A hand-off needs a person to confirm what stays behind, and no interactive session is attached.\n${I(n.status())}`};let c=await s.ask({id:`handoff:${r}`,title:`Move this session to ${r}?`,description:[`What will NOT travel:`,...o].join(`
35
- `),options:[{value:`move`,label:`Move it to ${r}`},{value:`stay`,label:`Keep it here`}]});if(c.type!==`answer`||!c.values.includes(`move`))return{success:!0,message:`Hand-off cancelled.\n${I(n.status())}`};let l=[],u=await n.transfer(r,e=>{l.push(Zr(e,r))});return{success:u.state===`done`,message:[...l,u.state===`done`?`Hand-off complete. ${r} is running this session now.`:`Hand-off stopped: ${u.reason??`no reason was reported`}.`,I(u)].join(`
36
- `)}}function Zr(e,t){switch(e.state){case`offered`:return`Offering the session to ${t}...`;case`sending`:return`Sending the session...`;case`awaiting-confirmation`:return`Sent. Waiting for ${t} to confirm it has the session on disk — until it does, this machine keeps it.`;case`done`:return`${t} confirmed it has the session.`;case`stopped`:return`Stopped: ${e.reason??`no reason was reported`}.`;default:return``}}function Qr(){return{name:`handoff`,displayName:`Hand off`,description:`Move this session to another machine, after confirming what stays behind`,source:`handoff`,modelInvocable:!1}}function $r(){let e=Qr();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(e,t)=>Xr(e,t)}}var ei=class{name=`handoff`;getCommands(){return[Qr()]}};function ti(){return{name:`agent-command-handoff`,commandSources:[new ei],systemCommands:[$r()]}}function ni(t,n){return{success:!0,message:(0,e.formatCommandHelpMessage)(t)}}function ri(){return{name:`help`,displayName:`Help`,description:e.HELP_COMMAND_DESCRIPTION,source:`help`,modelInvocable:!1}}function ii(){let e=ri();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:ni}}var ai=class{name=`help`;getCommands(){return[ri()]}};function oi(){return{name:`agent-command-help`,commandSources:[new ai],systemCommands:[ii()]}}function si(){return{name:`keybindings`,displayName:`Keybindings`,description:`Open the contextual terminal keybindings file in $EDITOR`,source:`keybindings`,modelInvocable:!1}}async function ci(e,t){if(!t.canHandoffTerminal())return{success:!1,message:`Keybindings editor is unavailable here.`};let n=await e.ensureFile(),r=_n(),i=await t.runWithTerminal(()=>k(r.command,[...r.args,n],t.getCwd()));return i===0?{success:!0,message:`Opened keybindings: ${n}`,data:{path:n}}:{success:!1,message:`Keybindings editor exited with code ${i}.`,data:{path:n,exitCode:i}}}var li=class{name=`keybindings`;getCommands(){return[si()]}};function ui(e){let t=si(),n={name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:t=>ci(e,t)};return{name:`agent-command-keybindings`,commandSources:[new li],systemCommands:[n]}}async function di(n){let r=n.getUserInteraction();if(!r)return;let i=(0,e.buildLanguageCommandSubcommands)().map(e=>({value:e.name,label:e.name,description:e.description})),a=await r.ask((0,t.selectAction)(`language`,`Select language`,i)),o=a.type===`answer`?a.values[0]:void 0;return o===void 0?void 0:(0,e.parseLanguageArgument)(o)}async function fi(t,n){let r=(0,e.parseLanguageArgument)(n);return r===void 0&&(r=await di(t),r===void 0)?{message:(0,e.formatLanguageUsageMessage)(),success:!1}:{message:`Language set to "${r}".`,success:!0,data:{language:r},hostActions:[{type:`language-change`,language:r}]}}function pi(){return{name:`language`,displayName:`Language`,description:e.LANGUAGE_COMMAND_DESCRIPTION,source:`language`,argumentHint:e.LANGUAGE_COMMAND_ARGUMENT_HINT,subcommands:(0,e.buildLanguageCommandSubcommands)(`language`),modelInvocable:!1}}function mi(){let e=pi();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:fi}}var hi=class{name=`language`;getCommands(){return[pi()]}};function gi(){return{name:`agent-command-language`,commandSources:[new hi],systemCommands:[mi()]}}function _i(e,n,r=`session`){let i=(0,t.shellArgumentForDisplay)(e)??`<server>`;switch(n){case`approve`:return`/mcp approve ${i}`;case`sign-in`:return r===`terminal`?`robota mcp login ${i}`:`/mcp login ${i}`;case`trust-workspace`:return`robota trust`}}const vi={approve:`is waiting for the user’s approval`,"sign-in":`needs the user to sign in`,"trust-workspace":`needs the user to trust this workspace`};function yi(e){let n=(0,t.shellArgumentForDisplay)(e);return n===void 0?"An MCP server (its name cannot be shown here; `/mcp status` lists it)":`MCP server "${n}"`}function bi(e,t,n=`session`){let r=t===`trust-workspace`||t===`sign-in`&&n===`terminal`?` in a terminal, then restart the session`:``;return`${yi(e)} ${vi[t]}, so its tools are unavailable. You cannot do this yourself; ask the user to run \`${_i(e,t,n)}\`${r}.`}function xi(e){if(e.size!==0)return[`MCP servers that did not start this session. Mention this only when the user needs one of these servers or its tools:`,...[...e].map(([e,t])=>`- ${bi(e,t)}`)].join(`
35
+ `),options:[{value:`move`,label:`Move it to ${r}`},{value:`stay`,label:`Keep it here`}]});if(c.type!==`answer`||!c.values.includes(`move`))return{success:!0,message:`Hand-off cancelled.\n${I(n.status())}`};let l=[],u=await n.transfer(r,e=>{l.push(Zr(e,r))});return{success:u.state===`done`,message:[...l,u.state===`done`?`Hand-off complete. ${r} saved this session and has not started it; resume it there.`:`Hand-off stopped: ${u.reason??`no reason was reported`}.`,I(u)].join(`
36
+ `)}}function Zr(e,t){switch(e.state){case`offered`:return`Offering the session to ${t}...`;case`sending`:return`Sending the session...`;case`awaiting-confirmation`:return`Sent. Waiting for ${t} to confirm it has the session on disk — until it does, this machine keeps it.`;case`done`:return`${t} confirmed it has the session.`;case`stopped`:return`Stopped: ${e.reason??`no reason was reported`}.`;default:return``}}function Qr(){return{name:`handoff`,displayName:`Hand off`,description:"Push this conversation to another running Robota session of the same user on this machine, after the operator confirms what stays behind (uncommitted changes, running processes; credentials never travel). The receiving operator must also accept; the session arrives saved, not started, and this one ends once it is saved there. With no argument it lists the sessions it could go to. User-only: the model cannot run it; when the user wants to continue this work in another session, suggest they run `/handoff <session-id>`.",source:`handoff`,modelInvocable:!1,userInvocable:!0,argumentHint:`[session-id]`}}function $r(){let e=Qr();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(e,t)=>Xr(e,t)}}var ei=class{name=`handoff`;getCommands(){return[Qr()]}};function ti(){return{name:`agent-command-handoff`,commandSources:[new ei],systemCommands:[$r()]}}function ni(t,n){return{success:!0,message:(0,e.formatCommandHelpMessage)(t)}}function ri(){return{name:`help`,displayName:`Help`,description:e.HELP_COMMAND_DESCRIPTION,source:`help`,modelInvocable:!1}}function ii(){let e=ri();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:ni}}var ai=class{name=`help`;getCommands(){return[ri()]}};function oi(){return{name:`agent-command-help`,commandSources:[new ai],systemCommands:[ii()]}}function si(){return{name:`keybindings`,displayName:`Keybindings`,description:`Open the contextual terminal keybindings file in $EDITOR`,source:`keybindings`,modelInvocable:!1}}async function ci(e,t){if(!t.canHandoffTerminal())return{success:!1,message:`Keybindings editor is unavailable here.`};let n=await e.ensureFile(),r=_n(),i=await t.runWithTerminal(()=>k(r.command,[...r.args,n],t.getCwd()));return i===0?{success:!0,message:`Opened keybindings: ${n}`,data:{path:n}}:{success:!1,message:`Keybindings editor exited with code ${i}.`,data:{path:n,exitCode:i}}}var li=class{name=`keybindings`;getCommands(){return[si()]}};function ui(e){let t=si(),n={name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:t=>ci(e,t)};return{name:`agent-command-keybindings`,commandSources:[new li],systemCommands:[n]}}async function di(n){let r=n.getUserInteraction();if(!r)return;let i=(0,e.buildLanguageCommandSubcommands)().map(e=>({value:e.name,label:e.name,description:e.description})),a=await r.ask((0,t.selectAction)(`language`,`Select language`,i)),o=a.type===`answer`?a.values[0]:void 0;return o===void 0?void 0:(0,e.parseLanguageArgument)(o)}async function fi(t,n){let r=(0,e.parseLanguageArgument)(n);return r===void 0&&(r=await di(t),r===void 0)?{message:(0,e.formatLanguageUsageMessage)(),success:!1}:{message:`Language set to "${r}".`,success:!0,data:{language:r},hostActions:[{type:`language-change`,language:r}]}}function pi(){return{name:`language`,displayName:`Language`,description:e.LANGUAGE_COMMAND_DESCRIPTION,source:`language`,argumentHint:e.LANGUAGE_COMMAND_ARGUMENT_HINT,subcommands:(0,e.buildLanguageCommandSubcommands)(`language`),modelInvocable:!1}}function mi(){let e=pi();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:fi}}var hi=class{name=`language`;getCommands(){return[pi()]}};function gi(){return{name:`agent-command-language`,commandSources:[new hi],systemCommands:[mi()]}}function _i(e,n,r=`session`){let i=(0,t.shellArgumentForDisplay)(e)??`<server>`;switch(n){case`approve`:return`/mcp approve ${i}`;case`sign-in`:return r===`terminal`?`robota mcp login ${i}`:`/mcp login ${i}`;case`trust-workspace`:return`robota trust`}}const vi={approve:`is waiting for the user’s approval`,"sign-in":`needs the user to sign in`,"trust-workspace":`needs the user to trust this workspace`};function yi(e){let n=(0,t.shellArgumentForDisplay)(e);return n===void 0?"An MCP server (its name cannot be shown here; `/mcp status` lists it)":`MCP server "${n}"`}function bi(e,t,n=`session`){let r=t===`trust-workspace`||t===`sign-in`&&n===`terminal`?` in a terminal, then restart the session`:``;return`${yi(e)} ${vi[t]}, so its tools are unavailable. You cannot do this yourself; ask the user to run \`${_i(e,t,n)}\`${r}.`}function xi(e){if(e.size!==0)return[`MCP servers that did not start this session. Mention this only when the user needs one of these servers or its tools:`,...[...e].map(([e,t])=>`- ${bi(e,t)}`)].join(`
37
37
  `)}function Si(e,t){if(e===`pending`||e===`stale`)return`approve`;if(e===`untrusted`)return`trust-workspace`;if(e===`approved`&&(t===`sign-in-required`||t===`signed-out`))return`sign-in`}function Ci(e,n,r){let i=(0,t.shellArgumentForDisplay)(e.serverId),a=Si(e.status,n);return{...i===void 0?{}:{name:i},status:e.status,...n===void 0?{}:{oauth:n},...a===void 0?{}:{suggestCommand:_i(e.serverId,a,r)}}}function wi(e){let t=e.name??`(name not shown)`,n=e.oauth===void 0?``:` — sign-in: ${e.oauth}`,r=e.suggestCommand===void 0?``:` — ask the user to run \`${e.suggestCommand}\``;return` ${t} — ${e.status}${n}${r}`}async function Ti(e){if(!e)return{message:`MCP is not available in this environment.`,success:!0};let t=new Map((await e.oauthStatus?.()??[]).map(e=>[e.serverId,e.state])),n=e.list().map(n=>Ci(n,t.get(n.serverId),e.userActionSurface??`session`)),r=(e.sourceProblems?.()??[]).length,i=n.length===0?[`No MCP servers are configured.`]:[`MCP servers:`,...n.map(wi)];return r>0&&i.push(`${r} MCP configuration source(s) could not be read; the user can see which with \`/mcp status\`.`),{message:i.join(`
38
38
  `),success:!0,data:{servers:n,unreadableSources:r}}}function L(e){return e.getCommandHostAdapters?.().mcpActivation}const Ei={"signed-in":`signed in`,"expired-refreshable":`token expired, will refresh`,"sign-in-required":`sign-in required`,"signed-out":`signed out`},Di={refresh_token:`refresh token`,access_token:`access token`};function Oi(e){let t=e.revocationFailure??`revocation-failed`;switch(e.revocation){case`revoked`:return`the tokens were revoked`;case`not-attempted`:return`there were no tokens to revoke`;case`unsupported`:return`the authorization server offers no token revocation; the tokens stay valid until they expire`;case`failed`:return`token revocation failed (${t}); the tokens stay valid until they expire`;case`partial`:return(e.tokens??[]).map(e=>e.revoked?`the ${Di[e.token]} was revoked`:`the ${Di[e.token]} was not (${e.failure??`revocation-failed`}) and stays valid until it expires`).join(`; `)}}function R(e){return(0,t.shellArgumentForDisplay)(e)??`<server>`}function ki(e){let n=R(e),r=`run /mcp login ${n}, or robota mcp login ${n} in a terminal`;return(0,t.shellArgumentForDisplay)(e)===void 0?` (${r}; its name cannot be shown safely here)`:` (${r})`}function Ai(e,t){let n=e.displayName?` (${e.displayName})`:``,r=t===void 0?``:` — OAuth: ${Ei[t]}${t===`sign-in-required`||t===`signed-out`?ki(e.serverId):``}`;return` ${e.serverId}${n} — ${e.status} — ${e.source} — ${e.reason}${r}`}function ji(e){let t=e.blockedServerNames??[],n=t.length===0?``:` Blocked until fixed: ${t.join(`, `)}.`;return` ${e.source} (${e.origin}) could not be read: ${e.reason}.${n}`}async function Mi(e){let t=await e.oauthStatus?.()??[];return new Map(t.map(e=>[e.serverId,e.state]))}async function Ni(e){if(!e)return{message:`MCP activation management is not available in this environment.`,success:!0};let t=e.list(),n=await Mi(e),r=e.sourceProblems?.()??[],i=r.length===0?[]:[`MCP source problems:\n${r.map(ji).join(`
39
39
  `)}`];return t.length===0?{message:i.length===0?`No MCP definitions are registered.`:i[0],success:!0,data:{servers:[],sourceProblems:r}}:{message:[`MCP activation status:\n${t.map(e=>Ai(e,n.get(e.serverId))).join(`
@@ -45,21 +45,22 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
45
45
  `),success:!0,data:{count:t.length}}}function $i(t,n){(0,e.recordCommandMemoryEvent)(t,n)}async function ea(t,n,r){if(!r)return qi();try{let{record:i,saved:a}=await(0,e.approvePendingMemoryCandidate)(n,r);return $i(t,{type:`memory_candidate_approved`,candidateId:i.id,topic:i.topic,reason:`approved-by-user`}),$i(t,{type:`memory_candidate_saved`,candidateId:i.id,topic:i.topic,reason:a.deduplicated?`deduplicated`:`approved-and-saved`}),{message:a.deduplicated?`Saved memory candidate ${r} was already present in ${a.topicPath}`:`Saved memory candidate ${r} to ${a.topicPath}`,success:!0,data:{id:r,status:i.status,topic:a.topic,topicPath:a.topicPath,deduplicated:a.deduplicated}}}catch(e){return Ji(e instanceof Error?e:String(e))}}async function ta(e,t,n){if(!n)return qi();try{let r=await t.markPending(n,`rejected`,`rejected-by-user`);return $i(e,{type:`memory_candidate_rejected`,candidateId:r.id,topic:r.topic,reason:`rejected-by-user`}),{message:`Rejected memory candidate ${n}`,success:!0,data:{id:n,status:r.status}}}catch(e){return Ji(e instanceof Error?e:String(e))}}function na(t){let n=(0,e.listCommandUsedMemoryReferences)(t);return{message:[`Used memory references:`,...n.length>0?n.map(e=>{let t=e.truncated?` truncated=true`:``;return`- ${e.topic} score=${e.score}${t}: ${e.path}`}):[`(no memory used in current turn)`]].join(`
46
46
  `),success:!0,data:{count:n.length,references:[...n]}}}async function ra(t,n){let r=n.trim().split(/\s+/).filter(Boolean),i=r[0]??`list`,a=(0,e.createCommandMemoryStores)(t);if(i===`list`)return Yi(a);if(i===`show`)return Xi(a,r[1]);if(i===`pending`)return Qi(a);if(i===`approve`)return ea(t,a,r[1]);if(i===`reject`)return ta(t,a,r[1]);if(i===`used`)return na(t);if(i===`add`){let t=Zi(r);if(!t)return qi();if((0,e.hasSensitiveCommandMemoryContent)(t.text))return{message:`Refusing to save sensitive memory content.`,success:!1};let n=await a.append(t);return{message:n.deduplicated?`${t.type} memory already exists in ${n.topicPath}`:`Saved ${t.type} memory to ${n.topicPath}`,success:!0,data:{indexPath:n.indexPath,topicPath:n.topicPath,topic:n.topic,deduplicated:n.deduplicated}}}return qi()}function ia(){return{name:`memory`,displayName:`Memory`,description:e.MEMORY_COMMAND_DESCRIPTION,modelDescription:"Read and write this project’s durable memory. Use `list` or `show [topic]` to look up stored conventions, preferences or references before asking the user again; `add <type> <topic> <text>` to save a durable preference, project convention, feedback item or reference worth reusing across sessions (never secrets, credentials or transient facts); `pending` to see candidates awaiting the user’s review; `used` to report which memory items informed this turn. Bare lists topics. Returns the requested topics or entries, or a confirmation of what was saved. Approving or rejecting a pending candidate is the user’s review: suggest `/memory approve <id>` or `/memory reject <id>`.",source:`memory`,argumentHint:e.MEMORY_COMMAND_ARGUMENT_HINT,modelInvocable:!0,safety:`write`,subcommands:(0,e.buildMemoryCommandSubcommands)()}}function aa(){let e=ia();return{name:e.name,displayName:e.displayName,description:e.description,...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,subcommands:e.subcommands,execute:ra}}var oa=class{name=`memory`;getCommands(){return[ia()]}};function sa(){return{name:`agent-command-memory`,commandSources:[new oa],systemCommands:[aa()]}}function ca(t,n){try{(0,e.writeCommandPermissionMode)(t,n);return}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}}function la(t,n){let r=(0,e.retryCommandPermissionDenial)(t,Number(n.trim().split(/\s+/)[1]));return r===void 0?{message:`Usage: /permissions retry <n>, where <n> numbers a call blocked by the auto-mode classifier in /permissions.`,success:!1}:{message:`${r.argument===void 0?r.toolName:`${r.toolName}(${r.argument})`} will run once, without the classifier, when the model tries it again.`,success:!0}}function ua(t,n){let r=(0,e.parsePermissionModeArgument)(n);if(r===`retry`)return la(t,n);if(r!==void 0){if(!(0,e.isPermissionMode)(r))return{message:(0,e.formatInvalidPermissionModeMessage)(),success:!1};let n=ca(t,r);if(n!==void 0)return n;let i=(0,e.readCommandPermissionsState)(t);return{message:`Permission mode set to: ${r}\n${(0,e.formatCommandPermissionsMessage)(i)}`,success:!0,data:{mode:i.mode,sessionAllowed:i.sessionAllowed}}}let i=(0,e.readCommandPermissionsState)(t);return{message:(0,e.formatCommandPermissionsMessage)(i),success:!0,data:{mode:i.mode,sessionAllowed:i.sessionAllowed}}}async function da(n){let r=n.getUserInteraction();if(!r)return;let i=(0,e.buildPermissionModeSubcommands)().map(e=>({value:e.name,label:e.name,description:e.description})),a=await r.ask((0,t.selectAction)(`mode`,`Select interaction mode`,i));return a.type===`answer`?a.values[0]:void 0}async function fa(t,n){let r=(0,e.parsePermissionModeArgument)(n);if(r===void 0&&(r=await da(t),r===void 0)){let n=(0,e.readCommandPermissionMode)(t);return{message:`Current mode: ${n}`,success:!0,data:{mode:n}}}if(!(0,e.isPermissionMode)(r))return{message:(0,e.formatInvalidPermissionModeMessage)(),success:!1};let i=ca(t,r);return i===void 0?{message:`Permission mode set to: ${r}`,success:!0,data:{mode:r}}:i}function pa(){return{name:`mode`,displayName:`Interaction Mode`,description:e.PERMISSION_MODE_COMMAND_DESCRIPTION,source:`mode`,argumentHint:e.PERMISSION_MODE_ARGUMENT_HINT,subcommands:(0,e.buildPermissionModeSubcommands)(`mode`),modelInvocable:!1}}function ma(){let e=pa();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:fa}}var ha=class{name=`mode`;getCommands(){return[pa()]}};function ga(){return{name:`agent-command-mode`,commandSources:[new ha],systemCommands:[ma()]}}const z=[{mode:`auto-allow`,description:`Confine shell commands; confined ones run without a prompt`},{mode:`regular`,description:`Confine shell commands; prompts work as usual`},{mode:`off`,description:`Run shell commands on this machine, unconfined`}];function _a(e){return z.some(t=>t.mode===e)}function va(e){let t=[`Sandbox: ${e.mode}${e.backend===void 0?``:` (${e.backend})`}`];return e.unavailable!==void 0&&t.push(e.mode===`off`?`Not available here: ${e.unavailable}.`:`Cannot run here: ${e.unavailable}. Commands run unconfined.`),e.mode!==`off`&&e.unavailable===void 0&&(t.push(`Writes are limited to the workspace and temp directories; settings and git hooks stay read-only.`,`Network: ${e.network?`allowed`:`blocked`}.`),e.excludedCommands.length>0&&t.push(`Run unconfined: ${e.excludedCommands.join(`, `)}.`)),t.join(`
47
47
  `)}async function ya(e,n){let r=e.getUserInteraction();if(!r)return;let i=z.map(({mode:e,description:t})=>({value:e,label:e===n?`${e} (current)`:e,description:t})),a=await r.ask((0,t.selectAction)(`sandbox`,`Sandbox mode`,i));return a.type===`answer`?a.values[0]:void 0}async function ba(e,t){let n=e.getCommandHostAdapters?.().sandbox;if(n===void 0)return{message:`This host has no OS sandbox.`,success:!1};let r=n.status(),i=t.trim().split(/\s+/)[0]||await ya(e,r.mode);if(i===void 0||i===``)return{message:va(r),success:!0,data:{...r}};if(!_a(i))return{message:`Unknown sandbox mode "${i}". Valid: ${z.map(e=>e.mode).join(` | `)}`,success:!1};n.setMode(i);let a=n.status();return{message:`Sandbox mode set to: ${i}\n${va(a)}`,success:!0,data:{...a}}}const xa=z.map(e=>e.mode).join(` | `);function Sa(){return{name:`sandbox`,displayName:`Sandbox`,description:`Show or change how shell commands are confined`,source:`sandbox`,argumentHint:xa,subcommands:z.map(({mode:e,description:t})=>({name:e,description:t,source:`sandbox`})),modelInvocable:!1}}function Ca(){let e=Sa();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:ba}}var wa=class{name=`sandbox`;getCommands(){return[Sa()]}};function Ta(){return{name:`agent-command-sandbox`,commandSources:[new wa],systemCommands:[Ca()]}}function Ea(e){return e.getCommandHostAdapters?.().outputStyleRegistry}function Da(e,t){return[`Available output styles:`,...t.listOutputStyles().map(t=>{let n=t.id===e?`* `:` `,r=t.tokenCost?` [input cost: ${t.tokenCost}]`:``;return`${n}${t.id} — ${t.name}: ${t.description}${r}`})].join(`
48
- `)}function Oa(e,t){let n=e.getActiveOutputStyleId(),r=t.listOutputStyles();return{success:!0,message:Da(n,t),data:{outputStyles:r,active:n}}}async function ka(e,n){let r=e.getUserInteraction();if(!r)return;let i=n.listOutputStyles().map(e=>({value:e.id,label:e.id,description:e.description})),a=await r.ask((0,t.selectAction)(`output-style`,`Select an output style`,i));return a.type===`answer`?a.values[0]:void 0}async function Aa(e,t){let n=Ea(e);if(!n)return{success:!1,message:`Output styles are not available in this environment.`};let r=t.trim();if(r===`list`||!r&&(r=await ka(e,n)??``,!r))return Oa(e,n);let i=n.getOutputStyle(r);return i?{success:!0,message:`Switching output style to ${i.name}...`,data:{outputStyle:i.id},hostActions:[{type:`output-style-change`,styleId:i.id}]}:{success:!1,message:`Unknown output style "${r}". Available: ${n.listOutputStyles().map(e=>e.id).join(`, `)||`(none)`}`}}function ja(){return{name:`output-style`,displayName:`Output Style`,description:`List or switch the active provider-neutral response style`,argumentHint:`list | <style-id>`,source:`output-style`,userInvocable:!0,modelInvocable:!1}}function Ma(){let e=ja();return{name:e.name,displayName:e.displayName,description:e.description,argumentHint:e.argumentHint,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Aa}}var Na=class{name=`output-style`;getCommands(){return[ja()]}};function Pa(){return{name:`agent-command-output-style`,commandSources:[new Na],systemCommands:[Ma()]}}function Fa(e){return e.liveness!==`dead`}function Ia(e,t){let n=e.sessionId===t?` (this session)`:``,r=e.liveness===`unknown`?` liveness unknown`:``,i=e.status===`needs-input`?`needs input`:e.status??`unknown`;return` ${e.sessionId}${e.name?` ${e.name}`:``} status ${i}${n?``:La(e)}${r}${n}`}function La(e){if(e.workspaceClaim===`mismatched`)return` workspace claim mismatched, not believed`;switch(e.workspaceRelation){case void 0:return``;case`unknown`:return` workspace unknown`;default:return` ${e.workspaceRelation.replace(`-`,` `)}`}}function Ra(e){let t=e.trim(),n=t.search(/\s/);if(n===-1)return;let r=t.slice(n).trim();if(r!==``)return{target:t.slice(0,n),text:r}}function za(e,t){let n=e.reason===void 0?``:` ${e.reason}`;switch(e.state){case`acknowledged`:case`delivered`:return{message:`Delivered to ${t}.`,success:!0};case`pending`:return{message:`${t} has the message; it is waiting behind work already running there.`,success:!0};case`duplicate`:return{message:`${t} had already seen that message.`,success:!0};default:return{message:`Not delivered to ${t}.${n}`,success:!1}}}async function Ba(e,t){if(e.send===void 0)return{message:`This environment can discover other sessions but cannot address them.`,success:!1};let n=Ra(t);return n===void 0?{message:`Usage: /peers send <session-id> <message>. Run /peers for the session ids.`,success:!1}:za(await e.send(n.target,n.text),n.target)}async function Va(e,t=``){let n=e.getCommandHostAdapters?.().localPeers;if(!n)return{message:`Local peer discovery is not available in this environment.`,success:!0};let r=t.trim(),i=/^send(?=\s|$)/.exec(r);if(i!==null)return Ba(n,r.slice(i[0].length));let a=n.ownSessionId(),o=(n.listWithWorkspace===void 0?n.list():await n.listWithWorkspace()).filter(Fa);return o.filter(e=>e.sessionId!==a).length===0?{message:`No other live session is announced. Start a second session on this host, as this user, and it appears here.`,success:!0}:{message:`Live sessions:\n${o.map(e=>Ia(e,a)).join(`
49
- `)}\n\nSend to one: /peers send <session-id> <message>`,success:!0}}function Ha(){return{name:`peers`,displayName:`Peers`,description:`List the other live sessions on this host, or send one a message`,source:`peers`,modelInvocable:!1}}function Ua(){let e=Ha();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(e,t)=>Va(e,t)}}var Wa=class{name=`peers`;getCommands(){return[Ha()]}};function Ga(){return{name:`agent-command-peers`,commandSources:[new Wa],systemCommands:[Ua()]}}function Ka(){return{name:`permissions`,displayName:`Permissions`,description:e.PERMISSIONS_COMMAND_DESCRIPTION,source:`permissions`,argumentHint:e.PERMISSION_MODE_ARGUMENT_HINT,subcommands:(0,e.buildPermissionModeSubcommands)(`permissions`),modelInvocable:!1}}function qa(){let e=Ka();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:ua}}var Ja=class{name=`permissions`;getCommands(){return[Ka()]}};function Ya(){return{name:`agent-command-permissions`,commandSources:[new Ja],systemCommands:[qa()]}}function Xa(e){let t=[`Plan: ${e.objective}`,`Phase: ${e.phase}${e.approvedAt?` (approved ${e.approvedAt})`:``}`];return e.steps.forEach((e,n)=>{t.push(` ${n+1}. [${e.status}] ${e.description}`)}),t.join(`
50
- `)}async function Za(e,t){let n=t.trim(),r=n.split(/\s+/)[0]?.toLowerCase()??``;if(n.length===0||r===`help`)return{message:`Usage:
48
+ `)}function Oa(e,t){let n=e.getActiveOutputStyleId(),r=t.listOutputStyles();return{success:!0,message:Da(n,t),data:{outputStyles:r,active:n}}}async function ka(e,n){let r=e.getUserInteraction();if(!r)return;let i=n.listOutputStyles().map(e=>({value:e.id,label:e.id,description:e.description})),a=await r.ask((0,t.selectAction)(`output-style`,`Select an output style`,i));return a.type===`answer`?a.values[0]:void 0}async function Aa(e,t){let n=Ea(e);if(!n)return{success:!1,message:`Output styles are not available in this environment.`};let r=t.trim();if(r===`list`||!r&&(r=await ka(e,n)??``,!r))return Oa(e,n);let i=n.getOutputStyle(r);return i?{success:!0,message:`Switching output style to ${i.name}...`,data:{outputStyle:i.id},hostActions:[{type:`output-style-change`,styleId:i.id}]}:{success:!1,message:`Unknown output style "${r}". Available: ${n.listOutputStyles().map(e=>e.id).join(`, `)||`(none)`}`}}function ja(){return{name:`output-style`,displayName:`Output Style`,description:`List or switch the active provider-neutral response style`,argumentHint:`list | <style-id>`,source:`output-style`,userInvocable:!0,modelInvocable:!1}}function Ma(){let e=ja();return{name:e.name,displayName:e.displayName,description:e.description,argumentHint:e.argumentHint,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Aa}}var Na=class{name=`output-style`;getCommands(){return[ja()]}};function Pa(){return{name:`agent-command-output-style`,commandSources:[new Na],systemCommands:[Ma()]}}function Fa(e){return e.liveness!==`dead`}function Ia(e,t){let n=e.sessionId===t?` (this session)`:``,r=e.liveness===`unknown`?` liveness unknown`:``,i=e.status===`needs-input`?`needs input`:e.status??`unknown`;return` ${e.sessionId}${e.name?` ${e.name}`:``} status ${i}${n?``:La(e)}${r}${n}`}function La(e){if(e.workspaceClaim===`mismatched`)return` workspace claim mismatched, not believed`;switch(e.workspaceRelation){case void 0:return``;case`unknown`:return` workspace unknown`;default:return` ${e.workspaceRelation.replace(`-`,` `)}`}}function Ra(e){let t=e.trim(),n=t.search(/\s/);if(n===-1)return;let r=t.slice(n).trim();if(r!==``)return{target:t.slice(0,n),text:r}}function za(e,t){let n=e.reason===void 0?``:` ${e.reason}`;switch(e.state){case`acknowledged`:case`delivered`:return{message:`Delivered to ${t}.`,success:!0};case`pending`:return{message:`${t} has the message; it is waiting behind work already running there.`,success:!0};case`duplicate`:return{message:`${t} had already seen that message.`,success:!0};default:return{message:`Not delivered to ${t}.${n}`,success:!1}}}async function Ba(e,t){if(e.send===void 0)return{message:`This environment can discover other sessions but cannot address them.`,success:!1};let n=Ra(t);return n===void 0?{message:`Usage: /peers send <session-id> <message>. Run /peers for the session ids.`,success:!1}:za(await e.send(n.target,n.text),n.target)}async function Va(e,t,n){if(e.prepareFile===void 0)return{message:`This environment cannot send files to other sessions.`,success:!1};let r=Ra(t);if(r===void 0)return{message:`Usage: /peers send-file <session-id> <path>. Run /peers for the session ids.`,success:!1};let i=await e.prepareFile(r.target,r.text,{origin:`operator`,cwd:n});if(!i.ok)return{message:`Not sent: ${i.reason}`,success:!1};let{file:a}=i,o=await a.send();if(o.state===`delivered`||o.state===`acknowledged`)return{message:`Sent ${a.path} to ${r.target}: ${a.size} bytes, sha256 ${a.sha256}.`,success:!0};let s=o.reason===void 0?``:` ${o.reason}`;return{message:`${a.path} was not sent to ${r.target}.${s}`,success:!1}}async function Ha(e,t=``){let n=e.getCommandHostAdapters?.().localPeers;if(!n)return{message:`Local peer discovery is not available in this environment.`,success:!0};let r=t.trim(),i=/^send-file(?=\s|$)/.exec(r);if(i!==null)return Va(n,r.slice(i[0].length),e.getCwd?.()??``);let a=/^send(?=\s|$)/.exec(r);if(a!==null)return Ba(n,r.slice(a[0].length));let o=n.ownSessionId(),s=(n.listWithWorkspace===void 0?n.list():await n.listWithWorkspace()).filter(Fa);return s.filter(e=>e.sessionId!==o).length===0?{message:`No other live session is announced. Start a second session on this host, as this user, and it appears here.`,success:!0}:{message:`Live sessions:\n${s.map(e=>Ia(e,o)).join(`
49
+ `)}\n\nSend to one: /peers send <session-id> <message>
50
+ Send a file: /peers send-file <session-id> <path>`,success:!0}}function Ua(){return{name:`peers`,displayName:`Peers`,description:`List the other live sessions on this host, send one a message, or send one a copy of a file`,source:`peers`,modelInvocable:!1}}function Wa(){let e=Ua();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(e,t)=>Ha(e,t)}}var Ga=class{name=`peers`;getCommands(){return[Ua()]}};function Ka(){return{name:`agent-command-peers`,commandSources:[new Ga],systemCommands:[Wa()]}}function qa(){return{name:`permissions`,displayName:`Permissions`,description:e.PERMISSIONS_COMMAND_DESCRIPTION,source:`permissions`,argumentHint:e.PERMISSION_MODE_ARGUMENT_HINT,subcommands:(0,e.buildPermissionModeSubcommands)(`permissions`),modelInvocable:!1}}function Ja(){let e=qa();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:ua}}var Ya=class{name=`permissions`;getCommands(){return[qa()]}};function Xa(){return{name:`agent-command-permissions`,commandSources:[new Ya],systemCommands:[Ja()]}}function Za(e){let t=[`Plan: ${e.objective}`,`Phase: ${e.phase}${e.approvedAt?` (approved ${e.approvedAt})`:``}`];return e.steps.forEach((e,n)=>{t.push(` ${n+1}. [${e.status}] ${e.description}`)}),t.join(`
51
+ `)}async function Qa(e,t){let n=t.trim(),r=n.split(/\s+/)[0]?.toLowerCase()??``;if(n.length===0||r===`help`)return{message:`Usage:
51
52
  /plan <objective> draft a plan for review (stays read-only until approved)
52
53
  /plan status show the current plan and phase
53
54
  /plan approve approve the plan (edits auto-apply; shell stays confirmed)
54
- /plan revert return to drafting (re-blocks edits)`,success:!0};if(r===`status`){let t=e.getPlanState();return t?{message:Xa(t),success:!0,data:{phase:t.phase}}:{message:`No plan is active.`,success:!0}}if(r===`approve`){if(!e.getPlanState())return{message:`No plan to approve. Start one with /plan <objective>.`,success:!1};try{let t=e.approvePlan();return{message:`Plan approved — edits will auto-apply; shell steps stay confirmed.\nPhase: ${t.phase}`,success:!0,data:{phase:t.phase}}}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}}if(r===`revert`){if(!e.getPlanState())return{message:`No plan to revert.`,success:!1};let t=e.revertPlan();return{message:`Reverted to drafting — edits are blocked again (plan mode).\nPhase: ${t.phase}`,success:!0,data:{phase:t.phase}}}let i;try{i=await e.setPlan(n)}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}return{message:`Plan drafted (read-only until approved). Review it, then run /plan approve:\n${i.objective}`,success:!0,data:{planId:i.id}}}function Qa(){return{name:`plan`,displayName:`Plan Mode`,description:`Draft a reviewable plan, then approve it to unblock edits (plan → review → approve → act).`,source:`plan`,modelInvocable:!1}}function $a(){let e=Qa();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Za}}var eo=class{name=`plan`;getCommands(){return[Qa()]}};function to(){return{name:`agent-command-plan`,commandSources:[new eo],systemCommands:[$a()]}}function no(e){let t=e.trim().split(/\s+/).filter(e=>e.length>0);return{subcommand:t[0]??``,subArgs:t.slice(1).join(` `).trim()}}function ro(e){return{success:!1,message:e}}function io(t){return(0,e.resolvePluginCommandAdapter)(t)}async function B(e,t){let n=io(e);if(n===void 0)return{success:!1,message:`Plugin management is not available.`};try{return{success:!0,message:await t(n)}}catch(e){return{success:!1,message:`Plugin error: ${e instanceof Error?e.message:String(e)}`}}}async function ao(e,t){let{subcommand:n,subArgs:r}=no(t);return n===`add`&&r.length>0?B(e,async e=>{let t=await e.marketplaceAdd(r);return`Added marketplace: "${t}" (from ${r})\nInstall plugins with: /plugin install <name>@${t}`}):n===`remove`&&r.length>0?B(e,async e=>(await e.marketplaceRemove(r),`Removed marketplace "${r}" and uninstalled its plugins.`)):n===`update`&&r.length>0?B(e,async e=>(await e.marketplaceUpdate(r),`Updated marketplace "${r}".`)):n===`list`?B(e,async e=>{let t=await e.marketplaceList();return t.length===0?`No marketplace sources configured.`:`Marketplace sources:\n${t.map(e=>` ${e.name} (${e.type})`).join(`
55
- `)}`}):ro(`Usage: /plugin marketplace add <source> | remove <name> | update <name> | list`)}function V(e,t,n,r){return t.length===0?Promise.resolve(ro(n)):B(e,e=>Promise.resolve(r(e,t)))}function oo(){return{success:!0,message:`Opening plugin manager...`,uiIntents:[(0,e.createShowPluginManagerIntent)()]}}function so(e,t){return V(e,t,`Usage: /plugin install <name>@<marketplace>`,async(e,t)=>(await e.install(t),`Installed plugin: ${t}`))}function co(e,t){return V(e,t,`Usage: /plugin uninstall <name>@<marketplace>`,async(e,t)=>(await e.uninstall(t),`Uninstalled plugin: ${t}`))}function lo(e,t){return V(e,t,`Usage: /plugin enable <name>@<marketplace>`,async(e,t)=>(await e.enable(t),`Enabled plugin: ${t}`))}function uo(e,t){return V(e,t,`Usage: /plugin disable <name>@<marketplace>`,async(e,t)=>(await e.disable(t),`Disabled plugin: ${t}`))}async function fo(e,t){let{subcommand:n,subArgs:r}=no(t);switch(n){case``:case`manage`:return oo();case`install`:return so(e,r);case`uninstall`:return co(e,r);case`enable`:return lo(e,r);case`disable`:return uo(e,r);case`marketplace`:return ao(e,r);default:return ro(`Unknown plugin subcommand: ${n}`)}}async function po(e,t){return B(e,async e=>{let t=await e.reloadPlugins();return`Reloaded ${t.loadedPluginCount===1?`1 plugin resource`:`${t.loadedPluginCount} plugin resources`}.`}).then(e=>e.success?{...e,data:{...e.data,pluginRegistryReloaded:!0}}:e)}function mo(){return{name:`plugin`,displayName:`Plugins`,description:e.PLUGIN_COMMAND_DESCRIPTION,source:`plugin-manager`,modelInvocable:!1,argumentHint:e.PLUGIN_COMMAND_ARGUMENT_HINT,subcommands:(0,e.buildPluginCommandSubcommands)()}}function ho(){return{name:`reload-plugins`,displayName:`Reload Plugins`,description:e.RELOAD_PLUGINS_COMMAND_DESCRIPTION,source:`plugin-manager`,modelInvocable:!1}}function go(){let e=mo();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,lifecycle:`inline`,subcommands:e.subcommands,execute:fo}}function _o(){let e=ho();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:po}}var vo=class{name=`plugin-manager`;getCommands(){return[mo(),ho()]}};function yo(){return{name:`agent-command-plugin`,commandSources:[new vo],systemCommands:[go(),_o()]}}function bo(e){return e.getCommandHostAdapters?.().presetRegistry??(0,c.createPresetRegistry)()}function xo(e){return e.getSession().getActivePresetId()}function So(e,t){return[`Available presets:`,...t.listPresets().map(t=>`${t.id===e?`* `:` `}${t.id} — ${t.title}: ${t.description}`)].join(`
56
- `)}function Co(e,t){return`Unknown preset: ${e}. Available: ${t.listPresets().map(e=>e.id).join(`, `)}`}function wo(e,t){let n=xo(e);return{message:So(n,t),success:!0,data:{presets:t.listPresets(),active:n}}}async function To(e,n){let r=e.getUserInteraction();if(!r)return;let i=n.listPresets().map(e=>({value:e.id,label:e.id,description:e.description})),a=await r.ask((0,t.selectAction)(`preset`,`Select a preset`,i));return a.type===`answer`?a.values[0]:void 0}async function Eo(t,n){let r=bo(t),i=n.trim().split(/\s+/)[0];if(i===`list`||(i===void 0||i.length===0)&&(i=await To(t,r),i===void 0))return wo(t,r);if(r.getPreset(i)===void 0)return{message:Co(i,r),success:!1};let a=r.resolvePreset(i),o=await(0,e.applyPresetToSession)(t,i,a),s=o.unknownCommandModules.map(({name:e,kind:t})=>`Preset command-module "${e}" (${t}) matched no module — expected the agent-command-* form; ignored.`);return{message:[`Switched to preset: ${i}`,...s].join(`
57
- `),success:!0,data:{preset:i,unknownCommandModules:o.unknownCommandModules}}}function Do(e=`preset`){return(0,c.createPresetRegistry)().listPresets().map(t=>({name:t.id,description:t.description,source:e}))}function Oo(){return{name:`preset`,displayName:`Agent Preset`,description:`List presets or switch the active preset`,source:`preset`,argumentHint:`list | <preset-id>`,subcommands:Do(`preset`),modelInvocable:!1}}function ko(){let e=Oo();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:Eo}}var Ao=class{name=`preset`;getCommands(){return[Oo()]}};function jo(){return{name:`agent-command-preset`,commandSources:[new Ao],systemCommands:[ko()]}}function H(e,t,n={}){let r=Ho(e,t);return{type:e,steps:Go(Uo(r),n.initialValues),setupHelpLinks:r.setupHelpLinks??[],stepIndex:0,values:{},existingProfileNames:n.existingProfileNames??[],...n.profileName===void 0?{}:{profileName:n.profileName},...n.setCurrent===void 0?{}:{setCurrent:n.setCurrent}}}function Mo(e){return e.length===0?` No providers are available.`:[` Select provider:`,...e.map((e,t)=>` ${t+1}. ${Ro(e)}`),` Provider [1-${e.length}] (default: 1): `].join(`
58
- `)}function No(e,n){let r=e.trim(),i=r.length>0?r:`1`,a=Bo(i);if(a!==void 0){let e=n[a];if(e!==void 0)return e.type;throw Error(`Provider selection ${i} is out of range. Currently supported: ${(0,t.formatSupportedProviderTypes)(n)}`)}let o=(0,t.findProviderDefinition)(n,i);if(o===void 0)throw Error(`Unknown provider: ${i}. Currently supported: ${(0,t.formatSupportedProviderTypes)(n)}`);return o.type}function U(e){let t=e.steps[e.stepIndex];if(t===void 0)throw Error(`Provider setup step ${e.stepIndex} is out of range`);return t}function Po(e,t){let n=U(e),r=t.trim()||n.defaultValue||``,i=Vo(n,r);if(i!==void 0)return{status:`error`,state:e,message:i};let a={...e,stepIndex:e.stepIndex+1,values:{...e.values,[n.key]:r}};return a.stepIndex<e.steps.length?{status:`next`,state:a}:{status:`complete`,input:Ko(a)}}async function Fo(e,t,n,r={}){let i=H(e,n,r),a=i.steps.length;for(;i.stepIndex<a;){let e=U(i),n=await t(Io(e,i.setupHelpLinks),e.masked===!0),r=Po(i,n);if(r.status===`complete`)return r.input;if(r.status===`error`)throw Error(r.message);i=r.state}throw Error(`Provider setup flow ended without completion`)}function Io(e,t=[]){let n=e.defaultValue===void 0?``:` (default: ${e.defaultValue})`,r=zo(t);return`${r.length>0?`${r}\n`:``} ${e.title}${n}: `}const Lo={"cloud-paid":`[Cloud/Paid]`,"cloud-free":`[Cloud/Free]`,"local-free":`[Local/Free]`};function Ro(e){let t=`${e.category===void 0?``:`${Lo[e.category]??``} `}${e.displayName===void 0?e.type:`${e.displayName} (${e.type})`}`;return e.description===void 0?t:`${t} — ${e.description}`}function zo(e=[]){return e.length===0?``:e.map(e=>` Setup help: ${Wo(e.kind)}: ${e.label} - ${e.url}`).join(`
59
- `)}function Bo(e){if(/^\d+$/.test(e))return Number(e)-1}function Vo(e,t){if(e.required===!0&&t.length===0)return`Required`}function Ho(e,n){let r=(0,t.findProviderDefinition)(n,e);if(r===void 0)throw Error(`Unknown provider: ${e}. Currently supported: ${(0,t.formatSupportedProviderTypes)(n)}`);return r}function Uo(e){if(e.setupSteps!==void 0)return[...e.setupSteps];let t=[{key:`model`,title:`${e.type} model`,defaultValue:e.defaults?.model,required:e.defaults?.model===void 0}];return e.defaults?.baseURL!==void 0&&t.unshift({key:`baseURL`,title:`${e.type} base URL`,defaultValue:e.defaults.baseURL}),e.requiresApiKey===!0&&t.push({key:`apiKey`,title:`${e.type} API key`,defaultValue:e.defaults?.apiKey,required:e.defaults?.apiKey===void 0,masked:!0}),t}function Wo(e){return e===`api-key`?`API key`:e===`console`?`Console`:`Official`}function Go(e,t){return t===void 0?[...e]:e.map(e=>{let n=t[e.key];return n===void 0?e:{...e,defaultValue:n,required:!1}})}function Ko(t){let n=t.profileName??(0,e.suggestProviderProfileName)({type:t.type},{existingProfileNames:t.existingProfileNames}),r=t.values.apiKey;return{profile:n,type:t.type,model:t.values.model,...r!==void 0&&r.length>0&&{apiKey:r},...t.values.baseURL!==void 0&&{baseURL:t.values.baseURL},setCurrent:t.setCurrent??!0}}const qo={type:`session-restart`,reason:`other`};function Jo(e,t){return H(e,t.providerDefinitions,{existingProfileNames:Object.keys(t.settings.readMergedSettings().providers??{})})}function Yo(e,n){let r=U(e),i=r.masked===!0&&r.defaultValue!==void 0?`(unchanged)`:r.defaultValue,a=zo(e.setupHelpLinks),o=[n,a.length>0?a:void 0].filter(e=>e!==void 0&&e.length>0).join(`
60
- `)||void 0;return(0,t.textAction)(`provider-setup-${r.key}`,r.title,{description:o,placeholder:i,allowEmpty:r.defaultValue!==void 0,masked:r.masked})}async function Xo(e,t,n,r){let i=t,a;for(;;){let t=await e.ask(Yo(i,a));if(t.type===`cancelled`)return{message:r,success:!0};let o=Po(i,t.text??``);if(o.status===`error`){a=o.message;continue}if(o.status===`complete`)return n(o.input);i=o.state,a=void 0}}function Zo(e,t,n){return Xo(e,t,e=>Qo(e,n),`Provider setup cancelled.`)}function Qo(t,n){let r=n.settings.readTargetSettings(),i=(0,e.buildProviderSetupPatch)(t,{providerDefinitions:n.providerDefinitions});return n.settings.writeTargetSettings((0,e.mergeProviderPatch)(r,i)),{message:`Provider ${t.profile} configured. Restarting...`,success:!0,hostActions:[{...qo,message:`Provider setup restart`}]}}function $o(e,t,n){return`${e===n?`* `:``}${e}: ${t.type??`unknown`} ${t.model??`(no model)`}`}function es(t,n,r){if(!n)return{message:`Usage: /provider switch <profile>`,success:!1};if(!t?.[n])return{message:`Provider profile "${n}" was not found.`,success:!1};let{orgPolicy:i}=r;if(i?.allowedProviders&&!i.allowedProviders.includes(n))return{message:(0,e.formatOrgPolicyViolationMessage)(`Provider "${n}" is not allowed by your organization policy. Allowed: ${i.allowedProviders.join(`, `)}.`,i.adminContact),success:!1};if(r.settings.readMergedSettings().currentProvider===n)return{message:`Already using provider "${n}".`,success:!0};let a=t[n],o=r.settings.readTargetSettings(),s=r.settings.readMergedSettings(),c=o.providers?.[n]!==void 0||s.providers?.[n]!==void 0?{...o,currentProvider:n}:(0,e.setCurrentProvider)(o,n);return r.settings.writeTargetSettings(c),{message:`Switched to ${n} (${a.model??`unknown model`}). History preserved.`,success:!0,hostActions:[{type:`provider-hot-swap`,profileName:n}]}}async function ts(e,t,n){let r=n.settings.readMergedSettings().providers?.[t];if(!r)return{message:`Provider profile "${t}" was not found.`,success:!1};if(!r.type)return{message:`Provider profile "${t}" is missing type.`,success:!1};let i;try{i=H(r.type,n.providerDefinitions,{profileName:t,setCurrent:!1,initialValues:ns(r)})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}return Xo(e,i,e=>rs(e,t,n),`Provider edit cancelled.`)}function ns(e){return{...typeof e.model==`string`?{model:e.model}:{},...typeof e.apiKey==`string`?{apiKey:e.apiKey}:{},...typeof e.baseURL==`string`?{baseURL:e.baseURL}:{}}}function rs(t,n,r){let i=r.settings.readMergedSettings(),a=i.providers?.[n];if(!a)return{message:`Provider profile "${n}" was not found.`,success:!1};let{orgPolicy:o}=r;if(o?.requireApiKeyFromEnv&&(0,e.isApiKeyPlaintext)(t.apiKey))return{message:(0,e.formatOrgPolicyViolationMessage)(`Your organization policy requires API keys to be stored as environment variable references ($ENV:VAR_NAME), not as plaintext.`,o.adminContact),success:!1};let s=r.settings.readTargetSettings(),c=(0,e.buildProviderSetupPatch)(t,{providerDefinitions:r.providerDefinitions}).providers[n];if(!c)return{message:`Provider profile "${n}" was not updated.`,success:!1};r.settings.writeTargetSettings((0,e.upsertProviderProfile)(s,n,{...a,...c}));let l=i.currentProvider===n;return{message:l?`Provider ${n} updated. Switching...`:`Provider ${n} updated.`,success:!0,...l?{hostActions:[{type:`provider-hot-swap`,profileName:n}]}:{}}}const is={type:`session-restart`,reason:`other`};async function as(e,n,r){let i=r.settings.readMergedSettings();if(!i.providers?.[n])return{message:`Provider profile "${n}" was not found.`,success:!1};let a=ds(n,Object.keys(i.providers)),o;for(;;){let i=await e.ask((0,t.textAction)(`provider-duplicate`,`Duplicate ${n} as`,{description:o,placeholder:a,allowEmpty:!0}));if(i.type===`cancelled`)return{message:`Provider duplicate cancelled.`,success:!0};let s=i.text??``,c=os(s,a,r);if(c!==void 0){o=c;continue}return ss(n,s,a,r)}}function os(e,t,n){let r=fs(e,t);if(r.length===0)return`Required`;if(n.settings.readMergedSettings().providers?.[r]!==void 0)return`Provider profile "${r}" already exists`}function ss(t,n,r,i){let a=i.settings.readMergedSettings().providers?.[t];if(!a)return{message:`Provider profile "${t}" was not found.`,success:!1};let o=fs(n,r),s=os(o,r,i);return s===void 0?(i.settings.writeTargetSettings((0,e.upsertProviderProfile)(i.settings.readTargetSettings(),o,{...a})),{message:`Provider profile duplicated: ${t} -> ${o}.`,success:!0}):{message:s,success:!1}}async function cs(e,n,r){let i=r.settings.readMergedSettings().providers??{};return i[n]?Object.keys(i).length<=1?{message:`Cannot delete the only provider profile.`,success:!1}:r.settings.readTargetSettings().providers?.[n]===void 0?{message:`Provider profile "${n}" is not stored in the active write target; edit its source settings file or override it before deleting.`,success:!1}:(0,t.isConfirmed)(await e.ask((0,t.confirmAction)(`provider-delete`,`Delete provider profile ${n}?`)))?ls(e,n,r):{message:`Provider delete cancelled.`,success:!0}:{message:`Provider profile "${n}" was not found.`,success:!1}}async function ls(n,r,i){let a=i.settings.readMergedSettings();if(a.currentProvider!==r)return i.settings.writeTargetSettings((0,e.deleteProviderProfile)(i.settings.readTargetSettings(),r)),{message:`Provider profile deleted: ${r}.`,success:!0};let o=Object.entries(a.providers??{}).filter(([e])=>e!==r).map(([e,t])=>({value:e,label:$o(e,t,a.currentProvider)})),s=await n.ask((0,t.selectAction)(`provider-delete-replacement`,`Replacement provider for ${r}`,o,{maxVisible:8}));return s.type!==`answer`||s.values[0]===void 0?{message:`Provider delete cancelled.`,success:!0}:us(r,s.values[0],i)}function us(t,n,r){if(r.settings.readMergedSettings().providers?.[n]===void 0||n===t)return{message:`Provider profile "${n}" was not found.`,success:!1};let i=(0,e.deleteProviderProfile)(r.settings.readTargetSettings(),t);return r.settings.writeTargetSettings({...i,currentProvider:n}),{message:`Provider profile deleted: ${t}. Restarting with ${n}...`,success:!0,hostActions:[{...is,message:`Provider delete restart`}]}}function ds(t,n){let r=(0,e.sanitizeProviderProfileName)(`${t}-copy`)??`provider-copy`;if(!n.includes(r))return r;for(let e=2;e<1e3;e+=1){let t=`${r}-${e}`;if(!n.includes(t))return t}return`${r}-${Date.now()}`}function fs(t,n){return(0,e.sanitizeProviderProfileName)(t.trim()||n)??``}const ps=`switch`,ms=`edit`,hs=`test`,gs=`duplicate`,_s=`delete`,vs=`cancel`;async function ys(e,n,r,i){let a=Object.entries(r??{}).map(([e,t])=>({value:e,label:$o(e,t,n)})),o=await e.ask((0,t.selectAction)(`provider-profile`,`Select provider profile`,a,{maxVisible:8}));return o.type!==`answer`||o.values[0]===void 0?{message:`Provider profile selection cancelled.`,success:!0}:bs(e,o.values[0],i)}async function bs(e,n,r){if(!r.settings.readMergedSettings().providers?.[n])return{message:`Provider profile "${n}" was not found.`,success:!1};let i=await e.ask((0,t.selectAction)(`provider-profile-action`,`Provider profile: ${n}`,[{value:ps,label:`Switch`},{value:ms,label:`Edit`},{value:hs,label:`Test`},{value:gs,label:`Duplicate`},{value:_s,label:`Delete`},{value:vs,label:`Cancel`}]));return i.type!==`answer`||i.values[0]===void 0?{message:`Provider profile action cancelled.`,success:!0}:xs(e,n,i.values[0],r)}async function xs(t,n,r,i){let a=i.settings.readMergedSettings();switch(r){case ps:return es(a.providers,n,i);case ms:return ts(t,n,i);case hs:return(0,e.testProviderProfileCommand)(a.currentProvider,a.providers,n,i);case gs:return as(t,n,i);case _s:return cs(t,n,i);case vs:return{message:`Provider profile action cancelled.`,success:!0};default:return{message:`Unknown provider profile action "${r}".`,success:!1}}}async function Ss(t,n,r){let i=t.getUserInteraction(),a=r.settings.readMergedSettings(),o=n.trim();if(o.length===0)return Cs(i,a.currentProvider,a.providers,r);let[s=`current`,c]=o.split(/\s+/);return s===`list`?Cs(i,a.currentProvider,a.providers,r):s===`current`||s===``?{message:Ts(a.currentProvider,a.providers),success:!0}:s===`switch`?es(a.providers,c,r):s===`test`?(0,e.testProviderProfileCommand)(a.currentProvider,a.providers,c,r):s===`add`?Es(i,c,r):{message:`Usage: provider [current|list|switch <profile>|add <type>|test [profile]]`,success:!1}}function Cs(e,t,n,r){return!e||Object.keys(n??{}).length===0?{message:ws(t,n),success:!0}:ys(e,t,n,r)}function ws(e,t){let n=Object.entries(t??{});return n.length===0?`No provider profiles configured.`:n.map(([t,n])=>`${t===e?`*`:`-`} ${t}: ${n.type??`unknown`} ${n.model??`(no model)`}`).join(`
61
- `)}function Ts(e,t){if(!e)return`No current provider configured.`;let n=t?.[e];return n?[`Current provider: ${e}`,`Type: ${n.type??`unknown`}`,`Model: ${n.model??`(no model)`}`,...n.baseURL?[`Base URL: ${n.baseURL}`]:[]].join(`
62
- `):`Current provider "${e}" was not found in providers.`}function Es(e,n,r){return n===void 0||n.length===0?e?Ds(e,r):{message:`Usage: provider add <type>. Supported: ${(0,t.formatSupportedProviderTypes)(r.providerDefinitions)}`,success:!1}:(0,t.findProviderDefinition)(r.providerDefinitions,n)===void 0?{message:`Usage: provider add <type>. Supported: ${(0,t.formatSupportedProviderTypes)(r.providerDefinitions)}`,success:!1}:e?Zo(e,Jo(n,r),r):{message:`Provider setup for "${n}" requires an interactive session.`,success:!1}}async function Ds(e,n){let r=n.providerDefinitions.map(e=>({value:e.type,label:Ro(e)})),i=await e.ask((0,t.selectAction)(`provider-type`,`Select provider`,r,{maxVisible:6}));if(i.type!==`answer`||i.values[0]===void 0)return{message:`Provider setup cancelled.`,success:!0};let a=i.values[0];return(0,t.findProviderDefinition)(n.providerDefinitions,a)===void 0?{message:`Usage: provider add <type>. Supported: ${(0,t.formatSupportedProviderTypes)(n.providerDefinitions)}`,success:!1}:Zo(e,Jo(a,n),n)}function Os(){return[{name:`current`,description:`Show current provider`,source:`provider`},{name:`list`,description:`List provider profiles`,source:`provider`},{name:`switch`,description:`Hot-swap to another provider profile`,source:`provider`},{name:`add`,description:`Configure a provider profile`,source:`provider`},{name:`test`,description:`Test provider profile`,source:`provider`}]}function ks(){return{name:`provider`,displayName:`Provider Setup`,description:`Manage provider profiles`,source:`provider`,modelInvocable:!1,argumentHint:`current | list | switch <profile> | add [type] | test [profile]`,subcommands:Os(),example:`/provider switch production`}}var As=class{name=`provider`;getCommands(){return[ks()]}};function js(e){let t=ks();return{name:t.name,displayName:t.displayName,description:t.description,example:t.example,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:t.argumentHint,subcommands:t.subcommands,lifecycle:`inline`,execute:(t,n)=>Ss(t,n,e)}}function Ms(e){return{name:`agent-command-provider`,commandSources:[new As],systemCommands:[js(e)]}}async function Ns(e,t){let n=(await e(`
55
+ /plan revert return to drafting (re-blocks edits)`,success:!0};if(r===`status`){let t=e.getPlanState();return t?{message:Za(t),success:!0,data:{phase:t.phase}}:{message:`No plan is active.`,success:!0}}if(r===`approve`){if(!e.getPlanState())return{message:`No plan to approve. Start one with /plan <objective>.`,success:!1};try{let t=e.approvePlan();return{message:`Plan approved — edits will auto-apply; shell steps stay confirmed.\nPhase: ${t.phase}`,success:!0,data:{phase:t.phase}}}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}}if(r===`revert`){if(!e.getPlanState())return{message:`No plan to revert.`,success:!1};let t=e.revertPlan();return{message:`Reverted to drafting — edits are blocked again (plan mode).\nPhase: ${t.phase}`,success:!0,data:{phase:t.phase}}}let i;try{i=await e.setPlan(n)}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}return{message:`Plan drafted (read-only until approved). Review it, then run /plan approve:\n${i.objective}`,success:!0,data:{planId:i.id}}}function $a(){return{name:`plan`,displayName:`Plan Mode`,description:`Draft a reviewable plan, then approve it to unblock edits (plan → review → approve → act).`,source:`plan`,modelInvocable:!1}}function eo(){let e=$a();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Qa}}var to=class{name=`plan`;getCommands(){return[$a()]}};function no(){return{name:`agent-command-plan`,commandSources:[new to],systemCommands:[eo()]}}function ro(e){let t=e.trim().split(/\s+/).filter(e=>e.length>0);return{subcommand:t[0]??``,subArgs:t.slice(1).join(` `).trim()}}function io(e){return{success:!1,message:e}}function ao(t){return(0,e.resolvePluginCommandAdapter)(t)}async function B(e,t){let n=ao(e);if(n===void 0)return{success:!1,message:`Plugin management is not available.`};try{return{success:!0,message:await t(n)}}catch(e){return{success:!1,message:`Plugin error: ${e instanceof Error?e.message:String(e)}`}}}async function oo(e,t){let{subcommand:n,subArgs:r}=ro(t);return n===`add`&&r.length>0?B(e,async e=>{let t=await e.marketplaceAdd(r);return`Added marketplace: "${t}" (from ${r})\nInstall plugins with: /plugin install <name>@${t}`}):n===`remove`&&r.length>0?B(e,async e=>(await e.marketplaceRemove(r),`Removed marketplace "${r}" and uninstalled its plugins.`)):n===`update`&&r.length>0?B(e,async e=>(await e.marketplaceUpdate(r),`Updated marketplace "${r}".`)):n===`list`?B(e,async e=>{let t=await e.marketplaceList();return t.length===0?`No marketplace sources configured.`:`Marketplace sources:\n${t.map(e=>` ${e.name} (${e.type})`).join(`
56
+ `)}`}):io(`Usage: /plugin marketplace add <source> | remove <name> | update <name> | list`)}function V(e,t,n,r){return t.length===0?Promise.resolve(io(n)):B(e,e=>Promise.resolve(r(e,t)))}function so(){return{success:!0,message:`Opening plugin manager...`,uiIntents:[(0,e.createShowPluginManagerIntent)()]}}function co(e,t){return V(e,t,`Usage: /plugin install <name>@<marketplace>`,async(e,t)=>(await e.install(t),`Installed plugin: ${t}`))}function lo(e,t){return V(e,t,`Usage: /plugin uninstall <name>@<marketplace>`,async(e,t)=>(await e.uninstall(t),`Uninstalled plugin: ${t}`))}function uo(e,t){return V(e,t,`Usage: /plugin enable <name>@<marketplace>`,async(e,t)=>(await e.enable(t),`Enabled plugin: ${t}`))}function fo(e,t){return V(e,t,`Usage: /plugin disable <name>@<marketplace>`,async(e,t)=>(await e.disable(t),`Disabled plugin: ${t}`))}async function po(e,t){let{subcommand:n,subArgs:r}=ro(t);switch(n){case``:case`manage`:return so();case`install`:return co(e,r);case`uninstall`:return lo(e,r);case`enable`:return uo(e,r);case`disable`:return fo(e,r);case`marketplace`:return oo(e,r);default:return io(`Unknown plugin subcommand: ${n}`)}}async function mo(e,t){return B(e,async e=>{let t=await e.reloadPlugins();return`Reloaded ${t.loadedPluginCount===1?`1 plugin resource`:`${t.loadedPluginCount} plugin resources`}.`}).then(e=>e.success?{...e,data:{...e.data,pluginRegistryReloaded:!0}}:e)}function ho(){return{name:`plugin`,displayName:`Plugins`,description:e.PLUGIN_COMMAND_DESCRIPTION,source:`plugin-manager`,modelInvocable:!1,argumentHint:e.PLUGIN_COMMAND_ARGUMENT_HINT,subcommands:(0,e.buildPluginCommandSubcommands)()}}function go(){return{name:`reload-plugins`,displayName:`Reload Plugins`,description:e.RELOAD_PLUGINS_COMMAND_DESCRIPTION,source:`plugin-manager`,modelInvocable:!1}}function _o(){let e=ho();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,lifecycle:`inline`,subcommands:e.subcommands,execute:po}}function vo(){let e=go();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:mo}}var yo=class{name=`plugin-manager`;getCommands(){return[ho(),go()]}};function bo(){return{name:`agent-command-plugin`,commandSources:[new yo],systemCommands:[_o(),vo()]}}function xo(e){return e.getCommandHostAdapters?.().presetRegistry??(0,c.createPresetRegistry)()}function So(e){return e.getSession().getActivePresetId()}function Co(e,t){return[`Available presets:`,...t.listPresets().map(t=>`${t.id===e?`* `:` `}${t.id} — ${t.title}: ${t.description}`)].join(`
57
+ `)}function wo(e,t){return`Unknown preset: ${e}. Available: ${t.listPresets().map(e=>e.id).join(`, `)}`}function To(e,t){let n=So(e);return{message:Co(n,t),success:!0,data:{presets:t.listPresets(),active:n}}}async function Eo(e,n){let r=e.getUserInteraction();if(!r)return;let i=n.listPresets().map(e=>({value:e.id,label:e.id,description:e.description})),a=await r.ask((0,t.selectAction)(`preset`,`Select a preset`,i));return a.type===`answer`?a.values[0]:void 0}async function Do(t,n){let r=xo(t),i=n.trim().split(/\s+/)[0];if(i===`list`||(i===void 0||i.length===0)&&(i=await Eo(t,r),i===void 0))return To(t,r);if(r.getPreset(i)===void 0)return{message:wo(i,r),success:!1};let a=r.resolvePreset(i),o=await(0,e.applyPresetToSession)(t,i,a),s=o.unknownCommandModules.map(({name:e,kind:t})=>`Preset command-module "${e}" (${t}) matched no module — expected the agent-command-* form; ignored.`);return{message:[`Switched to preset: ${i}`,...s].join(`
58
+ `),success:!0,data:{preset:i,unknownCommandModules:o.unknownCommandModules}}}function Oo(e=`preset`){return(0,c.createPresetRegistry)().listPresets().map(t=>({name:t.id,description:t.description,source:e}))}function ko(){return{name:`preset`,displayName:`Agent Preset`,description:`List presets or switch the active preset`,source:`preset`,argumentHint:`list | <preset-id>`,subcommands:Oo(`preset`),modelInvocable:!1}}function Ao(){let e=ko();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:Do}}var jo=class{name=`preset`;getCommands(){return[ko()]}};function Mo(){return{name:`agent-command-preset`,commandSources:[new jo],systemCommands:[Ao()]}}function H(e,t,n={}){let r=Uo(e,t);return{type:e,steps:Ko(Wo(r),n.initialValues),setupHelpLinks:r.setupHelpLinks??[],stepIndex:0,values:{},existingProfileNames:n.existingProfileNames??[],...n.profileName===void 0?{}:{profileName:n.profileName},...n.setCurrent===void 0?{}:{setCurrent:n.setCurrent}}}function No(e){return e.length===0?` No providers are available.`:[` Select provider:`,...e.map((e,t)=>` ${t+1}. ${zo(e)}`),` Provider [1-${e.length}] (default: 1): `].join(`
59
+ `)}function Po(e,n){let r=e.trim(),i=r.length>0?r:`1`,a=Vo(i);if(a!==void 0){let e=n[a];if(e!==void 0)return e.type;throw Error(`Provider selection ${i} is out of range. Currently supported: ${(0,t.formatSupportedProviderTypes)(n)}`)}let o=(0,t.findProviderDefinition)(n,i);if(o===void 0)throw Error(`Unknown provider: ${i}. Currently supported: ${(0,t.formatSupportedProviderTypes)(n)}`);return o.type}function U(e){let t=e.steps[e.stepIndex];if(t===void 0)throw Error(`Provider setup step ${e.stepIndex} is out of range`);return t}function Fo(e,t){let n=U(e),r=t.trim()||n.defaultValue||``,i=Ho(n,r);if(i!==void 0)return{status:`error`,state:e,message:i};let a={...e,stepIndex:e.stepIndex+1,values:{...e.values,[n.key]:r}};return a.stepIndex<e.steps.length?{status:`next`,state:a}:{status:`complete`,input:qo(a)}}async function Io(e,t,n,r={}){let i=H(e,n,r),a=i.steps.length;for(;i.stepIndex<a;){let e=U(i),n=await t(Lo(e,i.setupHelpLinks),e.masked===!0),r=Fo(i,n);if(r.status===`complete`)return r.input;if(r.status===`error`)throw Error(r.message);i=r.state}throw Error(`Provider setup flow ended without completion`)}function Lo(e,t=[]){let n=e.defaultValue===void 0?``:` (default: ${e.defaultValue})`,r=Bo(t);return`${r.length>0?`${r}\n`:``} ${e.title}${n}: `}const Ro={"cloud-paid":`[Cloud/Paid]`,"cloud-free":`[Cloud/Free]`,"local-free":`[Local/Free]`};function zo(e){let t=`${e.category===void 0?``:`${Ro[e.category]??``} `}${e.displayName===void 0?e.type:`${e.displayName} (${e.type})`}`;return e.description===void 0?t:`${t} — ${e.description}`}function Bo(e=[]){return e.length===0?``:e.map(e=>` Setup help: ${Go(e.kind)}: ${e.label} - ${e.url}`).join(`
60
+ `)}function Vo(e){if(/^\d+$/.test(e))return Number(e)-1}function Ho(e,t){if(e.required===!0&&t.length===0)return`Required`}function Uo(e,n){let r=(0,t.findProviderDefinition)(n,e);if(r===void 0)throw Error(`Unknown provider: ${e}. Currently supported: ${(0,t.formatSupportedProviderTypes)(n)}`);return r}function Wo(e){if(e.setupSteps!==void 0)return[...e.setupSteps];let t=[{key:`model`,title:`${e.type} model`,defaultValue:e.defaults?.model,required:e.defaults?.model===void 0}];return e.defaults?.baseURL!==void 0&&t.unshift({key:`baseURL`,title:`${e.type} base URL`,defaultValue:e.defaults.baseURL}),e.requiresApiKey===!0&&t.push({key:`apiKey`,title:`${e.type} API key`,defaultValue:e.defaults?.apiKey,required:e.defaults?.apiKey===void 0,masked:!0}),t}function Go(e){return e===`api-key`?`API key`:e===`console`?`Console`:`Official`}function Ko(e,t){return t===void 0?[...e]:e.map(e=>{let n=t[e.key];return n===void 0?e:{...e,defaultValue:n,required:!1}})}function qo(t){let n=t.profileName??(0,e.suggestProviderProfileName)({type:t.type},{existingProfileNames:t.existingProfileNames}),r=t.values.apiKey;return{profile:n,type:t.type,model:t.values.model,...r!==void 0&&r.length>0&&{apiKey:r},...t.values.baseURL!==void 0&&{baseURL:t.values.baseURL},setCurrent:t.setCurrent??!0}}const Jo={type:`session-restart`,reason:`other`};function Yo(e,t){return H(e,t.providerDefinitions,{existingProfileNames:Object.keys(t.settings.readMergedSettings().providers??{})})}function Xo(e,n){let r=U(e),i=r.masked===!0&&r.defaultValue!==void 0?`(unchanged)`:r.defaultValue,a=Bo(e.setupHelpLinks),o=[n,a.length>0?a:void 0].filter(e=>e!==void 0&&e.length>0).join(`
61
+ `)||void 0;return(0,t.textAction)(`provider-setup-${r.key}`,r.title,{description:o,placeholder:i,allowEmpty:r.defaultValue!==void 0,masked:r.masked})}async function Zo(e,t,n,r){let i=t,a;for(;;){let t=await e.ask(Xo(i,a));if(t.type===`cancelled`)return{message:r,success:!0};let o=Fo(i,t.text??``);if(o.status===`error`){a=o.message;continue}if(o.status===`complete`)return n(o.input);i=o.state,a=void 0}}function Qo(e,t,n){return Zo(e,t,e=>$o(e,n),`Provider setup cancelled.`)}function $o(t,n){let r=n.settings.readTargetSettings(),i=(0,e.buildProviderSetupPatch)(t,{providerDefinitions:n.providerDefinitions});return n.settings.writeTargetSettings((0,e.mergeProviderPatch)(r,i)),{message:`Provider ${t.profile} configured. Restarting...`,success:!0,hostActions:[{...Jo,message:`Provider setup restart`}]}}function es(e,t,n){return`${e===n?`* `:``}${e}: ${t.type??`unknown`} ${t.model??`(no model)`}`}function ts(t,n,r){if(!n)return{message:`Usage: /provider switch <profile>`,success:!1};if(!t?.[n])return{message:`Provider profile "${n}" was not found.`,success:!1};let{orgPolicy:i}=r;if(i?.allowedProviders&&!i.allowedProviders.includes(n))return{message:(0,e.formatOrgPolicyViolationMessage)(`Provider "${n}" is not allowed by your organization policy. Allowed: ${i.allowedProviders.join(`, `)}.`,i.adminContact),success:!1};if(r.settings.readMergedSettings().currentProvider===n)return{message:`Already using provider "${n}".`,success:!0};let a=t[n],o=r.settings.readTargetSettings(),s=r.settings.readMergedSettings(),c=o.providers?.[n]!==void 0||s.providers?.[n]!==void 0?{...o,currentProvider:n}:(0,e.setCurrentProvider)(o,n);return r.settings.writeTargetSettings(c),{message:`Switched to ${n} (${a.model??`unknown model`}). History preserved.`,success:!0,hostActions:[{type:`provider-hot-swap`,profileName:n}]}}async function ns(e,t,n){let r=n.settings.readMergedSettings().providers?.[t];if(!r)return{message:`Provider profile "${t}" was not found.`,success:!1};if(!r.type)return{message:`Provider profile "${t}" is missing type.`,success:!1};let i;try{i=H(r.type,n.providerDefinitions,{profileName:t,setCurrent:!1,initialValues:rs(r)})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}return Zo(e,i,e=>is(e,t,n),`Provider edit cancelled.`)}function rs(e){return{...typeof e.model==`string`?{model:e.model}:{},...typeof e.apiKey==`string`?{apiKey:e.apiKey}:{},...typeof e.baseURL==`string`?{baseURL:e.baseURL}:{}}}function is(t,n,r){let i=r.settings.readMergedSettings(),a=i.providers?.[n];if(!a)return{message:`Provider profile "${n}" was not found.`,success:!1};let{orgPolicy:o}=r;if(o?.requireApiKeyFromEnv&&(0,e.isApiKeyPlaintext)(t.apiKey))return{message:(0,e.formatOrgPolicyViolationMessage)(`Your organization policy requires API keys to be stored as environment variable references ($ENV:VAR_NAME), not as plaintext.`,o.adminContact),success:!1};let s=r.settings.readTargetSettings(),c=(0,e.buildProviderSetupPatch)(t,{providerDefinitions:r.providerDefinitions}).providers[n];if(!c)return{message:`Provider profile "${n}" was not updated.`,success:!1};r.settings.writeTargetSettings((0,e.upsertProviderProfile)(s,n,{...a,...c}));let l=i.currentProvider===n;return{message:l?`Provider ${n} updated. Switching...`:`Provider ${n} updated.`,success:!0,...l?{hostActions:[{type:`provider-hot-swap`,profileName:n}]}:{}}}const as={type:`session-restart`,reason:`other`};async function os(e,n,r){let i=r.settings.readMergedSettings();if(!i.providers?.[n])return{message:`Provider profile "${n}" was not found.`,success:!1};let a=fs(n,Object.keys(i.providers)),o;for(;;){let i=await e.ask((0,t.textAction)(`provider-duplicate`,`Duplicate ${n} as`,{description:o,placeholder:a,allowEmpty:!0}));if(i.type===`cancelled`)return{message:`Provider duplicate cancelled.`,success:!0};let s=i.text??``,c=ss(s,a,r);if(c!==void 0){o=c;continue}return cs(n,s,a,r)}}function ss(e,t,n){let r=ps(e,t);if(r.length===0)return`Required`;if(n.settings.readMergedSettings().providers?.[r]!==void 0)return`Provider profile "${r}" already exists`}function cs(t,n,r,i){let a=i.settings.readMergedSettings().providers?.[t];if(!a)return{message:`Provider profile "${t}" was not found.`,success:!1};let o=ps(n,r),s=ss(o,r,i);return s===void 0?(i.settings.writeTargetSettings((0,e.upsertProviderProfile)(i.settings.readTargetSettings(),o,{...a})),{message:`Provider profile duplicated: ${t} -> ${o}.`,success:!0}):{message:s,success:!1}}async function ls(e,n,r){let i=r.settings.readMergedSettings().providers??{};return i[n]?Object.keys(i).length<=1?{message:`Cannot delete the only provider profile.`,success:!1}:r.settings.readTargetSettings().providers?.[n]===void 0?{message:`Provider profile "${n}" is not stored in the active write target; edit its source settings file or override it before deleting.`,success:!1}:(0,t.isConfirmed)(await e.ask((0,t.confirmAction)(`provider-delete`,`Delete provider profile ${n}?`)))?us(e,n,r):{message:`Provider delete cancelled.`,success:!0}:{message:`Provider profile "${n}" was not found.`,success:!1}}async function us(n,r,i){let a=i.settings.readMergedSettings();if(a.currentProvider!==r)return i.settings.writeTargetSettings((0,e.deleteProviderProfile)(i.settings.readTargetSettings(),r)),{message:`Provider profile deleted: ${r}.`,success:!0};let o=Object.entries(a.providers??{}).filter(([e])=>e!==r).map(([e,t])=>({value:e,label:es(e,t,a.currentProvider)})),s=await n.ask((0,t.selectAction)(`provider-delete-replacement`,`Replacement provider for ${r}`,o,{maxVisible:8}));return s.type!==`answer`||s.values[0]===void 0?{message:`Provider delete cancelled.`,success:!0}:ds(r,s.values[0],i)}function ds(t,n,r){if(r.settings.readMergedSettings().providers?.[n]===void 0||n===t)return{message:`Provider profile "${n}" was not found.`,success:!1};let i=(0,e.deleteProviderProfile)(r.settings.readTargetSettings(),t);return r.settings.writeTargetSettings({...i,currentProvider:n}),{message:`Provider profile deleted: ${t}. Restarting with ${n}...`,success:!0,hostActions:[{...as,message:`Provider delete restart`}]}}function fs(t,n){let r=(0,e.sanitizeProviderProfileName)(`${t}-copy`)??`provider-copy`;if(!n.includes(r))return r;for(let e=2;e<1e3;e+=1){let t=`${r}-${e}`;if(!n.includes(t))return t}return`${r}-${Date.now()}`}function ps(t,n){return(0,e.sanitizeProviderProfileName)(t.trim()||n)??``}const ms=`switch`,hs=`edit`,gs=`test`,_s=`duplicate`,vs=`delete`,ys=`cancel`;async function bs(e,n,r,i){let a=Object.entries(r??{}).map(([e,t])=>({value:e,label:es(e,t,n)})),o=await e.ask((0,t.selectAction)(`provider-profile`,`Select provider profile`,a,{maxVisible:8}));return o.type!==`answer`||o.values[0]===void 0?{message:`Provider profile selection cancelled.`,success:!0}:xs(e,o.values[0],i)}async function xs(e,n,r){if(!r.settings.readMergedSettings().providers?.[n])return{message:`Provider profile "${n}" was not found.`,success:!1};let i=await e.ask((0,t.selectAction)(`provider-profile-action`,`Provider profile: ${n}`,[{value:ms,label:`Switch`},{value:hs,label:`Edit`},{value:gs,label:`Test`},{value:_s,label:`Duplicate`},{value:vs,label:`Delete`},{value:ys,label:`Cancel`}]));return i.type!==`answer`||i.values[0]===void 0?{message:`Provider profile action cancelled.`,success:!0}:Ss(e,n,i.values[0],r)}async function Ss(t,n,r,i){let a=i.settings.readMergedSettings();switch(r){case ms:return ts(a.providers,n,i);case hs:return ns(t,n,i);case gs:return(0,e.testProviderProfileCommand)(a.currentProvider,a.providers,n,i);case _s:return os(t,n,i);case vs:return ls(t,n,i);case ys:return{message:`Provider profile action cancelled.`,success:!0};default:return{message:`Unknown provider profile action "${r}".`,success:!1}}}async function Cs(t,n,r){let i=t.getUserInteraction(),a=r.settings.readMergedSettings(),o=n.trim();if(o.length===0)return ws(i,a.currentProvider,a.providers,r);let[s=`current`,c]=o.split(/\s+/);return s===`list`?ws(i,a.currentProvider,a.providers,r):s===`current`||s===``?{message:Es(a.currentProvider,a.providers),success:!0}:s===`switch`?ts(a.providers,c,r):s===`test`?(0,e.testProviderProfileCommand)(a.currentProvider,a.providers,c,r):s===`add`?Ds(i,c,r):{message:`Usage: provider [current|list|switch <profile>|add <type>|test [profile]]`,success:!1}}function ws(e,t,n,r){return!e||Object.keys(n??{}).length===0?{message:Ts(t,n),success:!0}:bs(e,t,n,r)}function Ts(e,t){let n=Object.entries(t??{});return n.length===0?`No provider profiles configured.`:n.map(([t,n])=>`${t===e?`*`:`-`} ${t}: ${n.type??`unknown`} ${n.model??`(no model)`}`).join(`
62
+ `)}function Es(e,t){if(!e)return`No current provider configured.`;let n=t?.[e];return n?[`Current provider: ${e}`,`Type: ${n.type??`unknown`}`,`Model: ${n.model??`(no model)`}`,...n.baseURL?[`Base URL: ${n.baseURL}`]:[]].join(`
63
+ `):`Current provider "${e}" was not found in providers.`}function Ds(e,n,r){return n===void 0||n.length===0?e?Os(e,r):{message:`Usage: provider add <type>. Supported: ${(0,t.formatSupportedProviderTypes)(r.providerDefinitions)}`,success:!1}:(0,t.findProviderDefinition)(r.providerDefinitions,n)===void 0?{message:`Usage: provider add <type>. Supported: ${(0,t.formatSupportedProviderTypes)(r.providerDefinitions)}`,success:!1}:e?Qo(e,Yo(n,r),r):{message:`Provider setup for "${n}" requires an interactive session.`,success:!1}}async function Os(e,n){let r=n.providerDefinitions.map(e=>({value:e.type,label:zo(e)})),i=await e.ask((0,t.selectAction)(`provider-type`,`Select provider`,r,{maxVisible:6}));if(i.type!==`answer`||i.values[0]===void 0)return{message:`Provider setup cancelled.`,success:!0};let a=i.values[0];return(0,t.findProviderDefinition)(n.providerDefinitions,a)===void 0?{message:`Usage: provider add <type>. Supported: ${(0,t.formatSupportedProviderTypes)(n.providerDefinitions)}`,success:!1}:Qo(e,Yo(a,n),n)}function ks(){return[{name:`current`,description:`Show current provider`,source:`provider`},{name:`list`,description:`List provider profiles`,source:`provider`},{name:`switch`,description:`Hot-swap to another provider profile`,source:`provider`},{name:`add`,description:`Configure a provider profile`,source:`provider`},{name:`test`,description:`Test provider profile`,source:`provider`}]}function As(){return{name:`provider`,displayName:`Provider Setup`,description:`Manage provider profiles`,source:`provider`,modelInvocable:!1,argumentHint:`current | list | switch <profile> | add [type] | test [profile]`,subcommands:ks(),example:`/provider switch production`}}var js=class{name=`provider`;getCommands(){return[As()]}};function Ms(e){let t=As();return{name:t.name,displayName:t.displayName,description:t.description,example:t.example,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:t.argumentHint,subcommands:t.subcommands,lifecycle:`inline`,execute:(t,n)=>Cs(t,n,e)}}function Ns(e){return{name:`agent-command-provider`,commandSources:[new js],systemCommands:[Ms(e)]}}async function Ps(e,t){let n=(await e(`
63
64
  Do you have an API key for an AI provider?
64
65
 
65
66
  1. Yes, I have an API key
@@ -86,21 +87,21 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
86
87
  When the server is running, come back here and press Enter to continue.
87
88
 
88
89
  ─────────────────────────────────────────────────────────────────────────────
89
- `),await e(` Press Enter when LM Studio server is running: `),{path:`local`,preselectedType:`gemma`}):{path:`has-key`}}async function Ps(t,n,r,i,a){let o=await Ns(r,i),s=Is(n),c=Object.keys((0,e.readMergedProviderSettings)(s.sources).providers??{}),l=Ls(s.stores,n.settingsScope),u;u=o.preselectedType===void 0?No(await r(Mo(a)),a):o.preselectedType,(0,e.applyProviderConfiguration)(l,await Fo(u,r,a,{existingProfileNames:c}),{providerDefinitions:a});let d=await r(` Response language (ko/en/ja/zh, default: en): `);if(d){let e=l.read();e.language=d,l.write(e)}i.writeLine(`\n Config saved to ${l.displayName}\n`)}async function Fs(t,n,r,i,a,o){let s=Is(n),c=(0,e.readMergedProviderSettings)(s.sources);if((0,e.checkSettingsDocument)(n.provider===void 0?c:{...c,currentProvider:n.provider},a)===`valid`||n.provider===void 0&&(0,e.resolveEnvDefaultProvider)(a,o.env)!==void 0)return;if(!(o.isInteractive??(()=>!1))())throw new e.ProviderConfigError(o.formatError(a));await Ps(t,Rs(n,s.stores),r,i,a);let l=(0,e.readMergedProviderSettings)(s.sources);if((0,e.checkSettingsDocument)(n.provider===void 0?l:{...l,currentProvider:n.provider},a)!==`valid`)throw new e.ProviderConfigError(o.formatError(a))}function Is(e){if(e.settingsSources===void 0||e.settingsStores===void 0)throw Error(`Provider startup requires host settings sources and stores.`);return{sources:e.settingsSources,stores:e.settingsStores}}function Ls(t,n){if(n===void 0)return(0,e.resolveProviderSettingsWriteTarget)(t);let r=n===`user`?`user`:`project-local`,i=t.findLast(e=>e.scope===r);if(i!==void 0)return i;throw new e.WorkspaceAuthorityRequiredError(`No authorized ${r} settings store is available.`)}function Rs(e,t){return e.settingsScope!==void 0||e.provider!==void 0?e:zs(t)?.kind===`project`?{...e,settingsScope:`project-local`}:e}function zs(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&typeof n.read().currentProvider==`string`)return n}}const Bs="only the operator at this terminal can do this; a connected surface cannot pair, enroll or revoke devices. Run `/remote-control` on the host terminal.";function Vs(e,t){if(!e)return{message:`Remote control is not available in this environment.`,success:!0};switch(e.state){case`off`:return{message:"Remote control is off. Use `/remote-control` to enable it.",success:!0};case`no-relay`:return{message:"Remote control is unavailable: no signaling relay is configured (set `transports.webrtc.options.relayUrl`).",success:!0};case`awaiting-pairing`:return{message:t?`Remote control is waiting for a device to pair.\nOpen: ${e.pairingUrl}`:`Remote control is waiting for a device to pair. The pairing link is shown only on the host terminal.`,success:!0};case`paired`:return{message:`Remote control is active — a device is paired.`,success:!0};default:return{message:`Remote control status is unknown.`,success:!0}}}function Hs(e,t){let n=e.getCommandInvocationSource()===`user`,r=t.trim(),i=r.indexOf(` `),a=(i===-1?r:r.slice(0,i)).toLowerCase(),o=i===-1?``:r.slice(i+1).trim();if(a===`status`){let t=e.getCommandHostAdapters?.().remoteControl,r=Vs(t?.getStatus(),n);if(!t?.describeKeyStorage)return r;let i=t.describeKeyStorage()??`chosen when remote control is first enabled`;return{...r,message:`${r.message}\nHost key storage: ${i}`}}if(a===`devices`){let t=(e.getCommandHostAdapters?.().remoteControl)?.listDevices?.();return t?t.length===0?{message:`No trusted devices are enrolled yet.`,success:!0}:{message:`Trusted devices:\n${t.map(e=>` ${e.deviceId} ${e.label} (last seen ${e.lastSeenAt})`).join(`
90
- `)}`,success:!0}:{message:`Trusted-device reconnect is not available in this environment.`,success:!0}}if(a===`revoke`){if(!n)return{message:`\`/remote-control revoke\`: ${Bs}`,success:!1};if(!o)return{message:`Usage: /remote-control revoke <deviceId>`,success:!1};let t=e.getCommandHostAdapters?.().remoteControl;return t?.revokeDevice?t.revokeDevice(o)?{message:`Revoked trusted device ${o}. It must re-pair to reconnect.`,success:!0}:{message:`No trusted device with id ${o}.`,success:!1}:{message:`Trusted-device reconnect is not available in this environment.`,success:!0}}return a===`stop`||a===`off`?{message:`Stopping remote control...`,success:!0,hostActions:[{type:`remote-control-stop`}]}:a===``||a===`enable`||a===`on`?n?{message:`Enabling remote control...`,success:!0,hostActions:[{type:`remote-control-enable`}]}:{message:`\`/remote-control enable\`: ${Bs}`,success:!1}:{message:`Unknown argument "${a}". Usage: /remote-control [enable|stop|status|devices|revoke <id>]`,success:!1}}function Us(){return{name:`remote-control`,displayName:`Remote control`,description:`Enable P2P remote control (pair a device to co-drive this session), or check status. Pairing and revoking run only for the operator at the host terminal; a connected surface can stop remote control and read its status, without the pairing link.`,source:`remote-control`,modelInvocable:!1,userInvocable:!0,argumentHint:`[enable|stop|status|devices|revoke <device-id>]`,subcommands:[{name:`status`,description:`Show remote-control status`,source:`remote-control`},{name:`devices`,description:`List trusted devices`,source:`remote-control`},{name:`enable`,description:`Enable remote control and pair a device`,source:`remote-control`},{name:`stop`,description:`Stop remote control`,source:`remote-control`},{name:`revoke`,description:`Revoke a trusted device`,source:`remote-control`,argumentHint:`<device-id>`}]}}function Ws(){return E(Us(),{requiresPermission:!1,lifecycle:`inline`,execute:(e,t)=>Hs(e,t)})}var Gs=class{name=`remote-control`;getCommands(){return[Us()]}};function Ks(){return{name:`agent-command-remote-control`,commandSources:[new Gs],systemCommands:[Ws()]}}function qs(){return{success:!0,message:`Reset requested.`,data:{resetRequested:!0},hostActions:[{type:`settings-reset`}]}}function Js(){return{name:`reset`,displayName:`Reset Settings`,description:`Delete settings`,source:`reset`,modelInvocable:!1}}function Ys(){let e=Js();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:qs}}var Xs=class{name=`reset`;getCommands(){return[Js()]}};function Zs(){return{name:`agent-command-reset`,commandSources:[new Xs],systemCommands:[Ys()]}}function W(){return{message:`Usage: rewind [list] | rewind inspect <checkpoint-id> | rewind restore <checkpoint-id> | rewind code <checkpoint-id> | rewind rollback <checkpoint-id>`,success:!1}}function Qs(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=120?t:`${t.slice(0,117)}...`}function $s(e){return{message:[`Edit checkpoints:`,...e.length>0?e.map(e=>`- ${e.id} files=${e.fileCount} ${e.createdAt} ${Qs(e.prompt)}`):[`(no edit checkpoints)`]].join(`
91
- `),success:!0,data:{count:e.length,checkpoints:[...e]}}}function ec(e){return e.length>0?e.join(`, `):`(none)`}function tc(e){let t=e.capturedFiles.length>0?e.capturedFiles.map(e=>{let t=e.snapshotSizeBytes===void 0?``:` size=${e.snapshotSizeBytes}B`;return`- ${e.relativePath} action=${e.restoreAction} snapshot=${String(e.snapshotAvailable)}${t}`}):[`(no files captured)`];return{message:[`Checkpoint ${e.target.id}`,`Prompt: ${Qs(e.target.prompt)}`,`Captured files:`,...t,`Restore later checkpoints: files=${e.restoreToCheckpoint.fileCount} checkpoints=${ec(e.restoreToCheckpoint.checkpointIds)}`,`Rollback through checkpoint: files=${e.rollbackThroughCheckpoint.fileCount} checkpoints=${ec(e.rollbackThroughCheckpoint.checkpointIds)}`].join(`
92
- `),success:!0,data:{inspection:e}}}function nc(e){return{message:[`Restored code to ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Rolled back checkpoints: ${e.restoredCheckpointCount}`].join(`
93
- `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function rc(e){return{message:[`Rolled back code through ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Removed checkpoints: ${e.removedCheckpointCount}`].join(`
94
- `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function G(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function ic(t,n){if(!n)return W();try{return tc((0,e.inspectCommandEditCheckpoint)(t,n))}catch(e){return G(e instanceof Error?e:String(e))}}async function ac(t,n){if(!n)return W();try{return nc(await(0,e.restoreCommandEditCheckpoint)(t,n))}catch(e){return G(e instanceof Error?e:String(e))}}async function oc(t,n){if(!n)return W();try{return rc(await(0,e.rollbackCommandEditCheckpoint)(t,n))}catch(e){return G(e instanceof Error?e:String(e))}}async function sc(t,n){if(!n)return W();try{let r=await(0,e.forkCommandEditCheckpoint)(t,n);return{message:[`Forked a new branch from ${r.target.id} (the previous future is preserved).`,`Restored files: ${r.restoredFileCount}`].join(`
95
- `),success:!0,data:{target:r.target,restoredFileCount:r.restoredFileCount}}}catch(e){return G(e instanceof Error?e:String(e))}}function cc(t,n){if(!n)return W();try{return(0,e.switchCommandEditCheckpointBranch)(t,n),{message:`Switched to checkpoint branch ${n}.`,success:!0}}catch(e){return G(e instanceof Error?e:String(e))}}function lc(t){try{let n=(0,e.listCommandEditCheckpointBranches)(t);return{message:n.length===0?`No checkpoint branches yet.`:`Branch tips:\n${n.map(e=>`- ${e}`).join(`
96
- `)}`,success:!0,data:{branches:n}}}catch(e){return G(e instanceof Error?e:String(e))}}async function uc(t,n){let r=n.trim().split(/\s+/).filter(Boolean),i=r[0]??`list`;return i===`list`?$s((0,e.listCommandEditCheckpoints)(t)):i===`inspect`?ic(t,r[1]):i===`restore`||i===`code`?ac(t,r[1]):i===`rollback`?oc(t,r[1]):i===`fork`?sc(t,r[1]):i===`switch`?cc(t,r[1]):i===`branches`?lc(t):W()}function dc(){return{name:`rewind`,displayName:`Rewind History`,description:e.REWIND_COMMAND_DESCRIPTION,source:`rewind`,argumentHint:e.REWIND_COMMAND_ARGUMENT_HINT,modelInvocable:!1,safety:`write`,subcommands:(0,e.buildRewindCommandSubcommands)()}}function fc(){let e=dc();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,argumentHint:e.argumentHint,userInvocable:!0,modelInvocable:!1,safety:`write`,subcommands:e.subcommands,execute:uc}}var pc=class{name=`rewind`;getCommands(){return[dc()]}};function mc(){return{name:`agent-command-rewind`,commandSources:[new pc],systemCommands:[fc()]}}function hc(e,t){let n=Math.floor(Math.min(1800,t.milliseconds/2e3)),r=(0,l.createHash)(`sha256`).update(e).digest().readUInt32BE(0)%(n+1);if(r===0)return{cronExpression:t.cronExpression,jitterSeconds:r};let i=/^(\d+)(s|m|h)$/.exec(t.description);if(!i)throw Error(`Unsupported fixed-loop cadence for jitter.`);let a=Number(i[1]),o=i[2],s=r%60,c=Math.floor(r/60);return o===`s`?{cronExpression:a===60?`${r} * * * * *`:`${r}-59/${a} * * * * *`,jitterSeconds:r}:o===`m`?{cronExpression:a===60?`${s} ${c} * * * *`:`${s} ${c}-59/${a} * * * *`,jitterSeconds:r}:{cronExpression:a===24?`${s} ${c} 0 * * *`:`${s} ${c} */${a} * * *`,jitterSeconds:r}}const gc=4096,K=new WeakMap,_c=new Set([`second`,`seconds`,`minute`,`minutes`,`hour`,`hours`,`day`,`days`,`s`,`m`,`h`,`d`]),vc=`Usage: /loop [<prompt>] | /loop <N><s|m|h|d> [<prompt>] | /loop <prompt> every <N> <unit> | /loop list | /loop stop <id>. Bare and interval-only forms require a host maintenance prompt.`,q={s:1e3,m:6e4,h:36e5,d:864e5},yc=[...bc(60).map(e=>({cronExpression:e===60?`0 * * * * *`:`*/${e} * * * * *`,milliseconds:e*q.s,description:`${e}s`})),...bc(60).filter(e=>e>1).map(e=>({cronExpression:e===60?`0 0 * * * *`:`0 */${e} * * * *`,milliseconds:e*q.m,description:`${e}m`})),...bc(24).filter(e=>e>1).map(e=>({cronExpression:e===24?`0 0 0 * * *`:`0 0 */${e} * * *`,milliseconds:e*q.h,description:`${e}h`}))];function bc(e){return Array.from({length:e},(e,t)=>t+1).filter(t=>e%t===0)}function xc(e,t){let n=Number(e),r=q[t];if(!Number.isSafeInteger(n)||n<=0||r===void 0)return;let i=n*r;return Number.isSafeInteger(i)&&i<=q.d?i:void 0}function Sc(e){let t=e.length;for(;t>0&&/[a-z]/i.test(e[t-1]);)--t;let n=e.slice(t).toLowerCase();if(!_c.has(n))return;for(;t>0&&/\s/u.test(e[t-1]);)--t;let r=t;for(;t>0&&e.charCodeAt(t-1)>=48&&e.charCodeAt(t-1)<=57;)--t;if(t===r)return;let i=e.slice(t,r),a=t;for(;t>0&&/\s/u.test(e[t-1]);)--t;if(t===a||e.slice(t-5,t).toLowerCase()!==`every`)return;t-=5;let o=t;for(;t>0&&/\s/u.test(e[t-1]);)--t;if(t===o)return;let s=e.slice(0,t).trim();return s?{instruction:s,amount:i,unit:n}:void 0}function Cc(e,t){let n=t&&t.length<=gc?t.trim():void 0;if(e===``)return;let r=/^(\d+)(s|m|h|d)$/i.exec(e);if(r&&n){let e=xc(r[1],r[2].toLowerCase());return e===void 0?void 0:{instruction:n,requestedMs:e}}let i=/^(\d+)(s|m|h|d)\s+([\s\S]+)$/i.exec(e);if(i){let e=i[3].trim(),t=xc(i[1],i[2].toLowerCase());return e&&t!==void 0&&!Sc(e)?{instruction:e,requestedMs:t}:void 0}let a=Sc(e);if(!a)return;let o=xc(a.amount,a.unit[0]);return o===void 0?void 0:{instruction:a.instruction,requestedMs:o}}function wc(e){return yc.find(t=>t.milliseconds>=e)}function J(e){return e.listSchedules().filter(e=>e.metadata?.sessionLoop===!0&&e.metadata?.sessionLoopSelfPaced!==!0&&e.status!==`cancelled`&&e.status!==`completed`&&e.status!==`failed`)}function Y(e){return(e.listSelfPacedLoops?.()??[]).filter(e=>e.phase!==`stopped`&&e.phase!==`expired`)}function X(e){let t=e.metadata?.sessionLoopId;return typeof t==`string`&&t.length>0?t:e.id}async function Tc(e,t,n,r={}){let i=n.trim();return i===`list`?Ec(e,r):/^stop(?:\s|$)/.test(i)?Dc(e,t,i):r.disabled?{success:!1,message:`Session loops are disabled by the host.`}:Oc(e,i,r)}function Ec(e,t){let n=J(e),r=Y(e);return{success:!0,message:(t.disabled?`Session loops are disabled by the host.
90
+ `),await e(` Press Enter when LM Studio server is running: `),{path:`local`,preselectedType:`gemma`}):{path:`has-key`}}async function Fs(t,n,r,i,a){let o=await Ps(r,i),s=Ls(n),c=Object.keys((0,e.readMergedProviderSettings)(s.sources).providers??{}),l=Rs(s.stores,n.settingsScope),u;u=o.preselectedType===void 0?Po(await r(No(a)),a):o.preselectedType,(0,e.applyProviderConfiguration)(l,await Io(u,r,a,{existingProfileNames:c}),{providerDefinitions:a});let d=await r(` Response language (ko/en/ja/zh, default: en): `);if(d){let e=l.read();e.language=d,l.write(e)}i.writeLine(`\n Config saved to ${l.displayName}\n`)}async function Is(t,n,r,i,a,o){let s=Ls(n),c=(0,e.readMergedProviderSettings)(s.sources);if((0,e.checkSettingsDocument)(n.provider===void 0?c:{...c,currentProvider:n.provider},a)===`valid`||n.provider===void 0&&(0,e.resolveEnvDefaultProvider)(a,o.env)!==void 0)return;if(!(o.isInteractive??(()=>!1))())throw new e.ProviderConfigError(o.formatError(a));await Fs(t,zs(n,s.stores),r,i,a);let l=(0,e.readMergedProviderSettings)(s.sources);if((0,e.checkSettingsDocument)(n.provider===void 0?l:{...l,currentProvider:n.provider},a)!==`valid`)throw new e.ProviderConfigError(o.formatError(a))}function Ls(e){if(e.settingsSources===void 0||e.settingsStores===void 0)throw Error(`Provider startup requires host settings sources and stores.`);return{sources:e.settingsSources,stores:e.settingsStores}}function Rs(t,n){if(n===void 0)return(0,e.resolveProviderSettingsWriteTarget)(t);let r=n===`user`?`user`:`project-local`,i=t.findLast(e=>e.scope===r);if(i!==void 0)return i;throw new e.WorkspaceAuthorityRequiredError(`No authorized ${r} settings store is available.`)}function zs(e,t){return e.settingsScope!==void 0||e.provider!==void 0?e:Bs(t)?.kind===`project`?{...e,settingsScope:`project-local`}:e}function Bs(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&typeof n.read().currentProvider==`string`)return n}}const Vs="only the operator at this terminal can do this; a connected surface cannot pair, enroll or revoke devices. Run `/remote-control` on the host terminal.";function Hs(e,t){if(!e)return{message:`Remote control is not available in this environment.`,success:!0};switch(e.state){case`off`:return{message:"Remote control is off. Use `/remote-control` to enable it.",success:!0};case`no-relay`:return{message:"Remote control is unavailable: no signaling relay is configured (set `transports.webrtc.options.relayUrl`).",success:!0};case`awaiting-pairing`:return{message:t?`Remote control is waiting for a device to pair.\nOpen: ${e.pairingUrl}`:`Remote control is waiting for a device to pair. The pairing link is shown only on the host terminal.`,success:!0};case`paired`:return{message:`Remote control is active — a device is paired.`,success:!0};default:return{message:`Remote control status is unknown.`,success:!0}}}function Us(e,t){let n=e.getCommandInvocationSource()===`user`,r=t.trim(),i=r.indexOf(` `),a=(i===-1?r:r.slice(0,i)).toLowerCase(),o=i===-1?``:r.slice(i+1).trim();if(a===`status`){let t=e.getCommandHostAdapters?.().remoteControl,r=Hs(t?.getStatus(),n);if(!t?.describeKeyStorage)return r;let i=t.describeKeyStorage()??`chosen when remote control is first enabled`;return{...r,message:`${r.message}\nHost key storage: ${i}`}}if(a===`devices`){let t=(e.getCommandHostAdapters?.().remoteControl)?.listDevices?.();return t?t.length===0?{message:`No trusted devices are enrolled yet.`,success:!0}:{message:`Trusted devices:\n${t.map(e=>` ${e.deviceId} ${e.label} (last seen ${e.lastSeenAt})`).join(`
91
+ `)}`,success:!0}:{message:`Trusted-device reconnect is not available in this environment.`,success:!0}}if(a===`revoke`){if(!n)return{message:`\`/remote-control revoke\`: ${Vs}`,success:!1};if(!o)return{message:`Usage: /remote-control revoke <deviceId>`,success:!1};let t=e.getCommandHostAdapters?.().remoteControl;return t?.revokeDevice?t.revokeDevice(o)?{message:`Revoked trusted device ${o}. It must re-pair to reconnect.`,success:!0}:{message:`No trusted device with id ${o}.`,success:!1}:{message:`Trusted-device reconnect is not available in this environment.`,success:!0}}return a===`stop`||a===`off`?{message:`Stopping remote control...`,success:!0,hostActions:[{type:`remote-control-stop`}]}:a===``||a===`enable`||a===`on`?n?{message:`Enabling remote control...`,success:!0,hostActions:[{type:`remote-control-enable`}]}:{message:`\`/remote-control enable\`: ${Vs}`,success:!1}:{message:`Unknown argument "${a}". Usage: /remote-control [enable|stop|status|devices|revoke <id>]`,success:!1}}function Ws(){return{name:`remote-control`,displayName:`Remote control`,description:`Enable P2P remote control (pair a device to co-drive this session), or check status. Pairing and revoking run only for the operator at the host terminal; a connected surface can stop remote control and read its status, without the pairing link.`,source:`remote-control`,modelInvocable:!1,userInvocable:!0,argumentHint:`[enable|stop|status|devices|revoke <device-id>]`,subcommands:[{name:`status`,description:`Show remote-control status`,source:`remote-control`},{name:`devices`,description:`List trusted devices`,source:`remote-control`},{name:`enable`,description:`Enable remote control and pair a device`,source:`remote-control`},{name:`stop`,description:`Stop remote control`,source:`remote-control`},{name:`revoke`,description:`Revoke a trusted device`,source:`remote-control`,argumentHint:`<device-id>`}]}}function Gs(){return E(Ws(),{requiresPermission:!1,lifecycle:`inline`,execute:(e,t)=>Us(e,t)})}var Ks=class{name=`remote-control`;getCommands(){return[Ws()]}};function qs(){return{name:`agent-command-remote-control`,commandSources:[new Ks],systemCommands:[Gs()]}}function Js(){return{success:!0,message:`Reset requested.`,data:{resetRequested:!0},hostActions:[{type:`settings-reset`}]}}function Ys(){return{name:`reset`,displayName:`Reset Settings`,description:`Delete settings`,source:`reset`,modelInvocable:!1}}function Xs(){let e=Ys();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Js}}var Zs=class{name=`reset`;getCommands(){return[Ys()]}};function Qs(){return{name:`agent-command-reset`,commandSources:[new Zs],systemCommands:[Xs()]}}function W(){return{message:`Usage: rewind [list] | rewind inspect <checkpoint-id> | rewind restore <checkpoint-id> | rewind code <checkpoint-id> | rewind rollback <checkpoint-id>`,success:!1}}function $s(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=120?t:`${t.slice(0,117)}...`}function ec(e){return{message:[`Edit checkpoints:`,...e.length>0?e.map(e=>`- ${e.id} files=${e.fileCount} ${e.createdAt} ${$s(e.prompt)}`):[`(no edit checkpoints)`]].join(`
92
+ `),success:!0,data:{count:e.length,checkpoints:[...e]}}}function tc(e){return e.length>0?e.join(`, `):`(none)`}function nc(e){let t=e.capturedFiles.length>0?e.capturedFiles.map(e=>{let t=e.snapshotSizeBytes===void 0?``:` size=${e.snapshotSizeBytes}B`;return`- ${e.relativePath} action=${e.restoreAction} snapshot=${String(e.snapshotAvailable)}${t}`}):[`(no files captured)`];return{message:[`Checkpoint ${e.target.id}`,`Prompt: ${$s(e.target.prompt)}`,`Captured files:`,...t,`Restore later checkpoints: files=${e.restoreToCheckpoint.fileCount} checkpoints=${tc(e.restoreToCheckpoint.checkpointIds)}`,`Rollback through checkpoint: files=${e.rollbackThroughCheckpoint.fileCount} checkpoints=${tc(e.rollbackThroughCheckpoint.checkpointIds)}`].join(`
93
+ `),success:!0,data:{inspection:e}}}function rc(e){return{message:[`Restored code to ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Rolled back checkpoints: ${e.restoredCheckpointCount}`].join(`
94
+ `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function ic(e){return{message:[`Rolled back code through ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Removed checkpoints: ${e.removedCheckpointCount}`].join(`
95
+ `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function G(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function ac(t,n){if(!n)return W();try{return nc((0,e.inspectCommandEditCheckpoint)(t,n))}catch(e){return G(e instanceof Error?e:String(e))}}async function oc(t,n){if(!n)return W();try{return rc(await(0,e.restoreCommandEditCheckpoint)(t,n))}catch(e){return G(e instanceof Error?e:String(e))}}async function sc(t,n){if(!n)return W();try{return ic(await(0,e.rollbackCommandEditCheckpoint)(t,n))}catch(e){return G(e instanceof Error?e:String(e))}}async function cc(t,n){if(!n)return W();try{let r=await(0,e.forkCommandEditCheckpoint)(t,n);return{message:[`Forked a new branch from ${r.target.id} (the previous future is preserved).`,`Restored files: ${r.restoredFileCount}`].join(`
96
+ `),success:!0,data:{target:r.target,restoredFileCount:r.restoredFileCount}}}catch(e){return G(e instanceof Error?e:String(e))}}function lc(t,n){if(!n)return W();try{return(0,e.switchCommandEditCheckpointBranch)(t,n),{message:`Switched to checkpoint branch ${n}.`,success:!0}}catch(e){return G(e instanceof Error?e:String(e))}}function uc(t){try{let n=(0,e.listCommandEditCheckpointBranches)(t);return{message:n.length===0?`No checkpoint branches yet.`:`Branch tips:\n${n.map(e=>`- ${e}`).join(`
97
+ `)}`,success:!0,data:{branches:n}}}catch(e){return G(e instanceof Error?e:String(e))}}async function dc(t,n){let r=n.trim().split(/\s+/).filter(Boolean),i=r[0]??`list`;return i===`list`?ec((0,e.listCommandEditCheckpoints)(t)):i===`inspect`?ac(t,r[1]):i===`restore`||i===`code`?oc(t,r[1]):i===`rollback`?sc(t,r[1]):i===`fork`?cc(t,r[1]):i===`switch`?lc(t,r[1]):i===`branches`?uc(t):W()}function fc(){return{name:`rewind`,displayName:`Rewind History`,description:e.REWIND_COMMAND_DESCRIPTION,source:`rewind`,argumentHint:e.REWIND_COMMAND_ARGUMENT_HINT,modelInvocable:!1,safety:`write`,subcommands:(0,e.buildRewindCommandSubcommands)()}}function pc(){let e=fc();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,argumentHint:e.argumentHint,userInvocable:!0,modelInvocable:!1,safety:`write`,subcommands:e.subcommands,execute:dc}}var mc=class{name=`rewind`;getCommands(){return[fc()]}};function hc(){return{name:`agent-command-rewind`,commandSources:[new mc],systemCommands:[pc()]}}function gc(e,t){let n=Math.floor(Math.min(1800,t.milliseconds/2e3)),r=(0,l.createHash)(`sha256`).update(e).digest().readUInt32BE(0)%(n+1);if(r===0)return{cronExpression:t.cronExpression,jitterSeconds:r};let i=/^(\d+)(s|m|h)$/.exec(t.description);if(!i)throw Error(`Unsupported fixed-loop cadence for jitter.`);let a=Number(i[1]),o=i[2],s=r%60,c=Math.floor(r/60);return o===`s`?{cronExpression:a===60?`${r} * * * * *`:`${r}-59/${a} * * * * *`,jitterSeconds:r}:o===`m`?{cronExpression:a===60?`${s} ${c} * * * *`:`${s} ${c}-59/${a} * * * *`,jitterSeconds:r}:{cronExpression:a===24?`${s} ${c} 0 * * *`:`${s} ${c} */${a} * * *`,jitterSeconds:r}}const _c=4096,K=new WeakMap,vc=new Set([`second`,`seconds`,`minute`,`minutes`,`hour`,`hours`,`day`,`days`,`s`,`m`,`h`,`d`]),yc=`Usage: /loop [<prompt>] | /loop <N><s|m|h|d> [<prompt>] | /loop <prompt> every <N> <unit> | /loop list | /loop stop <id>. Bare and interval-only forms require a host maintenance prompt.`,q={s:1e3,m:6e4,h:36e5,d:864e5},bc=[...xc(60).map(e=>({cronExpression:e===60?`0 * * * * *`:`*/${e} * * * * *`,milliseconds:e*q.s,description:`${e}s`})),...xc(60).filter(e=>e>1).map(e=>({cronExpression:e===60?`0 0 * * * *`:`0 */${e} * * * *`,milliseconds:e*q.m,description:`${e}m`})),...xc(24).filter(e=>e>1).map(e=>({cronExpression:e===24?`0 0 0 * * *`:`0 0 */${e} * * *`,milliseconds:e*q.h,description:`${e}h`}))];function xc(e){return Array.from({length:e},(e,t)=>t+1).filter(t=>e%t===0)}function Sc(e,t){let n=Number(e),r=q[t];if(!Number.isSafeInteger(n)||n<=0||r===void 0)return;let i=n*r;return Number.isSafeInteger(i)&&i<=q.d?i:void 0}function Cc(e){let t=e.length;for(;t>0&&/[a-z]/i.test(e[t-1]);)--t;let n=e.slice(t).toLowerCase();if(!vc.has(n))return;for(;t>0&&/\s/u.test(e[t-1]);)--t;let r=t;for(;t>0&&e.charCodeAt(t-1)>=48&&e.charCodeAt(t-1)<=57;)--t;if(t===r)return;let i=e.slice(t,r),a=t;for(;t>0&&/\s/u.test(e[t-1]);)--t;if(t===a||e.slice(t-5,t).toLowerCase()!==`every`)return;t-=5;let o=t;for(;t>0&&/\s/u.test(e[t-1]);)--t;if(t===o)return;let s=e.slice(0,t).trim();return s?{instruction:s,amount:i,unit:n}:void 0}function wc(e,t){let n=t&&t.length<=_c?t.trim():void 0;if(e===``)return;let r=/^(\d+)(s|m|h|d)$/i.exec(e);if(r&&n){let e=Sc(r[1],r[2].toLowerCase());return e===void 0?void 0:{instruction:n,requestedMs:e}}let i=/^(\d+)(s|m|h|d)\s+([\s\S]+)$/i.exec(e);if(i){let e=i[3].trim(),t=Sc(i[1],i[2].toLowerCase());return e&&t!==void 0&&!Cc(e)?{instruction:e,requestedMs:t}:void 0}let a=Cc(e);if(!a)return;let o=Sc(a.amount,a.unit[0]);return o===void 0?void 0:{instruction:a.instruction,requestedMs:o}}function Tc(e){return bc.find(t=>t.milliseconds>=e)}function J(e){return e.listSchedules().filter(e=>e.metadata?.sessionLoop===!0&&e.metadata?.sessionLoopSelfPaced!==!0&&e.status!==`cancelled`&&e.status!==`completed`&&e.status!==`failed`)}function Y(e){return(e.listSelfPacedLoops?.()??[]).filter(e=>e.phase!==`stopped`&&e.phase!==`expired`)}function X(e){let t=e.metadata?.sessionLoopId;return typeof t==`string`&&t.length>0?t:e.id}async function Ec(e,t,n,r={}){let i=n.trim();return i===`list`?Dc(e,r):/^stop(?:\s|$)/.test(i)?Oc(e,t,i):r.disabled?{success:!1,message:`Session loops are disabled by the host.`}:kc(e,i,r)}function Dc(e,t){let n=J(e),r=Y(e);return{success:!0,message:(t.disabled?`Session loops are disabled by the host.
97
98
  `:``)+(n.length+r.length===0?`No active loops.`:[...n.map(e=>`- ${X(e)} [${e.status}] ${e.label}`),...r.map(e=>`- ${e.loopId} [${e.phase}] Loop: ${e.instruction}`+(e.phase===`waiting`&&e.delaySeconds!==void 0&&e.reason?` — next ${e.delaySeconds}s: ${e.reason}`:``))].join(`
98
- `)),data:{count:n.length+r.length}}}async function Dc(e,t,n){let r=/^stop\s+(\S+)$/.exec(n);if(!r)return{success:!1,message:vc};let i=Y(e).find(e=>e.loopId===r[1]);if(i)return e.stopSelfPacedLoop?(await e.stopSelfPacedLoop(i.loopId,`Loop stopped by user`),{success:!0,message:`Loop stopped: ${i.loopId}. An already-running turn may finish.`,data:{loopId:i.loopId}}):{success:!1,message:`This host cannot stop self-paced loops.`};let a=J(e).find(e=>X(e)===r[1]);return a?(await t(a.id,`Loop stopped by user`),{success:!0,message:`Loop stopped: ${X(a)}. An already-running turn may finish.`,data:{loopId:X(a),taskId:a.id}}):{success:!1,message:`Active loop not found: ${r[1]}`}}async function Oc(e,t,n){let r=t===``||/^\d+(s|m|h|d)$/i.test(t),i=n.defaultPrompt;if(r&&n.resolveDefaultPrompt)try{i=n.resolveDefaultPrompt()}catch(e){return{success:!1,message:`Default loop prompt could not be loaded: ${e instanceof Error?e.message:String(e)}`}}let a=Cc(t,i);if(!a){if(/^\d+[a-z](?:\s|$)/i.test(t)||Sc(t))return{success:!1,message:vc};let n=(t||i||``).trim();if(!n||t===``&&n.length>gc)return{success:!1,message:vc};if(!e.createSelfPacedLoop)return{success:!1,message:`Self-paced loops require a persistent interactive session.`};let a=K.get(e)??0;if(J(e).length+Y(e).length+a>=3)return{success:!1,message:`At most 3 active loops are allowed. Stop one before creating another.`};K.set(e,a+1);try{let t=r?await e.createSelfPacedLoop(n,{useDefaultPrompt:!0}):await e.createSelfPacedLoop(n);return{success:!0,message:`Self-paced loop ${t.loopId} started. It will choose a 1–60 minute delay after each iteration and expires ${t.expiresAt}. Stop with /loop stop ${t.loopId}.`,data:{loopId:t.loopId,expiresAt:t.expiresAt}}}finally{let t=(K.get(e)??1)-1;t===0?K.delete(e):K.set(e,t)}}let o=K.get(e)??0;if(J(e).length+Y(e).length+o>=3)return{success:!1,message:`At most 3 active loops are allowed. Stop one before creating another.`};let s=wc(a.requestedMs),c=`Loop: ${a.instruction.slice(0,48)}`,u=`loop_${(0,l.randomUUID)()}`,d=hc(u,s),f=Date.now(),p=new Date(f+a.requestedMs).toISOString(),m=new Date(f+6048e5).toISOString();K.set(e,o+1);let h;try{h=await e.spawnScheduledWake({label:c,cronExpression:d.cronExpression,agentInstruction:a.instruction,sessionLoop:!0,sessionLoopId:u,...r?{sessionLoopDefaultPrompt:!0}:{},sessionLoopFirstAllowedAt:p,sessionLoopExpiresAt:m})}finally{let t=(K.get(e)??1)-1;t===0?K.delete(e):K.set(e,t)}let g=s.milliseconds===a.requestedMs?``:` (rounded up)`,_=h.kind===`scheduled`&&h.nextFireAt&&h.nextFireAt>=p?` Next fire: ${h.nextFireAt}.`:``;return{success:!0,message:`Loop ${u} uses a ${s.description}${g} local-clock step with stable offset +${d.jitterSeconds}s; elapsed gaps can change with daylight saving. First eligible at or after ${p}.${_} Expires: ${m}. Stop with /loop stop ${u}.`,data:{loopId:u,taskId:h.id,requestedMs:a.requestedMs,cadenceLabel:s.description,cronExpression:d.cronExpression,jitterSeconds:d.jitterSeconds,firstAllowedAt:p,expiresAt:m}}}const kc={s:1e3,m:6e4,h:36e5,d:864e5},Z=`Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron "<expr>" <instruction>`;function Ac(e,t){let n=e.trim();if(n.length===0)return{ok:!1,error:Z};if(n.startsWith(`in `)){let e=n.slice(3).trim(),r=e.indexOf(` `);if(r===-1)return{ok:!1,error:`Missing instruction. ${Z}`};let i=e.slice(0,r),a=e.slice(r+1).trim(),o=/^(\d+)(s|m|h|d)$/.exec(i);if(!o)return{ok:!1,error:`Invalid duration "${i}". ${Z}`};if(a.length===0)return{ok:!1,error:`Missing instruction. ${Z}`};let s=parseInt(o[1],10)*kc[o[2]];return{ok:!0,spec:{cronExpression:new Date(t+s).toISOString(),instruction:a,recurring:!1}}}if(n.startsWith(`cron `)){let e=n.slice(5).trim(),t=/^["']([^"']+)["']\s+(\S.*)$/.exec(e);if(!t)return{ok:!1,error:`cron form needs a quoted expression. ${Z}`};let r=t[2].trim();return r.length===0?{ok:!1,error:`Missing instruction. ${Z}`}:{ok:!0,spec:{cronExpression:t[1].trim(),instruction:r,recurring:!0}}}return{ok:!1,error:Z}}function jc(e,t){return`${e}: ${t.slice(0,48)}${t.length>48?`…`:``}`}const Mc=`Usage: /schedule list | pause <id> | resume <id> | edit <id> <spec> (or a create spec: in <N><s|m|h|d> … | cron "<expr>" …)`;function Nc(e){return e.length===0?`No schedules.`:e.map(e=>{let t=e.kind===`scheduled`?e.schedule?.cronExpression??`(unknown)`:`(unknown)`,n=e.kind===`scheduled`&&e.nextFireAt?`next ${e.nextFireAt}`:`—`;return`- ${e.id} [${e.status}] ${t} — ${e.label} (${n})`}).join(`
99
- `)}async function Pc(e,t,n,r){if(t===`list`){let t=e.listSchedules();return{message:Nc(t),success:!0,data:{count:t.length}}}if(t===`pause`||t===`resume`){let r=n.split(/\s+/)[0];return r?t===`pause`?(await e.pauseSchedule(r),{message:`Schedule paused: ${r}`,success:!0,data:{taskId:r}}):(await e.resumeSchedule(r),{message:`Schedule resumed: ${r}`,success:!0,data:{taskId:r}}):{message:Mc,success:!1}}if(t===`edit`){let t=n.indexOf(` `),i=t===-1?n:n.slice(0,t),a=t===-1?``:n.slice(t+1).trim();if(!i||!a)return{message:Mc,success:!1};let o=Ac(a,r);return o.ok?(await e.editSchedule(i,{cronExpression:o.spec.cronExpression,agentInstruction:o.spec.instruction,label:jc(`Scheduled`,o.spec.instruction)}),{message:`Schedule updated: ${i} (cron \`${o.spec.cronExpression}\`).`,success:!0,data:{taskId:i,cronExpression:o.spec.cronExpression}}):{message:o.error,success:!1}}}async function Fc(e,t,n=Date.now()){let r=t.trim(),i=r.indexOf(` `),a=await Pc(e,(i===-1?r:r.slice(0,i)).toLowerCase(),i===-1?``:r.slice(i+1).trim(),n);if(a)return a;let o=Ac(t,n);if(!o.ok)return{message:`${o.error}\n${Mc}`,success:!1};let{cronExpression:s,instruction:c,recurring:l}=o.spec,u=await e.spawnScheduledWake({label:jc(`Scheduled`,c),cronExpression:s,agentInstruction:c});return{message:`Scheduled wake (${l?`cron \`${s}\``:`once at ${s}`}): "${c}" — task ${u.id}.`,success:!0,data:{taskId:u.id,cronExpression:s,recurring:l}}}function Ic(e){let t=/^["']([^"']+)["']\s+["']([^"']+)["']\s+(\S.*)$/.exec(e.trim());if(!t)return null;let n=t[3].trim();return n.length===0?null:{command:t[1],matchPattern:t[2],instruction:n}}async function Lc(t,n){let r=Ic(n);if(!r)return{message:`Usage: /monitor "<command>" "<pattern>" <instruction>`,success:!1};let i;try{i=await t.spawnMonitorWake({label:jc(`Monitor`,r.instruction),command:r.command,matchPattern:r.matchPattern,agentInstruction:r.instruction})}catch(t){if(t instanceof e.MonitorCommandRefusedError)return{message:t.message,success:!1};throw t}return{message:`Monitoring \`${r.command}\` for /${r.matchPattern}/ — task ${i.id}.`,success:!0,data:{taskId:i.id,matchPattern:r.matchPattern}}}function Rc(e){let t=e.getAgentJobCapability();if(!t)throw Error(`Scheduling requires an active agent runtime.`);return t}function zc(){return{name:`schedule`,displayName:`Schedule Wake`,description:`Schedule the agent to wake on a timer, and manage schedules (list / pause / resume / edit).`,modelDescription:'Wake yourself later with an instruction. Use it when work must wait (a deploy, a long build, a reply) instead of polling: `in <N><s|m|h|d> <instruction>` or `cron "<expr>" <instruction>`; `list`, `pause`, `resume` and `edit` manage existing schedules. Returns the schedule id, or the schedule list.',source:`schedule`,argumentHint:`in <N><s|m|h|d> <instruction> | cron "<expr>" <instruction> | list | pause <id> | resume <id> | edit <id> <spec>`,modelInvocable:!0}}function Bc(){return{name:`monitor`,displayName:`Monitor Process`,description:`Watch a process’s output and wake the agent when a line matches a pattern.`,modelDescription:`Run a command in the background and wake yourself when a line of its output matches a pattern. Use it to wait for a server to start, a test to fail or a log line to appear instead of polling. The command is allowed, refused or asked about by the same permission rules as a shell tool call. Returns the monitor task id, or a refusal naming what the user must allow.`,source:`schedule`,argumentHint:`"<command>" "<pattern>" <instruction>`,modelInvocable:!0}}function Vc(){return{name:`loop`,displayName:`Repeat Prompt`,description:`Repeat a prompt on a fixed cadence or let each iteration choose its next delay; list or stop active loops.`,modelDescription:"Repeat a prompt on a fixed cadence (`<N><s|m|h|d> [prompt]`) or self-paced (bare or prompt only: each iteration chooses its next delay or stops). Use it when the user asks for recurring work in this session. `list` shows active loops; `stop <id>` ends one. Returns the loop id and its next fire time, or the loop list.",source:`schedule`,argumentHint:`[prompt] | <N><s|m|h|d> [prompt] | <prompt> every <N> <unit> | list | stop <id>`,modelInvocable:!0,subcommands:[{name:`list`,description:`List active loops`,source:`schedule`},{name:`stop`,description:`Stop an active loop`,source:`schedule`,argumentHint:`<id>`}]}}function Hc(){let e=zc();return{name:e.name,displayName:e.displayName,description:e.description,...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Fc(Rc(e),t)}}function Uc(){let e=Bc();return{name:e.name,displayName:e.displayName,description:e.description,...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},requiresPermission:!0,modelRequiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Lc(Rc(e),t)}}function Wc(e){let t=Vc();return{name:t.name,displayName:t.displayName,description:t.description,...t.modelDescription===void 0?{}:{modelDescription:t.modelDescription},requiresPermission:!0,userInvocable:!0,modelInvocable:!0,argumentHint:t.argumentHint,subcommands:t.subcommands,lifecycle:`inline`,execute:(t,n)=>Tc(Rc(t),(e,n)=>t.cancelBackgroundTask(e,n),n,e)}}var Gc=class{name=`schedule`;getCommands(){return[zc(),Bc(),Vc()]}};function Kc(e={}){return{name:`agent-command-schedule`,commandSources:[new Gc],systemCommands:[Hc(),Uc(),Wc(e)],sessionRequirements:[`agent-runtime`]}}function qc(e,n,r){return(0,t.calculateModelCost)(e,n,r)}function Q(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Jc(e){return e.toLocaleString(`en-US`)}const Yc=`Conversation cleared.`;function Xc(e,t){let n=t.trim();return n===``?{success:!1,message:`Usage: /cd <directory>`}:{success:!0,message:``,hostActions:[{type:`workspace-move`,path:n}]}}async function Zc(n,r){let i=n.getUserInteraction();return i&&!(0,t.isConfirmed)(await i.ask((0,t.confirmAction)(`clear`,`Clear conversation history?`)))?{success:!0,message:`Clear cancelled.`}:((0,e.clearConversationHistory)(n),{success:!0,message:Yc})}function Qc(t,n){let r=(0,e.parseSessionNameArgument)(n);return r===void 0?{success:!1,message:e.RENAME_COMMAND_USAGE}:{success:!0,message:`Session renamed to "${r}".`,data:{name:r},hostActions:[(0,e.createSessionRenameHostAction)(r)]}}function $c(){return{success:!0,message:`Opening session picker...`,data:{triggerResumePicker:!0},uiIntents:[(0,e.createShowSessionPickerIntent)()]}}function el(e){return e.getCommandHostAdapters?.().costBudget}const tl=`Budget persistence is not available on this host (no cost-budget adapter was composed).`;function nl(e){return`Could not write the budget: ${e instanceof Error?e.message:String(e)}`}function rl(e,t){if(e.length===0)return;let n={inputTokens:0,outputTokens:0,partial:!1,models:[]},r=new Set,i=0,a=!1;for(let o of e){n.inputTokens+=o.promptTokens,n.outputTokens+=o.completionTokens;let e=o.source?.scope===`tool`,s=o.costUsd??(!e&&t?qc(t,o.promptTokens,o.completionTokens):void 0);if(s===void 0){n.partial=!0;continue}i+=s,a=!0,r.add(e?o.source?.label??`another model`:t??`main model`)}return a&&(n.costUsd=i),n.models=[...r],n}function il(t){let n=t.getSession(),r=(0,e.readCommandSessionInfo)(t),i=n.getModelId(),a=rl(t.getSessionUsage(),i),o=[`Session: ${r.sessionId}`,`Messages: ${r.messageCount}`],s={sessionId:r.sessionId,messageCount:r.messageCount};if(a){o.push(`Tokens: ${Jc(a.inputTokens)} input / ${Jc(a.outputTokens)} output`),s.inputTokens=a.inputTokens,s.outputTokens=a.outputTokens;let e=a.costUsd;if(e!==void 0){let n=a.models.length>1?`mixed: ${a.models.join(`, `)}`:a.models[0]??``,r=a.partial?`; some usage could not be priced`:``;o.push(`Cost: ${Q(e)} (${n}${r})`),s.estimatedCostUsd=e,s.costModels=a.models,a.partial&&(s.costPartial=!0);let i=el(t)?.read();if(i?.monthly){let t=i.monthly-e,n=Math.min(100,Math.round(e/i.monthly*100));o.push(`Budget: ${Q(t)} remaining of ${Q(i.monthly)}/mo (${n}% used)`),s.budgetMonthly=i.monthly,s.budgetRemainingUsd=t}}}else o.push(`Tokens: not yet available (no turns completed)`);return{lines:o,data:s}}function al(e,t){let n=t.trim();if(n.startsWith(`budget`)){let t=n.slice(6).trim(),r=t===`clear`||t===``?void 0:parseFloat(t);if(r!==void 0&&(!Number.isFinite(r)||r<=0))return{success:!1,message:`Usage: /cost budget <amount> (e.g. /cost budget 5.00)`};let i=el(e);if(i===void 0)return{success:!1,message:tl};if(t===`clear`){try{i.clear()}catch(e){return{success:!1,message:nl(e)}}return{success:!0,message:`Monthly budget cleared.`}}if(t===``){let e=i.read();return e?.monthly?{success:!0,message:`Monthly budget: ${Q(e.monthly)}`}:{success:!0,message:`No budget set. Use: /cost budget <amount>`}}if(r===void 0)return{success:!1,message:tl};try{i.write({monthly:r})}catch(e){return{success:!1,message:nl(e)}}return{success:!0,message:`Monthly budget set to ${Q(r)}.`}}let{lines:r,data:i}=il(e);return{success:!0,message:r.join(`
100
- `),data:i}}function ol(t,n){let r=(0,e.validateCommandSessionReplayLog)(t);return{success:r.validation.ok,message:(0,e.formatCommandSessionReplayValidationReport)(r),data:{logFile:r.logFile,entryCount:r.entryCount,issueCount:r.validation.issues.length,ok:r.validation.ok}}}function sl(){return{name:`clear`,displayName:`Clear History`,description:e.CLEAR_COMMAND_DESCRIPTION,source:`session`,modelInvocable:!1,userInvocable:!0}}function cl(){return{name:`rename`,displayName:`Rename Session`,description:e.RENAME_COMMAND_DESCRIPTION,argumentHint:`<name>`,source:`session`,modelInvocable:!1,userInvocable:!0}}function ll(){return{name:`cd`,displayName:`Change Directory`,description:`Move this session to another working directory`,argumentHint:`<directory>`,source:`session`,modelInvocable:!1,userInvocable:!0}}function ul(){return{name:`resume`,displayName:`Resume Session`,description:e.RESUME_COMMAND_DESCRIPTION,source:`session`,modelInvocable:!1,userInvocable:!0}}function dl(){return{name:`cost`,displayName:`Session Cost`,description:e.COST_COMMAND_DESCRIPTION,modelDescription:"Report this session’s token usage and estimated cost. Use it before an expensive step (a large refactor, many subagents) or when the user asks what the session has cost. Returns the message count, input/output token totals and the estimated USD cost, with the remaining monthly budget when one is set. Setting or clearing the budget is the user’s decision: suggest `/cost budget <amount>`.",argumentHint:`[budget [<amount>|clear]]`,runsBare:!0,source:`session`,modelInvocable:!0,userInvocable:!0,subcommands:[{name:`budget`,description:`Show, set, or clear the monthly budget`,argumentHint:`[<amount>|clear]`,source:`session`,modelInvocable:!1}]}}function fl(){return{name:`validate-session`,displayName:`Validate Session`,description:e.VALIDATE_SESSION_COMMAND_DESCRIPTION,source:`session`,modelInvocable:!1,userInvocable:!0}}function pl(){return E(sl(),{requiresPermission:!1,lifecycle:`inline`,execute:Zc})}function ml(){return E(cl(),{requiresPermission:!1,lifecycle:`inline`,execute:Qc})}function hl(){return E(ll(),{requiresPermission:!1,lifecycle:`inline`,execute:Xc})}function gl(){return E(ul(),{requiresPermission:!1,lifecycle:`inline`,execute:$c})}function _l(){return E(dl(),{requiresPermission:!1,lifecycle:`inline`,execute:al})}function vl(){return E(fl(),{requiresPermission:!1,lifecycle:`inline`,execute:ol})}var yl=class{name=`session`;getCommands(){return[sl(),cl(),ll(),ul(),dl(),fl()]}};function bl(){return{name:`agent-command-session`,commandSources:[new yl],systemCommands:[pl(),ml(),hl(),gl(),_l(),vl()]}}function xl(){return{name:`settings`,displayName:`Settings`,description:`Open transport settings — enable/disable transports and configure options`,source:`settings`,modelInvocable:!1}}function Sl(){let e=xl();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:async()=>({success:!0,message:`Opening settings...`,uiIntents:[{type:`show-settings`}]})}}var Cl=class{name=`settings`;getCommands(){return[xl()]}};function wl(){return{name:`agent-command-settings`,commandSources:[new Cl],systemCommands:[Sl()]}}function Tl(e){let n=(0,t.resolvePlatformShell)({executable:e});return{command:n.command,interactiveArgs:n.interactiveArgs,commandArgs:e=>n.commandArgs(e)}}const El="Drop to an interactive shell (or run `/shell <command>` interactively), then return to the agent.";async function Dl(e,t,n){if(!e.canHandoffTerminal())return{message:`An interactive shell is unavailable here (no interactive terminal).`,success:!1};let r=Tl(n),i=e.getCwd(),a=t.trim(),o=await e.runWithTerminal(async()=>a.length>0?k(r.command,r.commandArgs(a),i):k(r.command,r.interactiveArgs,i));return{message:a.length>0?`Command exited (code ${o}).`:`Shell session ended (code ${o}).`,success:o===0,data:{exitCode:o}}}function Ol(){return{name:`shell`,displayName:`Shell`,description:El,source:`shell`,modelInvocable:!1}}function kl(e){let t=Ol();return{name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(t,n)=>Dl(t,n,e)}}var Al=class{name=`shell`;getCommands(){return[Ol()]}};function jl(e){return{name:`agent-command-shell`,commandSources:[new Al],systemCommands:[kl(e)]}}const Ml=`List registered skills, or activate one by name`;function Nl(e){let t=[];return e.modelInvocable||t.push(`model-disabled`),e.userInvocable||t.push(`model-only`),e.context&&t.push(`context:${e.context}`),e.agent&&t.push(`agent:${e.agent}`),t.length>0?` [${t.join(`, `)}]`:``}function Pl(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}${Nl(e)}`}function Fl(e){return e.length===0?[`No skills are registered for this session.`,``,`Skills are metadata until activated. Do not invent or imitate a skill workflow when no matching registered skill exists.`].join(`
101
- `):[`Registered skills:`,...e.map(Pl),``,`Activation contract:`,`- Use /skills <skill-name> [args] to activate a matching skill.`,`- Treat /<skill-name> as a virtual alias for /skills <skill-name>.`,`- The system prompt Skills section is skill selection metadata.`,`- Treat descriptions as selection metadata only, not as loaded SKILL.md content.`,`- Do not answer by merely naming, recommending, or imitating a matching skill.`,`- If no listed skill matches the task, continue without claiming a skill was activated.`].join(`
102
- `)}function Il(e){let t=e.trim();if(t.length===0||t===`list`)return{action:`list`,skillArgs:``};let[n=``,...r]=t.split(/\s+/);return n.length===0?{action:`list`,skillArgs:``}:{action:`activate`,skillName:n,skillArgs:r.join(` `)}}async function Ll(e,t=``){let n=Il(t);if(n.action===`activate`&&n.skillName!==void 0){let t=`/${n.skillName}${n.skillArgs?` ${n.skillArgs}`:``}`;return await e.executeSkillCommandByName(n.skillName,n.skillArgs,{invocationSource:e.getCommandInvocationSource(),displayInput:t,rawInput:t})??{success:!1,message:`Unknown skill: ${n.skillName}`}}let r=e.listSkills();return{success:!0,message:Fl(r),data:{skills:r,activationContract:{activateWith:`/skills <skill-name> [args]`,activationRequiredBeforeWorkflow:!0,metadataIsNotSkillContent:!0}}}}function Rl(){return{name:`skills`,displayName:`Skills`,description:Ml,modelDescription:`Skill command. Before following a matching registered skill from the system prompt Skills section, invoke the projected skills command tool with args "<skill-name> [args]". Without arguments, list registered skills. With a skill name, activate that skill; a skill that declares it is not model-invocable is refused. Returns the skill list with each skill's description, or the activated skill's instructions to follow. Slash syntax is a UI input/display concern; the SDK command identity is "skills".`,source:`skills`,modelInvocable:!0,userInvocable:!0,argumentHint:`[list | <skill-name> [args]]`,safety:`read-only`}}function zl(){let e=Rl();return{name:e.name,semanticRole:`skillActivation`,...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,lifecycle:`inline`,execute:Ll}}var Bl=class{name=`skills`;getCommands(){return[Rl()]}};function Vl(t){let n=[new Bl];return n.push(new e.SkillCommandSource(t.contributionSources,t.skillRoots??[])),{name:`agent-command-skills`,commandSources:n,systemCommands:[zl()]}}const Hl=[`Usage: /statusline on | off | reset | git on | git off`,`Fields: model, context, permission mode, message count, session name, thinking state, git branch.`].join(`
103
- `);function Ul(t){let n=t.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0),[r,i]=n;return r===`on`&&i===void 0?{success:!0,message:`Status line enabled.`,patch:{enabled:!0}}:r===`off`&&i===void 0?{success:!0,message:`Status line disabled.`,patch:{enabled:!1}}:r===`reset`&&i===void 0?{success:!0,message:`Status line settings reset.`,patch:{...e.DEFAULT_STATUS_LINE_COMMAND_SETTINGS}}:r===`git`&&i===`on`&&n.length===2?{success:!0,message:`Status line git branch shown.`,patch:{gitBranch:!0}}:r===`git`&&i===`off`&&n.length===2?{success:!0,message:`Status line git branch hidden.`,patch:{gitBranch:!1}}:{success:!1,message:Hl}}function Wl(e,t){let n=Ul(t);return n.success?{success:!0,message:n.message,hostActions:[{type:`statusline-settings-patch`,patch:n.patch}]}:{success:!1,message:n.message}}function Gl(){return{name:`statusline`,displayName:`Status Line`,description:e.STATUSLINE_COMMAND_DESCRIPTION,source:`statusline`,argumentHint:e.STATUSLINE_COMMAND_ARGUMENT_HINT,subcommands:(0,e.buildStatusLineCommandSubcommands)(`statusline`),modelInvocable:!1}}function Kl(){let e=Gl();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:Wl}}var ql=class{name=`statusline`;getCommands(){return[Gl()]}};function Jl(){return{name:`agent-command-statusline`,commandSources:[new ql],systemCommands:[Kl()]}}const Yl=`list | <theme-id> | syntax on|off | motion on|off`;function $(e){return e?`on`:`off`}function Xl(e){let{settings:t,reducedMotionPin:n}=e.getAppearance(),r=e.listThemes().map(e=>`${e.id===t.theme?`* `:` `}${e.id} — ${e.name} (${e.appearance}, ${e.source})`),i=n?`${$(n.reducedMotion)} for this run (pinned by ${n.tier}; saved ${$(t.reducedMotion)})`:$(t.reducedMotion);return[`Available themes:`,...r,``,`syntax highlighting: ${$(t.syntaxHighlighting)}`,`reduced motion: ${i}`].join(`
104
- `)}function Zl(e){return{success:!0,message:Xl(e),data:{themes:e.listThemes().map(e=>({...e})),appearance:{...e.getAppearance().settings}}}}function Ql(e,t){return{success:!1,message:`Unknown theme "${e}". Available: ${t.listThemes().map(e=>e.id).join(`, `)||`(none)`}`}}function $l(e){if(e===`on`)return!0;if(e===`off`)return!1}function eu(e){let t={},n=0,r;for(e[0]!==`syntax`&&e[0]!==`motion`&&(r=e[0],n=1);n<e.length;){let r=e[n],i=$l(e[n+1]);if(r!==`syntax`&&r!==`motion`||i===void 0)return{error:`Usage: /theme ${Yl}`};r===`syntax`?t.syntaxHighlighting=i:t.reducedMotion=!i,n+=2}return{patch:t,...r===void 0?{}:{themeId:r}}}function tu(e,t,n){let r=[];t&&r.push(`theme ${t.name}`),e.syntaxHighlighting!==void 0&&r.push(`syntax highlighting ${$(e.syntaxHighlighting)}`),e.reducedMotion!==void 0&&r.push(`motion ${$(!e.reducedMotion)}`);let i=r.length>0?`Applied: ${r.join(`, `)}.`:`Nothing to change.`;return e.reducedMotion!==void 0&&n.reducedMotionPin?`${i} Saved, but this run keeps reduced motion pinned by ${n.reducedMotionPin.tier}.`:i}function nu(e,t){if(!e)return{success:!1,message:`Themes are not available in this environment.`};let n=t.trim().split(/\s+/u).filter(Boolean);if(n.length===0)return{success:!0,message:`Opening the theme picker...`,uiIntents:[{type:`show-theme-picker`}]};if(n.length===1&&n[0]===`list`)return Zl(e);let r=eu(n);if(r.error!==void 0||!r.patch)return{success:!1,message:r.error??`Usage: /theme ${Yl}`};let i={...r.patch},a;if(r.themeId!==void 0){if(a=e.getTheme(r.themeId),!a)return Ql(r.themeId,e);i.theme=a.id}return{success:!0,message:tu(i,a,e.getAppearance()),data:{appearance:{...i}},hostActions:[{type:`appearance-settings-patch`,patch:i}]}}function ru(){return{name:`theme`,displayName:`Theme`,description:`List, preview or switch the terminal colour theme, and toggle syntax highlighting and motion`,argumentHint:Yl,source:`theme`,userInvocable:!0,modelInvocable:!1}}var iu=class{name=`theme`;getCommands(){return[ru()]}};function au(e){let t=ru(),n={name:t.name,displayName:t.displayName,description:t.description,argumentHint:t.argumentHint,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(t,n)=>nu(e,n)};return{name:`agent-command-theme`,commandSources:[new iu],systemCommands:[n]}}const ou=`Inspect user-local storage and memory state.`,su=`storage list [--format json] | memory set/list/inspect/disable/delete`,cu=`Usage: user-local storage list [--format json] | user-local memory set <category> <key> <value> --summary <summary> --source <source> | user-local memory list [--format json] | user-local memory inspect <category> <key> [--format json] | user-local memory disable <category> <key> | user-local memory delete <category> <key>`;function lu(e){return e.length===0?`No user-local memory items.`:e.map(e=>`- ${e.category}/${e.key} (${e.enabled?`enabled`:`disabled`})`).join(`
105
- `)}function uu(e){if(e===void 0)throw Error(`User-local memory category is required.`);return e}async function du(t,n,r){let i=await(0,e.listUserLocalMemoryItems)({activeRepositoryRoot:t,storageRoot:n});return{message:r.format===`json`?JSON.stringify(i,null,2):lu(i.items),success:!0,data:{list:i}}}async function fu(t,n,r){let[i,a,o]=r.positional,s=await(0,e.setUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:uu(i),key:a??``,value:o??``,summary:r.summary??``,source:r.source??``});return{message:`Stored user-local memory item ${s.category}/${s.key} at ${s.storageLocation}`,success:!0,data:{item:s}}}async function pu(t,n,r){let[i,a]=r.positional,o=await(0,e.inspectUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:uu(i),key:a??``});return{message:r.format===`json`?JSON.stringify(o,null,2):`${o.category}/${o.key}: ${o.summary}`,success:!0,data:{item:o}}}async function mu(t,n,r){let[i,a]=r.positional,o=await(0,e.disableUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:uu(i),key:a??``});return{message:`Disabled user-local memory item ${o.category}/${o.key}`,success:!0,data:{item:o}}}async function hu(t,n,r){let[i,a]=r.positional,o=await(0,e.deleteUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:uu(i),key:a??``});return{message:`Deleted user-local memory item ${o.category}/${o.key}`,success:!0,data:{result:o}}}async function gu(e,t,n){return(n.action??`list`)===`list`?du(e,t,n):n.action===`set`?fu(e,t,n):n.action===`inspect`?pu(e,t,n):n.action===`disable`?mu(e,t,n):n.action===`delete`?hu(e,t,n):{message:cu,success:!1}}function _u(e){if(e===void 0||e===`text`)return`text`;if(e===`json`)return`json`;throw Error(`Unsupported user-local output format: ${e}`)}function vu(e,t,n){return e===`--format`?{format:t[n+1],nextIndex:n+1}:e.startsWith(`--format=`)?{format:e.slice(9),nextIndex:n}:e===`--summary`?{summary:t[n+1],nextIndex:n+1}:e.startsWith(`--summary=`)?{summary:e.slice(10),nextIndex:n}:e===`--source`?{source:t[n+1],nextIndex:n+1}:e.startsWith(`--source=`)?{source:e.slice(9),nextIndex:n}:null}function yu(e,t={}){let n=t.format,r=t.summary,i=t.source,a=[];for(let t=0;t<e.length;t+=1){let o=e[t],s=vu(o,e,t);if(s!==null){n=s.format??n,r=s.summary??r,i=s.source??i,t=s.nextIndex;continue}a.push(o)}return{target:a[0],action:a[1],positional:a.slice(2),format:_u(n),summary:r,source:i}}function bu(e){return e.trim().split(/\s+/).filter(Boolean)}function xu(e,t){let n=t.map(e=>`- ${e.category}`);return[`User-local storage root: ${e}`,`Categories:`,...n].join(`
106
- `)}async function Su(t,n,r){if((r.action??`list`)!==`list`)return{message:cu,success:!1};let i=await(0,e.inspectUserLocalStorage)({activeRepositoryRoot:t,storageRoot:n});return{message:r.format===`json`?JSON.stringify(i,null,2):xu(i.root,i.categories),success:!0,data:{root:i.root,categories:i.categories,inspection:i}}}async function Cu(e,t,n){return n.target===`storage`?Su(e,t,n):n.target===`memory`?gu(e,t,n):{message:cu,success:!1}}function wu(e){return e.includes(`ENOENT`)?`User-local memory item not found.`:e}async function Tu(e){try{return await Cu(e.cwd,e.storageRoot,yu(e.argv,{format:e.format,summary:e.summary,source:e.source}))}catch(e){return{message:wu(e instanceof Error?e.message:String(e)),success:!1}}}async function Eu(e,t,n){try{return await Cu(e.getCwd(),n,yu(bu(t)))}catch(e){return{message:wu(e instanceof Error?e.message:String(e)),success:!1}}}function Du(){return{name:`user-local`,displayName:`User Config`,description:ou,source:`user-local`,argumentHint:su,modelInvocable:!1,safety:`read-only`,subcommands:[{name:`storage`,description:`Inspect user-local storage categories`,source:`user-local`},{name:`memory`,description:`Inspect and manage user-local memory items`,source:`user-local`}]}}function Ou(e){let t=Du();return{name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:t.argumentHint,safety:t.safety,subcommands:t.subcommands,execute:(t,n)=>Eu(t,n,e)}}var ku=class{name=`user-local`;getCommands(){return[Du()]}};function Au(e){return{name:`agent-command-user-local`,commandSources:[new ku],systemCommands:[Ou(e)]}}function ju(t,n,r){return(0,e.selectCommandModules)(t,n,r)}function Mu({cwd:t,userLocalStorageRoot:n,editorTemporaryDirectoryPrefix:r,contributionSources:i,skillRoots:a,providerDefinitions:o,providerSettingsAdapter:s,orgPolicy:c,keybindingsFilePort:l,themeCataloguePort:u,devicesPort:d,doctorInputs:f,doctorDisplay:p,formatForkResumeCommand:m,loopOptions:h,enabledCommandModules:g,disabledCommandModules:_}){let v=[Vl({contributionSources:i??[],skillRoots:a}),oi(),_e(),Hn(),An(),Ya(),ga(),Ta(),jo(),Pa(),gi(),Ce(),rr(m),qr(),to(),jl(),Cn(r),Br(),...l===void 0?[]:[ui(l)],...u===void 0?[]:[au(u)],...f===void 0?[]:[gn(f,void 0,p)],sa(),Ki(),Au(n),ke(),Qe(),qn(),bl(),Zs(),mc(),Kc(h),Jl(),yo(),wl(),Ga(),ti(),Ks(),...d===void 0?[]:[ct(d)],Ms({providerDefinitions:o,settings:s,...c===void 0?{}:{orgPolicy:c}})],y=v.map(e=>e.name);return{modules:ju(v,g,_),unknownModuleNames:(0,e.findUnknownModuleNames)(y,g,_)}}exports.ADVISOR_SETTING_KEY=wn,exports.AdvisorCommandSource=kn,exports.AgentCommandSource=ge,exports.BackgroundCommandSource=Se,exports.CLEAR_COMMAND_MESSAGE=Yc,exports.CompactCommandSource=Oe,exports.ContextCommandSource=Ze,exports.DoctorCommandSource=fn,exports.EDITOR_COMMAND_DESCRIPTION=vn,exports.EditorCommandSource=Sn,exports.EffortCommandSource=Vn,exports.ExitCommandSource=Kn,exports.GOAL_COMMAND_DESCRIPTION=Vr,exports.GitCommandSource=zr,exports.GoalCommandSource=Kr,exports.HandoffCommandSource=ei,exports.HelpCommandSource=ai,exports.KeybindingsCommandSource=li,exports.LanguageCommandSource=hi,exports.MCPActivationCommandSource=Gi,exports.MemoryCommandSource=oa,exports.ModeCommandSource=ha,exports.OutputStyleCommandSource=Na,exports.PermissionsCommandSource=Ja,exports.PluginManagerCommandSource=vo,exports.PresetCommandSource=Ao,exports.ProviderCommandSource=As,exports.RemoteControlCommandSource=Gs,exports.RewindCommandSource=pc,exports.SANDBOX_MODES=z,exports.SHELL_COMMAND_DESCRIPTION=El,exports.SKILLS_COMMAND_DESCRIPTION=Ml,exports.STATUSLINE_USAGE=Hl,exports.STORAGE_REPAIR_ID=Ut,exports.SandboxCommandSource=wa,exports.ScheduleCommandSource=Gc,exports.SessionCommandSource=yl,exports.SettingsCommandSource=Cl,exports.ShellCommandSource=Al,exports.SkillsCommandSource=Bl,exports.StatusLineCommandSource=ql,exports.ThemeCommandSource=iu,exports.USER_LOCAL_COMMAND_ARGUMENT_HINT=su,exports.USER_LOCAL_COMMAND_DESCRIPTION=ou,exports.USER_LOCAL_COMMAND_USAGE=cu,exports.UserLocalCommandSource=ku,exports.applyDoctorRepair=Yt,exports.buildDoctorReport=cn,exports.collectSettingsSecrets=Tt,exports.createAdvisorCommandEntry=Dn,exports.createAdvisorCommandModule=An,exports.createAgentCommandEntry=me,exports.createAgentCommandModule=_e,exports.createAgentSystemCommand=he,exports.createBackgroundCommandEntry=be,exports.createBackgroundCommandModule=Ce,exports.createClearCommandEntry=sl,exports.createCompactCommandEntry=Ee,exports.createCompactCommandModule=ke,exports.createContextCommandEntry=Ye,exports.createContextCommandModule=Qe,exports.createCostCommandEntry=dl,exports.createDefaultCommandModules=Mu,exports.createDevicesCommandModule=ct,exports.createDoctorCommandEntry=dn,exports.createDoctorCommandModule=gn,exports.createEditorCommandEntry=bn,exports.createEditorCommandModule=Cn,exports.createEffortCommandEntry=zn,exports.createEffortCommandModule=Hn,exports.createExitCommandEntry=Wn,exports.createExitCommandModule=qn,exports.createGitCommandEntry=Ir,exports.createGitCommandModule=Br,exports.createGitProcess=cr,exports.createGoalCommandEntry=Wr,exports.createGoalCommandModule=qr,exports.createHandoffCommandEntry=Qr,exports.createHandoffCommandModule=ti,exports.createHelpCommandEntry=ri,exports.createHelpCommandModule=oi,exports.createKeybindingsCommandEntry=si,exports.createKeybindingsCommandModule=ui,exports.createLanguageCommandEntry=pi,exports.createLanguageCommandModule=gi,exports.createLoopCommandEntry=Vc,exports.createMCPActivationCommandEntry=Hi,exports.createMCPActivationCommandModule=Ki,exports.createMemoryCommandEntry=ia,exports.createMemoryCommandModule=sa,exports.createModeCommandEntry=pa,exports.createModeCommandModule=ga,exports.createMonitorCommandEntry=Bc,exports.createNodeDoctorDeps=pt,exports.createOutputStyleCommandEntry=ja,exports.createOutputStyleCommandModule=Pa,exports.createPermissionsCommandEntry=Ka,exports.createPermissionsCommandModule=Ya,exports.createPlanCommandModule=to,exports.createPluginCommandEntry=mo,exports.createPluginCommandModule=yo,exports.createPresetCommandEntry=Oo,exports.createPresetCommandModule=jo,exports.createProviderCommandEntry=ks,exports.createProviderCommandModule=Ms,exports.createProviderSetupFlow=H,exports.createReloadPluginsCommandEntry=ho,exports.createRemoteControlCommandEntry=Us,exports.createRemoteControlCommandModule=Ks,exports.createRenameCommandEntry=cl,exports.createResetCommandEntry=Js,exports.createResetCommandModule=Zs,exports.createResumeCommandEntry=ul,exports.createRewindCommandModule=mc,exports.createSandboxCommandModule=Ta,exports.createScheduleCommandEntry=zc,exports.createScheduleCommandModule=Kc,exports.createSessionCommandModule=bl,exports.createSettingsCommandEntry=xl,exports.createSettingsCommandModule=wl,exports.createShellCommandEntry=Ol,exports.createShellCommandModule=jl,exports.createSkillsCommandEntry=Rl,exports.createSkillsCommandModule=Vl,exports.createStatusLineCommandEntry=Gl,exports.createStatusLineCommandModule=Jl,exports.createThemeCommandEntry=ru,exports.createThemeCommandModule=au,exports.createUserLocalCommandEntry=Du,exports.createUserLocalCommandModule=Au,exports.createValidateSessionCommandEntry=fl,exports.doctorRepairAllowlist=Wt,exports.ensureProviderConfig=Fs,exports.executeAdvisorCommand=En,exports.executeAgentCommand=ue,exports.executeBackgroundCommand=ye,exports.executeClearCommand=Zc,exports.executeCompactCommand=Te,exports.executeContextCommand=Be,exports.executeCostCommand=al,exports.executeEditorCommand=yn,exports.executeEffortCommand=Ln,exports.executeExitCommand=Un,exports.executeGitCommand=Lr,exports.executeGoalCommand=Ur,exports.executeHandoffCommand=Xr,exports.executeHelpCommand=ni,exports.executeLanguageCommand=fi,exports.executeLoopCommand=Tc,exports.executeMCPActivationCommand=Pi,exports.executeMemoryCommand=ra,exports.executeModeCommand=fa,exports.executeMonitorCommand=Lc,exports.executeOutputStyleCommand=Aa,exports.executePermissionsCommand=ua,exports.executePluginCommand=fo,exports.executePresetCommand=Eo,exports.executeProviderCommand=Ss,exports.executeReloadPluginsCommand=po,exports.executeRemoteControlCommand=Hs,exports.executeRenameCommand=Qc,exports.executeResetCommand=qs,exports.executeResumeCommand=$c,exports.executeRewindCommand=uc,exports.executeSandboxCommand=ba,exports.executeScheduleCommand=Fc,exports.executeShellCommand=Dl,exports.executeSkillsCommand=Ll,exports.executeStatusLineCommand=Wl,exports.executeThemeCommand=nu,exports.executeUserLocalCommand=Eu,exports.executeUserLocalDirectCommand=Tu,exports.executeValidateSessionCommand=ol,exports.formatProviderSetupChoiceLabel=Ro,exports.formatProviderSetupHelpLinks=zo,exports.formatProviderSetupPromptLabel=Io,exports.formatProviderSetupSelectionPrompt=Mo,exports.formatSandboxStatus=va,exports.getProviderSetupStep=U,exports.gitEnvironment=ar,exports.isDoctorRepairId=Gt,exports.mcpUnavailableServersNotice=xi,exports.mcpUserActionCommand=_i,exports.mcpUserActionNotice=bi,exports.parseScheduleSpec=Ac,exports.planDoctorRepair=Jt,exports.redactDiagnosticText=Ct,exports.renderDoctorReport=_t,exports.resolveCommandOnPath=ft,exports.resolveEditor=_n,exports.resolveProviderSetupSelection=No,exports.resolveShell=Tl,exports.runDoctor=un,exports.runProviderSetupPromptFlow=Fo,exports.runProviderStartupSetup=Ps,exports.spawnInherited=k,exports.submitProviderSetupValue=Po,exports.validateProviderSetupValue=Vo;
99
+ `)),data:{count:n.length+r.length}}}async function Oc(e,t,n){let r=/^stop\s+(\S+)$/.exec(n);if(!r)return{success:!1,message:yc};let i=Y(e).find(e=>e.loopId===r[1]);if(i)return e.stopSelfPacedLoop?(await e.stopSelfPacedLoop(i.loopId,`Loop stopped by user`),{success:!0,message:`Loop stopped: ${i.loopId}. An already-running turn may finish.`,data:{loopId:i.loopId}}):{success:!1,message:`This host cannot stop self-paced loops.`};let a=J(e).find(e=>X(e)===r[1]);return a?(await t(a.id,`Loop stopped by user`),{success:!0,message:`Loop stopped: ${X(a)}. An already-running turn may finish.`,data:{loopId:X(a),taskId:a.id}}):{success:!1,message:`Active loop not found: ${r[1]}`}}async function kc(e,t,n){let r=t===``||/^\d+(s|m|h|d)$/i.test(t),i=n.defaultPrompt;if(r&&n.resolveDefaultPrompt)try{i=n.resolveDefaultPrompt()}catch(e){return{success:!1,message:`Default loop prompt could not be loaded: ${e instanceof Error?e.message:String(e)}`}}let a=wc(t,i);if(!a){if(/^\d+[a-z](?:\s|$)/i.test(t)||Cc(t))return{success:!1,message:yc};let n=(t||i||``).trim();if(!n||t===``&&n.length>_c)return{success:!1,message:yc};if(!e.createSelfPacedLoop)return{success:!1,message:`Self-paced loops require a persistent interactive session.`};let a=K.get(e)??0;if(J(e).length+Y(e).length+a>=3)return{success:!1,message:`At most 3 active loops are allowed. Stop one before creating another.`};K.set(e,a+1);try{let t=r?await e.createSelfPacedLoop(n,{useDefaultPrompt:!0}):await e.createSelfPacedLoop(n);return{success:!0,message:`Self-paced loop ${t.loopId} started. It will choose a 1–60 minute delay after each iteration and expires ${t.expiresAt}. Stop with /loop stop ${t.loopId}.`,data:{loopId:t.loopId,expiresAt:t.expiresAt}}}finally{let t=(K.get(e)??1)-1;t===0?K.delete(e):K.set(e,t)}}let o=K.get(e)??0;if(J(e).length+Y(e).length+o>=3)return{success:!1,message:`At most 3 active loops are allowed. Stop one before creating another.`};let s=Tc(a.requestedMs),c=`Loop: ${a.instruction.slice(0,48)}`,u=`loop_${(0,l.randomUUID)()}`,d=gc(u,s),f=Date.now(),p=new Date(f+a.requestedMs).toISOString(),m=new Date(f+6048e5).toISOString();K.set(e,o+1);let h;try{h=await e.spawnScheduledWake({label:c,cronExpression:d.cronExpression,agentInstruction:a.instruction,sessionLoop:!0,sessionLoopId:u,...r?{sessionLoopDefaultPrompt:!0}:{},sessionLoopFirstAllowedAt:p,sessionLoopExpiresAt:m})}finally{let t=(K.get(e)??1)-1;t===0?K.delete(e):K.set(e,t)}let g=s.milliseconds===a.requestedMs?``:` (rounded up)`,_=h.kind===`scheduled`&&h.nextFireAt&&h.nextFireAt>=p?` Next fire: ${h.nextFireAt}.`:``;return{success:!0,message:`Loop ${u} uses a ${s.description}${g} local-clock step with stable offset +${d.jitterSeconds}s; elapsed gaps can change with daylight saving. First eligible at or after ${p}.${_} Expires: ${m}. Stop with /loop stop ${u}.`,data:{loopId:u,taskId:h.id,requestedMs:a.requestedMs,cadenceLabel:s.description,cronExpression:d.cronExpression,jitterSeconds:d.jitterSeconds,firstAllowedAt:p,expiresAt:m}}}const Ac={s:1e3,m:6e4,h:36e5,d:864e5},Z=`Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron "<expr>" <instruction>`;function jc(e,t){let n=e.trim();if(n.length===0)return{ok:!1,error:Z};if(n.startsWith(`in `)){let e=n.slice(3).trim(),r=e.indexOf(` `);if(r===-1)return{ok:!1,error:`Missing instruction. ${Z}`};let i=e.slice(0,r),a=e.slice(r+1).trim(),o=/^(\d+)(s|m|h|d)$/.exec(i);if(!o)return{ok:!1,error:`Invalid duration "${i}". ${Z}`};if(a.length===0)return{ok:!1,error:`Missing instruction. ${Z}`};let s=parseInt(o[1],10)*Ac[o[2]];return{ok:!0,spec:{cronExpression:new Date(t+s).toISOString(),instruction:a,recurring:!1}}}if(n.startsWith(`cron `)){let e=n.slice(5).trim(),t=/^["']([^"']+)["']\s+(\S.*)$/.exec(e);if(!t)return{ok:!1,error:`cron form needs a quoted expression. ${Z}`};let r=t[2].trim();return r.length===0?{ok:!1,error:`Missing instruction. ${Z}`}:{ok:!0,spec:{cronExpression:t[1].trim(),instruction:r,recurring:!0}}}return{ok:!1,error:Z}}function Mc(e,t){return`${e}: ${t.slice(0,48)}${t.length>48?`…`:``}`}const Nc=`Usage: /schedule list | pause <id> | resume <id> | edit <id> <spec> (or a create spec: in <N><s|m|h|d> … | cron "<expr>" …)`;function Pc(e){return e.length===0?`No schedules.`:e.map(e=>{let t=e.kind===`scheduled`?e.schedule?.cronExpression??`(unknown)`:`(unknown)`,n=e.kind===`scheduled`&&e.nextFireAt?`next ${e.nextFireAt}`:`—`;return`- ${e.id} [${e.status}] ${t} — ${e.label} (${n})`}).join(`
100
+ `)}async function Fc(e,t,n,r){if(t===`list`){let t=e.listSchedules();return{message:Pc(t),success:!0,data:{count:t.length}}}if(t===`pause`||t===`resume`){let r=n.split(/\s+/)[0];return r?t===`pause`?(await e.pauseSchedule(r),{message:`Schedule paused: ${r}`,success:!0,data:{taskId:r}}):(await e.resumeSchedule(r),{message:`Schedule resumed: ${r}`,success:!0,data:{taskId:r}}):{message:Nc,success:!1}}if(t===`edit`){let t=n.indexOf(` `),i=t===-1?n:n.slice(0,t),a=t===-1?``:n.slice(t+1).trim();if(!i||!a)return{message:Nc,success:!1};let o=jc(a,r);return o.ok?(await e.editSchedule(i,{cronExpression:o.spec.cronExpression,agentInstruction:o.spec.instruction,label:Mc(`Scheduled`,o.spec.instruction)}),{message:`Schedule updated: ${i} (cron \`${o.spec.cronExpression}\`).`,success:!0,data:{taskId:i,cronExpression:o.spec.cronExpression}}):{message:o.error,success:!1}}}async function Ic(e,t,n=Date.now()){let r=t.trim(),i=r.indexOf(` `),a=await Fc(e,(i===-1?r:r.slice(0,i)).toLowerCase(),i===-1?``:r.slice(i+1).trim(),n);if(a)return a;let o=jc(t,n);if(!o.ok)return{message:`${o.error}\n${Nc}`,success:!1};let{cronExpression:s,instruction:c,recurring:l}=o.spec,u=await e.spawnScheduledWake({label:Mc(`Scheduled`,c),cronExpression:s,agentInstruction:c});return{message:`Scheduled wake (${l?`cron \`${s}\``:`once at ${s}`}): "${c}" — task ${u.id}.`,success:!0,data:{taskId:u.id,cronExpression:s,recurring:l}}}function Lc(e){let t=/^["']([^"']+)["']\s+["']([^"']+)["']\s+(\S.*)$/.exec(e.trim());if(!t)return null;let n=t[3].trim();return n.length===0?null:{command:t[1],matchPattern:t[2],instruction:n}}async function Rc(t,n){let r=Lc(n);if(!r)return{message:`Usage: /monitor "<command>" "<pattern>" <instruction>`,success:!1};let i;try{i=await t.spawnMonitorWake({label:Mc(`Monitor`,r.instruction),command:r.command,matchPattern:r.matchPattern,agentInstruction:r.instruction})}catch(t){if(t instanceof e.MonitorCommandRefusedError)return{message:t.message,success:!1};throw t}return{message:`Monitoring \`${r.command}\` for /${r.matchPattern}/ — task ${i.id}.`,success:!0,data:{taskId:i.id,matchPattern:r.matchPattern}}}function zc(e){let t=e.getAgentJobCapability();if(!t)throw Error(`Scheduling requires an active agent runtime.`);return t}function Bc(){return{name:`schedule`,displayName:`Schedule Wake`,description:`Schedule the agent to wake on a timer, and manage schedules (list / pause / resume / edit).`,modelDescription:'Wake yourself later with an instruction. Use it when work must wait (a deploy, a long build, a reply) instead of polling: `in <N><s|m|h|d> <instruction>` or `cron "<expr>" <instruction>`; `list`, `pause`, `resume` and `edit` manage existing schedules. Returns the schedule id, or the schedule list.',source:`schedule`,argumentHint:`in <N><s|m|h|d> <instruction> | cron "<expr>" <instruction> | list | pause <id> | resume <id> | edit <id> <spec>`,modelInvocable:!0}}function Vc(){return{name:`monitor`,displayName:`Monitor Process`,description:`Watch a process’s output and wake the agent when a line matches a pattern.`,modelDescription:`Run a command in the background and wake yourself when a line of its output matches a pattern. Use it to wait for a server to start, a test to fail or a log line to appear instead of polling. The command is allowed, refused or asked about by the same permission rules as a shell tool call. Returns the monitor task id, or a refusal naming what the user must allow.`,source:`schedule`,argumentHint:`"<command>" "<pattern>" <instruction>`,modelInvocable:!0}}function Hc(){return{name:`loop`,displayName:`Repeat Prompt`,description:`Repeat a prompt on a fixed cadence or let each iteration choose its next delay; list or stop active loops.`,modelDescription:"Repeat a prompt on a fixed cadence (`<N><s|m|h|d> [prompt]`) or self-paced (bare or prompt only: each iteration chooses its next delay or stops). Use it when the user asks for recurring work in this session. `list` shows active loops; `stop <id>` ends one. Returns the loop id and its next fire time, or the loop list.",source:`schedule`,argumentHint:`[prompt] | <N><s|m|h|d> [prompt] | <prompt> every <N> <unit> | list | stop <id>`,modelInvocable:!0,subcommands:[{name:`list`,description:`List active loops`,source:`schedule`},{name:`stop`,description:`Stop an active loop`,source:`schedule`,argumentHint:`<id>`}]}}function Uc(){let e=Bc();return{name:e.name,displayName:e.displayName,description:e.description,...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Ic(zc(e),t)}}function Wc(){let e=Vc();return{name:e.name,displayName:e.displayName,description:e.description,...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},requiresPermission:!0,modelRequiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Rc(zc(e),t)}}function Gc(e){let t=Hc();return{name:t.name,displayName:t.displayName,description:t.description,...t.modelDescription===void 0?{}:{modelDescription:t.modelDescription},requiresPermission:!0,userInvocable:!0,modelInvocable:!0,argumentHint:t.argumentHint,subcommands:t.subcommands,lifecycle:`inline`,execute:(t,n)=>Ec(zc(t),(e,n)=>t.cancelBackgroundTask(e,n),n,e)}}var Kc=class{name=`schedule`;getCommands(){return[Bc(),Vc(),Hc()]}};function qc(e={}){return{name:`agent-command-schedule`,commandSources:[new Kc],systemCommands:[Uc(),Wc(),Gc(e)],sessionRequirements:[`agent-runtime`]}}function Jc(e,n,r){return(0,t.calculateModelCost)(e,n,r)}function Q(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Yc(e){return e.toLocaleString(`en-US`)}const Xc=`Conversation cleared.`;function Zc(e,t){let n=t.trim();return n===``?{success:!1,message:`Usage: /cd <directory>`}:{success:!0,message:``,hostActions:[{type:`workspace-move`,path:n}]}}async function Qc(n,r){let i=n.getUserInteraction();return i&&!(0,t.isConfirmed)(await i.ask((0,t.confirmAction)(`clear`,`Clear conversation history?`)))?{success:!0,message:`Clear cancelled.`}:((0,e.clearConversationHistory)(n),{success:!0,message:Xc})}function $c(t,n){let r=(0,e.parseSessionNameArgument)(n);return r===void 0?{success:!1,message:e.RENAME_COMMAND_USAGE}:{success:!0,message:`Session renamed to "${r}".`,data:{name:r},hostActions:[(0,e.createSessionRenameHostAction)(r)]}}function el(){return{success:!0,message:`Opening session picker...`,data:{triggerResumePicker:!0},uiIntents:[(0,e.createShowSessionPickerIntent)()]}}function tl(e){return e.getCommandHostAdapters?.().costBudget}const nl=`Budget persistence is not available on this host (no cost-budget adapter was composed).`;function rl(e){return`Could not write the budget: ${e instanceof Error?e.message:String(e)}`}function il(e,t){if(e.length===0)return;let n={inputTokens:0,outputTokens:0,partial:!1,models:[]},r=new Set,i=0,a=!1;for(let o of e){n.inputTokens+=o.promptTokens,n.outputTokens+=o.completionTokens;let e=o.source?.scope===`tool`,s=o.costUsd??(!e&&t?Jc(t,o.promptTokens,o.completionTokens):void 0);if(s===void 0){n.partial=!0;continue}i+=s,a=!0,r.add(e?o.source?.label??`another model`:t??`main model`)}return a&&(n.costUsd=i),n.models=[...r],n}function al(t){let n=t.getSession(),r=(0,e.readCommandSessionInfo)(t),i=n.getModelId(),a=il(t.getSessionUsage(),i),o=[`Session: ${r.sessionId}`,`Messages: ${r.messageCount}`],s={sessionId:r.sessionId,messageCount:r.messageCount};if(a){o.push(`Tokens: ${Yc(a.inputTokens)} input / ${Yc(a.outputTokens)} output`),s.inputTokens=a.inputTokens,s.outputTokens=a.outputTokens;let e=a.costUsd;if(e!==void 0){let n=a.models.length>1?`mixed: ${a.models.join(`, `)}`:a.models[0]??``,r=a.partial?`; some usage could not be priced`:``;o.push(`Cost: ${Q(e)} (${n}${r})`),s.estimatedCostUsd=e,s.costModels=a.models,a.partial&&(s.costPartial=!0);let i=tl(t)?.read();if(i?.monthly){let t=i.monthly-e,n=Math.min(100,Math.round(e/i.monthly*100));o.push(`Budget: ${Q(t)} remaining of ${Q(i.monthly)}/mo (${n}% used)`),s.budgetMonthly=i.monthly,s.budgetRemainingUsd=t}}}else o.push(`Tokens: not yet available (no turns completed)`);return{lines:o,data:s}}function ol(e,t){let n=t.trim();if(n.startsWith(`budget`)){let t=n.slice(6).trim(),r=t===`clear`||t===``?void 0:parseFloat(t);if(r!==void 0&&(!Number.isFinite(r)||r<=0))return{success:!1,message:`Usage: /cost budget <amount> (e.g. /cost budget 5.00)`};let i=tl(e);if(i===void 0)return{success:!1,message:nl};if(t===`clear`){try{i.clear()}catch(e){return{success:!1,message:rl(e)}}return{success:!0,message:`Monthly budget cleared.`}}if(t===``){let e=i.read();return e?.monthly?{success:!0,message:`Monthly budget: ${Q(e.monthly)}`}:{success:!0,message:`No budget set. Use: /cost budget <amount>`}}if(r===void 0)return{success:!1,message:nl};try{i.write({monthly:r})}catch(e){return{success:!1,message:rl(e)}}return{success:!0,message:`Monthly budget set to ${Q(r)}.`}}let{lines:r,data:i}=al(e);return{success:!0,message:r.join(`
101
+ `),data:i}}function sl(t,n){let r=(0,e.validateCommandSessionReplayLog)(t);return{success:r.validation.ok,message:(0,e.formatCommandSessionReplayValidationReport)(r),data:{logFile:r.logFile,entryCount:r.entryCount,issueCount:r.validation.issues.length,ok:r.validation.ok}}}function cl(){return{name:`clear`,displayName:`Clear History`,description:e.CLEAR_COMMAND_DESCRIPTION,source:`session`,modelInvocable:!1,userInvocable:!0}}function ll(){return{name:`rename`,displayName:`Rename Session`,description:e.RENAME_COMMAND_DESCRIPTION,argumentHint:`<name>`,source:`session`,modelInvocable:!1,userInvocable:!0}}function ul(){return{name:`cd`,displayName:`Change Directory`,description:`Move this session to another working directory`,argumentHint:`<directory>`,source:`session`,modelInvocable:!1,userInvocable:!0}}function dl(){return{name:`resume`,displayName:`Resume Session`,description:e.RESUME_COMMAND_DESCRIPTION,source:`session`,modelInvocable:!1,userInvocable:!0}}function fl(){return{name:`cost`,displayName:`Session Cost`,description:e.COST_COMMAND_DESCRIPTION,modelDescription:"Report this session’s token usage and estimated cost. Use it before an expensive step (a large refactor, many subagents) or when the user asks what the session has cost. Returns the message count, input/output token totals and the estimated USD cost, with the remaining monthly budget when one is set. Setting or clearing the budget is the user’s decision: suggest `/cost budget <amount>`.",argumentHint:`[budget [<amount>|clear]]`,runsBare:!0,source:`session`,modelInvocable:!0,userInvocable:!0,subcommands:[{name:`budget`,description:`Show, set, or clear the monthly budget`,argumentHint:`[<amount>|clear]`,source:`session`,modelInvocable:!1}]}}function pl(){return{name:`validate-session`,displayName:`Validate Session`,description:e.VALIDATE_SESSION_COMMAND_DESCRIPTION,source:`session`,modelInvocable:!1,userInvocable:!0}}function ml(){return E(cl(),{requiresPermission:!1,lifecycle:`inline`,execute:Qc})}function hl(){return E(ll(),{requiresPermission:!1,lifecycle:`inline`,execute:$c})}function gl(){return E(ul(),{requiresPermission:!1,lifecycle:`inline`,execute:Zc})}function _l(){return E(dl(),{requiresPermission:!1,lifecycle:`inline`,execute:el})}function vl(){return E(fl(),{requiresPermission:!1,lifecycle:`inline`,execute:ol})}function yl(){return E(pl(),{requiresPermission:!1,lifecycle:`inline`,execute:sl})}var bl=class{name=`session`;getCommands(){return[cl(),ll(),ul(),dl(),fl(),pl()]}};function xl(){return{name:`agent-command-session`,commandSources:[new bl],systemCommands:[ml(),hl(),gl(),_l(),vl(),yl()]}}function Sl(){return{name:`settings`,displayName:`Settings`,description:`Open transport settings — enable/disable transports and configure options`,source:`settings`,modelInvocable:!1}}function Cl(){let e=Sl();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:async()=>({success:!0,message:`Opening settings...`,uiIntents:[{type:`show-settings`}]})}}var wl=class{name=`settings`;getCommands(){return[Sl()]}};function Tl(){return{name:`agent-command-settings`,commandSources:[new wl],systemCommands:[Cl()]}}function El(e){let n=(0,t.resolvePlatformShell)({executable:e});return{command:n.command,interactiveArgs:n.interactiveArgs,commandArgs:e=>n.commandArgs(e)}}const Dl="Drop to an interactive shell (or run `/shell <command>` interactively), then return to the agent.";async function Ol(e,t,n){if(!e.canHandoffTerminal())return{message:`An interactive shell is unavailable here (no interactive terminal).`,success:!1};let r=El(n),i=e.getCwd(),a=t.trim(),o=await e.runWithTerminal(async()=>a.length>0?k(r.command,r.commandArgs(a),i):k(r.command,r.interactiveArgs,i));return{message:a.length>0?`Command exited (code ${o}).`:`Shell session ended (code ${o}).`,success:o===0,data:{exitCode:o}}}function kl(){return{name:`shell`,displayName:`Shell`,description:Dl,source:`shell`,modelInvocable:!1}}function Al(e){let t=kl();return{name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(t,n)=>Ol(t,n,e)}}var jl=class{name=`shell`;getCommands(){return[kl()]}};function Ml(e){return{name:`agent-command-shell`,commandSources:[new jl],systemCommands:[Al(e)]}}const Nl=`List registered skills, or activate one by name`;function Pl(e){let t=[];return e.modelInvocable||t.push(`model-disabled`),e.userInvocable||t.push(`model-only`),e.context&&t.push(`context:${e.context}`),e.agent&&t.push(`agent:${e.agent}`),t.length>0?` [${t.join(`, `)}]`:``}function Fl(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}${Pl(e)}`}function Il(e){return e.length===0?[`No skills are registered for this session.`,``,`Skills are metadata until activated. Do not invent or imitate a skill workflow when no matching registered skill exists.`].join(`
102
+ `):[`Registered skills:`,...e.map(Fl),``,`Activation contract:`,`- Use /skills <skill-name> [args] to activate a matching skill.`,`- Treat /<skill-name> as a virtual alias for /skills <skill-name>.`,`- The system prompt Skills section is skill selection metadata.`,`- Treat descriptions as selection metadata only, not as loaded SKILL.md content.`,`- Do not answer by merely naming, recommending, or imitating a matching skill.`,`- If no listed skill matches the task, continue without claiming a skill was activated.`].join(`
103
+ `)}function Ll(e){let t=e.trim();if(t.length===0||t===`list`)return{action:`list`,skillArgs:``};let[n=``,...r]=t.split(/\s+/);return n.length===0?{action:`list`,skillArgs:``}:{action:`activate`,skillName:n,skillArgs:r.join(` `)}}async function Rl(e,t=``){let n=Ll(t);if(n.action===`activate`&&n.skillName!==void 0){let t=`/${n.skillName}${n.skillArgs?` ${n.skillArgs}`:``}`;return await e.executeSkillCommandByName(n.skillName,n.skillArgs,{invocationSource:e.getCommandInvocationSource(),displayInput:t,rawInput:t})??{success:!1,message:`Unknown skill: ${n.skillName}`}}let r=e.listSkills();return{success:!0,message:Il(r),data:{skills:r,activationContract:{activateWith:`/skills <skill-name> [args]`,activationRequiredBeforeWorkflow:!0,metadataIsNotSkillContent:!0}}}}function zl(){return{name:`skills`,displayName:`Skills`,description:Nl,modelDescription:`Skill command. Before following a matching registered skill from the system prompt Skills section, invoke the projected skills command tool with args "<skill-name> [args]". Without arguments, list registered skills. With a skill name, activate that skill; a skill that declares it is not model-invocable is refused. Returns the skill list with each skill's description, or the activated skill's instructions to follow. Slash syntax is a UI input/display concern; the SDK command identity is "skills".`,source:`skills`,modelInvocable:!0,userInvocable:!0,argumentHint:`[list | <skill-name> [args]]`,safety:`read-only`}}function Bl(){let e=zl();return{name:e.name,semanticRole:`skillActivation`,...e.modelDescription===void 0?{}:{modelDescription:e.modelDescription},displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,lifecycle:`inline`,execute:Rl}}var Vl=class{name=`skills`;getCommands(){return[zl()]}};function Hl(t){let n=[new Vl];return n.push(new e.SkillCommandSource(t.contributionSources,t.skillRoots??[])),{name:`agent-command-skills`,commandSources:n,systemCommands:[Bl()]}}const Ul=[`Usage: /statusline on | off | reset | git on | git off`,`Fields: model, context, permission mode, message count, session name, thinking state, git branch.`].join(`
104
+ `);function Wl(t){let n=t.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0),[r,i]=n;return r===`on`&&i===void 0?{success:!0,message:`Status line enabled.`,patch:{enabled:!0}}:r===`off`&&i===void 0?{success:!0,message:`Status line disabled.`,patch:{enabled:!1}}:r===`reset`&&i===void 0?{success:!0,message:`Status line settings reset.`,patch:{...e.DEFAULT_STATUS_LINE_COMMAND_SETTINGS}}:r===`git`&&i===`on`&&n.length===2?{success:!0,message:`Status line git branch shown.`,patch:{gitBranch:!0}}:r===`git`&&i===`off`&&n.length===2?{success:!0,message:`Status line git branch hidden.`,patch:{gitBranch:!1}}:{success:!1,message:Ul}}function Gl(e,t){let n=Wl(t);return n.success?{success:!0,message:n.message,hostActions:[{type:`statusline-settings-patch`,patch:n.patch}]}:{success:!1,message:n.message}}function Kl(){return{name:`statusline`,displayName:`Status Line`,description:e.STATUSLINE_COMMAND_DESCRIPTION,source:`statusline`,argumentHint:e.STATUSLINE_COMMAND_ARGUMENT_HINT,subcommands:(0,e.buildStatusLineCommandSubcommands)(`statusline`),modelInvocable:!1}}function ql(){let e=Kl();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:Gl}}var Jl=class{name=`statusline`;getCommands(){return[Kl()]}};function Yl(){return{name:`agent-command-statusline`,commandSources:[new Jl],systemCommands:[ql()]}}const Xl=`list | <theme-id> | syntax on|off | motion on|off`;function $(e){return e?`on`:`off`}function Zl(e){let{settings:t,reducedMotionPin:n}=e.getAppearance(),r=e.listThemes().map(e=>`${e.id===t.theme?`* `:` `}${e.id} — ${e.name} (${e.appearance}, ${e.source})`),i=n?`${$(n.reducedMotion)} for this run (pinned by ${n.tier}; saved ${$(t.reducedMotion)})`:$(t.reducedMotion);return[`Available themes:`,...r,``,`syntax highlighting: ${$(t.syntaxHighlighting)}`,`reduced motion: ${i}`].join(`
105
+ `)}function Ql(e){return{success:!0,message:Zl(e),data:{themes:e.listThemes().map(e=>({...e})),appearance:{...e.getAppearance().settings}}}}function $l(e,t){return{success:!1,message:`Unknown theme "${e}". Available: ${t.listThemes().map(e=>e.id).join(`, `)||`(none)`}`}}function eu(e){if(e===`on`)return!0;if(e===`off`)return!1}function tu(e){let t={},n=0,r;for(e[0]!==`syntax`&&e[0]!==`motion`&&(r=e[0],n=1);n<e.length;){let r=e[n],i=eu(e[n+1]);if(r!==`syntax`&&r!==`motion`||i===void 0)return{error:`Usage: /theme ${Xl}`};r===`syntax`?t.syntaxHighlighting=i:t.reducedMotion=!i,n+=2}return{patch:t,...r===void 0?{}:{themeId:r}}}function nu(e,t,n){let r=[];t&&r.push(`theme ${t.name}`),e.syntaxHighlighting!==void 0&&r.push(`syntax highlighting ${$(e.syntaxHighlighting)}`),e.reducedMotion!==void 0&&r.push(`motion ${$(!e.reducedMotion)}`);let i=r.length>0?`Applied: ${r.join(`, `)}.`:`Nothing to change.`;return e.reducedMotion!==void 0&&n.reducedMotionPin?`${i} Saved, but this run keeps reduced motion pinned by ${n.reducedMotionPin.tier}.`:i}function ru(e,t){if(!e)return{success:!1,message:`Themes are not available in this environment.`};let n=t.trim().split(/\s+/u).filter(Boolean);if(n.length===0)return{success:!0,message:`Opening the theme picker...`,uiIntents:[{type:`show-theme-picker`}]};if(n.length===1&&n[0]===`list`)return Ql(e);let r=tu(n);if(r.error!==void 0||!r.patch)return{success:!1,message:r.error??`Usage: /theme ${Xl}`};let i={...r.patch},a;if(r.themeId!==void 0){if(a=e.getTheme(r.themeId),!a)return $l(r.themeId,e);i.theme=a.id}return{success:!0,message:nu(i,a,e.getAppearance()),data:{appearance:{...i}},hostActions:[{type:`appearance-settings-patch`,patch:i}]}}function iu(){return{name:`theme`,displayName:`Theme`,description:`List, preview or switch the terminal colour theme, and toggle syntax highlighting and motion`,argumentHint:Xl,source:`theme`,userInvocable:!0,modelInvocable:!1}}var au=class{name=`theme`;getCommands(){return[iu()]}};function ou(e){let t=iu(),n={name:t.name,displayName:t.displayName,description:t.description,argumentHint:t.argumentHint,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:(t,n)=>ru(e,n)};return{name:`agent-command-theme`,commandSources:[new au],systemCommands:[n]}}const su=`Inspect user-local storage and memory state.`,cu=`storage list [--format json] | memory set/list/inspect/disable/delete`,lu=`Usage: user-local storage list [--format json] | user-local memory set <category> <key> <value> --summary <summary> --source <source> | user-local memory list [--format json] | user-local memory inspect <category> <key> [--format json] | user-local memory disable <category> <key> | user-local memory delete <category> <key>`;function uu(e){return e.length===0?`No user-local memory items.`:e.map(e=>`- ${e.category}/${e.key} (${e.enabled?`enabled`:`disabled`})`).join(`
106
+ `)}function du(e){if(e===void 0)throw Error(`User-local memory category is required.`);return e}async function fu(t,n,r){let i=await(0,e.listUserLocalMemoryItems)({activeRepositoryRoot:t,storageRoot:n});return{message:r.format===`json`?JSON.stringify(i,null,2):uu(i.items),success:!0,data:{list:i}}}async function pu(t,n,r){let[i,a,o]=r.positional,s=await(0,e.setUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:du(i),key:a??``,value:o??``,summary:r.summary??``,source:r.source??``});return{message:`Stored user-local memory item ${s.category}/${s.key} at ${s.storageLocation}`,success:!0,data:{item:s}}}async function mu(t,n,r){let[i,a]=r.positional,o=await(0,e.inspectUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:du(i),key:a??``});return{message:r.format===`json`?JSON.stringify(o,null,2):`${o.category}/${o.key}: ${o.summary}`,success:!0,data:{item:o}}}async function hu(t,n,r){let[i,a]=r.positional,o=await(0,e.disableUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:du(i),key:a??``});return{message:`Disabled user-local memory item ${o.category}/${o.key}`,success:!0,data:{item:o}}}async function gu(t,n,r){let[i,a]=r.positional,o=await(0,e.deleteUserLocalMemoryItem)({activeRepositoryRoot:t,storageRoot:n,category:du(i),key:a??``});return{message:`Deleted user-local memory item ${o.category}/${o.key}`,success:!0,data:{result:o}}}async function _u(e,t,n){return(n.action??`list`)===`list`?fu(e,t,n):n.action===`set`?pu(e,t,n):n.action===`inspect`?mu(e,t,n):n.action===`disable`?hu(e,t,n):n.action===`delete`?gu(e,t,n):{message:lu,success:!1}}function vu(e){if(e===void 0||e===`text`)return`text`;if(e===`json`)return`json`;throw Error(`Unsupported user-local output format: ${e}`)}function yu(e,t,n){return e===`--format`?{format:t[n+1],nextIndex:n+1}:e.startsWith(`--format=`)?{format:e.slice(9),nextIndex:n}:e===`--summary`?{summary:t[n+1],nextIndex:n+1}:e.startsWith(`--summary=`)?{summary:e.slice(10),nextIndex:n}:e===`--source`?{source:t[n+1],nextIndex:n+1}:e.startsWith(`--source=`)?{source:e.slice(9),nextIndex:n}:null}function bu(e,t={}){let n=t.format,r=t.summary,i=t.source,a=[];for(let t=0;t<e.length;t+=1){let o=e[t],s=yu(o,e,t);if(s!==null){n=s.format??n,r=s.summary??r,i=s.source??i,t=s.nextIndex;continue}a.push(o)}return{target:a[0],action:a[1],positional:a.slice(2),format:vu(n),summary:r,source:i}}function xu(e){return e.trim().split(/\s+/).filter(Boolean)}function Su(e,t){let n=t.map(e=>`- ${e.category}`);return[`User-local storage root: ${e}`,`Categories:`,...n].join(`
107
+ `)}async function Cu(t,n,r){if((r.action??`list`)!==`list`)return{message:lu,success:!1};let i=await(0,e.inspectUserLocalStorage)({activeRepositoryRoot:t,storageRoot:n});return{message:r.format===`json`?JSON.stringify(i,null,2):Su(i.root,i.categories),success:!0,data:{root:i.root,categories:i.categories,inspection:i}}}async function wu(e,t,n){return n.target===`storage`?Cu(e,t,n):n.target===`memory`?_u(e,t,n):{message:lu,success:!1}}function Tu(e){return e.includes(`ENOENT`)?`User-local memory item not found.`:e}async function Eu(e){try{return await wu(e.cwd,e.storageRoot,bu(e.argv,{format:e.format,summary:e.summary,source:e.source}))}catch(e){return{message:Tu(e instanceof Error?e.message:String(e)),success:!1}}}async function Du(e,t,n){try{return await wu(e.getCwd(),n,bu(xu(t)))}catch(e){return{message:Tu(e instanceof Error?e.message:String(e)),success:!1}}}function Ou(){return{name:`user-local`,displayName:`User Config`,description:su,source:`user-local`,argumentHint:cu,modelInvocable:!1,safety:`read-only`,subcommands:[{name:`storage`,description:`Inspect user-local storage categories`,source:`user-local`},{name:`memory`,description:`Inspect and manage user-local memory items`,source:`user-local`}]}}function ku(e){let t=Ou();return{name:t.name,displayName:t.displayName,description:t.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:t.argumentHint,safety:t.safety,subcommands:t.subcommands,execute:(t,n)=>Du(t,n,e)}}var Au=class{name=`user-local`;getCommands(){return[Ou()]}};function ju(e){return{name:`agent-command-user-local`,commandSources:[new Au],systemCommands:[ku(e)]}}function Mu(t,n,r){return(0,e.selectCommandModules)(t,n,r)}function Nu({cwd:t,userLocalStorageRoot:n,editorTemporaryDirectoryPrefix:r,contributionSources:i,skillRoots:a,providerDefinitions:o,providerSettingsAdapter:s,orgPolicy:c,keybindingsFilePort:l,themeCataloguePort:u,devicesPort:d,doctorInputs:f,doctorDisplay:p,formatForkResumeCommand:m,loopOptions:h,enabledCommandModules:g,disabledCommandModules:_}){let v=[Hl({contributionSources:i??[],skillRoots:a}),oi(),_e(),Hn(),An(),Xa(),ga(),Ta(),Mo(),Pa(),gi(),Ce(),rr(m),qr(),no(),Ml(),Cn(r),Br(),...l===void 0?[]:[ui(l)],...u===void 0?[]:[ou(u)],...f===void 0?[]:[gn(f,void 0,p)],sa(),Ki(),ju(n),ke(),Qe(),qn(),xl(),Qs(),hc(),qc(h),Yl(),bo(),Tl(),Ka(),ti(),qs(),...d===void 0?[]:[ct(d)],Ns({providerDefinitions:o,settings:s,...c===void 0?{}:{orgPolicy:c}})],y=v.map(e=>e.name);return{modules:Mu(v,g,_),unknownModuleNames:(0,e.findUnknownModuleNames)(y,g,_)}}exports.ADVISOR_SETTING_KEY=wn,exports.AdvisorCommandSource=kn,exports.AgentCommandSource=ge,exports.BackgroundCommandSource=Se,exports.CLEAR_COMMAND_MESSAGE=Xc,exports.CompactCommandSource=Oe,exports.ContextCommandSource=Ze,exports.DoctorCommandSource=fn,exports.EDITOR_COMMAND_DESCRIPTION=vn,exports.EditorCommandSource=Sn,exports.EffortCommandSource=Vn,exports.ExitCommandSource=Kn,exports.GOAL_COMMAND_DESCRIPTION=Vr,exports.GitCommandSource=zr,exports.GoalCommandSource=Kr,exports.HandoffCommandSource=ei,exports.HelpCommandSource=ai,exports.KeybindingsCommandSource=li,exports.LanguageCommandSource=hi,exports.MCPActivationCommandSource=Gi,exports.MemoryCommandSource=oa,exports.ModeCommandSource=ha,exports.OutputStyleCommandSource=Na,exports.PermissionsCommandSource=Ya,exports.PluginManagerCommandSource=yo,exports.PresetCommandSource=jo,exports.ProviderCommandSource=js,exports.RemoteControlCommandSource=Ks,exports.RewindCommandSource=mc,exports.SANDBOX_MODES=z,exports.SHELL_COMMAND_DESCRIPTION=Dl,exports.SKILLS_COMMAND_DESCRIPTION=Nl,exports.STATUSLINE_USAGE=Ul,exports.STORAGE_REPAIR_ID=Ut,exports.SandboxCommandSource=wa,exports.ScheduleCommandSource=Kc,exports.SessionCommandSource=bl,exports.SettingsCommandSource=wl,exports.ShellCommandSource=jl,exports.SkillsCommandSource=Vl,exports.StatusLineCommandSource=Jl,exports.ThemeCommandSource=au,exports.USER_LOCAL_COMMAND_ARGUMENT_HINT=cu,exports.USER_LOCAL_COMMAND_DESCRIPTION=su,exports.USER_LOCAL_COMMAND_USAGE=lu,exports.UserLocalCommandSource=Au,exports.applyDoctorRepair=Yt,exports.buildDoctorReport=cn,exports.collectSettingsSecrets=Tt,exports.createAdvisorCommandEntry=Dn,exports.createAdvisorCommandModule=An,exports.createAgentCommandEntry=me,exports.createAgentCommandModule=_e,exports.createAgentSystemCommand=he,exports.createBackgroundCommandEntry=be,exports.createBackgroundCommandModule=Ce,exports.createClearCommandEntry=cl,exports.createCompactCommandEntry=Ee,exports.createCompactCommandModule=ke,exports.createContextCommandEntry=Ye,exports.createContextCommandModule=Qe,exports.createCostCommandEntry=fl,exports.createDefaultCommandModules=Nu,exports.createDevicesCommandModule=ct,exports.createDoctorCommandEntry=dn,exports.createDoctorCommandModule=gn,exports.createEditorCommandEntry=bn,exports.createEditorCommandModule=Cn,exports.createEffortCommandEntry=zn,exports.createEffortCommandModule=Hn,exports.createExitCommandEntry=Wn,exports.createExitCommandModule=qn,exports.createGitCommandEntry=Ir,exports.createGitCommandModule=Br,exports.createGitProcess=cr,exports.createGoalCommandEntry=Wr,exports.createGoalCommandModule=qr,exports.createHandoffCommandEntry=Qr,exports.createHandoffCommandModule=ti,exports.createHelpCommandEntry=ri,exports.createHelpCommandModule=oi,exports.createKeybindingsCommandEntry=si,exports.createKeybindingsCommandModule=ui,exports.createLanguageCommandEntry=pi,exports.createLanguageCommandModule=gi,exports.createLoopCommandEntry=Hc,exports.createMCPActivationCommandEntry=Hi,exports.createMCPActivationCommandModule=Ki,exports.createMemoryCommandEntry=ia,exports.createMemoryCommandModule=sa,exports.createModeCommandEntry=pa,exports.createModeCommandModule=ga,exports.createMonitorCommandEntry=Vc,exports.createNodeDoctorDeps=pt,exports.createOutputStyleCommandEntry=ja,exports.createOutputStyleCommandModule=Pa,exports.createPermissionsCommandEntry=qa,exports.createPermissionsCommandModule=Xa,exports.createPlanCommandModule=no,exports.createPluginCommandEntry=ho,exports.createPluginCommandModule=bo,exports.createPresetCommandEntry=ko,exports.createPresetCommandModule=Mo,exports.createProviderCommandEntry=As,exports.createProviderCommandModule=Ns,exports.createProviderSetupFlow=H,exports.createReloadPluginsCommandEntry=go,exports.createRemoteControlCommandEntry=Ws,exports.createRemoteControlCommandModule=qs,exports.createRenameCommandEntry=ll,exports.createResetCommandEntry=Ys,exports.createResetCommandModule=Qs,exports.createResumeCommandEntry=dl,exports.createRewindCommandModule=hc,exports.createSandboxCommandModule=Ta,exports.createScheduleCommandEntry=Bc,exports.createScheduleCommandModule=qc,exports.createSessionCommandModule=xl,exports.createSettingsCommandEntry=Sl,exports.createSettingsCommandModule=Tl,exports.createShellCommandEntry=kl,exports.createShellCommandModule=Ml,exports.createSkillsCommandEntry=zl,exports.createSkillsCommandModule=Hl,exports.createStatusLineCommandEntry=Kl,exports.createStatusLineCommandModule=Yl,exports.createThemeCommandEntry=iu,exports.createThemeCommandModule=ou,exports.createUserLocalCommandEntry=Ou,exports.createUserLocalCommandModule=ju,exports.createValidateSessionCommandEntry=pl,exports.doctorRepairAllowlist=Wt,exports.ensureProviderConfig=Is,exports.executeAdvisorCommand=En,exports.executeAgentCommand=ue,exports.executeBackgroundCommand=ye,exports.executeClearCommand=Qc,exports.executeCompactCommand=Te,exports.executeContextCommand=Be,exports.executeCostCommand=ol,exports.executeEditorCommand=yn,exports.executeEffortCommand=Ln,exports.executeExitCommand=Un,exports.executeGitCommand=Lr,exports.executeGoalCommand=Ur,exports.executeHandoffCommand=Xr,exports.executeHelpCommand=ni,exports.executeLanguageCommand=fi,exports.executeLoopCommand=Ec,exports.executeMCPActivationCommand=Pi,exports.executeMemoryCommand=ra,exports.executeModeCommand=fa,exports.executeMonitorCommand=Rc,exports.executeOutputStyleCommand=Aa,exports.executePermissionsCommand=ua,exports.executePluginCommand=po,exports.executePresetCommand=Do,exports.executeProviderCommand=Cs,exports.executeReloadPluginsCommand=mo,exports.executeRemoteControlCommand=Us,exports.executeRenameCommand=$c,exports.executeResetCommand=Js,exports.executeResumeCommand=el,exports.executeRewindCommand=dc,exports.executeSandboxCommand=ba,exports.executeScheduleCommand=Ic,exports.executeShellCommand=Ol,exports.executeSkillsCommand=Rl,exports.executeStatusLineCommand=Gl,exports.executeThemeCommand=ru,exports.executeUserLocalCommand=Du,exports.executeUserLocalDirectCommand=Eu,exports.executeValidateSessionCommand=sl,exports.formatProviderSetupChoiceLabel=zo,exports.formatProviderSetupHelpLinks=Bo,exports.formatProviderSetupPromptLabel=Lo,exports.formatProviderSetupSelectionPrompt=No,exports.formatSandboxStatus=va,exports.getProviderSetupStep=U,exports.gitEnvironment=ar,exports.isDoctorRepairId=Gt,exports.mcpUnavailableServersNotice=xi,exports.mcpUserActionCommand=_i,exports.mcpUserActionNotice=bi,exports.parseScheduleSpec=jc,exports.planDoctorRepair=Jt,exports.redactDiagnosticText=Ct,exports.renderDoctorReport=_t,exports.resolveCommandOnPath=ft,exports.resolveEditor=_n,exports.resolveProviderSetupSelection=Po,exports.resolveShell=El,exports.runDoctor=un,exports.runProviderSetupPromptFlow=Io,exports.runProviderStartupSetup=Fs,exports.spawnInherited=k,exports.submitProviderSetupValue=Fo,exports.validateProviderSetupValue=Ho;