@robota-sdk/agent-command 3.0.0-beta.74 → 3.0.0-beta.75

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.
@@ -1,28 +1,29 @@
1
- import{BACKGROUND_COMMAND_DESCRIPTION as e,BACKGROUND_COMMAND_USAGE as t,BundlePluginInstaller as n,BundlePluginLoader as r,CLEAR_COMMAND_DESCRIPTION as i,COST_COMMAND_DESCRIPTION as a,DEFAULT_AUTO_COMPACT_THRESHOLD as o,DEFAULT_STATUS_LINE_COMMAND_SETTINGS as s,EXIT_COMMAND_DESCRIPTION as c,HELP_COMMAND_DESCRIPTION as l,LANGUAGE_COMMAND_ARGUMENT_HINT as ee,LANGUAGE_COMMAND_DESCRIPTION as te,MEMORY_COMMAND_ARGUMENT_HINT as ne,MEMORY_COMMAND_DESCRIPTION as re,MEMORY_COMMAND_USAGE as ie,MarketplaceClient as u,PERMISSIONS_COMMAND_DESCRIPTION as d,PERMISSION_MODE_ARGUMENT_HINT as f,PERMISSION_MODE_COMMAND_DESCRIPTION as ae,PLUGIN_COMMAND_ARGUMENT_HINT as oe,PLUGIN_COMMAND_DESCRIPTION as se,PluginCommandSource as ce,PluginSettingsStore as le,ProviderConfigError as ue,RELOAD_PLUGINS_COMMAND_DESCRIPTION as de,RENAME_COMMAND_DESCRIPTION as fe,RENAME_COMMAND_USAGE as pe,RESUME_COMMAND_DESCRIPTION as me,REWIND_COMMAND_ARGUMENT_HINT as he,REWIND_COMMAND_DESCRIPTION as ge,STATUSLINE_COMMAND_ARGUMENT_HINT as _e,STATUSLINE_COMMAND_DESCRIPTION as ve,SkillCommandSource as ye,VALIDATE_SESSION_COMMAND_DESCRIPTION as be,addCommandContextReference as xe,applyProviderConfiguration as Se,buildBackgroundCommandSubcommands as Ce,buildLanguageCommandSubcommands as we,buildMemoryCommandSubcommands as Te,buildPermissionModeSubcommands as p,buildPluginCommandSubcommands as Ee,buildProviderSetupPatch as De,buildRewindCommandSubcommands as Oe,buildStatusLineCommandSubcommands as ke,cancelCommandBackgroundTask as Ae,checkSettingsDocument as je,clearCommandContextReferences as Me,clearConversationHistory as Ne,closeCommandBackgroundTask as Pe,compactCommandContext as Fe,createCommandMemoryStores as Ie,createPluginRegistryReloadRequestedEffect as Le,createPluginTuiRequestedEffect as Re,createSessionExitRequestedEffect as ze,createSessionPickerRequestedEffect as Be,createSessionRenamedEffect as Ve,deleteProviderProfile as He,deleteUserLocalMemoryItem as Ue,disableUserLocalMemoryItem as We,formatCommandBackgroundTaskList as Ge,formatCommandHelpMessage as Ke,formatCommandPermissionsMessage as qe,formatCommandSessionReplayValidationReport as Je,formatInvalidPermissionModeMessage as Ye,formatLanguageUsageMessage as Xe,formatOrgPolicyViolationMessage as Ze,getProviderSettingsPaths as Qe,hasSensitiveCommandMemoryContent as $e,inspectCommandEditCheckpoint as et,inspectUserLocalMemoryItem as tt,inspectUserLocalStorage as nt,isApiKeyPlaintext as rt,isCommandMemoryType as it,isPermissionMode as at,listCommandBackgroundTasks as ot,listCommandContextReferences as st,listCommandEditCheckpoints as ct,listCommandUsedMemoryReferences as lt,listUserLocalMemoryItems as ut,mergeProviderPatch as dt,parseCommandBackgroundLogCursor as ft,parseLanguageArgument as pt,parsePermissionModeArgument as mt,parseSessionNameArgument as ht,readAutoCompactThreshold as m,readAutoCompactThresholdSource as h,readCommandBackgroundTaskLog as gt,readCommandContextState as _t,readCommandPermissionMode as vt,readCommandPermissionsState as yt,readCommandSessionInfo as bt,readMergedProviderSettings as xt,readSettings as St,recordCommandMemoryEvent as Ct,removeCommandContextReference as wt,resetAutoCompactThresholdSetting as Tt,resolveEnvDefaultProvider as Et,resolvePluginCommandAdapter as Dt,resolveSettingsPathForScope as Ot,restoreCommandEditCheckpoint as kt,rollbackCommandEditCheckpoint as At,sanitizeProviderProfileName as jt,setCommandAutoCompactThreshold as Mt,setCurrentProvider as Nt,setUserLocalMemoryItem as Pt,suggestProviderProfileName as Ft,summarizeBackgroundJobGroup as It,testProviderProfileCommand as Lt,upsertProviderProfile as Rt,validateCommandSessionReplayLog as zt,writeAutoCompactThresholdSetting as Bt,writeCommandPermissionMode as Vt,writeSettings as Ht}from"@robota-sdk/agent-framework";import{findProviderDefinition as Ut,formatSupportedProviderTypes as g}from"@robota-sdk/agent-core";import{join as _}from"node:path";import{existsSync as Wt,mkdirSync as Gt,readFileSync as Kt,writeFileSync as qt}from"node:fs";import{execSync as Jt}from"node:child_process";import{homedir as Yt}from"node:os";const v=`general-purpose`;function Xt(e){let t=[],n=``,r,i=!1;for(let a of e){if(i){n+=a,i=!1;continue}if(r&&a===`\\`){i=!0;continue}if(r){a===r?r=void 0:n+=a;continue}if(a===`"`||a===`'`){r=a;continue}if(/\s/.test(a)){n.length>0&&(t.push(n),n=``);continue}n+=a}return n.length>0&&t.push(n),t}function Zt(e){let t=[],n,r,i;for(let a=0;a<e.length;a+=1){let o=e[a];if(o!==`--background`){if(o===`--agent`||o===`--type`||o===`-a`){n=e[a+1],a+=1;continue}if(o===`--model`){r=e[a+1],a+=1;continue}if(o===`--isolation`){let t=e[a+1];(t===`none`||t===`worktree`)&&(i=t),a+=1;continue}o!==void 0&&t.push(o)}}return{positional:t,...n?{agentType:n}:{},...r?{model:r}:{},...i?{isolation:i}:{}}}function y(e,t,n,r){return{agentType:t,label:n,mode:`background`,prompt:r,...e.model?{model:e.model}:{},...e.isolation?{isolation:e.isolation}:{}}}function Qt(e,t){let n=Zt(e),[r,...i]=n.positional,a=n.agentType??v,o=n.positional;!n.agentType&&r&&t.has(r)&&(a=r,o=i);let s=o.join(` `).trim();if(s)return y(n,a,a,s)}function $t(e,t){let n=Zt(e);return n.positional.map(e=>en(e,n,t)).filter(e=>e!==void 0)}function en(e,t,n){let r=e.indexOf(`=`);if(r>0)return tn(e.slice(0,r),e.slice(r+1),t,n);let i=e.indexOf(`:`);if(i<=0||i===e.length-1)return;let a=e.slice(0,i),o=e.slice(i+1);return y(t,t.agentType??(n.has(a)?a:v),a,o)}function tn(e,t,n,r){let i=t.indexOf(`:`);if(i===-1)return y(n,n.agentType??(r.has(e)?e:v),e,t);if(!(i===0||i===t.length-1))return y(n,t.slice(0,i),e,t.slice(i+1))}function b(e){return e instanceof Error?e.message:String(e)}function nn(e){return new Set(e.listAgentDefinitions().map(e=>e.name))}function rn(e,t){let n=e.listAgentDefinitions();if(!n.some(e=>e.name===t))return{message:`Unknown agent type: ${t}\nAvailable agents: ${n.map(e=>e.name).join(`, `)}`,success:!1}}async function an(e,t){let n=rn(e,t.agentType);if(n)return n;try{return{state:await e.spawnAgentJob(t)}}catch(e){return{message:b(e),success:!1}}}function on(){return{message:``,effects:[{type:`agent-switcher-requested`}],success:!0}}async function sn(e){let t=e.listAgentDefinitions(),n=e.listAgentJobs();return{message:[`Available agents:`,...t.map(e=>` ${e.name} - ${e.description}`),``,n.length===0?`No active agent jobs.`:`Agent jobs:`,...n.map(e=>` ${cn(e)}`)].join(`
2
- `),success:!0,data:{agents:t.length,jobs:n.length}}}function cn(e){let t=[e.worktreePath?`worktree=${e.worktreePath}`:void 0,e.branchName?`branch=${e.branchName}`:void 0].filter(e=>e!==void 0),n=t.length>0?` ${t.join(` `)}`:``;return`${e.id} [${e.status}${n}] ${e.label} - ${e.promptPreview}`}async function ln(e,t){let n=Qt(t,nn(e));if(!n)return{message:`Usage: agent run [AGENT_NAME] [--agent AGENT_NAME] PROMPT`,success:!1};let r=await an(e,n);if(`success`in r)return r;let{state:i}=r;return{message:`Started agent job: ${i.id}`,success:!0,data:{agentId:i.id,status:i.status}}}async function un(e,t){let n=t.includes(`--wait`)||!t.includes(`--detach`),r=$t(t.filter(e=>e!==`--wait`&&e!==`--detach`),nn(e));if(r.length===0)return{message:`Usage: agent parallel [--wait|--detach] LABEL:"PROMPT" [LABEL=AGENT_NAME:"PROMPT"]`,success:!1};let i=r.map(t=>rn(e,t.agentType)).find(e=>e!==void 0);if(i)return i;let a;try{a=await Promise.all(r.map(t=>e.spawnAgentJob(t)))}catch(e){return{message:b(e),success:!1}}let o=e.createBackgroundJobGroup({waitPolicy:`wait_all`,taskIds:a.map(e=>e.id),label:`agent parallel`});if(n){let t=It(await e.waitBackgroundJobGroup(o.id));return{message:_n(t),success:!0,data:{agentIds:a.map(e=>e.id),groupId:o.id,summary:t}}}return{message:[`Started agent jobs:`,...a.map(e=>`${e.label}: ${e.id}`)].join(`
3
- `),success:!0,data:{agentIds:a.map(e=>e.id),groupId:o.id}}}async function dn(e,t){let[n]=t;if(!n)return{message:`Usage: agent wait GROUP_ID`,success:!1};let r=It(await e.waitBackgroundJobGroup(n));return{message:_n(r),success:!0,data:{groupId:n,summary:r}}}async function fn(e,t){let[n,r]=t;if(!n)return{message:`Usage: agent read AGENT_ID [OFFSET]`,success:!1};let i=r?{offset:Number.parseInt(r,10)}:void 0,a=await e.readBackgroundTaskLog(n,i),o=a.nextCursor?`\nNext offset: ${a.nextCursor.offset}`:``;return{message:a.lines.length>0?`${a.lines.join(`
4
- `)}${o}`:`No log lines: ${n}`,success:!0,data:{agentId:n,nextOffset:a.nextCursor?.offset}}}async function pn(e,t){let[n,...r]=t,i=r.join(` `).trim();return!n||!i?{message:`Usage: agent send AGENT_ID PROMPT`,success:!1}:(await e.sendAgentJob(n,i),{message:`Sent input to agent job: ${n}`,success:!0,data:{agentId:n}})}async function mn(e,t){let[n,...r]=t;return n?(await e.cancelAgentJob(n,r.join(` `)||void 0),{message:`Agent job stopped: ${n}`,success:!0,data:{agentId:n}}):{message:`Usage: agent stop AGENT_ID [REASON]`,success:!1}}async function hn(e,t){let[n]=t;return n?(await e.closeAgentJob(n),{message:`Agent job closed: ${n}`,success:!0,data:{agentId:n}}):{message:`Usage: agent close AGENT_ID`,success:!1}}async function gn(e,t){try{if(t.trim()===``)return on();let[n=`list`,...r]=Xt(t);return n===`list`&&r.length===0?sn(e):n===`run`?ln(e,r):n===`parallel`?un(e,r):n===`wait`?dn(e,r):n===`read`||n===`open`?fn(e,r):n===`send`?pn(e,r):n===`stop`||n===`cancel`?mn(e,r):n===`close`?hn(e,r):ln(e,[n,...r])}catch(e){return{message:b(e),success:!1}}}function _n(e){return[`Background job group ${e.groupId}: ${e.status} (${e.completed}/${e.total} completed, ${e.failed} failed, ${e.cancelled} cancelled, ${e.pending} pending)`,...e.lines].join(`
5
- `)}function vn(e){let t=e.getAgentJobCapability?.();if(!t)throw Error(`Agent job capability is not available in this context.`);return t}function yn(){return[{name:`list`,description:`List available agents and active jobs`,source:`agent`},{name:`run`,description:`Start one background agent job`,source:`agent`},{name:`parallel`,description:`Run multiple agents in parallel`,source:`agent`},{name:`wait`,description:`Wait for a background agent group summary`,source:`agent`},{name:`read`,description:`Read an agent job log page`,source:`agent`},{name:`send`,description:`Send follow-up input to an agent job`,source:`agent`},{name:`stop`,description:`Cancel a running agent job`,source:`agent`},{name:`close`,description:`Dismiss a terminal agent job`,source:`agent`},{name:`open`,description:`Focus an agent job detail view when supported`,source:`agent`}]}function x(){return{name:`agent`,displayName:`Agent Jobs`,description:[`Subagent jobs command.`,`Natural-language arguments start one background agent job.`,`When the user explicitly asks to create, run, spawn, delegate to, or use agents/subagents, start the requested agent command immediately and do not ask a follow-up question unless execution is impossible or unsafe.`,`If the target item is unspecified, include target selection inside the agent prompt instead of delaying execution.`,`The parallel form starts multiple background agent jobs as a wait_all group and returns a consolidated group summary unless --detach is present.`,`list, wait, read, send, stop, close, and open manage existing agent jobs.`].join(` `),source:`agent`,modelInvocable:!0,argumentHint:`PROMPT | AGENT_NAME PROMPT | list | parallel [--wait|--detach] LABEL:"PROMPT" [LABEL=AGENT_NAME:"PROMPT"] | wait GROUP_ID | read AGENT_ID [OFFSET] | send AGENT_ID PROMPT | stop AGENT_ID | close AGENT_ID`,safety:`background-agent`,subcommands:yn()}}function bn(){let e=x();return{name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description,requiresPermission:!1,execute:(e,t)=>gn(vn(e),t),...e.modelInvocable===void 0?{}:{modelInvocable:e.modelInvocable},...e.userInvocable===void 0?{}:{userInvocable:e.userInvocable},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.safety===void 0?{}:{safety:e.safety}}}var xn=class{name=`agent`;getCommands(){return[x()]}};function Sn(){return{name:`agent-command-agent`,commandSources:[new xn],systemCommands:[bn()],sessionRequirements:[`agent-runtime`]}}function Cn(e){return e.trim().split(/\s+/).filter(Boolean)}async function wn(e,n){let[r=`list`,i,...a]=Cn(n);if(r===`list`){let t=ot(e);return{message:Ge(t),success:!0,data:{count:t.length}}}if(!i)return{message:t,success:!1};if(r===`read`||r===`log`||r===`open`){let t=await gt(e,i,ft(a[0])),n=t.nextCursor?`\nNext offset: ${t.nextCursor.offset}`:``;return{message:t.lines.length>0?`${t.lines.join(`
6
- `)}${n}`:`No log lines: ${i}`,success:!0,data:{taskId:i,nextOffset:t.nextCursor?.offset}}}return r===`cancel`||r===`stop`?(await Ae(e,i,a.join(` `)||void 0),{message:`Background task cancelled: ${i}`,success:!0,data:{taskId:i}}):r===`close`||r===`dismiss`?(await Pe(e,i),{message:`Background task closed: ${i}`,success:!0,data:{taskId:i}}):{message:`Unknown background action: ${r}`,success:!1}}function S(){return{name:`background`,displayName:`Background Tasks`,description:e,source:`background`,modelInvocable:!1,subcommands:Ce()}}function Tn(){let e=S();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,subcommands:e.subcommands,execute:wn}}var En=class{name=`background`;getCommands(){return[S()]}};function Dn(){return{name:`agent-command-background`,commandSources:[new En],systemCommands:[Tn()]}}function On(e){let t=e.trim();return t.length>0?t:void 0}async function kn(e,t){let{before:n,after:r,beforeMessageCount:i,afterMessageCount:a}=await Fe(e,On(t)),o=i-a;return{message:[`Context compacted.`,` Removed messages: ${o} (${i>0?Math.round(o/i*100):0}% of total)`,` Context: ${Math.round(n.usedPercentage)}% → ${Math.round(r.usedPercentage)}%`].join(`
7
- `),success:!0,data:{before:n,after:r,beforeMessageCount:i,afterMessageCount:a}}}function C(){return{name:`compact`,displayName:`Compact Context`,description:`Compress context window`,source:`compact`,modelInvocable:!0,argumentHint:`[instructions]`,safety:`write`,example:`/compact Summarize the current context`}}function An(){let e=C();return{name:e.name,displayName:e.displayName,description:e.description,example:e.example,requiresPermission:!1,userInvocable:!0,modelInvocable:e.modelInvocable,argumentHint:e.argumentHint,safety:e.safety,lifecycle:`blocking`,execute:kn}}var jn=class{name=`compact`;getCommands(){return[C()]}};function Mn(){return{name:`agent-command-compact`,commandSources:[new jn],systemCommands:[An()]}}const w=[`Usage: /context [list] | add <path> | remove <path> | clear | auto on | off | <percent> | reset`,`Examples: /context list, /context add AGENTS.md, /context remove AGENTS.md, /context auto 85%`].join(`
8
- `);function T(e){return e===!1?`disabled`:`${Math.round(e*100)}%`}function Nn(e,t){return e===!1?`Auto compact: disabled (${t})`:`Auto compact: ${T(e)} (${t})`}function Pn(e){return e?`settings`:`current session only`}async function Fn(e,t){let n=t.trim().split(/\s+/).filter(e=>e.length>0);if(n.length>0)return In(e,n);let r=_t(e),i=m(e),a=h(e),o=qn(e.getSession().getFullHistory()),s=st(e);return{message:[`Context: ${r.usedTokens.toLocaleString()} / ${r.maxTokens.toLocaleString()} tokens (${Math.round(r.usedPercentage)}%)`,Nn(i,a),Un(s),`History: ${o.turnCount} turn${o.turnCount===1?``:`s`}`].join(`
9
- `),success:!0,data:{usedTokens:r.usedTokens,maxTokens:r.maxTokens,percentage:r.usedPercentage,autoCompactThreshold:i,autoCompactThresholdSource:a,references:s}}}async function In(e,t){let[n,...r]=t;if(n===`list`)return r.length>0?{success:!1,message:w}:Yn(e);if(n===`add`)return Rn(e,r);if(n===`remove`)return zn(e,r);if(n===`clear`){if(r.length>0)return{success:!1,message:w};let t=Me(e);return{success:!0,message:`Context references cleared: ${t.removed.length} removed.`,data:{removed:t.removed}}}return n===`auto`?Ln(e,r):{success:!1,message:w}}function Ln(e,t){let[n,r]=t;if(r!==void 0)return{success:!1,message:w};if(n===void 0){let t=m(e),n=h(e);return{success:!0,message:[Nn(t,n),w].join(`
10
- `),data:{autoCompactThreshold:t,autoCompactThresholdSource:n}}}if(n===`on`)return Bn(e,o,`enabled`);if(n===`off`)return Bn(e,!1,`disabled`);if(n===`reset`){let t=Tt(e);return Mt(e,o,`default`),{success:!0,message:`Auto compact reset to default: ${T(o)} (${Pn(t)}).`,data:{autoCompactThreshold:o,autoCompactThresholdSource:`default`,persisted:t}}}let i=Hn(n);return i.success?Bn(e,i.threshold,`threshold set`):{success:!1,message:`${i.message}\n${w}`}}async function Rn(e,t){let n=t.join(` `).trim();if(!n)return{success:!1,message:w};let r=await xe(e,n);return r.reference?{success:!0,message:[`Context reference added: ${D(r.reference)}.`,...r.evicted.length>0?[`Evicted ${r.evicted.length} older context reference(s).`]:[]].join(`
1
+ import{BACKGROUND_COMMAND_DESCRIPTION as e,BACKGROUND_COMMAND_USAGE as t,BundlePluginInstaller as n,BundlePluginLoader as r,CLEAR_COMMAND_DESCRIPTION as i,COST_COMMAND_DESCRIPTION as a,DEFAULT_AUTO_COMPACT_THRESHOLD as o,DEFAULT_STATUS_LINE_COMMAND_SETTINGS as s,EXIT_COMMAND_DESCRIPTION as c,HELP_COMMAND_DESCRIPTION as l,LANGUAGE_COMMAND_ARGUMENT_HINT as ee,LANGUAGE_COMMAND_DESCRIPTION as te,MEMORY_COMMAND_ARGUMENT_HINT as ne,MEMORY_COMMAND_DESCRIPTION as re,MEMORY_COMMAND_USAGE as ie,MarketplaceClient as u,PERMISSIONS_COMMAND_DESCRIPTION as d,PERMISSION_MODE_ARGUMENT_HINT as f,PERMISSION_MODE_COMMAND_DESCRIPTION as ae,PLUGIN_COMMAND_ARGUMENT_HINT as oe,PLUGIN_COMMAND_DESCRIPTION as se,PluginCommandSource as ce,PluginSettingsStore as le,ProviderConfigError as ue,RELOAD_PLUGINS_COMMAND_DESCRIPTION as de,RENAME_COMMAND_DESCRIPTION as fe,RENAME_COMMAND_USAGE as pe,RESUME_COMMAND_DESCRIPTION as me,REWIND_COMMAND_ARGUMENT_HINT as he,REWIND_COMMAND_DESCRIPTION as ge,STATUSLINE_COMMAND_ARGUMENT_HINT as _e,STATUSLINE_COMMAND_DESCRIPTION as ve,SkillCommandSource as ye,VALIDATE_SESSION_COMMAND_DESCRIPTION as be,addCommandContextReference as xe,applyPresetToSession as Se,applyProviderConfiguration as Ce,buildBackgroundCommandSubcommands as we,buildLanguageCommandSubcommands as Te,buildMemoryCommandSubcommands as Ee,buildPermissionModeSubcommands as De,buildPluginCommandSubcommands as Oe,buildProviderSetupPatch as ke,buildRewindCommandSubcommands as Ae,buildStatusLineCommandSubcommands as je,cancelCommandBackgroundTask as Me,checkSettingsDocument as Ne,clearCommandContextReferences as Pe,clearConversationHistory as Fe,closeCommandBackgroundTask as Ie,compactCommandContext as Le,createCommandMemoryStores as Re,createPluginRegistryReloadRequestedEffect as ze,createPluginTuiRequestedEffect as Be,createSessionExitRequestedEffect as Ve,createSessionPickerRequestedEffect as He,createSessionRenamedEffect as Ue,deleteProviderProfile as We,deleteUserLocalMemoryItem as Ge,disableUserLocalMemoryItem as Ke,formatCommandBackgroundTaskList as qe,formatCommandHelpMessage as Je,formatCommandPermissionsMessage as Ye,formatCommandSessionReplayValidationReport as Xe,formatInvalidPermissionModeMessage as Ze,formatLanguageUsageMessage as Qe,formatOrgPolicyViolationMessage as $e,getProviderSettingsPaths as et,hasSensitiveCommandMemoryContent as tt,inspectCommandEditCheckpoint as nt,inspectUserLocalMemoryItem as rt,inspectUserLocalStorage as it,isApiKeyPlaintext as at,isCommandMemoryType as ot,isPermissionMode as st,listCommandBackgroundTasks as ct,listCommandContextReferences as lt,listCommandEditCheckpoints as ut,listCommandUsedMemoryReferences as dt,listUserLocalMemoryItems as ft,mergeProviderPatch as pt,parseCommandBackgroundLogCursor as mt,parseLanguageArgument as ht,parsePermissionModeArgument as gt,parseSessionNameArgument as _t,readAutoCompactThreshold as p,readAutoCompactThresholdSource as m,readCommandBackgroundTaskLog as vt,readCommandContextState as yt,readCommandPermissionMode as bt,readCommandPermissionsState as xt,readCommandSessionInfo as St,readMergedProviderSettings as Ct,readSettings as wt,recordCommandMemoryEvent as Tt,removeCommandContextReference as Et,resetAutoCompactThresholdSetting as Dt,resolveEnvDefaultProvider as Ot,resolvePluginCommandAdapter as kt,resolveSettingsPathForScope as At,restoreCommandEditCheckpoint as jt,rollbackCommandEditCheckpoint as Mt,sanitizeProviderProfileName as Nt,setCommandAutoCompactThreshold as Pt,setCurrentProvider as Ft,setUserLocalMemoryItem as It,suggestProviderProfileName as Lt,summarizeBackgroundJobGroup as Rt,testProviderProfileCommand as zt,upsertProviderProfile as Bt,validateCommandSessionReplayLog as Vt,writeAutoCompactThresholdSetting as Ht,writeCommandPermissionMode as Ut,writeSettings as Wt}from"@robota-sdk/agent-framework";import{getPreset as Gt,listPresets as h,resolvePreset as Kt}from"@robota-sdk/agent-preset";import{findProviderDefinition as qt,formatSupportedProviderTypes as g}from"@robota-sdk/agent-core";import{join as _}from"node:path";import{existsSync as Jt,mkdirSync as Yt,readFileSync as Xt,writeFileSync as Zt}from"node:fs";import{execSync as Qt}from"node:child_process";import{homedir as $t}from"node:os";const v=`general-purpose`;function en(e){let t=[],n=``,r,i=!1;for(let a of e){if(i){n+=a,i=!1;continue}if(r&&a===`\\`){i=!0;continue}if(r){a===r?r=void 0:n+=a;continue}if(a===`"`||a===`'`){r=a;continue}if(/\s/.test(a)){n.length>0&&(t.push(n),n=``);continue}n+=a}return n.length>0&&t.push(n),t}function tn(e){let t=[],n,r,i;for(let a=0;a<e.length;a+=1){let o=e[a];if(o!==`--background`){if(o===`--agent`||o===`--type`||o===`-a`){n=e[a+1],a+=1;continue}if(o===`--model`){r=e[a+1],a+=1;continue}if(o===`--isolation`){let t=e[a+1];(t===`none`||t===`worktree`)&&(i=t),a+=1;continue}o!==void 0&&t.push(o)}}return{positional:t,...n?{agentType:n}:{},...r?{model:r}:{},...i?{isolation:i}:{}}}function y(e,t,n,r){return{agentType:t,label:n,mode:`background`,prompt:r,...e.model?{model:e.model}:{},...e.isolation?{isolation:e.isolation}:{}}}function nn(e,t){let n=tn(e),[r,...i]=n.positional,a=n.agentType??v,o=n.positional;!n.agentType&&r&&t.has(r)&&(a=r,o=i);let s=o.join(` `).trim();if(s)return y(n,a,a,s)}function rn(e,t){let n=tn(e);return n.positional.map(e=>an(e,n,t)).filter(e=>e!==void 0)}function an(e,t,n){let r=e.indexOf(`=`);if(r>0)return on(e.slice(0,r),e.slice(r+1),t,n);let i=e.indexOf(`:`);if(i<=0||i===e.length-1)return;let a=e.slice(0,i),o=e.slice(i+1);return y(t,t.agentType??(n.has(a)?a:v),a,o)}function on(e,t,n,r){let i=t.indexOf(`:`);if(i===-1)return y(n,n.agentType??(r.has(e)?e:v),e,t);if(!(i===0||i===t.length-1))return y(n,t.slice(0,i),e,t.slice(i+1))}function b(e){return e instanceof Error?e.message:String(e)}function sn(e){return new Set(e.listAgentDefinitions().map(e=>e.name))}function cn(e,t){let n=e.listAgentDefinitions();if(!n.some(e=>e.name===t))return{message:`Unknown agent type: ${t}\nAvailable agents: ${n.map(e=>e.name).join(`, `)}`,success:!1}}async function ln(e,t){let n=cn(e,t.agentType);if(n)return n;try{return{state:await e.spawnAgentJob(t)}}catch(e){return{message:b(e),success:!1}}}function un(){return{message:``,effects:[{type:`agent-switcher-requested`}],success:!0}}async function dn(e){let t=e.listAgentDefinitions(),n=e.listAgentJobs();return{message:[`Available agents:`,...t.map(e=>` ${e.name} - ${e.description}`),``,n.length===0?`No active agent jobs.`:`Agent jobs:`,...n.map(e=>` ${fn(e)}`)].join(`
2
+ `),success:!0,data:{agents:t.length,jobs:n.length}}}function fn(e){let t=[e.worktreePath?`worktree=${e.worktreePath}`:void 0,e.branchName?`branch=${e.branchName}`:void 0].filter(e=>e!==void 0),n=t.length>0?` ${t.join(` `)}`:``;return`${e.id} [${e.status}${n}] ${e.label} - ${e.promptPreview}`}async function pn(e,t){let n=nn(t,sn(e));if(!n)return{message:`Usage: agent run [AGENT_NAME] [--agent AGENT_NAME] PROMPT`,success:!1};let r=await ln(e,n);if(`success`in r)return r;let{state:i}=r;return{message:`Started agent job: ${i.id}`,success:!0,data:{agentId:i.id,status:i.status}}}async function mn(e,t){let n=t.includes(`--wait`)||!t.includes(`--detach`),r=rn(t.filter(e=>e!==`--wait`&&e!==`--detach`),sn(e));if(r.length===0)return{message:`Usage: agent parallel [--wait|--detach] LABEL:"PROMPT" [LABEL=AGENT_NAME:"PROMPT"]`,success:!1};let i=r.map(t=>cn(e,t.agentType)).find(e=>e!==void 0);if(i)return i;let a;try{a=await Promise.all(r.map(t=>e.spawnAgentJob(t)))}catch(e){return{message:b(e),success:!1}}let o=e.createBackgroundJobGroup({waitPolicy:`wait_all`,taskIds:a.map(e=>e.id),label:`agent parallel`});if(n){let t=Rt(await e.waitBackgroundJobGroup(o.id));return{message:xn(t),success:!0,data:{agentIds:a.map(e=>e.id),groupId:o.id,summary:t}}}return{message:[`Started agent jobs:`,...a.map(e=>`${e.label}: ${e.id}`)].join(`
3
+ `),success:!0,data:{agentIds:a.map(e=>e.id),groupId:o.id}}}async function hn(e,t){let[n]=t;if(!n)return{message:`Usage: agent wait GROUP_ID`,success:!1};let r=Rt(await e.waitBackgroundJobGroup(n));return{message:xn(r),success:!0,data:{groupId:n,summary:r}}}async function gn(e,t){let[n,r]=t;if(!n)return{message:`Usage: agent read AGENT_ID [OFFSET]`,success:!1};let i=r?{offset:Number.parseInt(r,10)}:void 0,a=await e.readBackgroundTaskLog(n,i),o=a.nextCursor?`\nNext offset: ${a.nextCursor.offset}`:``;return{message:a.lines.length>0?`${a.lines.join(`
4
+ `)}${o}`:`No log lines: ${n}`,success:!0,data:{agentId:n,nextOffset:a.nextCursor?.offset}}}async function _n(e,t){let[n,...r]=t,i=r.join(` `).trim();return!n||!i?{message:`Usage: agent send AGENT_ID PROMPT`,success:!1}:(await e.sendAgentJob(n,i),{message:`Sent input to agent job: ${n}`,success:!0,data:{agentId:n}})}async function vn(e,t){let[n,...r]=t;return n?(await e.cancelAgentJob(n,r.join(` `)||void 0),{message:`Agent job stopped: ${n}`,success:!0,data:{agentId:n}}):{message:`Usage: agent stop AGENT_ID [REASON]`,success:!1}}async function yn(e,t){let[n]=t;return n?(await e.closeAgentJob(n),{message:`Agent job closed: ${n}`,success:!0,data:{agentId:n}}):{message:`Usage: agent close AGENT_ID`,success:!1}}async function bn(e,t){try{if(t.trim()===``)return un();let[n=`list`,...r]=en(t);return n===`list`&&r.length===0?dn(e):n===`run`?pn(e,r):n===`parallel`?mn(e,r):n===`wait`?hn(e,r):n===`read`||n===`open`?gn(e,r):n===`send`?_n(e,r):n===`stop`||n===`cancel`?vn(e,r):n===`close`?yn(e,r):pn(e,[n,...r])}catch(e){return{message:b(e),success:!1}}}function xn(e){return[`Background job group ${e.groupId}: ${e.status} (${e.completed}/${e.total} completed, ${e.failed} failed, ${e.cancelled} cancelled, ${e.pending} pending)`,...e.lines].join(`
5
+ `)}function Sn(e){let t=e.getAgentJobCapability?.();if(!t)throw Error(`Agent job capability is not available in this context.`);return t}function Cn(){return[{name:`list`,description:`List available agents and active jobs`,source:`agent`},{name:`run`,description:`Start one background agent job`,source:`agent`},{name:`parallel`,description:`Run multiple agents in parallel`,source:`agent`},{name:`wait`,description:`Wait for a background agent group summary`,source:`agent`},{name:`read`,description:`Read an agent job log page`,source:`agent`},{name:`send`,description:`Send follow-up input to an agent job`,source:`agent`},{name:`stop`,description:`Cancel a running agent job`,source:`agent`},{name:`close`,description:`Dismiss a terminal agent job`,source:`agent`},{name:`open`,description:`Focus an agent job detail view when supported`,source:`agent`}]}function x(){return{name:`agent`,displayName:`Agent Jobs`,description:[`Subagent jobs command.`,`Natural-language arguments start one background agent job.`,`When the user explicitly asks to create, run, spawn, delegate to, or use agents/subagents, start the requested agent command immediately and do not ask a follow-up question unless execution is impossible or unsafe.`,`If the target item is unspecified, include target selection inside the agent prompt instead of delaying execution.`,`The parallel form starts multiple background agent jobs as a wait_all group and returns a consolidated group summary unless --detach is present.`,`list, wait, read, send, stop, close, and open manage existing agent jobs.`].join(` `),source:`agent`,modelInvocable:!0,argumentHint:`PROMPT | AGENT_NAME PROMPT | list | parallel [--wait|--detach] LABEL:"PROMPT" [LABEL=AGENT_NAME:"PROMPT"] | wait GROUP_ID | read AGENT_ID [OFFSET] | send AGENT_ID PROMPT | stop AGENT_ID | close AGENT_ID`,safety:`background-agent`,subcommands:Cn()}}function wn(){let e=x();return{name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description,requiresPermission:!1,execute:(e,t)=>bn(Sn(e),t),...e.modelInvocable===void 0?{}:{modelInvocable:e.modelInvocable},...e.userInvocable===void 0?{}:{userInvocable:e.userInvocable},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.safety===void 0?{}:{safety:e.safety}}}var Tn=class{name=`agent`;getCommands(){return[x()]}};function En(){return{name:`agent-command-agent`,commandSources:[new Tn],systemCommands:[wn()],sessionRequirements:[`agent-runtime`]}}function Dn(e){return e.trim().split(/\s+/).filter(Boolean)}async function On(e,n){let[r=`list`,i,...a]=Dn(n);if(r===`list`){let t=ct(e);return{message:qe(t),success:!0,data:{count:t.length}}}if(!i)return{message:t,success:!1};if(r===`read`||r===`log`||r===`open`){let t=await vt(e,i,mt(a[0])),n=t.nextCursor?`\nNext offset: ${t.nextCursor.offset}`:``;return{message:t.lines.length>0?`${t.lines.join(`
6
+ `)}${n}`:`No log lines: ${i}`,success:!0,data:{taskId:i,nextOffset:t.nextCursor?.offset}}}return r===`cancel`||r===`stop`?(await Me(e,i,a.join(` `)||void 0),{message:`Background task cancelled: ${i}`,success:!0,data:{taskId:i}}):r===`close`||r===`dismiss`?(await Ie(e,i),{message:`Background task closed: ${i}`,success:!0,data:{taskId:i}}):{message:`Unknown background action: ${r}`,success:!1}}function S(){return{name:`background`,displayName:`Background Tasks`,description:e,source:`background`,modelInvocable:!1,subcommands:we()}}function kn(){let e=S();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,subcommands:e.subcommands,execute:On}}var An=class{name=`background`;getCommands(){return[S()]}};function jn(){return{name:`agent-command-background`,commandSources:[new An],systemCommands:[kn()]}}function Mn(e){let t=e.trim();return t.length>0?t:void 0}async function Nn(e,t){let{before:n,after:r,beforeMessageCount:i,afterMessageCount:a}=await Le(e,Mn(t)),o=i-a;return{message:[`Context compacted.`,` Removed messages: ${o} (${i>0?Math.round(o/i*100):0}% of total)`,` Context: ${Math.round(n.usedPercentage)}% → ${Math.round(r.usedPercentage)}%`].join(`
7
+ `),success:!0,data:{before:n,after:r,beforeMessageCount:i,afterMessageCount:a}}}function Pn(){return{name:`compact`,displayName:`Compact Context`,description:`Compress context window`,source:`compact`,modelInvocable:!0,argumentHint:`[instructions]`,safety:`write`,example:`/compact Summarize the current context`}}function Fn(){let e=Pn();return{name:e.name,displayName:e.displayName,description:e.description,example:e.example,requiresPermission:!1,userInvocable:!0,modelInvocable:e.modelInvocable,argumentHint:e.argumentHint,safety:e.safety,lifecycle:`blocking`,execute:Nn}}var In=class{name=`compact`;getCommands(){return[Pn()]}};function Ln(){return{name:`agent-command-compact`,commandSources:[new In],systemCommands:[Fn()]}}const C=[`Usage: /context [list] | add <path> | remove <path> | clear | auto on | off | <percent> | reset`,`Examples: /context list, /context add AGENTS.md, /context remove AGENTS.md, /context auto 85%`].join(`
8
+ `);function w(e){return e===!1?`disabled`:`${Math.round(e*100)}%`}function Rn(e,t){return e===!1?`Auto compact: disabled (${t})`:`Auto compact: ${w(e)} (${t})`}function zn(e){return e?`settings`:`current session only`}async function Bn(e,t){let n=t.trim().split(/\s+/).filter(e=>e.length>0);if(n.length>0)return Vn(e,n);let r=yt(e),i=p(e),a=m(e),o=Qn(e.getSession().getFullHistory()),s=lt(e);return{message:[`Context: ${r.usedTokens.toLocaleString()} / ${r.maxTokens.toLocaleString()} tokens (${Math.round(r.usedPercentage)}%)`,Rn(i,a),Jn(s),`History: ${o.turnCount} turn${o.turnCount===1?``:`s`}`].join(`
9
+ `),success:!0,data:{usedTokens:r.usedTokens,maxTokens:r.maxTokens,percentage:r.usedPercentage,autoCompactThreshold:i,autoCompactThresholdSource:a,references:s}}}async function Vn(e,t){let[n,...r]=t;if(n===`list`)return r.length>0?{success:!1,message:C}:er(e);if(n===`add`)return Un(e,r);if(n===`remove`)return Wn(e,r);if(n===`clear`){if(r.length>0)return{success:!1,message:C};let t=Pe(e);return{success:!0,message:`Context references cleared: ${t.removed.length} removed.`,data:{removed:t.removed}}}return n===`auto`?Hn(e,r):{success:!1,message:C}}function Hn(e,t){let[n,r]=t;if(r!==void 0)return{success:!1,message:C};if(n===void 0){let t=p(e),n=m(e);return{success:!0,message:[Rn(t,n),C].join(`
10
+ `),data:{autoCompactThreshold:t,autoCompactThresholdSource:n}}}if(n===`on`)return Gn(e,o,`enabled`);if(n===`off`)return Gn(e,!1,`disabled`);if(n===`reset`){let t=Dt(e);return Pt(e,o,`default`),{success:!0,message:`Auto compact reset to default: ${w(o)} (${zn(t)}).`,data:{autoCompactThreshold:o,autoCompactThresholdSource:`default`,persisted:t}}}let i=qn(n);return i.success?Gn(e,i.threshold,`threshold set`):{success:!1,message:`${i.message}\n${C}`}}async function Un(e,t){let n=t.join(` `).trim();if(!n)return{success:!1,message:C};let r=await xe(e,n);return r.reference?{success:!0,message:[`Context reference added: ${E(r.reference)}.`,...r.evicted.length>0?[`Evicted ${r.evicted.length} older context reference(s).`]:[]].join(`
11
11
  `),data:{reference:r.reference,evicted:r.evicted}}:{success:!1,message:r.diagnostics.join(`
12
- `)||`Context reference not found: ${n}`,data:{diagnostics:r.diagnostics}}}function zn(e,t){let n=t.join(` `).trim();if(!n)return{success:!1,message:w};let r=wt(e,n);return r.removed?{success:!0,message:`Context reference removed: ${D(r.removed)}.`,data:{removed:r.removed}}:{success:!1,message:`Context reference not found: ${n}`}}function Bn(e,t,n){let r=Bt(e,t),i=r?`settings`:`session`;return Mt(e,t,i),{success:!0,message:Vn(n,t,r),data:{autoCompactThreshold:t,autoCompactThresholdSource:i,persisted:r}}}function Vn(e,t,n){let r=Pn(n);return e===`disabled`?`Auto compact disabled (${r}).`:e===`enabled`?`Auto compact enabled at ${T(t)} (${r}).`:`Auto compact threshold set to ${T(t)} (${r}).`}function Hn(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 Un(e){return`References: ${e.filter(e=>e.status===`active`).length} active, ${e.filter(e=>e.status===`observed`).length} observed`}function E(e){return Math.ceil(e/4)}function D(e){return[e.relativePath,`[${e.loadType}, ${e.status}]`,`~${E(e.byteLength).toLocaleString()} tokens`].join(` `)}function Wn(e){try{return JSON.parse(e)}catch{return null}}function Gn(e){let t=Wn(e);if(t===null)return``;let n=Object.values(t)[0],r=typeof n==`string`?n:JSON.stringify(n);return r.length>60?`${r.slice(0,60)}…`:r}function Kn(e){let t=0,n=0,r=0,i=0,a=0,o=0,s=0;for(let c of e){let e=Math.ceil(JSON.stringify(c).length/4);c.role===`system`?t+=e:c.role===`user`?(n+=e,r++):c.role===`assistant`?(i+=e,a++):c.role===`tool`&&(o+=e,s++)}return{systemTokens:t,userTokens:n,userCount:r,assistantTokens:i,assistantCount:a,toolTokens:o,toolCallCount:s,totalTokens:t+n+i+o}}function qn(e){let t=new Map;for(let n of e){if(n.category!==`chat`||n.type!==`assistant`)continue;let e=n.data;for(let n of e.toolCalls??[])t.set(n.id,{name:n.function.name,firstArg:Gn(n.function.arguments)})}let n=0,r=0,i=new Map;for(let a of e)if(a.category===`chat`){if(a.type===`user`)n++;else if(a.type===`tool`){let e=a.data,n=t.get(e.toolCallId??``),o=n?.name??`tool`,s=n?.firstArg??``;r++,i.set(`${o}:${s}`,{toolName:o,displayArg:s})}}return{turnCount:n,toolResults:[...i.values()],totalToolCallCount:r}}function Jn(e,t,n){let r=`${e}${t>0?` — ~${t.toLocaleString()} tokens`:``}:`;return n.length===0?`${r}\n (none)`:[r,...n.map(e=>` ${e}`)].join(`
13
- `)}function Yn(e){let t=_t(e),n=m(e),r=h(e),i=Kn(e.getSession().getHistory()),a=qn(e.getSession().getFullHistory()),o=st(e),s=o.filter(e=>e.loadType===`system`),c=o.filter(e=>e.loadType===`manual`),l=o.filter(e=>e.loadType===`prompt-reference`),ee=s.reduce((e,t)=>e+E(t.byteLength),0),te=c.reduce((e,t)=>e+E(t.byteLength),0),ne=l.reduce((e,t)=>e+E(t.byteLength),0),re=a.turnCount===0?`Conversation history — 0 turns`:`Conversation history — ${a.turnCount} turn${a.turnCount===1?``:`s`} | ~${i.totalTokens.toLocaleString()} tokens`,ie=a.toolResults.map(e=>`${e.toolName}${e.displayArg?`: ${e.displayArg}`:``}`),u=a.toolResults.length,d=a.totalToolCallCount,f=d===0?`Tool results (0): (none)`:u<d?`Tool results (${u} unique / ${d} calls, ~${i.toolTokens.toLocaleString()} tokens):`:`Tool results (${u}, ~${i.toolTokens.toLocaleString()} tokens):`,ae=a.turnCount===0?[]:[`User (${i.userCount}): ~${i.userTokens.toLocaleString()} tokens`,`Assistant (${i.assistantCount}): ~${i.assistantTokens.toLocaleString()} tokens`,...i.systemTokens>0?[`System messages: ~${i.systemTokens.toLocaleString()} tokens`]:[],d>0?[f,...ie.map(e=>` ${e}`)].join(`
12
+ `)||`Context reference not found: ${n}`,data:{diagnostics:r.diagnostics}}}function Wn(e,t){let n=t.join(` `).trim();if(!n)return{success:!1,message:C};let r=Et(e,n);return r.removed?{success:!0,message:`Context reference removed: ${E(r.removed)}.`,data:{removed:r.removed}}:{success:!1,message:`Context reference not found: ${n}`}}function Gn(e,t,n){let r=Ht(e,t),i=r?`settings`:`session`;return Pt(e,t,i),{success:!0,message:Kn(n,t,r),data:{autoCompactThreshold:t,autoCompactThresholdSource:i,persisted:r}}}function Kn(e,t,n){let r=zn(n);return e===`disabled`?`Auto compact disabled (${r}).`:e===`enabled`?`Auto compact enabled at ${w(t)} (${r}).`:`Auto compact threshold set to ${w(t)} (${r}).`}function qn(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 Jn(e){return`References: ${e.filter(e=>e.status===`active`).length} active, ${e.filter(e=>e.status===`observed`).length} observed`}function T(e){return Math.ceil(e/4)}function E(e){return[e.relativePath,`[${e.loadType}, ${e.status}]`,`~${T(e.byteLength).toLocaleString()} tokens`].join(` `)}function Yn(e){try{return JSON.parse(e)}catch{return null}}function Xn(e){let t=Yn(e);if(t===null)return``;let n=Object.values(t)[0],r=typeof n==`string`?n:JSON.stringify(n);return r.length>60?`${r.slice(0,60)}…`:r}function Zn(e){let t=0,n=0,r=0,i=0,a=0,o=0,s=0;for(let c of e){let e=Math.ceil(JSON.stringify(c).length/4);c.role===`system`?t+=e:c.role===`user`?(n+=e,r++):c.role===`assistant`?(i+=e,a++):c.role===`tool`&&(o+=e,s++)}return{systemTokens:t,userTokens:n,userCount:r,assistantTokens:i,assistantCount:a,toolTokens:o,toolCallCount:s,totalTokens:t+n+i+o}}function Qn(e){let t=new Map;for(let n of e){if(n.category!==`chat`||n.type!==`assistant`)continue;let e=n.data;for(let n of e.toolCalls??[])t.set(n.id,{name:n.function.name,firstArg:Xn(n.function.arguments)})}let n=0,r=0,i=new Map;for(let a of e)if(a.category===`chat`){if(a.type===`user`)n++;else if(a.type===`tool`){let e=a.data,n=t.get(e.toolCallId??``),o=n?.name??`tool`,s=n?.firstArg??``;r++,i.set(`${o}:${s}`,{toolName:o,displayArg:s})}}return{turnCount:n,toolResults:[...i.values()],totalToolCallCount:r}}function $n(e,t,n){let r=`${e}${t>0?` — ~${t.toLocaleString()} tokens`:``}:`;return n.length===0?`${r}\n (none)`:[r,...n.map(e=>` ${e}`)].join(`
13
+ `)}function er(e){let t=yt(e),n=p(e),r=m(e),i=Zn(e.getSession().getHistory()),a=Qn(e.getSession().getFullHistory()),o=lt(e),s=o.filter(e=>e.loadType===`system`),c=o.filter(e=>e.loadType===`manual`),l=o.filter(e=>e.loadType===`prompt-reference`),ee=s.reduce((e,t)=>e+T(t.byteLength),0),te=c.reduce((e,t)=>e+T(t.byteLength),0),ne=l.reduce((e,t)=>e+T(t.byteLength),0),re=a.turnCount===0?`Conversation history — 0 turns`:`Conversation history — ${a.turnCount} turn${a.turnCount===1?``:`s`} | ~${i.totalTokens.toLocaleString()} tokens`,ie=a.toolResults.map(e=>`${e.toolName}${e.displayArg?`: ${e.displayArg}`:``}`),u=a.toolResults.length,d=a.totalToolCallCount,f=d===0?`Tool results (0): (none)`:u<d?`Tool results (${u} unique / ${d} calls, ~${i.toolTokens.toLocaleString()} tokens):`:`Tool results (${u}, ~${i.toolTokens.toLocaleString()} tokens):`,ae=a.turnCount===0?[]:[`User (${i.userCount}): ~${i.userTokens.toLocaleString()} tokens`,`Assistant (${i.assistantCount}): ~${i.assistantTokens.toLocaleString()} tokens`,...i.systemTokens>0?[`System messages: ~${i.systemTokens.toLocaleString()} tokens`]:[],d>0?[f,...ie.map(e=>` ${e}`)].join(`
14
14
  `):f],oe=a.turnCount===0?`${re}:\n (none)`:[`${re}:`,...ae.map(e=>` ${e}`)].join(`
15
- `);return{success:!0,message:[`Context: ${t.usedTokens.toLocaleString()} / ${t.maxTokens.toLocaleString()} tokens (${Math.round(t.usedPercentage)}%)`,Nn(n,r),``,Jn(`System prompt (active every turn)`,ee,s.map(D)),``,oe,``,Jn(`Manually added`,te,c.map(D)),``,Jn(`Prompt references (@-syntax)`,ne,l.map(D))].join(`
16
- `),data:{references:o,history:{turnCount:a.turnCount,toolResults:a.toolResults}}}}function O(){return{name:`context`,displayName:`Context References`,description:`Context window info, reference inventory, and auto-compact controls`,source:`context`,modelInvocable:!1,argumentHint:`list | add <path> | remove <path> | clear | auto ...`,subcommands:[{name:`list`,description:`List loaded context references`,source:`context`},{name:`add`,description:`Add a file to active context references`,source:`context`},{name:`remove`,description:`Remove a context reference`,source:`context`},{name:`clear`,description:`Clear context references`,source:`context`},{name:`auto`,description:`Inspect or change auto-compact policy`,source:`context`}]}}function Xn(){let e=O();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,execute:Fn}}var Zn=class{name=`context`;getCommands(){return[O()]}};function Qn(){return{name:`agent-command-context`,commandSources:[new Zn],systemCommands:[Xn()]}}function $n(e,t){return{success:!0,message:`Exit requested.`,effects:[ze()]}}function k(){return{name:`exit`,displayName:`Exit Session`,description:c,source:`exit`,modelInvocable:!1}}function er(){let e=k();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:$n}}var tr=class{name=`exit`;getCommands(){return[k()]}};const nr={exit:{type:`confirm`,message:`Exit the session?`}};function rr(){return{name:`agent-command-exit`,commandSources:[new tr],systemCommands:[er()],interactionHints:nr}}function ir(e,t){return{success:!0,message:Ke(e)}}function A(){return{name:`help`,displayName:`Help`,description:l,source:`help`,modelInvocable:!1}}function ar(){let e=A();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:ir}}var or=class{name=`help`;getCommands(){return[A()]}};function sr(){return{name:`agent-command-help`,commandSources:[new or],systemCommands:[ar()]}}function cr(e,t){let n=pt(t);return n===void 0?{message:Xe(),success:!1}:{message:`Language set to "${n}".`,success:!0,data:{language:n},effects:[{type:`language-change-requested`,language:n}]}}function j(){return{name:`language`,displayName:`Language`,description:te,source:`language`,argumentHint:ee,subcommands:we(`language`),modelInvocable:!1}}function lr(){let e=j();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:cr}}var ur=class{name=`language`;getCommands(){return[j()]}};const dr={language:{type:`pick`,getItems:()=>we().map(e=>({label:`${e.name} ${e.description??``}`.trimEnd(),value:e.name,description:e.description}))}};function fr(){return{name:`agent-command-language`,commandSources:[new ur],systemCommands:[lr()],interactionHints:dr}}function M(){return{message:ie,success:!1}}function pr(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function mr(e){let t=e.list(),n=t.topics.length>0?t.topics.map(e=>`- ${e.name}: ${e.path}`).join(`
15
+ `);return{success:!0,message:[`Context: ${t.usedTokens.toLocaleString()} / ${t.maxTokens.toLocaleString()} tokens (${Math.round(t.usedPercentage)}%)`,Rn(n,r),``,$n(`System prompt (active every turn)`,ee,s.map(E)),``,oe,``,$n(`Manually added`,te,c.map(E)),``,$n(`Prompt references (@-syntax)`,ne,l.map(E))].join(`
16
+ `),data:{references:o,history:{turnCount:a.turnCount,toolResults:a.toolResults}}}}function tr(){return{name:`context`,displayName:`Context References`,description:`Context window info, reference inventory, and auto-compact controls`,source:`context`,modelInvocable:!1,argumentHint:`list | add <path> | remove <path> | clear | auto ...`,subcommands:[{name:`list`,description:`List loaded context references`,source:`context`},{name:`add`,description:`Add a file to active context references`,source:`context`},{name:`remove`,description:`Remove a context reference`,source:`context`},{name:`clear`,description:`Clear context references`,source:`context`},{name:`auto`,description:`Inspect or change auto-compact policy`,source:`context`}]}}function nr(){let e=tr();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,execute:Bn}}var rr=class{name=`context`;getCommands(){return[tr()]}};function ir(){return{name:`agent-command-context`,commandSources:[new rr],systemCommands:[nr()]}}function ar(e,t){return{success:!0,message:`Exit requested.`,effects:[Ve()]}}function D(){return{name:`exit`,displayName:`Exit Session`,description:c,source:`exit`,modelInvocable:!1}}function or(){let e=D();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:ar}}var sr=class{name=`exit`;getCommands(){return[D()]}};const cr={exit:{type:`confirm`,message:`Exit the session?`}};function lr(){return{name:`agent-command-exit`,commandSources:[new sr],systemCommands:[or()],interactionHints:cr}}function ur(e,t){return{success:!0,message:Je(e)}}function O(){return{name:`help`,displayName:`Help`,description:l,source:`help`,modelInvocable:!1}}function dr(){let e=O();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:ur}}var fr=class{name=`help`;getCommands(){return[O()]}};function pr(){return{name:`agent-command-help`,commandSources:[new fr],systemCommands:[dr()]}}function mr(e,t){let n=ht(t);return n===void 0?{message:Qe(),success:!1}:{message:`Language set to "${n}".`,success:!0,data:{language:n},effects:[{type:`language-change-requested`,language:n}]}}function k(){return{name:`language`,displayName:`Language`,description:te,source:`language`,argumentHint:ee,subcommands:Te(`language`),modelInvocable:!1}}function hr(){let e=k();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:mr}}var gr=class{name=`language`;getCommands(){return[k()]}};const _r={language:{type:`pick`,getItems:()=>Te().map(e=>({label:`${e.name} ${e.description??``}`.trimEnd(),value:e.name,description:e.description}))}};function vr(){return{name:`agent-command-language`,commandSources:[new gr],systemCommands:[hr()],interactionHints:_r}}function A(){return{message:ie,success:!1}}function yr(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function br(e){let t=e.list(),n=t.topics.length>0?t.topics.map(e=>`- ${e.name}: ${e.path}`).join(`
17
17
  `):`(none)`;return{message:[`Memory index: ${t.indexPath}`,`Topics directory: ${t.topicsPath}`,`Topics:`,n].join(`
18
- `),success:!0,data:{indexPath:t.indexPath,topicsPath:t.topicsPath,topicCount:t.topics.length}}}function hr(e,t){if(!t||t===`index`){let t=e.loadStartupMemory();return{message:t.content||`(empty memory index)`,success:!0,data:{path:t.path,lineCount:t.lineCount,truncated:t.truncated}}}return{message:e.readTopic(t)||`(empty memory topic: ${t})`,success:!0,data:{topic:t}}}function gr(e){let t=e[1],n=e[2],r=e.slice(3).join(` `).trim();if(!(!t||!it(t)||!n||r.length===0))return{type:t,topic:n,text:r}}function _r(e){let t=e.list(`pending`);return{message:[`Pending memory candidates:`,...t.length>0?t.map(e=>`- ${e.id} ${e.type}/${e.topic} confidence=${e.confidence}: ${e.text}`):[`(no pending memory candidates)`]].join(`
19
- `),success:!0,data:{count:t.length}}}function N(e,t){Ct(e,t)}function vr(e,t,n,r){if(!r)return M();try{let i=t.mark(r,`approved`,`approved-by-user`),a=n.append(i),o=t.mark(r,`saved`,`approved-and-saved`);return N(e,{type:`memory_candidate_approved`,candidateId:o.id,topic:o.topic,reason:`approved-by-user`}),N(e,{type:`memory_candidate_saved`,candidateId:o.id,topic:o.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:o.status,topic:a.topic,topicPath:a.topicPath,deduplicated:a.deduplicated}}}catch(e){return pr(e instanceof Error?e:String(e))}}function yr(e,t,n){if(!n)return M();try{let r=t.mark(n,`rejected`,`rejected-by-user`);return N(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 pr(e instanceof Error?e:String(e))}}function br(e){let t=lt(e);return{message:[`Used memory references:`,...t.length>0?t.map(e=>{let t=e.truncated?` truncated=true`:``;return`- ${e.topic} score=${e.score}${t}: ${e.path}`}):[`(no memory used in current turn)`]].join(`
20
- `),success:!0,data:{count:t.length,references:[...t]}}}function xr(e,t){let n=t.trim().split(/\s+/).filter(Boolean),r=n[0]??`list`,i=Ie(e);if(r===`list`)return mr(i.project);if(r===`show`)return hr(i.project,n[1]);if(r===`pending`)return _r(i.pending);if(r===`approve`)return vr(e,i.pending,i.project,n[1]);if(r===`reject`)return yr(e,i.pending,n[1]);if(r===`used`)return br(e);if(r===`add`){let e=gr(n);if(!e)return M();if($e(e.text))return{message:`Refusing to save sensitive memory content.`,success:!1};let t=i.project.append(e);return{message:t.deduplicated?`${e.type} memory already exists in ${t.topicPath}`:`Saved ${e.type} memory to ${t.topicPath}`,success:!0,data:{indexPath:t.indexPath,topicPath:t.topicPath,topic:t.topic,deduplicated:t.deduplicated}}}return M()}function P(){return{name:`memory`,displayName:`Memory`,description:re,source:`memory`,argumentHint:ne,modelInvocable:!0,safety:`write`,subcommands:Te()}}function Sr(){let e=P();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,subcommands:e.subcommands,execute:xr}}var Cr=class{name=`memory`;getCommands(){return[P()]}};function wr(){return{name:`agent-command-memory`,commandSources:[new Cr],systemCommands:[Sr()]}}function Tr(e,t){let n=mt(t);if(n===void 0){let t=vt(e);return{message:`Current mode: ${t}`,success:!0,data:{mode:t}}}return at(n)?(Vt(e,n),{message:`Permission mode set to: ${n}`,success:!0,data:{mode:n}}):{message:Ye(),success:!1}}function F(){return{name:`mode`,displayName:`Interaction Mode`,description:ae,source:`mode`,argumentHint:f,subcommands:p(`mode`),modelInvocable:!1}}function Er(){let e=F();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:Tr}}var Dr=class{name=`mode`;getCommands(){return[F()]}};const Or={mode:{type:`pick`,getItems:()=>p().map(e=>({label:e.name,value:e.name,description:e.description}))}};function kr(){return{name:`agent-command-mode`,commandSources:[new Dr],systemCommands:[Er()],interactionHints:Or}}function Ar(e,t){let n=mt(t);if(n!==void 0){if(!at(n))return{message:Ye(),success:!1};Vt(e,n);let t=yt(e);return{message:`Permission mode set to: ${n}\n${qe(t)}`,success:!0,data:{mode:t.mode,sessionAllowed:t.sessionAllowed}}}let r=yt(e);return{message:qe(r),success:!0,data:{mode:r.mode,sessionAllowed:r.sessionAllowed}}}function I(){return{name:`permissions`,displayName:`Permissions`,description:d,source:`permissions`,argumentHint:f,subcommands:p(`permissions`),modelInvocable:!1}}function jr(){let e=I();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:Ar}}var Mr=class{name=`permissions`;getCommands(){return[I()]}};function Nr(){return{name:`agent-command-permissions`,commandSources:[new Mr],systemCommands:[jr()]}}function Pr(e){let t=e.trim().split(/\s+/).filter(e=>e.length>0);return{subcommand:t[0]??``,subArgs:t.slice(1).join(` `).trim()}}function L(e){return{success:!1,message:e}}function Fr(e){return Dt(e)}async function R(e,t){let n=Fr(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 Ir(e,t){let{subcommand:n,subArgs:r}=Pr(t);return n===`add`&&r.length>0?R(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?R(e,async e=>(await e.marketplaceRemove(r),`Removed marketplace "${r}" and uninstalled its plugins.`)):n===`update`&&r.length>0?R(e,async e=>(await e.marketplaceUpdate(r),`Updated marketplace "${r}".`)):n===`list`?R(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(`
21
- `)}`}):L(`Usage: /plugin marketplace add <source> | remove <name> | update <name> | list`)}function z(e,t,n,r){return t.length===0?Promise.resolve(L(n)):R(e,e=>Promise.resolve(r(e,t)))}function Lr(){return{success:!0,message:`Opening plugin manager...`,effects:[Re()]}}function Rr(e,t){return z(e,t,`Usage: /plugin install <name>@<marketplace>`,async(e,t)=>(await e.install(t),`Installed plugin: ${t}`))}function zr(e,t){return z(e,t,`Usage: /plugin uninstall <name>@<marketplace>`,async(e,t)=>(await e.uninstall(t),`Uninstalled plugin: ${t}`))}function Br(e,t){return z(e,t,`Usage: /plugin enable <name>@<marketplace>`,async(e,t)=>(await e.enable(t),`Enabled plugin: ${t}`))}function Vr(e,t){return z(e,t,`Usage: /plugin disable <name>@<marketplace>`,async(e,t)=>(await e.disable(t),`Disabled plugin: ${t}`))}async function Hr(e,t){let{subcommand:n,subArgs:r}=Pr(t);switch(n){case``:case`manage`:return Lr();case`install`:return Rr(e,r);case`uninstall`:return zr(e,r);case`enable`:return Br(e,r);case`disable`:return Vr(e,r);case`marketplace`:return Ir(e,r);default:return L(`Unknown plugin subcommand: ${n}`)}}async function Ur(e,t){return R(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,effects:[Le()]}:e)}function B(){return{name:`plugin`,displayName:`Plugins`,description:se,source:`plugin-manager`,modelInvocable:!1,argumentHint:oe,subcommands:Ee()}}function V(){return{name:`reload-plugins`,displayName:`Reload Plugins`,description:de,source:`plugin-manager`,modelInvocable:!1}}function Wr(){let e=B();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:Hr}}function Gr(){let e=V();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Ur}}var Kr=class{name=`plugin-manager`;getCommands(){return[B(),V()]}};function qr(){return{name:`agent-command-plugin`,commandSources:[new Kr],systemCommands:[Wr(),Gr()]}}function H(e,t,n={}){let r=ti(e,t);return{type:e,steps:ii(ni(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 Jr(e){return e.length===0?` No providers are available.`:[` Select provider:`,...e.map((e,t)=>` ${t+1}. ${G(e)}`),` Provider [1-${e.length}] (default: 1): `].join(`
22
- `)}function Yr(e,t){let n=e.trim(),r=n.length>0?n:`1`,i=$r(r);if(i!==void 0){let e=t[i];if(e!==void 0)return e.type;throw Error(`Provider selection ${r} is out of range. Currently supported: ${g(t)}`)}let a=Ut(t,r);if(a===void 0)throw Error(`Unknown provider: ${r}. Currently supported: ${g(t)}`);return a.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 W(e,t){let n=U(e),r=t.trim()||n.defaultValue||``,i=ei(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:ai(a)}}async function Xr(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(Zr(e,i.setupHelpLinks),e.masked===!0),r=W(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 Zr(e,t=[]){let n=e.defaultValue===void 0?``:` (default: ${e.defaultValue})`,r=K(t);return`${r.length>0?`${r}\n`:``} ${e.title}${n}: `}const Qr={"cloud-paid":`[Cloud/Paid]`,"cloud-free":`[Cloud/Free]`,"local-free":`[Local/Free]`};function G(e){let t=`${e.category===void 0?``:`${Qr[e.category]??``} `}${e.displayName===void 0?e.type:`${e.displayName} (${e.type})`}`;return e.description===void 0?t:`${t} — ${e.description}`}function K(e=[]){return e.length===0?``:e.map(e=>` Setup help: ${ri(e.kind)}: ${e.label} - ${e.url}`).join(`
23
- `)}function $r(e){if(/^\d+$/.test(e))return Number(e)-1}function ei(e,t){if(e.required===!0&&t.length===0)return`Required`}function ti(e,t){let n=Ut(t,e);if(n===void 0)throw Error(`Unknown provider: ${e}. Currently supported: ${g(t)}`);return n}function ni(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 ri(e){return e===`api-key`?`API key`:e===`console`?`Console`:`Official`}function ii(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 ai(e){let t=e.profileName??Ft({type:e.type},{existingProfileNames:e.existingProfileNames}),n=e.values.apiKey;return{profile:t,type:e.type,model:e.values.model,...n!==void 0&&n.length>0&&{apiKey:n},...e.values.baseURL!==void 0&&{baseURL:e.values.baseURL},setCurrent:e.setCurrent??!0}}const oi={type:`session-restart-requested`,reason:`other`};function si(e,t){return H(e,t.providerDefinitions,{existingProfileNames:Object.keys(t.settings.readMergedSettings().providers??{})})}function q(e,t){return{prompt:ci(e),submit:n=>ui(e,n,t),cancel:()=>({message:`Provider setup cancelled.`,success:!0})}}function ci(e){let t=U(e),n=t.masked===!0&&t.defaultValue!==void 0?`(unchanged)`:t.defaultValue;return{kind:`text`,title:t.title,...li(e),...n===void 0?{}:{placeholder:n},...t.defaultValue===void 0?{}:{allowEmpty:!0},...t.masked===void 0?{}:{masked:t.masked},validate:e=>ei(t,e)}}function li(e){let t=K(e.setupHelpLinks);return t.length>0?{description:t}:{}}function ui(e,t,n){let r=W(e,t);return r.status===`error`?{message:r.message,success:!1,interaction:q(e,n)}:r.status===`complete`?di(r.input,n):{message:``,success:!0,interaction:q(r.state,n)}}function di(e,t){let n=t.settings.readTargetSettings(),r=De(e,{providerDefinitions:t.providerDefinitions});return t.settings.writeTargetSettings(dt(n,r)),{message:`Provider ${e.profile} configured. Restarting...`,success:!0,effects:[{...oi,message:`Provider setup restart`}]}}function fi(e,t,n){return`${e===n?`* `:``}${e}: ${t.type??`unknown`} ${t.model??`(no model)`}`}function pi(e,t,n){if(!t)return{message:`Usage: /provider switch <profile>`,success:!1};if(!e?.[t])return{message:`Provider profile "${t}" was not found.`,success:!1};let{orgPolicy:r}=n;if(r?.allowedProviders&&!r.allowedProviders.includes(t))return{message:Ze(`Provider "${t}" is not allowed by your organization policy. Allowed: ${r.allowedProviders.join(`, `)}.`,r.adminContact),success:!1};if(n.settings.readMergedSettings().currentProvider===t)return{message:`Already using provider "${t}".`,success:!0};let i=e[t],a=n.settings.readTargetSettings(),o=n.settings.readMergedSettings(),s=a.providers?.[t]!==void 0||o.providers?.[t]!==void 0?{...a,currentProvider:t}:Nt(a,t);return n.settings.writeTargetSettings(s),{message:`Switched to ${t} (${i.model??`unknown model`}). History preserved.`,success:!0,effects:[{type:`provider-hot-swap-requested`,profileName:t}]}}function mi(e,t){let n=t.settings.readMergedSettings().providers?.[e];if(!n)return{message:`Provider profile "${e}" was not found.`,success:!1};if(!n.type)return{message:`Provider profile "${e}" is missing type.`,success:!1};try{let r=H(n.type,t.providerDefinitions,{profileName:e,setCurrent:!1,initialValues:hi(n)});return{message:`Provider edit requested: ${e}`,success:!0,interaction:gi(r,e,t)}}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}}function hi(e){return{...typeof e.model==`string`?{model:e.model}:{},...typeof e.apiKey==`string`?{apiKey:e.apiKey}:{},...typeof e.baseURL==`string`?{baseURL:e.baseURL}:{}}}function gi(e,t,n){return{prompt:ci(e),submit:r=>_i(e,t,r,n),cancel:()=>({message:`Provider edit cancelled.`,success:!0})}}function _i(e,t,n,r){let i=W(e,n);return i.status===`error`?{message:i.message,success:!1,interaction:gi(e,t,r)}:i.status===`complete`?vi(i.input,t,r):{message:``,success:!0,interaction:gi(i.state,t,r)}}function vi(e,t,n){let r=n.settings.readMergedSettings(),i=r.providers?.[t];if(!i)return{message:`Provider profile "${t}" was not found.`,success:!1};let{orgPolicy:a}=n;if(a?.requireApiKeyFromEnv&&rt(e.apiKey))return{message:Ze(`Your organization policy requires API keys to be stored as environment variable references ($ENV:VAR_NAME), not as plaintext.`,a.adminContact),success:!1};let o=n.settings.readTargetSettings(),s=De(e,{providerDefinitions:n.providerDefinitions}).providers[t];if(!s)return{message:`Provider profile "${t}" was not updated.`,success:!1};n.settings.writeTargetSettings(Rt(o,t,{...i,...s}));let c=r.currentProvider===t;return{message:c?`Provider ${t} updated. Switching...`:`Provider ${t} updated.`,success:!0,...c?{effects:[{type:`provider-hot-swap-requested`,profileName:t}]}:{}}}const yi={type:`session-restart-requested`,reason:`other`};function bi(e,t){let n=t.settings.readMergedSettings();if(!n.providers?.[e])return{message:`Provider profile "${e}" was not found.`,success:!1};let r=Oi(e,Object.keys(n.providers));return{message:`Provider duplicate requested: ${e}`,success:!0,interaction:xi(e,r,t)}}function xi(e,t,n){return{prompt:{kind:`text`,title:`Duplicate ${e} as`,placeholder:t,allowEmpty:!0,validate:e=>Si(e,t,n)},submit:r=>Ci(e,r,t,n),cancel:()=>({message:`Provider duplicate cancelled.`,success:!0})}}function Si(e,t,n){let r=ki(e,t);if(r.length===0)return`Required`;if(n.settings.readMergedSettings().providers?.[r]!==void 0)return`Provider profile "${r}" already exists`}function Ci(e,t,n,r){let i=r.settings.readMergedSettings().providers?.[e];if(!i)return{message:`Provider profile "${e}" was not found.`,success:!1};let a=ki(t,n),o=Si(a,n,r);return o===void 0?(r.settings.writeTargetSettings(Rt(r.settings.readTargetSettings(),a,{...i})),{message:`Provider profile duplicated: ${e} -> ${a}.`,success:!0}):{message:o,success:!1}}function wi(e,t){let n=t.settings.readMergedSettings().providers??{};return n[e]?Object.keys(n).length<=1?{message:`Cannot delete the only provider profile.`,success:!1}:t.settings.readTargetSettings().providers?.[e]===void 0?{message:`Provider profile "${e}" is not stored in the active write target; edit its source settings file or override it before deleting.`,success:!1}:{message:`Provider delete requested: ${e}`,success:!0,interaction:Ti(e,t)}:{message:`Provider profile "${e}" was not found.`,success:!1}}function Ti(e,t){return{prompt:{kind:`choice`,title:`Delete provider profile ${e}?`,options:[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}]},submit:n=>n===`yes`?Ei(e,t):{message:`Provider delete cancelled.`,success:!0},cancel:()=>({message:`Provider delete cancelled.`,success:!0})}}function Ei(e,t){let n=t.settings.readMergedSettings();if(n.currentProvider!==e)return t.settings.writeTargetSettings(He(t.settings.readTargetSettings(),e)),{message:`Provider profile deleted: ${e}.`,success:!0};let r=Object.entries(n.providers??{}).filter(([t])=>t!==e).map(([e,t])=>({value:e,label:fi(e,t,n.currentProvider)}));return{message:`Select a replacement provider before deleting ${e}.`,success:!0,interaction:{prompt:{kind:`choice`,title:`Replacement provider for ${e}`,options:r,maxVisible:8},submit:n=>Di(e,n,t),cancel:()=>({message:`Provider delete cancelled.`,success:!0})}}}function Di(e,t,n){if(n.settings.readMergedSettings().providers?.[t]===void 0||t===e)return{message:`Provider profile "${t}" was not found.`,success:!1};let r=He(n.settings.readTargetSettings(),e);return n.settings.writeTargetSettings({...r,currentProvider:t}),{message:`Provider profile deleted: ${e}. Restarting with ${t}...`,success:!0,effects:[{...yi,message:`Provider delete restart`}]}}function Oi(e,t){let n=jt(`${e}-copy`)??`provider-copy`;if(!t.includes(n))return n;for(let e=2;e<1e3;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return`${n}-${Date.now()}`}function ki(e,t){return jt(e.trim()||t)??``}const Ai=`switch`,ji=`edit`,Mi=`test`,Ni=`duplicate`,Pi=`delete`,Fi=`cancel`;function Ii(e,t,n){return{prompt:{kind:`choice`,title:`Select provider profile`,options:Object.entries(t??{}).map(([t,n])=>({value:t,label:fi(t,n,e)})),maxVisible:8},submit:e=>Li(e,n),cancel:()=>({message:`Provider profile selection cancelled.`,success:!0})}}function Li(e,t){return t.settings.readMergedSettings().providers?.[e]?{message:`Provider profile selected: ${e}`,success:!0,interaction:Ri(e,t)}:{message:`Provider profile "${e}" was not found.`,success:!1}}function Ri(e,t){return{prompt:{kind:`choice`,title:`Provider profile: ${e}`,options:[{value:Ai,label:`Switch`},{value:ji,label:`Edit`},{value:Mi,label:`Test`},{value:Ni,label:`Duplicate`},{value:Pi,label:`Delete`},{value:Fi,label:`Cancel`}]},submit:n=>zi(e,n,t),cancel:()=>({message:`Provider profile action cancelled.`,success:!0})}}async function zi(e,t,n){let r=n.settings.readMergedSettings();switch(t){case Ai:return pi(r.providers,e,n);case ji:return mi(e,n);case Mi:return await Lt(r.currentProvider,r.providers,e,n);case Ni:return bi(e,n);case Pi:return wi(e,n);case Fi:return{message:`Provider profile action cancelled.`,success:!0};default:return{message:`Unknown provider profile action "${t}".`,success:!1}}}async function Bi(e,t){let n=t.settings.readMergedSettings(),r=e.trim();if(r.length===0)return Vi(n.currentProvider,n.providers,t);let[i=`current`,a]=r.split(/\s+/);return i===`list`?Vi(n.currentProvider,n.providers,t):i===`current`||i===``?{message:Ui(n.currentProvider,n.providers),success:!0}:i===`switch`?pi(n.providers,a,t):i===`test`?await Lt(n.currentProvider,n.providers,a,t):i===`add`?Wi(a,t):{message:`Usage: provider [current|list|switch <profile>|add <type>|test [profile]]`,success:!1}}function Vi(e,t,n){let r=Hi(e,t);return Object.keys(t??{}).length===0?{message:r,success:!0}:{message:r,success:!0,interaction:Ii(e,t,n)}}function Hi(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(`
24
- `)}function Ui(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(`
25
- `):`Current provider "${e}" was not found in providers.`}function Wi(e,t){return e===void 0||e.length===0?{message:`Provider setup requested. Select a provider to continue.`,success:!0,interaction:Gi(t)}:Ut(t.providerDefinitions,e)===void 0?{message:`Usage: provider add <type>. Supported: ${g(t.providerDefinitions)}`,success:!1}:{message:`Provider setup requested: ${e}`,success:!0,interaction:q(si(e,t),t)}}function Gi(e){return{prompt:{kind:`choice`,title:`Select provider`,options:e.providerDefinitions.map(e=>({value:e.type,label:G(e)})),maxVisible:6},submit:t=>{let n=si(t,e);return{message:`Provider setup requested: ${t}`,success:!0,interaction:q(n,e)}},cancel:()=>({message:`Provider setup cancelled.`,success:!0})}}function Ki(){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 qi(){return{name:`provider`,displayName:`Provider Setup`,description:`Manage provider profiles`,source:`provider`,modelInvocable:!1,argumentHint:`current | list | switch <profile> | add [type] | test [profile]`,subcommands:Ki(),example:`/provider switch production`}}var Ji=class{name=`provider`;getCommands(){return[qi()]}};function Yi(e){let t=qi();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,execute:async(t,n)=>Bi(n,e)}}const Xi={provider:{type:`pick`,getItems:()=>Ki().map(e=>({label:e.name,value:e.name,description:e.description}))}};function Zi(e){return{name:`agent-command-provider`,commandSources:[new Ji],systemCommands:[Yi(e)],interactionHints:Xi}}async function Qi(e,t){let n=(await e(`
18
+ `),success:!0,data:{indexPath:t.indexPath,topicsPath:t.topicsPath,topicCount:t.topics.length}}}function xr(e,t){if(!t||t===`index`){let t=e.loadStartupMemory();return{message:t.content||`(empty memory index)`,success:!0,data:{path:t.path,lineCount:t.lineCount,truncated:t.truncated}}}return{message:e.readTopic(t)||`(empty memory topic: ${t})`,success:!0,data:{topic:t}}}function Sr(e){let t=e[1],n=e[2],r=e.slice(3).join(` `).trim();if(!(!t||!ot(t)||!n||r.length===0))return{type:t,topic:n,text:r}}function Cr(e){let t=e.list(`pending`);return{message:[`Pending memory candidates:`,...t.length>0?t.map(e=>`- ${e.id} ${e.type}/${e.topic} confidence=${e.confidence}: ${e.text}`):[`(no pending memory candidates)`]].join(`
19
+ `),success:!0,data:{count:t.length}}}function j(e,t){Tt(e,t)}function wr(e,t,n,r){if(!r)return A();try{let i=t.mark(r,`approved`,`approved-by-user`),a=n.append(i),o=t.mark(r,`saved`,`approved-and-saved`);return j(e,{type:`memory_candidate_approved`,candidateId:o.id,topic:o.topic,reason:`approved-by-user`}),j(e,{type:`memory_candidate_saved`,candidateId:o.id,topic:o.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:o.status,topic:a.topic,topicPath:a.topicPath,deduplicated:a.deduplicated}}}catch(e){return yr(e instanceof Error?e:String(e))}}function Tr(e,t,n){if(!n)return A();try{let r=t.mark(n,`rejected`,`rejected-by-user`);return j(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 yr(e instanceof Error?e:String(e))}}function Er(e){let t=dt(e);return{message:[`Used memory references:`,...t.length>0?t.map(e=>{let t=e.truncated?` truncated=true`:``;return`- ${e.topic} score=${e.score}${t}: ${e.path}`}):[`(no memory used in current turn)`]].join(`
20
+ `),success:!0,data:{count:t.length,references:[...t]}}}function Dr(e,t){let n=t.trim().split(/\s+/).filter(Boolean),r=n[0]??`list`,i=Re(e);if(r===`list`)return br(i.project);if(r===`show`)return xr(i.project,n[1]);if(r===`pending`)return Cr(i.pending);if(r===`approve`)return wr(e,i.pending,i.project,n[1]);if(r===`reject`)return Tr(e,i.pending,n[1]);if(r===`used`)return Er(e);if(r===`add`){let e=Sr(n);if(!e)return A();if(tt(e.text))return{message:`Refusing to save sensitive memory content.`,success:!1};let t=i.project.append(e);return{message:t.deduplicated?`${e.type} memory already exists in ${t.topicPath}`:`Saved ${e.type} memory to ${t.topicPath}`,success:!0,data:{indexPath:t.indexPath,topicPath:t.topicPath,topic:t.topic,deduplicated:t.deduplicated}}}return A()}function M(){return{name:`memory`,displayName:`Memory`,description:re,source:`memory`,argumentHint:ne,modelInvocable:!0,safety:`write`,subcommands:Ee()}}function Or(){let e=M();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,subcommands:e.subcommands,execute:Dr}}var kr=class{name=`memory`;getCommands(){return[M()]}};function Ar(){return{name:`agent-command-memory`,commandSources:[new kr],systemCommands:[Or()]}}function jr(e,t){let n=gt(t);if(n===void 0){let t=bt(e);return{message:`Current mode: ${t}`,success:!0,data:{mode:t}}}return st(n)?(Ut(e,n),{message:`Permission mode set to: ${n}`,success:!0,data:{mode:n}}):{message:Ze(),success:!1}}function N(){return{name:`mode`,displayName:`Interaction Mode`,description:ae,source:`mode`,argumentHint:f,subcommands:De(`mode`),modelInvocable:!1}}function Mr(){let e=N();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:jr}}var Nr=class{name=`mode`;getCommands(){return[N()]}};const Pr={mode:{type:`pick`,getItems:()=>De().map(e=>({label:e.name,value:e.name,description:e.description}))}};function Fr(){return{name:`agent-command-mode`,commandSources:[new Nr],systemCommands:[Mr()],interactionHints:Pr}}function Ir(e,t){let n=gt(t);if(n!==void 0){if(!st(n))return{message:Ze(),success:!1};Ut(e,n);let t=xt(e);return{message:`Permission mode set to: ${n}\n${Ye(t)}`,success:!0,data:{mode:t.mode,sessionAllowed:t.sessionAllowed}}}let r=xt(e);return{message:Ye(r),success:!0,data:{mode:r.mode,sessionAllowed:r.sessionAllowed}}}function P(){return{name:`permissions`,displayName:`Permissions`,description:d,source:`permissions`,argumentHint:f,subcommands:De(`permissions`),modelInvocable:!1}}function Lr(){let e=P();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:Ir}}var Rr=class{name=`permissions`;getCommands(){return[P()]}};function zr(){return{name:`agent-command-permissions`,commandSources:[new Rr],systemCommands:[Lr()]}}function Br(e){let t=e.trim().split(/\s+/).filter(e=>e.length>0);return{subcommand:t[0]??``,subArgs:t.slice(1).join(` `).trim()}}function F(e){return{success:!1,message:e}}function Vr(e){return kt(e)}async function I(e,t){let n=Vr(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 Hr(e,t){let{subcommand:n,subArgs:r}=Br(t);return n===`add`&&r.length>0?I(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?I(e,async e=>(await e.marketplaceRemove(r),`Removed marketplace "${r}" and uninstalled its plugins.`)):n===`update`&&r.length>0?I(e,async e=>(await e.marketplaceUpdate(r),`Updated marketplace "${r}".`)):n===`list`?I(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(`
21
+ `)}`}):F(`Usage: /plugin marketplace add <source> | remove <name> | update <name> | list`)}function L(e,t,n,r){return t.length===0?Promise.resolve(F(n)):I(e,e=>Promise.resolve(r(e,t)))}function Ur(){return{success:!0,message:`Opening plugin manager...`,effects:[Be()]}}function Wr(e,t){return L(e,t,`Usage: /plugin install <name>@<marketplace>`,async(e,t)=>(await e.install(t),`Installed plugin: ${t}`))}function Gr(e,t){return L(e,t,`Usage: /plugin uninstall <name>@<marketplace>`,async(e,t)=>(await e.uninstall(t),`Uninstalled plugin: ${t}`))}function Kr(e,t){return L(e,t,`Usage: /plugin enable <name>@<marketplace>`,async(e,t)=>(await e.enable(t),`Enabled plugin: ${t}`))}function qr(e,t){return L(e,t,`Usage: /plugin disable <name>@<marketplace>`,async(e,t)=>(await e.disable(t),`Disabled plugin: ${t}`))}async function Jr(e,t){let{subcommand:n,subArgs:r}=Br(t);switch(n){case``:case`manage`:return Ur();case`install`:return Wr(e,r);case`uninstall`:return Gr(e,r);case`enable`:return Kr(e,r);case`disable`:return qr(e,r);case`marketplace`:return Hr(e,r);default:return F(`Unknown plugin subcommand: ${n}`)}}async function Yr(e,t){return I(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,effects:[ze()]}:e)}function R(){return{name:`plugin`,displayName:`Plugins`,description:se,source:`plugin-manager`,modelInvocable:!1,argumentHint:oe,subcommands:Oe()}}function z(){return{name:`reload-plugins`,displayName:`Reload Plugins`,description:de,source:`plugin-manager`,modelInvocable:!1}}function Xr(){let e=R();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:Jr}}function Zr(){let e=z();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Yr}}var Qr=class{name=`plugin-manager`;getCommands(){return[R(),z()]}};function $r(){return{name:`agent-command-plugin`,commandSources:[new Qr],systemCommands:[Xr(),Zr()]}}function ei(e){return e.getSession().getActivePresetId?.()??`default`}function ti(e){return[`Available presets:`,...h().map(t=>`${t.id===e?`* `:` `}${t.id} — ${t.title}: ${t.description}`)].join(`
22
+ `)}function ni(e){return`Unknown preset: ${e}. Available: ${h().map(e=>e.id).join(`, `)}`}function ri(e,t){let n=t.trim().split(/\s+/)[0];if(n===void 0||n.length===0||n===`list`){let t=ei(e);return{message:ti(t),success:!0,data:{presets:h(),active:t}}}return Gt(n)===void 0?{message:ni(n),success:!1}:(Se(e,n,Kt(n)),{message:`Switched to preset: ${n}`,success:!0,data:{preset:n}})}function ii(e=`preset`){return h().map(t=>({name:t.id,description:t.description,source:e}))}function B(){return{name:`preset`,displayName:`Agent Preset`,description:`List presets or switch the active preset`,source:`preset`,argumentHint:`list | <preset-id>`,subcommands:ii(`preset`),modelInvocable:!1}}function ai(){let e=B();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:ri}}var oi=class{name=`preset`;getCommands(){return[B()]}};const si={preset:{type:`pick`,getItems:()=>ii().map(e=>({label:e.name,value:e.name,description:e.description}))}};function ci(){return{name:`agent-command-preset`,commandSources:[new oi],systemCommands:[ai()],interactionHints:si}}function V(e,t,n={}){let r=hi(e,t);return{type:e,steps:vi(gi(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 li(e){return e.length===0?` No providers are available.`:[` Select provider:`,...e.map((e,t)=>` ${t+1}. ${W(e)}`),` Provider [1-${e.length}] (default: 1): `].join(`
23
+ `)}function ui(e,t){let n=e.trim(),r=n.length>0?n:`1`,i=mi(r);if(i!==void 0){let e=t[i];if(e!==void 0)return e.type;throw Error(`Provider selection ${r} is out of range. Currently supported: ${g(t)}`)}let a=qt(t,r);if(a===void 0)throw Error(`Unknown provider: ${r}. Currently supported: ${g(t)}`);return a.type}function H(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 U(e,t){let n=H(e),r=t.trim()||n.defaultValue||``,i=K(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:yi(a)}}async function di(e,t,n,r={}){let i=V(e,n,r),a=i.steps.length;for(;i.stepIndex<a;){let e=H(i),n=await t(fi(e,i.setupHelpLinks),e.masked===!0),r=U(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 fi(e,t=[]){let n=e.defaultValue===void 0?``:` (default: ${e.defaultValue})`,r=G(t);return`${r.length>0?`${r}\n`:``} ${e.title}${n}: `}const pi={"cloud-paid":`[Cloud/Paid]`,"cloud-free":`[Cloud/Free]`,"local-free":`[Local/Free]`};function W(e){let t=`${e.category===void 0?``:`${pi[e.category]??``} `}${e.displayName===void 0?e.type:`${e.displayName} (${e.type})`}`;return e.description===void 0?t:`${t} — ${e.description}`}function G(e=[]){return e.length===0?``:e.map(e=>` Setup help: ${_i(e.kind)}: ${e.label} - ${e.url}`).join(`
24
+ `)}function mi(e){if(/^\d+$/.test(e))return Number(e)-1}function K(e,t){if(e.required===!0&&t.length===0)return`Required`}function hi(e,t){let n=qt(t,e);if(n===void 0)throw Error(`Unknown provider: ${e}. Currently supported: ${g(t)}`);return n}function gi(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 _i(e){return e===`api-key`?`API key`:e===`console`?`Console`:`Official`}function vi(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 yi(e){let t=e.profileName??Lt({type:e.type},{existingProfileNames:e.existingProfileNames}),n=e.values.apiKey;return{profile:t,type:e.type,model:e.values.model,...n!==void 0&&n.length>0&&{apiKey:n},...e.values.baseURL!==void 0&&{baseURL:e.values.baseURL},setCurrent:e.setCurrent??!0}}const bi={type:`session-restart-requested`,reason:`other`};function xi(e,t){return V(e,t.providerDefinitions,{existingProfileNames:Object.keys(t.settings.readMergedSettings().providers??{})})}function q(e,t){return{prompt:Si(e),submit:n=>wi(e,n,t),cancel:()=>({message:`Provider setup cancelled.`,success:!0})}}function Si(e){let t=H(e),n=t.masked===!0&&t.defaultValue!==void 0?`(unchanged)`:t.defaultValue;return{kind:`text`,title:t.title,...Ci(e),...n===void 0?{}:{placeholder:n},...t.defaultValue===void 0?{}:{allowEmpty:!0},...t.masked===void 0?{}:{masked:t.masked},validate:e=>K(t,e)}}function Ci(e){let t=G(e.setupHelpLinks);return t.length>0?{description:t}:{}}function wi(e,t,n){let r=U(e,t);return r.status===`error`?{message:r.message,success:!1,interaction:q(e,n)}:r.status===`complete`?Ti(r.input,n):{message:``,success:!0,interaction:q(r.state,n)}}function Ti(e,t){let n=t.settings.readTargetSettings(),r=ke(e,{providerDefinitions:t.providerDefinitions});return t.settings.writeTargetSettings(pt(n,r)),{message:`Provider ${e.profile} configured. Restarting...`,success:!0,effects:[{...bi,message:`Provider setup restart`}]}}function Ei(e,t,n){return`${e===n?`* `:``}${e}: ${t.type??`unknown`} ${t.model??`(no model)`}`}function Di(e,t,n){if(!t)return{message:`Usage: /provider switch <profile>`,success:!1};if(!e?.[t])return{message:`Provider profile "${t}" was not found.`,success:!1};let{orgPolicy:r}=n;if(r?.allowedProviders&&!r.allowedProviders.includes(t))return{message:$e(`Provider "${t}" is not allowed by your organization policy. Allowed: ${r.allowedProviders.join(`, `)}.`,r.adminContact),success:!1};if(n.settings.readMergedSettings().currentProvider===t)return{message:`Already using provider "${t}".`,success:!0};let i=e[t],a=n.settings.readTargetSettings(),o=n.settings.readMergedSettings(),s=a.providers?.[t]!==void 0||o.providers?.[t]!==void 0?{...a,currentProvider:t}:Ft(a,t);return n.settings.writeTargetSettings(s),{message:`Switched to ${t} (${i.model??`unknown model`}). History preserved.`,success:!0,effects:[{type:`provider-hot-swap-requested`,profileName:t}]}}function Oi(e,t){let n=t.settings.readMergedSettings().providers?.[e];if(!n)return{message:`Provider profile "${e}" was not found.`,success:!1};if(!n.type)return{message:`Provider profile "${e}" is missing type.`,success:!1};try{let r=V(n.type,t.providerDefinitions,{profileName:e,setCurrent:!1,initialValues:ki(n)});return{message:`Provider edit requested: ${e}`,success:!0,interaction:Ai(r,e,t)}}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}}function ki(e){return{...typeof e.model==`string`?{model:e.model}:{},...typeof e.apiKey==`string`?{apiKey:e.apiKey}:{},...typeof e.baseURL==`string`?{baseURL:e.baseURL}:{}}}function Ai(e,t,n){return{prompt:Si(e),submit:r=>ji(e,t,r,n),cancel:()=>({message:`Provider edit cancelled.`,success:!0})}}function ji(e,t,n,r){let i=U(e,n);return i.status===`error`?{message:i.message,success:!1,interaction:Ai(e,t,r)}:i.status===`complete`?Mi(i.input,t,r):{message:``,success:!0,interaction:Ai(i.state,t,r)}}function Mi(e,t,n){let r=n.settings.readMergedSettings(),i=r.providers?.[t];if(!i)return{message:`Provider profile "${t}" was not found.`,success:!1};let{orgPolicy:a}=n;if(a?.requireApiKeyFromEnv&&at(e.apiKey))return{message:$e(`Your organization policy requires API keys to be stored as environment variable references ($ENV:VAR_NAME), not as plaintext.`,a.adminContact),success:!1};let o=n.settings.readTargetSettings(),s=ke(e,{providerDefinitions:n.providerDefinitions}).providers[t];if(!s)return{message:`Provider profile "${t}" was not updated.`,success:!1};n.settings.writeTargetSettings(Bt(o,t,{...i,...s}));let c=r.currentProvider===t;return{message:c?`Provider ${t} updated. Switching...`:`Provider ${t} updated.`,success:!0,...c?{effects:[{type:`provider-hot-swap-requested`,profileName:t}]}:{}}}const Ni={type:`session-restart-requested`,reason:`other`};function Pi(e,t){let n=t.settings.readMergedSettings();if(!n.providers?.[e])return{message:`Provider profile "${e}" was not found.`,success:!1};let r=Hi(e,Object.keys(n.providers));return{message:`Provider duplicate requested: ${e}`,success:!0,interaction:Fi(e,r,t)}}function Fi(e,t,n){return{prompt:{kind:`text`,title:`Duplicate ${e} as`,placeholder:t,allowEmpty:!0,validate:e=>Ii(e,t,n)},submit:r=>Li(e,r,t,n),cancel:()=>({message:`Provider duplicate cancelled.`,success:!0})}}function Ii(e,t,n){let r=Ui(e,t);if(r.length===0)return`Required`;if(n.settings.readMergedSettings().providers?.[r]!==void 0)return`Provider profile "${r}" already exists`}function Li(e,t,n,r){let i=r.settings.readMergedSettings().providers?.[e];if(!i)return{message:`Provider profile "${e}" was not found.`,success:!1};let a=Ui(t,n),o=Ii(a,n,r);return o===void 0?(r.settings.writeTargetSettings(Bt(r.settings.readTargetSettings(),a,{...i})),{message:`Provider profile duplicated: ${e} -> ${a}.`,success:!0}):{message:o,success:!1}}function Ri(e,t){let n=t.settings.readMergedSettings().providers??{};return n[e]?Object.keys(n).length<=1?{message:`Cannot delete the only provider profile.`,success:!1}:t.settings.readTargetSettings().providers?.[e]===void 0?{message:`Provider profile "${e}" is not stored in the active write target; edit its source settings file or override it before deleting.`,success:!1}:{message:`Provider delete requested: ${e}`,success:!0,interaction:zi(e,t)}:{message:`Provider profile "${e}" was not found.`,success:!1}}function zi(e,t){return{prompt:{kind:`choice`,title:`Delete provider profile ${e}?`,options:[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}]},submit:n=>n===`yes`?Bi(e,t):{message:`Provider delete cancelled.`,success:!0},cancel:()=>({message:`Provider delete cancelled.`,success:!0})}}function Bi(e,t){let n=t.settings.readMergedSettings();if(n.currentProvider!==e)return t.settings.writeTargetSettings(We(t.settings.readTargetSettings(),e)),{message:`Provider profile deleted: ${e}.`,success:!0};let r=Object.entries(n.providers??{}).filter(([t])=>t!==e).map(([e,t])=>({value:e,label:Ei(e,t,n.currentProvider)}));return{message:`Select a replacement provider before deleting ${e}.`,success:!0,interaction:{prompt:{kind:`choice`,title:`Replacement provider for ${e}`,options:r,maxVisible:8},submit:n=>Vi(e,n,t),cancel:()=>({message:`Provider delete cancelled.`,success:!0})}}}function Vi(e,t,n){if(n.settings.readMergedSettings().providers?.[t]===void 0||t===e)return{message:`Provider profile "${t}" was not found.`,success:!1};let r=We(n.settings.readTargetSettings(),e);return n.settings.writeTargetSettings({...r,currentProvider:t}),{message:`Provider profile deleted: ${e}. Restarting with ${t}...`,success:!0,effects:[{...Ni,message:`Provider delete restart`}]}}function Hi(e,t){let n=Nt(`${e}-copy`)??`provider-copy`;if(!t.includes(n))return n;for(let e=2;e<1e3;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return`${n}-${Date.now()}`}function Ui(e,t){return Nt(e.trim()||t)??``}const Wi=`switch`,Gi=`edit`,Ki=`test`,qi=`duplicate`,Ji=`delete`,Yi=`cancel`;function Xi(e,t,n){return{prompt:{kind:`choice`,title:`Select provider profile`,options:Object.entries(t??{}).map(([t,n])=>({value:t,label:Ei(t,n,e)})),maxVisible:8},submit:e=>Zi(e,n),cancel:()=>({message:`Provider profile selection cancelled.`,success:!0})}}function Zi(e,t){return t.settings.readMergedSettings().providers?.[e]?{message:`Provider profile selected: ${e}`,success:!0,interaction:Qi(e,t)}:{message:`Provider profile "${e}" was not found.`,success:!1}}function Qi(e,t){return{prompt:{kind:`choice`,title:`Provider profile: ${e}`,options:[{value:Wi,label:`Switch`},{value:Gi,label:`Edit`},{value:Ki,label:`Test`},{value:qi,label:`Duplicate`},{value:Ji,label:`Delete`},{value:Yi,label:`Cancel`}]},submit:n=>$i(e,n,t),cancel:()=>({message:`Provider profile action cancelled.`,success:!0})}}async function $i(e,t,n){let r=n.settings.readMergedSettings();switch(t){case Wi:return Di(r.providers,e,n);case Gi:return Oi(e,n);case Ki:return await zt(r.currentProvider,r.providers,e,n);case qi:return Pi(e,n);case Ji:return Ri(e,n);case Yi:return{message:`Provider profile action cancelled.`,success:!0};default:return{message:`Unknown provider profile action "${t}".`,success:!1}}}async function ea(e,t){let n=t.settings.readMergedSettings(),r=e.trim();if(r.length===0)return ta(n.currentProvider,n.providers,t);let[i=`current`,a]=r.split(/\s+/);return i===`list`?ta(n.currentProvider,n.providers,t):i===`current`||i===``?{message:ra(n.currentProvider,n.providers),success:!0}:i===`switch`?Di(n.providers,a,t):i===`test`?await zt(n.currentProvider,n.providers,a,t):i===`add`?ia(a,t):{message:`Usage: provider [current|list|switch <profile>|add <type>|test [profile]]`,success:!1}}function ta(e,t,n){let r=na(e,t);return Object.keys(t??{}).length===0?{message:r,success:!0}:{message:r,success:!0,interaction:Xi(e,t,n)}}function na(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(`
25
+ `)}function ra(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(`
26
+ `):`Current provider "${e}" was not found in providers.`}function ia(e,t){return e===void 0||e.length===0?{message:`Provider setup requested. Select a provider to continue.`,success:!0,interaction:aa(t)}:qt(t.providerDefinitions,e)===void 0?{message:`Usage: provider add <type>. Supported: ${g(t.providerDefinitions)}`,success:!1}:{message:`Provider setup requested: ${e}`,success:!0,interaction:q(xi(e,t),t)}}function aa(e){return{prompt:{kind:`choice`,title:`Select provider`,options:e.providerDefinitions.map(e=>({value:e.type,label:W(e)})),maxVisible:6},submit:t=>{let n=xi(t,e);return{message:`Provider setup requested: ${t}`,success:!0,interaction:q(n,e)}},cancel:()=>({message:`Provider setup cancelled.`,success:!0})}}function oa(){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 sa(){return{name:`provider`,displayName:`Provider Setup`,description:`Manage provider profiles`,source:`provider`,modelInvocable:!1,argumentHint:`current | list | switch <profile> | add [type] | test [profile]`,subcommands:oa(),example:`/provider switch production`}}var ca=class{name=`provider`;getCommands(){return[sa()]}};function la(e){let t=sa();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,execute:async(t,n)=>ea(n,e)}}const ua={provider:{type:`pick`,getItems:()=>oa().map(e=>({label:e.name,value:e.name,description:e.description}))}};function da(e){return{name:`agent-command-provider`,commandSources:[new ca],systemCommands:[la(e)],interactionHints:ua}}async function fa(e,t){let n=(await e(`
26
27
  Do you have an API key for an AI provider?
27
28
 
28
29
  1. Yes, I have an API key
@@ -49,15 +50,15 @@ import{BACKGROUND_COMMAND_DESCRIPTION as e,BACKGROUND_COMMAND_USAGE as t,BundleP
49
50
  When the server is running, come back here and press Enter to continue.
50
51
 
51
52
  ─────────────────────────────────────────────────────────────────────────────
52
- `),await e(` Press Enter when LM Studio server is running: `),{path:`local`,preselectedType:`gemma`}):{path:`has-key`}}async function $i(e,t,n,r,i){let a=await Qi(n,r),o=Object.keys(xt(e).providers??{}),s=Ot(e,t.settingsScope),c;c=a.preselectedType===void 0?Yr(await n(Jr(i)),i):a.preselectedType,Se(s,await Xr(c,n,i,{existingProfileNames:o}),{providerDefinitions:i});let l=await n(` Response language (ko/en/ja/zh, default: en): `);if(l){let e=St(s);e.language=l,Ht(s,e)}r.writeLine(`\n Config saved to ${s}\n`)}async function ea(e,t,n,r,i,a){let o=xt(e);if(je(t.provider===void 0?o:{...o,currentProvider:t.provider},i)===`valid`||t.provider===void 0&&Et(i,a.env)!==void 0)return;if(!(a.isInteractive??(()=>!1))())throw new ue(a.formatError(i));await $i(e,ta(e,t),n,r,i);let s=xt(e);if(je(t.provider===void 0?s:{...s,currentProvider:t.provider},i)!==`valid`)throw new ue(a.formatError(i))}function ta(e,t){if(t.settingsScope!==void 0||t.provider!==void 0)return t;let n=na(Qe(e));if(n===void 0)return t;let r=_(e,`.robota`,`settings.json`),i=_(e,`.robota`,`settings.local.json`);return n===r||n===i?{...t,settingsScope:`project-local`}:t}function na(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&typeof St(n).currentProvider==`string`)return n}}function ra(e,t){return{success:!0,message:`Reset requested.`,data:{resetRequested:!0},effects:[{type:`settings-reset-requested`}]}}function ia(){return{name:`reset`,displayName:`Reset Settings`,description:`Delete settings`,source:`reset`,modelInvocable:!1}}function aa(){let e=ia();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:ra}}var oa=class{name=`reset`;getCommands(){return[ia()]}};function sa(){return{name:`agent-command-reset`,commandSources:[new oa],systemCommands:[aa()]}}function J(){return{message:`Usage: rewind [list] | rewind inspect <checkpoint-id> | rewind restore <checkpoint-id> | rewind code <checkpoint-id> | rewind rollback <checkpoint-id>`,success:!1}}function ca(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=120?t:`${t.slice(0,117)}...`}function la(e){return{message:[`Edit checkpoints:`,...e.length>0?e.map(e=>`- ${e.id} files=${e.fileCount} ${e.createdAt} ${ca(e.prompt)}`):[`(no edit checkpoints)`]].join(`
53
- `),success:!0,data:{count:e.length,checkpoints:[...e]}}}function ua(e){return e.length>0?e.join(`, `):`(none)`}function da(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: ${ca(e.target.prompt)}`,`Captured files:`,...t,`Restore later checkpoints: files=${e.restoreToCheckpoint.fileCount} checkpoints=${ua(e.restoreToCheckpoint.checkpointIds)}`,`Rollback through checkpoint: files=${e.rollbackThroughCheckpoint.fileCount} checkpoints=${ua(e.rollbackThroughCheckpoint.checkpointIds)}`].join(`
54
- `),success:!0,data:{inspection:e}}}function fa(e){return{message:[`Restored code to ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Rolled back checkpoints: ${e.restoredCheckpointCount}`].join(`
55
- `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function pa(e){return{message:[`Rolled back code through ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Removed checkpoints: ${e.removedCheckpointCount}`].join(`
56
- `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function ma(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function ha(e,t){if(!t)return J();try{return da(et(e,t))}catch(e){return ma(e instanceof Error?e:String(e))}}async function ga(e,t){if(!t)return J();try{return fa(await kt(e,t))}catch(e){return ma(e instanceof Error?e:String(e))}}async function _a(e,t){if(!t)return J();try{return pa(await At(e,t))}catch(e){return ma(e instanceof Error?e:String(e))}}async function va(e,t){let n=t.trim().split(/\s+/).filter(Boolean),r=n[0]??`list`;return r===`list`?la(ct(e)):r===`inspect`?ha(e,n[1]):r===`restore`||r===`code`?ga(e,n[1]):r===`rollback`?_a(e,n[1]):J()}function ya(){return{name:`rewind`,displayName:`Rewind History`,description:ge,source:`rewind`,argumentHint:he,modelInvocable:!1,safety:`write`,subcommands:Oe()}}function ba(){let e=ya();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:va}}var xa=class{name=`rewind`;getCommands(){return[ya()]}};function Sa(){return{name:`agent-command-rewind`,commandSources:[new xa],systemCommands:[ba()]}}const Ca={s:1e3,m:6e4,h:36e5,d:864e5},Y=`Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron "<expr>" <instruction>`;function wa(e,t){let n=e.trim();if(n.length===0)return{ok:!1,error:Y};if(n.startsWith(`in `)){let e=n.slice(3).trim(),r=e.indexOf(` `);if(r===-1)return{ok:!1,error:`Missing instruction. ${Y}`};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}". ${Y}`};if(a.length===0)return{ok:!1,error:`Missing instruction. ${Y}`};let s=parseInt(o[1],10)*Ca[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+(.+)$/.exec(e);if(!t)return{ok:!1,error:`cron form needs a quoted expression. ${Y}`};let r=t[2].trim();return r.length===0?{ok:!1,error:`Missing instruction. ${Y}`}:{ok:!0,spec:{cronExpression:t[1].trim(),instruction:r,recurring:!0}}}return{ok:!1,error:Y}}function Ta(e,t){return`${e}: ${t.slice(0,48)}${t.length>48?`…`:``}`}async function Ea(e,t,n=Date.now()){let r=wa(t,n);if(!r.ok)return{message:r.error,success:!1};let{cronExpression:i,instruction:a,recurring:o}=r.spec,s=await e.spawnScheduledWake({label:Ta(`Scheduled`,a),cronExpression:i,agentInstruction:a});return{message:`Scheduled wake (${o?`cron \`${i}\``:`once at ${i}`}): "${a}" — task ${s.id}.`,success:!0,data:{taskId:s.id,cronExpression:i,recurring:o}}}function Da(e){let t=/^["']([^"']+)["']\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 Oa(e,t){let n=Da(t);if(!n)return{message:`Usage: /monitor "<command>" "<pattern>" <instruction>`,success:!1};let r=await e.spawnMonitorWake({label:Ta(`Monitor`,n.instruction),command:n.command,matchPattern:n.matchPattern,agentInstruction:n.instruction});return{message:`Monitoring \`${n.command}\` for /${n.matchPattern}/ — task ${r.id}.`,success:!0,data:{taskId:r.id,matchPattern:n.matchPattern}}}function ka(e){let t=e.getAgentJobCapability?.();if(!t)throw Error(`Scheduling requires an active agent runtime.`);return t}function Aa(){return{name:`schedule`,displayName:`Schedule Wake`,description:`Schedule the agent to wake and run an instruction on a timer (one-shot or cron).`,source:`schedule`,argumentHint:`in <N><s|m|h|d> <instruction> | cron "<expr>" <instruction>`,modelInvocable:!0}}function ja(){return{name:`monitor`,displayName:`Monitor Process`,description:`Watch a process’s output and wake the agent when a line matches a pattern.`,source:`schedule`,argumentHint:`"<command>" "<pattern>" <instruction>`,modelInvocable:!0}}function Ma(){let e=Aa();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Ea(ka(e),t)}}function Na(){let e=ja();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Oa(ka(e),t)}}var Pa=class{name=`schedule`;getCommands(){return[Aa(),ja()]}};function Fa(){return{name:`agent-command-schedule`,commandSources:[new Pa],systemCommands:[Ma(),Na()],sessionRequirements:[`agent-runtime`]}}const Ia={"claude-opus-4-7":{inputPerMillion:15,outputPerMillion:75},"claude-opus-4-5":{inputPerMillion:15,outputPerMillion:75},"claude-sonnet-4-6":{inputPerMillion:3,outputPerMillion:15},"claude-sonnet-4-5":{inputPerMillion:3,outputPerMillion:15},"claude-haiku-4-5":{inputPerMillion:.8,outputPerMillion:4},"claude-3-5-sonnet-20241022":{inputPerMillion:3,outputPerMillion:15},"claude-3-5-haiku-20241022":{inputPerMillion:.8,outputPerMillion:4},"claude-3-opus-20240229":{inputPerMillion:15,outputPerMillion:75},"gpt-4o":{inputPerMillion:2.5,outputPerMillion:10},"gpt-4o-mini":{inputPerMillion:.15,outputPerMillion:.6},o1:{inputPerMillion:15,outputPerMillion:60},"o1-mini":{inputPerMillion:3,outputPerMillion:12},o3:{inputPerMillion:10,outputPerMillion:40},"o3-mini":{inputPerMillion:1.1,outputPerMillion:4.4},"deepseek-chat":{inputPerMillion:.14,outputPerMillion:.28},"deepseek-reasoner":{inputPerMillion:.55,outputPerMillion:2.19},"gemini-2.0-flash":{inputPerMillion:.1,outputPerMillion:.4},"gemini-2.0-flash-thinking":{inputPerMillion:.35,outputPerMillion:3.5},"gemini-1.5-pro":{inputPerMillion:1.25,outputPerMillion:5},"gemini-1.5-flash":{inputPerMillion:.075,outputPerMillion:.3}},La=[{pattern:/claude-opus/i,price:{inputPerMillion:15,outputPerMillion:75}},{pattern:/claude-sonnet/i,price:{inputPerMillion:3,outputPerMillion:15}},{pattern:/claude-haiku/i,price:{inputPerMillion:.8,outputPerMillion:4}},{pattern:/gpt-4o-mini/i,price:{inputPerMillion:.15,outputPerMillion:.6}},{pattern:/gpt-4/i,price:{inputPerMillion:2.5,outputPerMillion:10}},{pattern:/deepseek/i,price:{inputPerMillion:.14,outputPerMillion:.28}},{pattern:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Ra(e){let t=Ia[e];if(t)return t;for(let{pattern:t,price:n}of La)if(t.test(e))return n}function za(e,t,n){let r=Ra(e);if(r)return t/1e6*r.inputPerMillion+n/1e6*r.outputPerMillion}function X(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Ba(e){return e.toLocaleString(`en-US`)}const Va=`Conversation cleared.`;function Ha(e,t){return Ne(e),{success:!0,message:Va,effects:[{type:`conversation-history-cleared`}]}}function Ua(e,t){let n=ht(t);return n===void 0?{success:!1,message:pe}:{success:!0,message:`Session renamed to "${n}".`,data:{name:n},effects:[Ve(n)]}}function Wa(e,t){return{success:!0,message:`Opening session picker...`,data:{triggerResumePicker:!0},effects:[Be()]}}const Ga=`.robota/budget.json`;function Ka(e){let t=_(e,Ga);if(!Wt(t))return;let n;try{n=Kt(t,`utf-8`)}catch{return}try{return JSON.parse(n)}catch{return}}function qa(e,t){Gt(_(e,`.robota`),{recursive:!0}),qt(_(e,Ga),JSON.stringify(t,null,2))}function Ja(e){let t=_(e,Ga);Wt(t)&&qt(t,`{}`)}function Ya(e){let t=e.getSession(),n=bt(e),r=t.getSessionTokenUsage?.(),i=t.getModelId?.(),a=[`Session: ${n.sessionId}`,`Messages: ${n.messageCount}`],o={sessionId:n.sessionId,messageCount:n.messageCount};if(r){if(a.push(`Tokens: ${Ba(r.inputTokens)} input / ${Ba(r.outputTokens)} output`),o.inputTokens=r.inputTokens,o.outputTokens=r.outputTokens,i){let t=za(i,r.inputTokens,r.outputTokens);if(t!==void 0){a.push(`Cost: ${X(t)} (${i})`),o.estimatedCostUsd=t;let n=Ka(e.getCwd());if(n?.monthly){let e=n.monthly-t,r=Math.min(100,Math.round(t/n.monthly*100));a.push(`Budget: ${X(e)} remaining of ${X(n.monthly)}/mo (${r}% used)`),o.budgetMonthly=n.monthly,o.budgetRemainingUsd=e}}}}else a.push(`Tokens: not yet available (no turns completed)`);return{lines:a,data:o}}function Xa(e,t){let n=t.trim();if(n.startsWith(`budget`)){let t=n.slice(6).trim();if(t===`clear`)return Ja(e.getCwd()),{success:!0,message:`Monthly budget cleared.`};if(t===``){let t=Ka(e.getCwd());return t?.monthly?{success:!0,message:`Monthly budget: ${X(t.monthly)}`}:{success:!0,message:`No budget set. Use: /cost budget <amount>`}}let r=parseFloat(t);return!Number.isFinite(r)||r<=0?{success:!1,message:`Usage: /cost budget <amount> (e.g. /cost budget 5.00)`}:(qa(e.getCwd(),{monthly:r}),{success:!0,message:`Monthly budget set to ${X(r)}.`})}let{lines:r,data:i}=Ya(e);return{success:!0,message:r.join(`
57
- `),data:i}}function Za(e,t){let n=zt(e);return{success:n.validation.ok,message:Je(n),data:{logFile:n.logFile,entryCount:n.entryCount,issueCount:n.validation.issues.length,ok:n.validation.ok}}}function Qa(){return{name:`clear`,displayName:`Clear History`,description:i,source:`session`,modelInvocable:!1}}function $a(){return{name:`rename`,displayName:`Rename Session`,description:fe,source:`session`,modelInvocable:!1}}function eo(){return{name:`resume`,displayName:`Resume Session`,description:me,source:`session`,modelInvocable:!1}}function to(){return{name:`cost`,displayName:`Session Cost`,description:a,source:`session`,modelInvocable:!1}}function no(){return{name:`validate-session`,displayName:`Validate Session`,description:be,source:`session`,modelInvocable:!1}}function ro(){let e=Qa();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Ha}}function io(){let e=$a();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Ua}}function ao(){let e=eo();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Wa}}function oo(){let e=to();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Xa}}function so(){let e=no();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Za}}var co=class{name=`session`;getCommands(){return[Qa(),$a(),eo(),to(),no()]}};const lo={clear:{type:`confirm`,message:`Clear conversation history?`}};function uo(){return{name:`agent-command-session`,commandSources:[new co],systemCommands:[ro(),io(),ao(),oo(),so()],interactionHints:lo}}function Z(){return{name:`settings`,displayName:`Settings`,description:`Open transport settings — enable/disable transports and configure options`,source:`settings`,modelInvocable:!1}}function fo(){let e=Z();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...`,effects:[{type:`settings-tui-requested`}]})}}var po=class{name=`settings`;getCommands(){return[Z()]}};function mo(){return{name:`agent-command-settings`,commandSources:[new po],systemCommands:[fo()]}}const ho=`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. Slash syntax is a UI input/display concern; the SDK command identity is "skills".`;function go(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 _o(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}${go(e)}`}function vo(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(`
58
- `):[`Registered skills:`,...e.map(_o),``,`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(`
59
- `)}function yo(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 bo(e,t=``){let n=yo(t);if(n.action===`activate`&&n.skillName!==void 0){if(!e.executeSkillCommandByName)return{success:!1,message:`Skill activation is not available in this session.`};let t=`/${n.skillName}${n.skillArgs?` ${n.skillArgs}`:``}`;return await e.executeSkillCommandByName(n.skillName,n.skillArgs,{invocationSource:e.getCommandInvocationSource?.()??`user`,displayInput:t,rawInput:t})??{success:!1,message:`Unknown skill: ${n.skillName}`}}let r=e.listSkills?.()??[];return{success:!0,message:vo(r),data:{skills:r,activationContract:{activateWith:`/skills <skill-name> [args]`,activationRequiredBeforeWorkflow:!0,metadataIsNotSkillContent:!0}}}}function xo(){return{name:`skills`,displayName:`Skills`,description:ho,source:`skills`,modelInvocable:!0,userInvocable:!0,argumentHint:`[list | <skill-name> [args]]`,safety:`read-only`}}function So(){let e=xo();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,lifecycle:`inline`,execute:bo}}var Co=class{name=`skills`;getCommands(){return[xo()]}};function wo(e){let t=[new Co];return t.push(new ye(e.cwd)),{name:`agent-command-skills`,commandSources:t,systemCommands:[So()]}}const To=[`Usage: /statusline on | off | reset | git on | git off`,`Fields: model, context, permission mode, message count, session name, thinking state, git branch.`].join(`
60
- `);function Eo(e){let t=e.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0),[n,r]=t;return n===`on`&&r===void 0?{success:!0,message:`Status line enabled.`,patch:{enabled:!0}}:n===`off`&&r===void 0?{success:!0,message:`Status line disabled.`,patch:{enabled:!1}}:n===`reset`&&r===void 0?{success:!0,message:`Status line settings reset.`,patch:{...s}}:n===`git`&&r===`on`&&t.length===2?{success:!0,message:`Status line git branch shown.`,patch:{gitBranch:!0}}:n===`git`&&r===`off`&&t.length===2?{success:!0,message:`Status line git branch hidden.`,patch:{gitBranch:!1}}:{success:!1,message:To}}function Do(e,t){let n=Eo(t);return n.success?{success:!0,message:n.message,effects:[{type:`statusline-settings-patch`,patch:n.patch}]}:{success:!1,message:n.message}}function Oo(){return{name:`statusline`,displayName:`Status Line`,description:ve,source:`statusline`,argumentHint:_e,subcommands:ke(`statusline`),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:Do}}var Ao=class{name=`statusline`;getCommands(){return[Oo()]}};function jo(){return{name:`agent-command-statusline`,commandSources:[new Ao],systemCommands:[ko()]}}const Mo=`Inspect Robota user-local storage and memory state.`,No=`storage list [--format json] | memory set/list/inspect/disable/delete`,Q=`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 Po(e){return e.length===0?`No user-local memory items.`:e.map(e=>`- ${e.category}/${e.key} (${e.enabled?`enabled`:`disabled`})`).join(`
61
- `)}function $(e){if(e===void 0)throw Error(`User-local memory category is required.`);return e}async function Fo(e,t){let n=await ut({activeRepositoryRoot:e});return{message:t.format===`json`?JSON.stringify(n,null,2):Po(n.items),success:!0,data:{list:n}}}async function Io(e,t){let[n,r,i]=t.positional,a=await Pt({activeRepositoryRoot:e,category:$(n),key:r??``,value:i??``,summary:t.summary??``,source:t.source??``});return{message:`Stored user-local memory item ${a.category}/${a.key} at ${a.storageLocation}`,success:!0,data:{item:a}}}async function Lo(e,t){let[n,r]=t.positional,i=await tt({activeRepositoryRoot:e,category:$(n),key:r??``});return{message:t.format===`json`?JSON.stringify(i,null,2):`${i.category}/${i.key}: ${i.summary}`,success:!0,data:{item:i}}}async function Ro(e,t){let[n,r]=t.positional,i=await We({activeRepositoryRoot:e,category:$(n),key:r??``});return{message:`Disabled user-local memory item ${i.category}/${i.key}`,success:!0,data:{item:i}}}async function zo(e,t){let[n,r]=t.positional,i=await Ue({activeRepositoryRoot:e,category:$(n),key:r??``});return{message:`Deleted user-local memory item ${i.category}/${i.key}`,success:!0,data:{result:i}}}async function Bo(e,t){return(t.action??`list`)===`list`?Fo(e,t):t.action===`set`?Io(e,t):t.action===`inspect`?Lo(e,t):t.action===`disable`?Ro(e,t):t.action===`delete`?zo(e,t):{message:Q,success:!1}}function Vo(e){if(e===void 0||e===`text`)return`text`;if(e===`json`)return`json`;throw Error(`Unsupported user-local output format: ${e}`)}function Ho(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 Uo(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=Ho(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:Vo(n),summary:r,source:i}}function Wo(e){return e.trim().split(/\s+/).filter(Boolean)}function Go(e,t){let n=t.map(e=>`- ${e.category}`);return[`User-local storage root: ${e}`,`Categories:`,...n].join(`
62
- `)}async function Ko(e,t){if((t.action??`list`)!==`list`)return{message:Q,success:!1};let n=await nt({activeRepositoryRoot:e});return{message:t.format===`json`?JSON.stringify(n,null,2):Go(n.root,n.categories),success:!0,data:{root:n.root,categories:n.categories,inspection:n}}}async function qo(e,t){return t.target===`storage`?Ko(e,t):t.target===`memory`?Bo(e,t):{message:Q,success:!1}}function Jo(e){return e.includes(`ENOENT`)?`User-local memory item not found.`:e}async function Yo(e){try{return await qo(e.cwd,Uo(e.argv,{format:e.format,summary:e.summary,source:e.source}))}catch(e){return{message:Jo(e instanceof Error?e.message:String(e)),success:!1}}}async function Xo(e,t){try{return await qo(e.getCwd(),Uo(Wo(t)))}catch(e){return{message:Jo(e instanceof Error?e.message:String(e)),success:!1}}}function Zo(){return{name:`user-local`,displayName:`User Config`,description:Mo,source:`user-local`,argumentHint:No,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 Qo(){let e=Zo();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,safety:e.safety,subcommands:e.subcommands,execute:Xo}}var $o=class{name=`user-local`;getCommands(){return[Zo()]}};function es(){return{name:`agent-command-user-local`,commandSources:[new $o],systemCommands:[Qo()]}}function ts({cwd:e,providerDefinitions:t,providerSettingsAdapter:n}){return[wo({cwd:e}),sr(),Sn(),Nr(),kr(),fr(),Dn(),wr(),es(),Mn(),Qn(),rr(),uo(),sa(),Sa(),Fa(),jo(),qr(),mo(),Zi({providerDefinitions:t,settings:n})]}function ns(e){let t=Yt(),i=_(t,`.robota`,`plugins`),a=_(t,`.robota`,`settings.json`),o=(e,t)=>Jt(e,{timeout:t.timeout,stdio:t.stdio??`pipe`}),s=new le(a),c=new u({pluginsDir:i,exec:o});return{cwd:e,marketplace:c,installer:new n({pluginsDir:i,settingsStore:s,marketplaceClient:c,exec:o}),loader:new r(i),settingsStore:s}}async function rs(e){let t=await e.loader.loadAll(),n=e.settingsStore.getEnabledPlugins();return t.map(e=>{let t=e.pluginDir.split(`/`),r=t.indexOf(`cache`),i=r>=0?t[r+1]??``:``,a=i?`${e.manifest.name}@${i}`:e.manifest.name;return{name:a,description:e.manifest.description,enabled:n[a]!==!1&&n[e.manifest.name]!==!1}})}async function is(e,t){let n;try{n=e.marketplace.fetchManifest(t)}catch{return[]}let r=e.installer.getInstalledPlugins(),i=new Set(Object.values(r).map(e=>e.pluginName));return n.plugins.map(e=>({name:e.name,description:e.description,installed:i.has(e.name)}))}async function as(e,t,r){let[i,a]=t.split(`@`);if(!i||!a)throw Error(`Plugin ID must be in format: name@marketplace`);if(r===`project`){await new n({pluginsDir:_(e.cwd,`.robota`,`plugins`),settingsStore:e.settingsStore,marketplaceClient:e.marketplace,exec:(e,t)=>Jt(e,{timeout:t.timeout,stdio:t.stdio??`pipe`})}).install(i,a);return}await e.installer.install(i,a)}async function os(e,t){let n=e.installer.getPluginsByMarketplace(t);for(let t of n)await e.installer.uninstall(`${t.pluginName}@${t.marketplace}`);e.marketplace.removeMarketplace(t)}function ss(e){return e.marketplace.listMarketplaces().map(e=>({name:e.name,type:e.source.type}))}function cs(e){let t=ns(e);return{listInstalled:()=>rs(t),listAvailablePlugins:e=>is(t,e),install:(e,n)=>as(t,e,n),uninstall:async e=>t.installer.uninstall(e),enable:async e=>t.installer.enable(e),disable:async e=>t.installer.disable(e),marketplaceAdd:async e=>e.includes(`/`)&&!e.includes(`:`)?t.marketplace.addMarketplace({type:`github`,repo:e}):t.marketplace.addMarketplace({type:`git`,url:e}),marketplaceRemove:e=>os(t,e),marketplaceUpdate:async e=>t.marketplace.updateMarketplace(e),marketplaceList:async()=>ss(t),reloadPlugins:async()=>({loadedPluginCount:(await t.loader.loadAll()).length})}}const ls=`plugin`;function us(){return process.env.HOME??Yt()}function ds(e){let t=new r(_(us(),`.robota`,`plugins`));try{let n=t.loadPluginsSync();return n.length===0?(e.replaceSource(ls),0):(e.replaceSource(ls,new ce(n)),n.length)}catch{return e.replaceSource(ls),0}}export{xn as AgentCommandSource,En as BackgroundCommandSource,Va as CLEAR_COMMAND_MESSAGE,jn as CompactCommandSource,Zn as ContextCommandSource,tr as ExitCommandSource,or as HelpCommandSource,ur as LanguageCommandSource,Cr as MemoryCommandSource,Dr as ModeCommandSource,Mr as PermissionsCommandSource,Kr as PluginManagerCommandSource,Ji as ProviderCommandSource,xa as RewindCommandSource,ho as SKILLS_COMMAND_DESCRIPTION,To as STATUSLINE_USAGE,Pa as ScheduleCommandSource,co as SessionCommandSource,po as SettingsCommandSource,Co as SkillsCommandSource,Ao as StatusLineCommandSource,No as USER_LOCAL_COMMAND_ARGUMENT_HINT,Mo as USER_LOCAL_COMMAND_DESCRIPTION,Q as USER_LOCAL_COMMAND_USAGE,$o as UserLocalCommandSource,x as createAgentCommandEntry,Sn as createAgentCommandModule,bn as createAgentSystemCommand,S as createBackgroundCommandEntry,Dn as createBackgroundCommandModule,Qa as createClearCommandEntry,C as createCompactCommandEntry,Mn as createCompactCommandModule,O as createContextCommandEntry,Qn as createContextCommandModule,to as createCostCommandEntry,ts as createDefaultCommandModules,cs as createDefaultPluginCommandAdapter,k as createExitCommandEntry,rr as createExitCommandModule,A as createHelpCommandEntry,sr as createHelpCommandModule,j as createLanguageCommandEntry,fr as createLanguageCommandModule,P as createMemoryCommandEntry,wr as createMemoryCommandModule,F as createModeCommandEntry,kr as createModeCommandModule,ja as createMonitorCommandEntry,I as createPermissionsCommandEntry,Nr as createPermissionsCommandModule,B as createPluginCommandEntry,qr as createPluginCommandModule,qi as createProviderCommandEntry,Zi as createProviderCommandModule,H as createProviderSetupFlow,V as createReloadPluginsCommandEntry,$a as createRenameCommandEntry,ia as createResetCommandEntry,sa as createResetCommandModule,eo as createResumeCommandEntry,Sa as createRewindCommandModule,Aa as createScheduleCommandEntry,Fa as createScheduleCommandModule,uo as createSessionCommandModule,Z as createSettingsCommandEntry,mo as createSettingsCommandModule,xo as createSkillsCommandEntry,wo as createSkillsCommandModule,Oo as createStatusLineCommandEntry,jo as createStatusLineCommandModule,Zo as createUserLocalCommandEntry,es as createUserLocalCommandModule,no as createValidateSessionCommandEntry,ea as ensureProviderConfig,gn as executeAgentCommand,wn as executeBackgroundCommand,Ha as executeClearCommand,kn as executeCompactCommand,Fn as executeContextCommand,Xa as executeCostCommand,$n as executeExitCommand,ir as executeHelpCommand,cr as executeLanguageCommand,xr as executeMemoryCommand,Tr as executeModeCommand,Oa as executeMonitorCommand,Ar as executePermissionsCommand,Hr as executePluginCommand,Bi as executeProviderCommand,Ur as executeReloadPluginsCommand,Ua as executeRenameCommand,ra as executeResetCommand,Wa as executeResumeCommand,va as executeRewindCommand,Ea as executeScheduleCommand,bo as executeSkillsCommand,Do as executeStatusLineCommand,Xo as executeUserLocalCommand,Yo as executeUserLocalDirectCommand,Za as executeValidateSessionCommand,G as formatProviderSetupChoiceLabel,K as formatProviderSetupHelpLinks,Zr as formatProviderSetupPromptLabel,Jr as formatProviderSetupSelectionPrompt,U as getProviderSetupStep,wa as parseScheduleSpec,ds as reloadPluginCommandSource,Yr as resolveProviderSetupSelection,Xr as runProviderSetupPromptFlow,$i as runProviderStartupSetup,W as submitProviderSetupValue,ei as validateProviderSetupValue};
53
+ `),await e(` Press Enter when LM Studio server is running: `),{path:`local`,preselectedType:`gemma`}):{path:`has-key`}}async function pa(e,t,n,r,i){let a=await fa(n,r),o=Object.keys(Ct(e).providers??{}),s=At(e,t.settingsScope),c;c=a.preselectedType===void 0?ui(await n(li(i)),i):a.preselectedType,Ce(s,await di(c,n,i,{existingProfileNames:o}),{providerDefinitions:i});let l=await n(` Response language (ko/en/ja/zh, default: en): `);if(l){let e=wt(s);e.language=l,Wt(s,e)}r.writeLine(`\n Config saved to ${s}\n`)}async function ma(e,t,n,r,i,a){let o=Ct(e);if(Ne(t.provider===void 0?o:{...o,currentProvider:t.provider},i)===`valid`||t.provider===void 0&&Ot(i,a.env)!==void 0)return;if(!(a.isInteractive??(()=>!1))())throw new ue(a.formatError(i));await pa(e,ha(e,t),n,r,i);let s=Ct(e);if(Ne(t.provider===void 0?s:{...s,currentProvider:t.provider},i)!==`valid`)throw new ue(a.formatError(i))}function ha(e,t){if(t.settingsScope!==void 0||t.provider!==void 0)return t;let n=ga(et(e));if(n===void 0)return t;let r=_(e,`.robota`,`settings.json`),i=_(e,`.robota`,`settings.local.json`);return n===r||n===i?{...t,settingsScope:`project-local`}:t}function ga(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&typeof wt(n).currentProvider==`string`)return n}}function _a(e,t){return{success:!0,message:`Reset requested.`,data:{resetRequested:!0},effects:[{type:`settings-reset-requested`}]}}function va(){return{name:`reset`,displayName:`Reset Settings`,description:`Delete settings`,source:`reset`,modelInvocable:!1}}function ya(){let e=va();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:_a}}var ba=class{name=`reset`;getCommands(){return[va()]}};function xa(){return{name:`agent-command-reset`,commandSources:[new ba],systemCommands:[ya()]}}function J(){return{message:`Usage: rewind [list] | rewind inspect <checkpoint-id> | rewind restore <checkpoint-id> | rewind code <checkpoint-id> | rewind rollback <checkpoint-id>`,success:!1}}function Sa(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=120?t:`${t.slice(0,117)}...`}function Ca(e){return{message:[`Edit checkpoints:`,...e.length>0?e.map(e=>`- ${e.id} files=${e.fileCount} ${e.createdAt} ${Sa(e.prompt)}`):[`(no edit checkpoints)`]].join(`
54
+ `),success:!0,data:{count:e.length,checkpoints:[...e]}}}function wa(e){return e.length>0?e.join(`, `):`(none)`}function Ta(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: ${Sa(e.target.prompt)}`,`Captured files:`,...t,`Restore later checkpoints: files=${e.restoreToCheckpoint.fileCount} checkpoints=${wa(e.restoreToCheckpoint.checkpointIds)}`,`Rollback through checkpoint: files=${e.rollbackThroughCheckpoint.fileCount} checkpoints=${wa(e.rollbackThroughCheckpoint.checkpointIds)}`].join(`
55
+ `),success:!0,data:{inspection:e}}}function Ea(e){return{message:[`Restored code to ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Rolled back checkpoints: ${e.restoredCheckpointCount}`].join(`
56
+ `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function Da(e){return{message:[`Rolled back code through ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Removed checkpoints: ${e.removedCheckpointCount}`].join(`
57
+ `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function Oa(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function ka(e,t){if(!t)return J();try{return Ta(nt(e,t))}catch(e){return Oa(e instanceof Error?e:String(e))}}async function Aa(e,t){if(!t)return J();try{return Ea(await jt(e,t))}catch(e){return Oa(e instanceof Error?e:String(e))}}async function ja(e,t){if(!t)return J();try{return Da(await Mt(e,t))}catch(e){return Oa(e instanceof Error?e:String(e))}}async function Ma(e,t){let n=t.trim().split(/\s+/).filter(Boolean),r=n[0]??`list`;return r===`list`?Ca(ut(e)):r===`inspect`?ka(e,n[1]):r===`restore`||r===`code`?Aa(e,n[1]):r===`rollback`?ja(e,n[1]):J()}function Na(){return{name:`rewind`,displayName:`Rewind History`,description:ge,source:`rewind`,argumentHint:he,modelInvocable:!1,safety:`write`,subcommands:Ae()}}function Pa(){let e=Na();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:Ma}}var Fa=class{name=`rewind`;getCommands(){return[Na()]}};function Ia(){return{name:`agent-command-rewind`,commandSources:[new Fa],systemCommands:[Pa()]}}const La={s:1e3,m:6e4,h:36e5,d:864e5},Y=`Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron "<expr>" <instruction>`;function Ra(e,t){let n=e.trim();if(n.length===0)return{ok:!1,error:Y};if(n.startsWith(`in `)){let e=n.slice(3).trim(),r=e.indexOf(` `);if(r===-1)return{ok:!1,error:`Missing instruction. ${Y}`};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}". ${Y}`};if(a.length===0)return{ok:!1,error:`Missing instruction. ${Y}`};let s=parseInt(o[1],10)*La[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+(.+)$/.exec(e);if(!t)return{ok:!1,error:`cron form needs a quoted expression. ${Y}`};let r=t[2].trim();return r.length===0?{ok:!1,error:`Missing instruction. ${Y}`}:{ok:!0,spec:{cronExpression:t[1].trim(),instruction:r,recurring:!0}}}return{ok:!1,error:Y}}function za(e,t){return`${e}: ${t.slice(0,48)}${t.length>48?`…`:``}`}async function Ba(e,t,n=Date.now()){let r=Ra(t,n);if(!r.ok)return{message:r.error,success:!1};let{cronExpression:i,instruction:a,recurring:o}=r.spec,s=await e.spawnScheduledWake({label:za(`Scheduled`,a),cronExpression:i,agentInstruction:a});return{message:`Scheduled wake (${o?`cron \`${i}\``:`once at ${i}`}): "${a}" — task ${s.id}.`,success:!0,data:{taskId:s.id,cronExpression:i,recurring:o}}}function Va(e){let t=/^["']([^"']+)["']\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 Ha(e,t){let n=Va(t);if(!n)return{message:`Usage: /monitor "<command>" "<pattern>" <instruction>`,success:!1};let r=await e.spawnMonitorWake({label:za(`Monitor`,n.instruction),command:n.command,matchPattern:n.matchPattern,agentInstruction:n.instruction});return{message:`Monitoring \`${n.command}\` for /${n.matchPattern}/ — task ${r.id}.`,success:!0,data:{taskId:r.id,matchPattern:n.matchPattern}}}function Ua(e){let t=e.getAgentJobCapability?.();if(!t)throw Error(`Scheduling requires an active agent runtime.`);return t}function Wa(){return{name:`schedule`,displayName:`Schedule Wake`,description:`Schedule the agent to wake and run an instruction on a timer (one-shot or cron).`,source:`schedule`,argumentHint:`in <N><s|m|h|d> <instruction> | cron "<expr>" <instruction>`,modelInvocable:!0}}function Ga(){return{name:`monitor`,displayName:`Monitor Process`,description:`Watch a process’s output and wake the agent when a line matches a pattern.`,source:`schedule`,argumentHint:`"<command>" "<pattern>" <instruction>`,modelInvocable:!0}}function Ka(){let e=Wa();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Ba(Ua(e),t)}}function qa(){let e=Ga();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>Ha(Ua(e),t)}}var Ja=class{name=`schedule`;getCommands(){return[Wa(),Ga()]}};function Ya(){return{name:`agent-command-schedule`,commandSources:[new Ja],systemCommands:[Ka(),qa()],sessionRequirements:[`agent-runtime`]}}const Xa={"claude-opus-4-7":{inputPerMillion:15,outputPerMillion:75},"claude-opus-4-5":{inputPerMillion:15,outputPerMillion:75},"claude-sonnet-4-6":{inputPerMillion:3,outputPerMillion:15},"claude-sonnet-4-5":{inputPerMillion:3,outputPerMillion:15},"claude-haiku-4-5":{inputPerMillion:.8,outputPerMillion:4},"claude-3-5-sonnet-20241022":{inputPerMillion:3,outputPerMillion:15},"claude-3-5-haiku-20241022":{inputPerMillion:.8,outputPerMillion:4},"claude-3-opus-20240229":{inputPerMillion:15,outputPerMillion:75},"gpt-4o":{inputPerMillion:2.5,outputPerMillion:10},"gpt-4o-mini":{inputPerMillion:.15,outputPerMillion:.6},o1:{inputPerMillion:15,outputPerMillion:60},"o1-mini":{inputPerMillion:3,outputPerMillion:12},o3:{inputPerMillion:10,outputPerMillion:40},"o3-mini":{inputPerMillion:1.1,outputPerMillion:4.4},"deepseek-chat":{inputPerMillion:.14,outputPerMillion:.28},"deepseek-reasoner":{inputPerMillion:.55,outputPerMillion:2.19},"gemini-2.0-flash":{inputPerMillion:.1,outputPerMillion:.4},"gemini-2.0-flash-thinking":{inputPerMillion:.35,outputPerMillion:3.5},"gemini-1.5-pro":{inputPerMillion:1.25,outputPerMillion:5},"gemini-1.5-flash":{inputPerMillion:.075,outputPerMillion:.3}},Za=[{pattern:/claude-opus/i,price:{inputPerMillion:15,outputPerMillion:75}},{pattern:/claude-sonnet/i,price:{inputPerMillion:3,outputPerMillion:15}},{pattern:/claude-haiku/i,price:{inputPerMillion:.8,outputPerMillion:4}},{pattern:/gpt-4o-mini/i,price:{inputPerMillion:.15,outputPerMillion:.6}},{pattern:/gpt-4/i,price:{inputPerMillion:2.5,outputPerMillion:10}},{pattern:/deepseek/i,price:{inputPerMillion:.14,outputPerMillion:.28}},{pattern:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Qa(e){let t=Xa[e];if(t)return t;for(let{pattern:t,price:n}of Za)if(t.test(e))return n}function $a(e,t,n){let r=Qa(e);if(r)return t/1e6*r.inputPerMillion+n/1e6*r.outputPerMillion}function X(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function eo(e){return e.toLocaleString(`en-US`)}const to=`Conversation cleared.`;function no(e,t){return Fe(e),{success:!0,message:to,effects:[{type:`conversation-history-cleared`}]}}function ro(e,t){let n=_t(t);return n===void 0?{success:!1,message:pe}:{success:!0,message:`Session renamed to "${n}".`,data:{name:n},effects:[Ue(n)]}}function io(e,t){return{success:!0,message:`Opening session picker...`,data:{triggerResumePicker:!0},effects:[He()]}}const ao=`.robota/budget.json`;function oo(e){let t=_(e,ao);if(!Jt(t))return;let n;try{n=Xt(t,`utf-8`)}catch{return}try{return JSON.parse(n)}catch{return}}function so(e,t){Yt(_(e,`.robota`),{recursive:!0}),Zt(_(e,ao),JSON.stringify(t,null,2))}function co(e){let t=_(e,ao);Jt(t)&&Zt(t,`{}`)}function lo(e){let t=e.getSession(),n=St(e),r=t.getSessionTokenUsage?.(),i=t.getModelId?.(),a=[`Session: ${n.sessionId}`,`Messages: ${n.messageCount}`],o={sessionId:n.sessionId,messageCount:n.messageCount};if(r){if(a.push(`Tokens: ${eo(r.inputTokens)} input / ${eo(r.outputTokens)} output`),o.inputTokens=r.inputTokens,o.outputTokens=r.outputTokens,i){let t=$a(i,r.inputTokens,r.outputTokens);if(t!==void 0){a.push(`Cost: ${X(t)} (${i})`),o.estimatedCostUsd=t;let n=oo(e.getCwd());if(n?.monthly){let e=n.monthly-t,r=Math.min(100,Math.round(t/n.monthly*100));a.push(`Budget: ${X(e)} remaining of ${X(n.monthly)}/mo (${r}% used)`),o.budgetMonthly=n.monthly,o.budgetRemainingUsd=e}}}}else a.push(`Tokens: not yet available (no turns completed)`);return{lines:a,data:o}}function uo(e,t){let n=t.trim();if(n.startsWith(`budget`)){let t=n.slice(6).trim();if(t===`clear`)return co(e.getCwd()),{success:!0,message:`Monthly budget cleared.`};if(t===``){let t=oo(e.getCwd());return t?.monthly?{success:!0,message:`Monthly budget: ${X(t.monthly)}`}:{success:!0,message:`No budget set. Use: /cost budget <amount>`}}let r=parseFloat(t);return!Number.isFinite(r)||r<=0?{success:!1,message:`Usage: /cost budget <amount> (e.g. /cost budget 5.00)`}:(so(e.getCwd(),{monthly:r}),{success:!0,message:`Monthly budget set to ${X(r)}.`})}let{lines:r,data:i}=lo(e);return{success:!0,message:r.join(`
58
+ `),data:i}}function fo(e,t){let n=Vt(e);return{success:n.validation.ok,message:Xe(n),data:{logFile:n.logFile,entryCount:n.entryCount,issueCount:n.validation.issues.length,ok:n.validation.ok}}}function po(){return{name:`clear`,displayName:`Clear History`,description:i,source:`session`,modelInvocable:!1}}function Z(){return{name:`rename`,displayName:`Rename Session`,description:fe,source:`session`,modelInvocable:!1}}function mo(){return{name:`resume`,displayName:`Resume Session`,description:me,source:`session`,modelInvocable:!1}}function ho(){return{name:`cost`,displayName:`Session Cost`,description:a,source:`session`,modelInvocable:!1}}function go(){return{name:`validate-session`,displayName:`Validate Session`,description:be,source:`session`,modelInvocable:!1}}function _o(){let e=po();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:no}}function vo(){let e=Z();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:ro}}function yo(){let e=mo();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:io}}function bo(){let e=ho();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:uo}}function xo(){let e=go();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:fo}}var So=class{name=`session`;getCommands(){return[po(),Z(),mo(),ho(),go()]}};const Co={clear:{type:`confirm`,message:`Clear conversation history?`}};function wo(){return{name:`agent-command-session`,commandSources:[new So],systemCommands:[_o(),vo(),yo(),bo(),xo()],interactionHints:Co}}function To(){return{name:`settings`,displayName:`Settings`,description:`Open transport settings — enable/disable transports and configure options`,source:`settings`,modelInvocable:!1}}function Eo(){let e=To();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...`,effects:[{type:`settings-tui-requested`}]})}}var Do=class{name=`settings`;getCommands(){return[To()]}};function Oo(){return{name:`agent-command-settings`,commandSources:[new Do],systemCommands:[Eo()]}}const ko=`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. Slash syntax is a UI input/display concern; the SDK command identity is "skills".`;function Ao(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 jo(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}${Ao(e)}`}function Mo(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(`
59
+ `):[`Registered skills:`,...e.map(jo),``,`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(`
60
+ `)}function No(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 Po(e,t=``){let n=No(t);if(n.action===`activate`&&n.skillName!==void 0){if(!e.executeSkillCommandByName)return{success:!1,message:`Skill activation is not available in this session.`};let t=`/${n.skillName}${n.skillArgs?` ${n.skillArgs}`:``}`;return await e.executeSkillCommandByName(n.skillName,n.skillArgs,{invocationSource:e.getCommandInvocationSource?.()??`user`,displayInput:t,rawInput:t})??{success:!1,message:`Unknown skill: ${n.skillName}`}}let r=e.listSkills?.()??[];return{success:!0,message:Mo(r),data:{skills:r,activationContract:{activateWith:`/skills <skill-name> [args]`,activationRequiredBeforeWorkflow:!0,metadataIsNotSkillContent:!0}}}}function Fo(){return{name:`skills`,displayName:`Skills`,description:ko,source:`skills`,modelInvocable:!0,userInvocable:!0,argumentHint:`[list | <skill-name> [args]]`,safety:`read-only`}}function Io(){let e=Fo();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,lifecycle:`inline`,execute:Po}}var Lo=class{name=`skills`;getCommands(){return[Fo()]}};function Ro(e){let t=[new Lo];return t.push(new ye(e.cwd)),{name:`agent-command-skills`,commandSources:t,systemCommands:[Io()]}}const zo=[`Usage: /statusline on | off | reset | git on | git off`,`Fields: model, context, permission mode, message count, session name, thinking state, git branch.`].join(`
61
+ `);function Bo(e){let t=e.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0),[n,r]=t;return n===`on`&&r===void 0?{success:!0,message:`Status line enabled.`,patch:{enabled:!0}}:n===`off`&&r===void 0?{success:!0,message:`Status line disabled.`,patch:{enabled:!1}}:n===`reset`&&r===void 0?{success:!0,message:`Status line settings reset.`,patch:{...s}}:n===`git`&&r===`on`&&t.length===2?{success:!0,message:`Status line git branch shown.`,patch:{gitBranch:!0}}:n===`git`&&r===`off`&&t.length===2?{success:!0,message:`Status line git branch hidden.`,patch:{gitBranch:!1}}:{success:!1,message:zo}}function Vo(e,t){let n=Bo(t);return n.success?{success:!0,message:n.message,effects:[{type:`statusline-settings-patch`,patch:n.patch}]}:{success:!1,message:n.message}}function Ho(){return{name:`statusline`,displayName:`Status Line`,description:ve,source:`statusline`,argumentHint:_e,subcommands:je(`statusline`),modelInvocable:!1}}function Uo(){let e=Ho();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:Vo}}var Wo=class{name=`statusline`;getCommands(){return[Ho()]}};function Go(){return{name:`agent-command-statusline`,commandSources:[new Wo],systemCommands:[Uo()]}}const Ko=`Inspect Robota user-local storage and memory state.`,qo=`storage list [--format json] | memory set/list/inspect/disable/delete`,Q=`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 Jo(e){return e.length===0?`No user-local memory items.`:e.map(e=>`- ${e.category}/${e.key} (${e.enabled?`enabled`:`disabled`})`).join(`
62
+ `)}function $(e){if(e===void 0)throw Error(`User-local memory category is required.`);return e}async function Yo(e,t){let n=await ft({activeRepositoryRoot:e});return{message:t.format===`json`?JSON.stringify(n,null,2):Jo(n.items),success:!0,data:{list:n}}}async function Xo(e,t){let[n,r,i]=t.positional,a=await It({activeRepositoryRoot:e,category:$(n),key:r??``,value:i??``,summary:t.summary??``,source:t.source??``});return{message:`Stored user-local memory item ${a.category}/${a.key} at ${a.storageLocation}`,success:!0,data:{item:a}}}async function Zo(e,t){let[n,r]=t.positional,i=await rt({activeRepositoryRoot:e,category:$(n),key:r??``});return{message:t.format===`json`?JSON.stringify(i,null,2):`${i.category}/${i.key}: ${i.summary}`,success:!0,data:{item:i}}}async function Qo(e,t){let[n,r]=t.positional,i=await Ke({activeRepositoryRoot:e,category:$(n),key:r??``});return{message:`Disabled user-local memory item ${i.category}/${i.key}`,success:!0,data:{item:i}}}async function $o(e,t){let[n,r]=t.positional,i=await Ge({activeRepositoryRoot:e,category:$(n),key:r??``});return{message:`Deleted user-local memory item ${i.category}/${i.key}`,success:!0,data:{result:i}}}async function es(e,t){return(t.action??`list`)===`list`?Yo(e,t):t.action===`set`?Xo(e,t):t.action===`inspect`?Zo(e,t):t.action===`disable`?Qo(e,t):t.action===`delete`?$o(e,t):{message:Q,success:!1}}function ts(e){if(e===void 0||e===`text`)return`text`;if(e===`json`)return`json`;throw Error(`Unsupported user-local output format: ${e}`)}function ns(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 rs(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=ns(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:ts(n),summary:r,source:i}}function is(e){return e.trim().split(/\s+/).filter(Boolean)}function as(e,t){let n=t.map(e=>`- ${e.category}`);return[`User-local storage root: ${e}`,`Categories:`,...n].join(`
63
+ `)}async function os(e,t){if((t.action??`list`)!==`list`)return{message:Q,success:!1};let n=await it({activeRepositoryRoot:e});return{message:t.format===`json`?JSON.stringify(n,null,2):as(n.root,n.categories),success:!0,data:{root:n.root,categories:n.categories,inspection:n}}}async function ss(e,t){return t.target===`storage`?os(e,t):t.target===`memory`?es(e,t):{message:Q,success:!1}}function cs(e){return e.includes(`ENOENT`)?`User-local memory item not found.`:e}async function ls(e){try{return await ss(e.cwd,rs(e.argv,{format:e.format,summary:e.summary,source:e.source}))}catch(e){return{message:cs(e instanceof Error?e.message:String(e)),success:!1}}}async function us(e,t){try{return await ss(e.getCwd(),rs(is(t)))}catch(e){return{message:cs(e instanceof Error?e.message:String(e)),success:!1}}}function ds(){return{name:`user-local`,displayName:`User Config`,description:Ko,source:`user-local`,argumentHint:qo,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 fs(){let e=ds();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,safety:e.safety,subcommands:e.subcommands,execute:us}}var ps=class{name=`user-local`;getCommands(){return[ds()]}};function ms(){return{name:`agent-command-user-local`,commandSources:[new ps],systemCommands:[fs()]}}function hs(e,t,n){let r=e;if(t!==void 0){let e=new Set(t);r=r.filter(t=>e.has(t.name))}if(n!==void 0){let e=new Set(n);r=r.filter(t=>!e.has(t.name))}return r}function gs({cwd:e,providerDefinitions:t,providerSettingsAdapter:n,enabledCommandModules:r,disabledCommandModules:i}){return hs([Ro({cwd:e}),pr(),En(),zr(),Fr(),ci(),vr(),jn(),Ar(),ms(),Ln(),ir(),lr(),wo(),xa(),Ia(),Ya(),Go(),$r(),Oo(),da({providerDefinitions:t,settings:n})],r,i)}function _s(e){let t=$t(),i=_(t,`.robota`,`plugins`),a=_(t,`.robota`,`settings.json`),o=(e,t)=>Qt(e,{timeout:t.timeout,stdio:t.stdio??`pipe`}),s=new le(a),c=new u({pluginsDir:i,exec:o});return{cwd:e,marketplace:c,installer:new n({pluginsDir:i,settingsStore:s,marketplaceClient:c,exec:o}),loader:new r(i),settingsStore:s}}async function vs(e){let t=await e.loader.loadAll(),n=e.settingsStore.getEnabledPlugins();return t.map(e=>{let t=e.pluginDir.split(`/`),r=t.indexOf(`cache`),i=r>=0?t[r+1]??``:``,a=i?`${e.manifest.name}@${i}`:e.manifest.name;return{name:a,description:e.manifest.description,enabled:n[a]!==!1&&n[e.manifest.name]!==!1}})}async function ys(e,t){let n;try{n=e.marketplace.fetchManifest(t)}catch{return[]}let r=e.installer.getInstalledPlugins(),i=new Set(Object.values(r).map(e=>e.pluginName));return n.plugins.map(e=>({name:e.name,description:e.description,installed:i.has(e.name)}))}async function bs(e,t,r){let[i,a]=t.split(`@`);if(!i||!a)throw Error(`Plugin ID must be in format: name@marketplace`);if(r===`project`){await new n({pluginsDir:_(e.cwd,`.robota`,`plugins`),settingsStore:e.settingsStore,marketplaceClient:e.marketplace,exec:(e,t)=>Qt(e,{timeout:t.timeout,stdio:t.stdio??`pipe`})}).install(i,a);return}await e.installer.install(i,a)}async function xs(e,t){let n=e.installer.getPluginsByMarketplace(t);for(let t of n)await e.installer.uninstall(`${t.pluginName}@${t.marketplace}`);e.marketplace.removeMarketplace(t)}function Ss(e){return e.marketplace.listMarketplaces().map(e=>({name:e.name,type:e.source.type}))}function Cs(e){let t=_s(e);return{listInstalled:()=>vs(t),listAvailablePlugins:e=>ys(t,e),install:(e,n)=>bs(t,e,n),uninstall:async e=>t.installer.uninstall(e),enable:async e=>t.installer.enable(e),disable:async e=>t.installer.disable(e),marketplaceAdd:async e=>e.includes(`/`)&&!e.includes(`:`)?t.marketplace.addMarketplace({type:`github`,repo:e}):t.marketplace.addMarketplace({type:`git`,url:e}),marketplaceRemove:e=>xs(t,e),marketplaceUpdate:async e=>t.marketplace.updateMarketplace(e),marketplaceList:async()=>Ss(t),reloadPlugins:async()=>({loadedPluginCount:(await t.loader.loadAll()).length})}}const ws=`plugin`;function Ts(){return process.env.HOME??$t()}function Es(e){let t=new r(_(Ts(),`.robota`,`plugins`));try{let n=t.loadPluginsSync();return n.length===0?(e.replaceSource(ws),0):(e.replaceSource(ws,new ce(n)),n.length)}catch{return e.replaceSource(ws),0}}export{Tn as AgentCommandSource,An as BackgroundCommandSource,to as CLEAR_COMMAND_MESSAGE,In as CompactCommandSource,rr as ContextCommandSource,sr as ExitCommandSource,fr as HelpCommandSource,gr as LanguageCommandSource,kr as MemoryCommandSource,Nr as ModeCommandSource,Rr as PermissionsCommandSource,Qr as PluginManagerCommandSource,oi as PresetCommandSource,ca as ProviderCommandSource,Fa as RewindCommandSource,ko as SKILLS_COMMAND_DESCRIPTION,zo as STATUSLINE_USAGE,Ja as ScheduleCommandSource,So as SessionCommandSource,Do as SettingsCommandSource,Lo as SkillsCommandSource,Wo as StatusLineCommandSource,qo as USER_LOCAL_COMMAND_ARGUMENT_HINT,Ko as USER_LOCAL_COMMAND_DESCRIPTION,Q as USER_LOCAL_COMMAND_USAGE,ps as UserLocalCommandSource,x as createAgentCommandEntry,En as createAgentCommandModule,wn as createAgentSystemCommand,S as createBackgroundCommandEntry,jn as createBackgroundCommandModule,po as createClearCommandEntry,Pn as createCompactCommandEntry,Ln as createCompactCommandModule,tr as createContextCommandEntry,ir as createContextCommandModule,ho as createCostCommandEntry,gs as createDefaultCommandModules,Cs as createDefaultPluginCommandAdapter,D as createExitCommandEntry,lr as createExitCommandModule,O as createHelpCommandEntry,pr as createHelpCommandModule,k as createLanguageCommandEntry,vr as createLanguageCommandModule,M as createMemoryCommandEntry,Ar as createMemoryCommandModule,N as createModeCommandEntry,Fr as createModeCommandModule,Ga as createMonitorCommandEntry,P as createPermissionsCommandEntry,zr as createPermissionsCommandModule,R as createPluginCommandEntry,$r as createPluginCommandModule,B as createPresetCommandEntry,ci as createPresetCommandModule,sa as createProviderCommandEntry,da as createProviderCommandModule,V as createProviderSetupFlow,z as createReloadPluginsCommandEntry,Z as createRenameCommandEntry,va as createResetCommandEntry,xa as createResetCommandModule,mo as createResumeCommandEntry,Ia as createRewindCommandModule,Wa as createScheduleCommandEntry,Ya as createScheduleCommandModule,wo as createSessionCommandModule,To as createSettingsCommandEntry,Oo as createSettingsCommandModule,Fo as createSkillsCommandEntry,Ro as createSkillsCommandModule,Ho as createStatusLineCommandEntry,Go as createStatusLineCommandModule,ds as createUserLocalCommandEntry,ms as createUserLocalCommandModule,go as createValidateSessionCommandEntry,ma as ensureProviderConfig,bn as executeAgentCommand,On as executeBackgroundCommand,no as executeClearCommand,Nn as executeCompactCommand,Bn as executeContextCommand,uo as executeCostCommand,ar as executeExitCommand,ur as executeHelpCommand,mr as executeLanguageCommand,Dr as executeMemoryCommand,jr as executeModeCommand,Ha as executeMonitorCommand,Ir as executePermissionsCommand,Jr as executePluginCommand,ri as executePresetCommand,ea as executeProviderCommand,Yr as executeReloadPluginsCommand,ro as executeRenameCommand,_a as executeResetCommand,io as executeResumeCommand,Ma as executeRewindCommand,Ba as executeScheduleCommand,Po as executeSkillsCommand,Vo as executeStatusLineCommand,us as executeUserLocalCommand,ls as executeUserLocalDirectCommand,fo as executeValidateSessionCommand,W as formatProviderSetupChoiceLabel,G as formatProviderSetupHelpLinks,fi as formatProviderSetupPromptLabel,li as formatProviderSetupSelectionPrompt,H as getProviderSetupStep,Ra as parseScheduleSpec,Es as reloadPluginCommandSource,ui as resolveProviderSetupSelection,di as runProviderSetupPromptFlow,pa as runProviderStartupSetup,U as submitProviderSetupValue,K as validateProviderSetupValue};
63
64
  //# sourceMappingURL=index.js.map