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

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.
Files changed (200) hide show
  1. package/README.md +11 -2
  2. package/dist/node/index.cjs +76 -38
  3. package/dist/node/index.d.cts +946 -0
  4. package/dist/node/index.d.cts.map +1 -0
  5. package/dist/node/index.d.ts +564 -51
  6. package/dist/node/index.d.ts.map +1 -1
  7. package/dist/node/index.js +76 -38
  8. package/dist/node/index.js.map +1 -1
  9. package/package.json +34 -16
  10. package/src/advisor/advisor-command-module.ts +47 -0
  11. package/src/advisor/advisor-command.test.ts +102 -0
  12. package/src/advisor/advisor-command.ts +55 -0
  13. package/src/advisor/advisor-cost-functional.test.ts +92 -0
  14. package/src/advisor/index.ts +6 -0
  15. package/src/agent/__tests__/agent-command.test.ts +39 -8
  16. package/src/agent/agent-command-module.ts +14 -7
  17. package/src/agent/agent-command-parser.ts +1 -1
  18. package/src/agent/agent-command.ts +3 -3
  19. package/src/background/__tests__/background-command-module.test.ts +59 -52
  20. package/src/background/background-command-module.ts +2 -1
  21. package/src/background/background-command.ts +3 -3
  22. package/src/command-module-utils.ts +33 -0
  23. package/src/compact/__tests__/compact-command-module.test.ts +31 -23
  24. package/src/compact/compact-command-module.ts +10 -1
  25. package/src/compact/compact-command.ts +6 -3
  26. package/src/context/__tests__/context-command-module.test.ts +214 -63
  27. package/src/context/auto-compact-format.ts +25 -0
  28. package/src/context/context-breakdown.ts +295 -0
  29. package/src/context/context-command-module.ts +45 -14
  30. package/src/context/context-command.ts +34 -257
  31. package/src/default/__tests__/__snapshots__/model-exposure.test.ts.snap +110 -0
  32. package/src/default/__tests__/default-command-modules.test.ts +59 -7
  33. package/src/default/__tests__/model-exposure.test.ts +241 -0
  34. package/src/default/__tests__/org-policy-forwarding.test.ts +98 -0
  35. package/src/default/default-command-modules.ts +130 -18
  36. package/src/default/index.ts +4 -1
  37. package/src/devices/__tests__/devices-command-module.test.ts +212 -0
  38. package/src/devices/devices-command-module.ts +224 -0
  39. package/src/devices/devices-command-port.ts +82 -0
  40. package/src/devices/index.ts +11 -0
  41. package/src/doctor/__tests__/doctor-command-module.test.ts +145 -0
  42. package/src/doctor/__tests__/doctor-display-vocabulary.test.ts +38 -0
  43. package/src/doctor/__tests__/doctor-fixture.ts +145 -0
  44. package/src/doctor/__tests__/doctor-redaction.test.ts +29 -0
  45. package/src/doctor/__tests__/doctor-runner.test.ts +464 -0
  46. package/src/doctor/doctor-command-module.ts +132 -0
  47. package/src/doctor/doctor-extensions-probe.ts +299 -0
  48. package/src/doctor/doctor-node-deps.ts +89 -0
  49. package/src/doctor/doctor-redaction.ts +99 -0
  50. package/src/doctor/doctor-render.ts +70 -0
  51. package/src/doctor/doctor-repair.ts +136 -0
  52. package/src/doctor/doctor-runner.ts +122 -0
  53. package/src/doctor/doctor-settings-probe.ts +239 -0
  54. package/src/doctor/doctor-storage-probe.ts +187 -0
  55. package/src/doctor/doctor-types.ts +109 -0
  56. package/src/doctor/index.ts +32 -0
  57. package/src/editor/__tests__/editor-command-functional.test.ts +49 -16
  58. package/src/editor/editor-command-module.ts +6 -5
  59. package/src/editor/editor-command.ts +10 -5
  60. package/src/effort/effort-command-module.ts +51 -0
  61. package/src/effort/effort-command.test.ts +140 -0
  62. package/src/effort/effort-command.ts +122 -0
  63. package/src/effort/index.ts +6 -0
  64. package/src/exit/__tests__/exit-command-module.test.ts +16 -9
  65. package/src/exit/exit-command-module.ts +2 -1
  66. package/src/exit/exit-command.ts +6 -6
  67. package/src/fork/__tests__/fork-command.test.ts +184 -0
  68. package/src/fork/fork-command-module.ts +61 -0
  69. package/src/fork/fork-command.ts +162 -0
  70. package/src/fork/index.ts +8 -0
  71. package/src/git/__tests__/fake-git-port.ts +28 -0
  72. package/src/git/__tests__/git-command-module.test.ts +103 -0
  73. package/src/git/__tests__/git-commit.test.ts +185 -0
  74. package/src/git/__tests__/git-diff.test.ts +125 -0
  75. package/src/git/__tests__/git-process.test.ts +221 -0
  76. package/src/git/__tests__/git-status.test.ts +117 -0
  77. package/src/git/git-command-module.ts +139 -0
  78. package/src/git/git-commit.ts +251 -0
  79. package/src/git/git-diff.ts +129 -0
  80. package/src/git/git-process.ts +169 -0
  81. package/src/git/git-status.ts +134 -0
  82. package/src/git/index.ts +17 -0
  83. package/src/goal/__tests__/goal-command.test.ts +9 -4
  84. package/src/goal/goal-command-module.ts +2 -1
  85. package/src/goal/goal-command.ts +6 -9
  86. package/src/handoff/__tests__/handoff-command.test.ts +218 -0
  87. package/src/handoff/handoff-command-module.ts +48 -0
  88. package/src/handoff/handoff-command.ts +187 -0
  89. package/src/handoff/index.ts +6 -0
  90. package/src/help/__tests__/help-command-module.test.ts +63 -40
  91. package/src/help/__tests__/help-command.test.ts +46 -37
  92. package/src/help/help-command-module.ts +2 -1
  93. package/src/help/help-command.ts +3 -3
  94. package/src/index.ts +124 -2
  95. package/src/keybindings/__tests__/keybindings-command-module.test.ts +57 -0
  96. package/src/keybindings/index.ts +6 -0
  97. package/src/keybindings/keybindings-command-module.ts +74 -0
  98. package/src/language/__tests__/language-command-module.test.ts +33 -28
  99. package/src/language/language-command-module.ts +2 -1
  100. package/src/language/language-command.ts +8 -6
  101. package/src/mcp-activation/__tests__/mcp-activation-command.test.ts +630 -0
  102. package/src/mcp-activation/__tests__/mcp-model-view.test.ts +211 -0
  103. package/src/mcp-activation/index.ts +12 -0
  104. package/src/mcp-activation/mcp-activation-command-module.ts +92 -0
  105. package/src/mcp-activation/mcp-activation-command.ts +448 -0
  106. package/src/mcp-activation/mcp-model-notice.ts +85 -0
  107. package/src/mcp-activation/mcp-model-status.ts +99 -0
  108. package/src/memory/__tests__/memory-command-module.test.ts +167 -74
  109. package/src/memory/memory-command-module.ts +18 -1
  110. package/src/memory/memory-command.ts +38 -38
  111. package/src/mode/__tests__/mode-command-module.test.ts +51 -38
  112. package/src/mode/mode-command-module.ts +2 -1
  113. package/src/mode/mode-command.ts +15 -7
  114. package/src/output-style/__tests__/output-style-command.test.ts +96 -0
  115. package/src/output-style/index.ts +6 -0
  116. package/src/output-style/output-style-command-module.ts +143 -0
  117. package/src/peers/__tests__/peers-command.test.ts +241 -0
  118. package/src/peers/index.ts +9 -0
  119. package/src/peers/peers-command-module.ts +47 -0
  120. package/src/peers/peers-command.ts +142 -0
  121. package/src/permissions/__tests__/permissions-command-module.test.ts +149 -37
  122. package/src/permissions/permissions-command-module.ts +2 -1
  123. package/src/permissions/permissions-command.ts +46 -4
  124. package/src/plan/__tests__/plan-command.test.ts +129 -0
  125. package/src/plan/index.ts +9 -0
  126. package/src/plan/plan-command-module.ts +49 -0
  127. package/src/plan/plan-command.ts +92 -0
  128. package/src/plugin/__tests__/plugin-command-module.test.ts +46 -40
  129. package/src/plugin/__tests__/plugin-host-boundary.test.ts +11 -0
  130. package/src/plugin/plugin-command-module.ts +3 -1
  131. package/src/plugin/plugin-command.ts +17 -16
  132. package/src/preset/__tests__/host-supplied-preset-registry.test.ts +98 -0
  133. package/src/preset/__tests__/preset-command-module.test.ts +102 -56
  134. package/src/preset/preset-command-module.ts +26 -8
  135. package/src/preset/preset-command.ts +85 -27
  136. package/src/provider/__tests__/org-policy.test.ts +4 -5
  137. package/src/provider/__tests__/provider-command-module.test.ts +11 -14
  138. package/src/provider/__tests__/provider-startup-host-settings.test.ts +16 -0
  139. package/src/provider/__tests__/scripted-interaction.ts +7 -5
  140. package/src/provider/provider-command-execution.ts +4 -4
  141. package/src/provider/provider-command-module.ts +2 -1
  142. package/src/provider/provider-command-profile-lifecycle.ts +4 -4
  143. package/src/provider/provider-command-profile-operations.ts +3 -3
  144. package/src/provider/provider-command-profile.ts +1 -1
  145. package/src/provider/provider-command-setup.ts +4 -4
  146. package/src/provider/provider-startup.ts +62 -35
  147. package/src/remote-control/__tests__/remote-control-command-module.test.ts +36 -0
  148. package/src/remote-control/__tests__/remote-control-command.test.ts +216 -0
  149. package/src/remote-control/index.ts +8 -0
  150. package/src/remote-control/remote-control-command-module.ts +61 -0
  151. package/src/remote-control/remote-control-command.ts +138 -0
  152. package/src/reset/__tests__/reset-command-module.test.ts +5 -5
  153. package/src/reset/reset-command-module.ts +2 -1
  154. package/src/reset/reset-command.ts +3 -4
  155. package/src/rewind/__tests__/rewind-command-module.test.ts +40 -0
  156. package/src/rewind/rewind-command-module.ts +2 -1
  157. package/src/rewind/rewind-command.ts +73 -6
  158. package/src/sandbox/__tests__/sandbox-command.test.ts +80 -0
  159. package/src/sandbox/index.ts +2 -0
  160. package/src/sandbox/sandbox-command-module.ts +56 -0
  161. package/src/sandbox/sandbox-command.ts +94 -0
  162. package/src/schedule/__tests__/loop-command-functional.test.ts +386 -0
  163. package/src/schedule/__tests__/loop-command.test.ts +360 -0
  164. package/src/schedule/__tests__/loop-jitter.test.ts +25 -0
  165. package/src/schedule/__tests__/monitor-model-permission-functional.test.ts +126 -0
  166. package/src/schedule/__tests__/schedule-command.test.ts +143 -3
  167. package/src/schedule/__tests__/schedule-redos.test.ts +81 -0
  168. package/src/schedule/index.ts +3 -0
  169. package/src/schedule/loop-command.ts +333 -0
  170. package/src/schedule/loop-jitter.ts +41 -0
  171. package/src/schedule/schedule-command-module.ts +92 -14
  172. package/src/schedule/schedule-command.ts +98 -9
  173. package/src/schedule/schedule-spec-parser.ts +5 -1
  174. package/src/session/__tests__/rename-host-persistence.test.ts +72 -0
  175. package/src/session/__tests__/session-command-module.test.ts +210 -45
  176. package/src/session/session-command-module.ts +68 -37
  177. package/src/session/session-command.ts +147 -80
  178. package/src/settings/settings-command-module.ts +3 -2
  179. package/src/shell/__tests__/resolve-shell-host.test.ts +11 -0
  180. package/src/shell/__tests__/shell-command-functional.test.ts +23 -1
  181. package/src/shell/resolve-shell.ts +2 -2
  182. package/src/shell/shell-command-module.ts +6 -5
  183. package/src/shell/shell-command.ts +9 -5
  184. package/src/skills/__tests__/skills-command-module.test.ts +69 -28
  185. package/src/skills/index.ts +1 -0
  186. package/src/skills/skills-command-module.ts +22 -5
  187. package/src/skills/skills-command.ts +14 -13
  188. package/src/statusline/__tests__/statusline-command-module.test.ts +5 -4
  189. package/src/statusline/statusline-command-module.ts +2 -1
  190. package/src/statusline/statusline-command.ts +4 -4
  191. package/src/theme/__tests__/theme-command.test.ts +204 -0
  192. package/src/theme/index.ts +12 -0
  193. package/src/theme/theme-command-module.ts +211 -0
  194. package/src/user-local/__tests__/user-local-command.test.ts +145 -110
  195. package/src/user-local/user-local-command-constants.ts +1 -1
  196. package/src/user-local/user-local-command-module.ts +6 -5
  197. package/src/user-local/user-local-command.ts +12 -6
  198. package/src/user-local/user-local-memory-command.ts +17 -7
  199. package/src/plugins/default-plugin-command-adapter.ts +0 -164
  200. package/src/plugins/default-plugin-command-source-loader.ts +0 -31
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["formatError","getAgentHostContext","USAGE","SUBCOMMAND_INDEX","usage","formatError","formatList","usage","PROVIDER_RESTART_EFFECT","executeMemoryCommand","executeMemoryCommand"],"sources":["../../src/agent/agent-command-parser.ts","../../src/agent/agent-command.ts","../../src/agent/agent-command-module.ts","../../src/background/background-command.ts","../../src/background/background-command-module.ts","../../src/compact/compact-command.ts","../../src/compact/compact-command-module.ts","../../src/context/context-command.ts","../../src/context/context-command-module.ts","../../src/editor/resolve-editor.ts","../../src/shell/spawn-inherited.ts","../../src/editor/editor-command.ts","../../src/editor/editor-command-module.ts","../../src/exit/exit-command.ts","../../src/exit/exit-command-module.ts","../../src/goal/goal-command.ts","../../src/goal/goal-command-module.ts","../../src/help/help-command.ts","../../src/help/help-command-module.ts","../../src/language/language-command.ts","../../src/language/language-command-module.ts","../../src/memory/memory-command.ts","../../src/memory/memory-command-module.ts","../../src/mode/mode-command.ts","../../src/mode/mode-command-module.ts","../../src/permissions/permissions-command.ts","../../src/permissions/permissions-command-module.ts","../../src/plugin/plugin-command.ts","../../src/plugin/plugin-command-module.ts","../../src/preset/preset-command.ts","../../src/preset/preset-command-module.ts","../../src/provider/provider-setup-flow.ts","../../src/provider/provider-command-setup.ts","../../src/provider/provider-command-profile-operations.ts","../../src/provider/provider-command-profile-lifecycle.ts","../../src/provider/provider-command-profile.ts","../../src/provider/provider-command-execution.ts","../../src/provider/provider-command-module.ts","../../src/provider/provider-onboarding.ts","../../src/provider/provider-startup.ts","../../src/reset/reset-command.ts","../../src/reset/reset-command-module.ts","../../src/rewind/rewind-command.ts","../../src/rewind/rewind-command-module.ts","../../src/schedule/schedule-spec-parser.ts","../../src/schedule/schedule-command.ts","../../src/schedule/schedule-command-module.ts","../../src/session/model-pricing.ts","../../src/session/session-command.ts","../../src/session/session-command-module.ts","../../src/settings/settings-command-module.ts","../../src/shell/resolve-shell.ts","../../src/shell/shell-command.ts","../../src/shell/shell-command-module.ts","../../src/skills/skills-command.ts","../../src/skills/skills-command-module.ts","../../src/statusline/statusline-command.ts","../../src/statusline/statusline-command-module.ts","../../src/user-local/user-local-command-constants.ts","../../src/user-local/user-local-memory-command.ts","../../src/user-local/user-local-command.ts","../../src/user-local/user-local-command-module.ts","../../src/default/default-command-modules.ts","../../src/plugins/default-plugin-command-adapter.ts","../../src/plugins/default-plugin-command-source-loader.ts"],"sourcesContent":["import type { TBackgroundTaskIsolation } from '@robota-sdk/agent-interface-transport';\n\nconst DEFAULT_AGENT_TYPE = 'general-purpose';\n\nexport type TAgentMode = 'background';\n\nexport interface IAgentRunRequest {\n readonly agentType: string;\n readonly label: string;\n readonly mode: TAgentMode;\n readonly prompt: string;\n readonly model?: string;\n readonly isolation?: TBackgroundTaskIsolation;\n}\n\ninterface IParsedAgentOptions {\n readonly agentType?: string;\n readonly model?: string;\n readonly isolation?: TBackgroundTaskIsolation;\n readonly positional: string[];\n}\n\nexport function tokenizeArgs(args: string): string[] {\n const tokens: string[] = [];\n let current = '';\n let quote: '\"' | \"'\" | undefined;\n let escaped = false;\n\n for (const char of args) {\n if (escaped) {\n current += char;\n escaped = false;\n continue;\n }\n if (quote && char === '\\\\') {\n escaped = true;\n continue;\n }\n if (quote) {\n if (char === quote) quote = undefined;\n else current += char;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n if (/\\s/.test(char)) {\n if (current.length > 0) {\n tokens.push(current);\n current = '';\n }\n continue;\n }\n current += char;\n }\n\n if (current.length > 0) tokens.push(current);\n return tokens;\n}\n\nfunction parseOptions(tokens: readonly string[]): IParsedAgentOptions {\n const positional: string[] = [];\n let agentType: string | undefined;\n let model: string | undefined;\n let isolation: TBackgroundTaskIsolation | undefined;\n\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index];\n if (token === '--background') {\n continue;\n }\n if (token === '--agent' || token === '--type' || token === '-a') {\n agentType = tokens[index + 1];\n index += 1;\n continue;\n }\n if (token === '--model') {\n model = tokens[index + 1];\n index += 1;\n continue;\n }\n if (token === '--isolation') {\n const value = tokens[index + 1];\n if (value === 'none' || value === 'worktree') isolation = value;\n index += 1;\n continue;\n }\n if (token !== undefined) positional.push(token);\n }\n\n return {\n positional,\n ...(agentType ? { agentType } : {}),\n ...(model ? { model } : {}),\n ...(isolation ? { isolation } : {}),\n };\n}\n\nfunction createRequest(\n options: IParsedAgentOptions,\n agentType: string,\n label: string,\n prompt: string,\n): IAgentRunRequest {\n return {\n agentType,\n label,\n mode: 'background',\n prompt,\n ...(options.model ? { model: options.model } : {}),\n ...(options.isolation ? { isolation: options.isolation } : {}),\n };\n}\n\nexport function parseRunRequest(\n tokens: readonly string[],\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest | undefined {\n const options = parseOptions(tokens);\n const [first, ...rest] = options.positional;\n let agentType = options.agentType ?? DEFAULT_AGENT_TYPE;\n let promptParts = options.positional;\n\n if (!options.agentType && first && availableAgentNames.has(first)) {\n agentType = first;\n promptParts = rest;\n }\n\n const prompt = promptParts.join(' ').trim();\n if (!prompt) return undefined;\n return createRequest(options, agentType, agentType, prompt);\n}\n\nexport function parseParallelRequests(\n tokens: readonly string[],\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest[] {\n const options = parseOptions(tokens);\n return options.positional\n .map((token) => parseAgentJobToken(token, options, availableAgentNames))\n .filter((job): job is IAgentRunRequest => job !== undefined);\n}\n\nfunction parseAgentJobToken(\n token: string,\n options: IParsedAgentOptions,\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest | undefined {\n const equalsIndex = token.indexOf('=');\n if (equalsIndex > 0) {\n const label = token.slice(0, equalsIndex);\n const spec = token.slice(equalsIndex + 1);\n return parseAgentPromptSpec(label, spec, options, availableAgentNames);\n }\n\n const colonIndex = token.indexOf(':');\n if (colonIndex <= 0 || colonIndex === token.length - 1) return undefined;\n const head = token.slice(0, colonIndex);\n const prompt = token.slice(colonIndex + 1);\n const agentType =\n options.agentType ?? (availableAgentNames.has(head) ? head : DEFAULT_AGENT_TYPE);\n return createRequest(options, agentType, head, prompt);\n}\n\nfunction parseAgentPromptSpec(\n label: string,\n spec: string,\n options: IParsedAgentOptions,\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest | undefined {\n const colonIndex = spec.indexOf(':');\n if (colonIndex === -1) {\n const agentType =\n options.agentType ?? (availableAgentNames.has(label) ? label : DEFAULT_AGENT_TYPE);\n return createRequest(options, agentType, label, spec);\n }\n if (colonIndex === 0 || colonIndex === spec.length - 1) return undefined;\n return createRequest(options, spec.slice(0, colonIndex), label, spec.slice(colonIndex + 1));\n}\n","import { summarizeBackgroundJobGroup } from '@robota-sdk/agent-framework';\n\nimport { parseParallelRequests, parseRunRequest, tokenizeArgs } from './agent-command-parser.js';\n\nimport type { IAgentRunRequest } from './agent-command-parser.js';\nimport type { IAgentJobHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\nimport type { ISubagentJobState } from '@robota-sdk/agent-interface-transport';\n\nfunction formatError<TError>(error: TError): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction getAvailableAgentNames(session: IAgentJobHostContext): ReadonlySet<string> {\n return new Set(session.listAgentDefinitions().map((agent) => agent.name));\n}\n\nfunction validateAgentType(\n session: IAgentJobHostContext,\n agentType: string,\n): ICommandResult | undefined {\n const agents = session.listAgentDefinitions();\n if (agents.some((agent) => agent.name === agentType)) return undefined;\n return {\n message: `Unknown agent type: ${agentType}\\nAvailable agents: ${agents.map((agent) => agent.name).join(', ')}`,\n success: false,\n };\n}\n\nasync function spawnAgentJob(\n session: IAgentJobHostContext,\n request: IAgentRunRequest,\n): Promise<ICommandResult | { state: ISubagentJobState }> {\n const invalid = validateAgentType(session, request.agentType);\n if (invalid) return invalid;\n try {\n return { state: await session.spawnAgentJob(request) };\n } catch (error) {\n return { message: formatError(error), success: false };\n }\n}\n\nfunction executeOpenSwitcher(): ICommandResult {\n return { message: '', effects: [{ type: 'agent-switcher-requested' }], success: true };\n}\n\nasync function executeList(session: IAgentJobHostContext): Promise<ICommandResult> {\n const agents = session.listAgentDefinitions();\n const jobs = session.listAgentJobs();\n const lines = [\n 'Available agents:',\n ...agents.map((agent) => ` ${agent.name} - ${agent.description}`),\n '',\n jobs.length === 0 ? 'No active agent jobs.' : 'Agent jobs:',\n ...jobs.map((job) => ` ${formatAgentJobLine(job)}`),\n ];\n return {\n message: lines.join('\\n'),\n success: true,\n data: { agents: agents.length, jobs: jobs.length },\n };\n}\n\nfunction formatAgentJobLine(job: ISubagentJobState): string {\n const worktree = [\n job.worktreePath ? `worktree=${job.worktreePath}` : undefined,\n job.branchName ? `branch=${job.branchName}` : undefined,\n ].filter((segment): segment is string => segment !== undefined);\n const metadata = worktree.length > 0 ? ` ${worktree.join(' ')}` : '';\n return `${job.id} [${job.status}${metadata}] ${job.label} - ${job.promptPreview}`;\n}\n\nasync function executeRun(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const request = parseRunRequest(tokens, getAvailableAgentNames(session));\n if (!request) {\n return {\n message: 'Usage: agent run [AGENT_NAME] [--agent AGENT_NAME] PROMPT',\n success: false,\n };\n }\n\n const spawned = await spawnAgentJob(session, request);\n if ('success' in spawned) return spawned;\n const { state } = spawned;\n\n return {\n message: `Started agent job: ${state.id}`,\n success: true,\n data: { agentId: state.id, status: state.status },\n };\n}\n\nasync function executeParallel(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const wait = tokens.includes('--wait') || !tokens.includes('--detach');\n const commandTokens = tokens.filter((token) => token !== '--wait' && token !== '--detach');\n const jobs = parseParallelRequests(commandTokens, getAvailableAgentNames(session));\n\n if (jobs.length === 0) {\n return {\n message: 'Usage: agent parallel [--wait|--detach] LABEL:\"PROMPT\" [LABEL=AGENT_NAME:\"PROMPT\"]',\n success: false,\n };\n }\n\n const invalid = jobs\n .map((job) => validateAgentType(session, job.agentType))\n .find((result): result is ICommandResult => result !== undefined);\n if (invalid) return invalid;\n\n let states: ISubagentJobState[];\n try {\n states = await Promise.all(jobs.map((job) => session.spawnAgentJob(job)));\n } catch (error) {\n return { message: formatError(error), success: false };\n }\n const group = session.createBackgroundJobGroup({\n waitPolicy: 'wait_all',\n taskIds: states.map((state) => state.id),\n label: 'agent parallel',\n });\n\n if (wait) {\n const completed = await session.waitBackgroundJobGroup(group.id);\n const summary = summarizeBackgroundJobGroup(completed);\n return {\n message: formatGroupSummary(summary),\n success: true,\n data: { agentIds: states.map((state) => state.id), groupId: group.id, summary },\n };\n }\n\n return {\n message: ['Started agent jobs:', ...states.map((state) => `${state.label}: ${state.id}`)].join(\n '\\n',\n ),\n success: true,\n data: { agentIds: states.map((state) => state.id), groupId: group.id },\n };\n}\n\nasync function executeWait(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [groupId] = tokens;\n if (!groupId) return { message: 'Usage: agent wait GROUP_ID', success: false };\n const completed = await session.waitBackgroundJobGroup(groupId);\n const summary = summarizeBackgroundJobGroup(completed);\n return {\n message: formatGroupSummary(summary),\n success: true,\n data: { groupId, summary },\n };\n}\n\nasync function executeRead(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId, offset] = tokens;\n if (!agentId) return { message: 'Usage: agent read AGENT_ID [OFFSET]', success: false };\n const cursor = offset ? { offset: Number.parseInt(offset, 10) } : undefined;\n const page = await session.readBackgroundTaskLog(agentId, cursor);\n const next = page.nextCursor ? `\\nNext offset: ${page.nextCursor.offset}` : '';\n return {\n message: page.lines.length > 0 ? `${page.lines.join('\\n')}${next}` : `No log lines: ${agentId}`,\n success: true,\n data: { agentId, nextOffset: page.nextCursor?.offset },\n };\n}\n\nasync function executeSend(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId, ...promptParts] = tokens;\n const prompt = promptParts.join(' ').trim();\n if (!agentId || !prompt) {\n return { message: 'Usage: agent send AGENT_ID PROMPT', success: false };\n }\n await session.sendAgentJob(agentId, prompt);\n return { message: `Sent input to agent job: ${agentId}`, success: true, data: { agentId } };\n}\n\nasync function executeStop(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId, ...reasonParts] = tokens;\n if (!agentId) return { message: 'Usage: agent stop AGENT_ID [REASON]', success: false };\n await session.cancelAgentJob(agentId, reasonParts.join(' ') || undefined);\n return { message: `Agent job stopped: ${agentId}`, success: true, data: { agentId } };\n}\n\nasync function executeClose(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId] = tokens;\n if (!agentId) return { message: 'Usage: agent close AGENT_ID', success: false };\n await session.closeAgentJob(agentId);\n return { message: `Agent job closed: ${agentId}`, success: true, data: { agentId } };\n}\n\nexport async function executeAgentCommand(\n session: IAgentJobHostContext,\n args: string,\n): Promise<ICommandResult> {\n try {\n if (args.trim() === '') return executeOpenSwitcher();\n const [action = 'list', ...tokens] = tokenizeArgs(args);\n if (action === 'list' && tokens.length === 0) return executeList(session);\n if (action === 'run') return executeRun(session, tokens);\n if (action === 'parallel') return executeParallel(session, tokens);\n if (action === 'wait') return executeWait(session, tokens);\n if (action === 'read' || action === 'open') return executeRead(session, tokens);\n if (action === 'send') return executeSend(session, tokens);\n if (action === 'stop' || action === 'cancel') return executeStop(session, tokens);\n if (action === 'close') return executeClose(session, tokens);\n return executeRun(session, [action, ...tokens]);\n } catch (error) {\n return { message: formatError(error), success: false };\n }\n}\n\nfunction formatGroupSummary(summary: ReturnType<typeof summarizeBackgroundJobGroup>): string {\n const header = `Background job group ${summary.groupId}: ${summary.status} (${summary.completed}/${summary.total} completed, ${summary.failed} failed, ${summary.cancelled} cancelled, ${summary.pending} pending)`;\n return [header, ...summary.lines].join('\\n');\n}\n","import { executeAgentCommand } from './agent-command.js';\n\nimport type {\n IAgentJobHostContext,\n ICommandHostContext,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nfunction getAgentHostContext(context: ICommandHostContext): IAgentJobHostContext {\n const cap = context.getAgentJobCapability?.();\n if (!cap) throw new Error('Agent job capability is not available in this context.');\n return cap;\n}\n\nfunction createAgentSubcommands(): ICommand[] {\n return [\n { name: 'list', description: 'List available agents and active jobs', source: 'agent' },\n { name: 'run', description: 'Start one background agent job', source: 'agent' },\n { name: 'parallel', description: 'Run multiple agents in parallel', source: 'agent' },\n { name: 'wait', description: 'Wait for a background agent group summary', source: 'agent' },\n { name: 'read', description: 'Read an agent job log page', source: 'agent' },\n { name: 'send', description: 'Send follow-up input to an agent job', source: 'agent' },\n { name: 'stop', description: 'Cancel a running agent job', source: 'agent' },\n { name: 'close', description: 'Dismiss a terminal agent job', source: 'agent' },\n { name: 'open', description: 'Focus an agent job detail view when supported', source: 'agent' },\n ];\n}\n\nexport function createAgentCommandEntry(): ICommand {\n return {\n name: 'agent',\n displayName: 'Agent Jobs',\n description: [\n 'Subagent jobs command.',\n 'Natural-language arguments start one background agent job.',\n '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.',\n 'If the target item is unspecified, include target selection inside the agent prompt instead of delaying execution.',\n 'The parallel form starts multiple background agent jobs as a wait_all group and returns a consolidated group summary unless --detach is present.',\n 'list, wait, read, send, stop, close, and open manage existing agent jobs.',\n ].join(' '),\n source: 'agent',\n modelInvocable: true,\n argumentHint:\n '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',\n safety: 'background-agent',\n subcommands: createAgentSubcommands(),\n };\n}\n\nexport function createAgentSystemCommand(): ISystemCommand {\n const entry = createAgentCommandEntry();\n return {\n name: entry.name,\n ...(entry.displayName !== undefined ? { displayName: entry.displayName } : {}),\n description: entry.description,\n requiresPermission: false,\n execute: (context, args) => executeAgentCommand(getAgentHostContext(context), args),\n ...(entry.modelInvocable !== undefined ? { modelInvocable: entry.modelInvocable } : {}),\n ...(entry.userInvocable !== undefined ? { userInvocable: entry.userInvocable } : {}),\n ...(entry.argumentHint !== undefined ? { argumentHint: entry.argumentHint } : {}),\n ...(entry.safety !== undefined ? { safety: entry.safety } : {}),\n };\n}\n\nexport class AgentCommandSource implements ICommandSource {\n readonly name = 'agent';\n\n getCommands(): ICommand[] {\n return [createAgentCommandEntry()];\n }\n}\n\nexport function createAgentCommandModule(): ICommandModule {\n return {\n name: 'agent-command-agent',\n commandSources: [new AgentCommandSource()],\n systemCommands: [createAgentSystemCommand()],\n sessionRequirements: ['agent-runtime'],\n };\n}\n","import {\n BACKGROUND_COMMAND_USAGE,\n cancelCommandBackgroundTask,\n closeCommandBackgroundTask,\n formatCommandBackgroundTaskList,\n listCommandBackgroundTasks,\n parseCommandBackgroundLogCursor,\n readCommandBackgroundTaskLog,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nfunction parseCommandParts(args: string): string[] {\n return args.trim().split(/\\s+/).filter(Boolean);\n}\n\nexport async function executeBackgroundCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n const [action = 'list', taskId, ...reasonParts] = parseCommandParts(args);\n if (action === 'list') {\n const tasks = listCommandBackgroundTasks(context);\n return {\n message: formatCommandBackgroundTaskList(tasks),\n success: true,\n data: { count: tasks.length },\n };\n }\n\n if (!taskId) {\n return {\n message: BACKGROUND_COMMAND_USAGE,\n success: false,\n };\n }\n\n if (action === 'read' || action === 'log' || action === 'open') {\n const page = await readCommandBackgroundTaskLog(\n context,\n taskId,\n parseCommandBackgroundLogCursor(reasonParts[0]),\n );\n const next = page.nextCursor ? `\\nNext offset: ${page.nextCursor.offset}` : '';\n return {\n message:\n page.lines.length > 0 ? `${page.lines.join('\\n')}${next}` : `No log lines: ${taskId}`,\n success: true,\n data: { taskId, nextOffset: page.nextCursor?.offset },\n };\n }\n\n if (action === 'cancel' || action === 'stop') {\n await cancelCommandBackgroundTask(context, taskId, reasonParts.join(' ') || undefined);\n return { message: `Background task cancelled: ${taskId}`, success: true, data: { taskId } };\n }\n\n if (action === 'close' || action === 'dismiss') {\n await closeCommandBackgroundTask(context, taskId);\n return { message: `Background task closed: ${taskId}`, success: true, data: { taskId } };\n }\n\n return { message: `Unknown background action: ${action}`, success: false };\n}\n","import {\n BACKGROUND_COMMAND_DESCRIPTION,\n buildBackgroundCommandSubcommands,\n} from '@robota-sdk/agent-framework';\n\nimport { executeBackgroundCommand } from './background-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createBackgroundCommandEntry(): ICommand {\n return {\n name: 'background',\n displayName: 'Background Tasks',\n description: BACKGROUND_COMMAND_DESCRIPTION,\n source: 'background',\n modelInvocable: false,\n subcommands: buildBackgroundCommandSubcommands(),\n };\n}\n\nfunction createBackgroundSystemCommand(): ISystemCommand {\n const entry = createBackgroundCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n subcommands: entry.subcommands,\n execute: executeBackgroundCommand,\n };\n}\n\nexport class BackgroundCommandSource implements ICommandSource {\n readonly name = 'background';\n\n getCommands(): ICommand[] {\n return [createBackgroundCommandEntry()];\n }\n}\n\nexport function createBackgroundCommandModule(): ICommandModule {\n return {\n name: 'agent-command-background',\n commandSources: [new BackgroundCommandSource()],\n systemCommands: [createBackgroundSystemCommand()],\n };\n}\n","import { compactCommandContext } from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nfunction parseInstructions(args: string): string | undefined {\n const instructions = args.trim();\n return instructions.length > 0 ? instructions : undefined;\n}\n\nexport async function executeCompactCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n const result = await compactCommandContext(context, parseInstructions(args));\n const { before, after, beforeMessageCount, afterMessageCount } = result;\n const removedMessages = beforeMessageCount - afterMessageCount;\n const removedPercent =\n beforeMessageCount > 0 ? Math.round((removedMessages / beforeMessageCount) * 100) : 0;\n const message = [\n 'Context compacted.',\n ` Removed messages: ${removedMessages} (${removedPercent}% of total)`,\n ` Context: ${Math.round(before.usedPercentage)}% → ${Math.round(after.usedPercentage)}%`,\n ].join('\\n');\n return {\n message,\n success: true,\n data: { before, after, beforeMessageCount, afterMessageCount },\n };\n}\n","import { executeCompactCommand } from './compact-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createCompactCommandEntry(): ICommand {\n return {\n name: 'compact',\n displayName: 'Compact Context',\n description: 'Compress context window',\n source: 'compact',\n modelInvocable: true,\n argumentHint: '[instructions]',\n safety: 'write',\n example: '/compact Summarize the current context',\n };\n}\n\nfunction createCompactSystemCommand(): ISystemCommand {\n const entry = createCompactCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n example: entry.example,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: entry.modelInvocable,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n lifecycle: 'blocking',\n execute: executeCompactCommand,\n };\n}\n\nexport class CompactCommandSource implements ICommandSource {\n readonly name = 'compact';\n\n getCommands(): ICommand[] {\n return [createCompactCommandEntry()];\n }\n}\n\nexport function createCompactCommandModule(): ICommandModule {\n return {\n name: 'agent-command-compact',\n commandSources: [new CompactCommandSource()],\n systemCommands: [createCompactSystemCommand()],\n };\n}\n","import { CONTEXT_ESTIMATE_CHARS_PER_TOKEN } from '@robota-sdk/agent-core';\nimport {\n addCommandContextReference,\n clearCommandContextReferences,\n DEFAULT_AUTO_COMPACT_THRESHOLD,\n listCommandContextReferences,\n readAutoCompactThreshold,\n readAutoCompactThresholdSource,\n readCommandContextState,\n removeCommandContextReference,\n resetAutoCompactThresholdSetting,\n setCommandAutoCompactThreshold,\n writeAutoCompactThresholdSetting,\n} from '@robota-sdk/agent-framework';\n\nimport type { IHistoryEntry, TUniversalMessage } from '@robota-sdk/agent-core';\nimport type {\n ICommandHostContext,\n TAutoCompactThreshold,\n TAutoCompactThresholdSource,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult, IContextReferenceItem } from '@robota-sdk/agent-interface-transport';\n\nconst PERCENT = 100;\nconst USAGE = [\n 'Usage: /context [list] | add <path> | remove <path> | clear | auto on | off | <percent> | reset',\n 'Examples: /context list, /context add AGENTS.md, /context remove AGENTS.md, /context auto 85%',\n].join('\\n');\n\nfunction formatThreshold(threshold: TAutoCompactThreshold): string {\n if (threshold === false) {\n return 'disabled';\n }\n return `${Math.round(threshold * PERCENT)}%`;\n}\n\nfunction formatAutoCompactLine(\n threshold: TAutoCompactThreshold,\n source: TAutoCompactThresholdSource,\n): string {\n if (threshold === false) {\n return `Auto compact: disabled (${source})`;\n }\n return `Auto compact: ${formatThreshold(threshold)} (${source})`;\n}\n\nfunction formatPersistenceSuffix(persisted: boolean): string {\n return persisted ? 'settings' : 'current session only';\n}\n\nexport async function executeContextCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n const parts = args\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n\n if (parts.length > 0) {\n return executeContextSubcommand(context, parts);\n }\n\n const state = readCommandContextState(context);\n const autoCompactThreshold = readAutoCompactThreshold(context);\n const autoCompactThresholdSource = readAutoCompactThresholdSource(context);\n const history = context.getSession().getFullHistory();\n const display = buildToolDisplayList(history);\n const references = listCommandContextReferences(context);\n return {\n message: [\n `Context: ${state.usedTokens.toLocaleString()} / ${state.maxTokens.toLocaleString()} tokens (${Math.round(state.usedPercentage)}%)`,\n formatAutoCompactLine(autoCompactThreshold, autoCompactThresholdSource),\n formatContextReferenceSummary(references),\n `History: ${display.turnCount} turn${display.turnCount !== 1 ? 's' : ''}`,\n ].join('\\n'),\n success: true,\n data: {\n usedTokens: state.usedTokens,\n maxTokens: state.maxTokens,\n percentage: state.usedPercentage,\n autoCompactThreshold,\n autoCompactThresholdSource,\n references,\n },\n };\n}\n\nasync function executeContextSubcommand(\n context: ICommandHostContext,\n parts: readonly string[],\n): Promise<ICommandResult> {\n const [subcommand, ...rest] = parts;\n if (subcommand === 'list') {\n if (rest.length > 0) return { success: false, message: USAGE };\n return formatFullContextBreakdown(context);\n }\n if (subcommand === 'add') {\n return executeAddContextReference(context, rest);\n }\n if (subcommand === 'remove') {\n return executeRemoveContextReference(context, rest);\n }\n if (subcommand === 'clear') {\n if (rest.length > 0) return { success: false, message: USAGE };\n const result = clearCommandContextReferences(context);\n return {\n success: true,\n message: `Context references cleared: ${result.removed.length} removed.`,\n data: { removed: result.removed },\n };\n }\n if (subcommand !== 'auto') {\n return { success: false, message: USAGE };\n }\n return executeAutoContextSubcommand(context, rest);\n}\n\nfunction executeAutoContextSubcommand(\n context: ICommandHostContext,\n parts: readonly string[],\n): ICommandResult {\n const [action, extra] = parts;\n if (extra !== undefined) return { success: false, message: USAGE };\n if (action === undefined) {\n const threshold = readAutoCompactThreshold(context);\n const source = readAutoCompactThresholdSource(context);\n return {\n success: true,\n message: [formatAutoCompactLine(threshold, source), USAGE].join('\\n'),\n data: { autoCompactThreshold: threshold, autoCompactThresholdSource: source },\n };\n }\n\n if (action === 'on') {\n return applyAutoCompactThreshold(context, DEFAULT_AUTO_COMPACT_THRESHOLD, 'enabled');\n }\n if (action === 'off') {\n return applyAutoCompactThreshold(context, false, 'disabled');\n }\n if (action === 'reset') {\n const persisted = resetAutoCompactThresholdSetting(context);\n setCommandAutoCompactThreshold(context, DEFAULT_AUTO_COMPACT_THRESHOLD, 'default');\n return {\n success: true,\n message: `Auto compact reset to default: ${formatThreshold(DEFAULT_AUTO_COMPACT_THRESHOLD)} (${formatPersistenceSuffix(persisted)}).`,\n data: {\n autoCompactThreshold: DEFAULT_AUTO_COMPACT_THRESHOLD,\n autoCompactThresholdSource: 'default',\n persisted,\n },\n };\n }\n\n const parsed = parseThreshold(action);\n if (!parsed.success) {\n return { success: false, message: `${parsed.message}\\n${USAGE}` };\n }\n return applyAutoCompactThreshold(context, parsed.threshold, 'threshold set');\n}\n\nasync function executeAddContextReference(\n context: ICommandHostContext,\n args: readonly string[],\n): Promise<ICommandResult> {\n const path = args.join(' ').trim();\n if (!path) return { success: false, message: USAGE };\n\n const result = await addCommandContextReference(context, path);\n if (!result.reference) {\n return {\n success: false,\n message: result.diagnostics.join('\\n') || `Context reference not found: ${path}`,\n data: { diagnostics: result.diagnostics },\n };\n }\n\n return {\n success: true,\n message: [\n `Context reference added: ${formatContextReferenceLine(result.reference)}.`,\n ...(result.evicted.length > 0\n ? [`Evicted ${result.evicted.length} older context reference(s).`]\n : []),\n ].join('\\n'),\n data: { reference: result.reference, evicted: result.evicted },\n };\n}\n\nfunction executeRemoveContextReference(\n context: ICommandHostContext,\n args: readonly string[],\n): ICommandResult {\n const path = args.join(' ').trim();\n if (!path) return { success: false, message: USAGE };\n\n const result = removeCommandContextReference(context, path);\n if (!result.removed) {\n return {\n success: false,\n message: `Context reference not found: ${path}`,\n };\n }\n\n return {\n success: true,\n message: `Context reference removed: ${formatContextReferenceLine(result.removed)}.`,\n data: { removed: result.removed },\n };\n}\n\nfunction applyAutoCompactThreshold(\n context: ICommandHostContext,\n threshold: TAutoCompactThreshold,\n action: 'enabled' | 'disabled' | 'threshold set',\n): ICommandResult {\n const persisted = writeAutoCompactThresholdSetting(context, threshold);\n const source: TAutoCompactThresholdSource = persisted ? 'settings' : 'session';\n setCommandAutoCompactThreshold(context, threshold, source);\n\n return {\n success: true,\n message: formatApplyMessage(action, threshold, persisted),\n data: {\n autoCompactThreshold: threshold,\n autoCompactThresholdSource: source,\n persisted,\n },\n };\n}\n\nfunction formatApplyMessage(\n action: 'enabled' | 'disabled' | 'threshold set',\n threshold: TAutoCompactThreshold,\n persisted: boolean,\n): string {\n const suffix = formatPersistenceSuffix(persisted);\n if (action === 'disabled') {\n return `Auto compact disabled (${suffix}).`;\n }\n if (action === 'enabled') {\n return `Auto compact enabled at ${formatThreshold(threshold)} (${suffix}).`;\n }\n return `Auto compact threshold set to ${formatThreshold(threshold)} (${suffix}).`;\n}\n\ntype TParseThresholdResult =\n | { success: true; threshold: number }\n | { success: false; message: string };\n\nfunction parseThreshold(raw: string): TParseThresholdResult {\n if (raw.endsWith('%')) {\n const percent = Number(raw.slice(0, -1));\n if (!Number.isFinite(percent) || percent <= 0 || percent > PERCENT) {\n return {\n success: false,\n message: 'Auto compact percentage must be greater than 0% and at most 100%.',\n };\n }\n return { success: true, threshold: percent / PERCENT };\n }\n\n if (raw.includes('.')) {\n const fraction = Number(raw);\n if (!Number.isFinite(fraction) || fraction <= 0 || fraction > 1) {\n return {\n success: false,\n message: 'Auto compact fraction must be greater than 0 and at most 1.',\n };\n }\n return { success: true, threshold: fraction };\n }\n\n return {\n success: false,\n message: 'Use a percentage such as 85% or a fraction such as 0.85.',\n };\n}\n\nfunction formatContextReferenceSummary(references: readonly IContextReferenceItem[]): string {\n const active = references.filter((reference) => reference.status === 'active').length;\n const observed = references.filter((reference) => reference.status === 'observed').length;\n return `References: ${active} active, ${observed} observed`;\n}\n\n// 1 token ≈ 4 chars — sourced from the agent-core estimation SSOT.\nconst TOOL_ARG_MAX_LEN = 60;\n\nfunction estimateTokens(charLength: number): number {\n return Math.ceil(charLength / CONTEXT_ESTIMATE_CHARS_PER_TOKEN);\n}\n\nfunction formatContextReferenceLine(reference: IContextReferenceItem): string {\n return [\n reference.relativePath,\n `[${reference.loadType}, ${reference.status}]`,\n `~${estimateTokens(reference.byteLength).toLocaleString()} tokens`,\n ].join(' ');\n}\n\n// ── History analysis ────────────────────────────────────────────────────────\n\ninterface IToolResultSummary {\n toolName: string;\n displayArg: string;\n}\n\ninterface IMessageTokensByRole {\n systemTokens: number;\n userTokens: number;\n userCount: number;\n assistantTokens: number;\n assistantCount: number;\n toolTokens: number;\n toolCallCount: number;\n totalTokens: number;\n}\n\ninterface IToolDisplayList {\n turnCount: number;\n toolResults: IToolResultSummary[];\n totalToolCallCount: number;\n}\n\nfunction parseToolCallArgs(argsJson: string): Record<string, unknown> | null {\n try {\n return JSON.parse(argsJson) as Record<string, unknown>;\n } catch {\n // allow-fallback: tool call arguments JSON may be malformed; display-only degradation, not a terminal path\n return null;\n }\n}\n\nfunction extractFirstToolArg(argsJson: string): string {\n const parsed = parseToolCallArgs(argsJson);\n if (parsed === null) return '';\n const first = Object.values(parsed)[0];\n const raw = typeof first === 'string' ? first : JSON.stringify(first);\n return raw.length > TOOL_ARG_MAX_LEN ? `${raw.slice(0, TOOL_ARG_MAX_LEN)}…` : raw;\n}\n\nfunction computeMessageTokensByRole(rawMessages: TUniversalMessage[]): IMessageTokensByRole {\n let systemTokens = 0;\n let userTokens = 0;\n let userCount = 0;\n let assistantTokens = 0;\n let assistantCount = 0;\n let toolTokens = 0;\n let toolCallCount = 0;\n\n for (const msg of rawMessages) {\n const t = Math.ceil(JSON.stringify(msg).length / CONTEXT_ESTIMATE_CHARS_PER_TOKEN);\n if (msg.role === 'system') {\n systemTokens += t;\n } else if (msg.role === 'user') {\n userTokens += t;\n userCount++;\n } else if (msg.role === 'assistant') {\n assistantTokens += t;\n assistantCount++;\n } else if (msg.role === 'tool') {\n toolTokens += t;\n toolCallCount++;\n }\n }\n\n return {\n systemTokens,\n userTokens,\n userCount,\n assistantTokens,\n assistantCount,\n toolTokens,\n toolCallCount,\n totalTokens: systemTokens + userTokens + assistantTokens + toolTokens,\n };\n}\n\nfunction buildToolDisplayList(history: IHistoryEntry[]): IToolDisplayList {\n type TToolCallEntry = { name: string; firstArg: string };\n const toolCallMap = new Map<string, TToolCallEntry>();\n\n for (const entry of history) {\n if (entry.category !== 'chat' || entry.type !== 'assistant') continue;\n const data = entry.data as {\n toolCalls?: Array<{ id: string; function: { name: string; arguments: string } }>;\n };\n for (const tc of data.toolCalls ?? []) {\n toolCallMap.set(tc.id, {\n name: tc.function.name,\n firstArg: extractFirstToolArg(tc.function.arguments),\n });\n }\n }\n\n let turnCount = 0;\n let totalToolCallCount = 0;\n const toolDisplayMap = new Map<string, IToolResultSummary>();\n\n for (const entry of history) {\n if (entry.category !== 'chat') continue;\n if (entry.type === 'user') {\n turnCount++;\n } else if (entry.type === 'tool') {\n const data = entry.data as { toolCallId?: string };\n const tc = toolCallMap.get(data.toolCallId ?? '');\n const toolName = tc?.name ?? 'tool';\n const displayArg = tc?.firstArg ?? '';\n totalToolCallCount++;\n toolDisplayMap.set(`${toolName}:${displayArg}`, { toolName, displayArg });\n }\n }\n\n return {\n turnCount,\n toolResults: [...toolDisplayMap.values()],\n totalToolCallCount,\n };\n}\n\n// ── Full context breakdown (for /context list) ──────────────────────────────\n\nfunction formatSection(title: string, tokens: number, lines: string[]): string {\n const tokenLabel = tokens > 0 ? ` — ~${tokens.toLocaleString()} tokens` : '';\n const header = `${title}${tokenLabel}:`;\n return lines.length === 0\n ? `${header}\\n (none)`\n : [header, ...lines.map((l) => ` ${l}`)].join('\\n');\n}\n\nfunction formatFullContextBreakdown(context: ICommandHostContext): ICommandResult {\n const state = readCommandContextState(context);\n const autoCompactThreshold = readAutoCompactThreshold(context);\n const autoCompactThresholdSource = readAutoCompactThresholdSource(context);\n const rawMessages = context.getSession().getHistory();\n const msgTokens = computeMessageTokensByRole(rawMessages);\n const display = buildToolDisplayList(context.getSession().getFullHistory());\n const references = listCommandContextReferences(context);\n\n const systemRefs = references.filter((r) => r.loadType === 'system');\n const manualRefs = references.filter((r) => r.loadType === 'manual');\n const promptRefs = references.filter((r) => r.loadType === 'prompt-reference');\n\n const systemRefTokens = systemRefs.reduce((s, r) => s + estimateTokens(r.byteLength), 0);\n const manualTokens = manualRefs.reduce((s, r) => s + estimateTokens(r.byteLength), 0);\n const promptRefTokens = promptRefs.reduce((s, r) => s + estimateTokens(r.byteLength), 0);\n\n const convTurnLabel =\n display.turnCount === 0\n ? 'Conversation history — 0 turns'\n : `Conversation history — ${display.turnCount} turn${display.turnCount !== 1 ? 's' : ''} | ~${msgTokens.totalTokens.toLocaleString()} tokens`;\n\n const toolResultLines = display.toolResults.map(\n (t) => `${t.toolName}${t.displayArg ? `: ${t.displayArg}` : ''}`,\n );\n\n const uniqueToolCount = display.toolResults.length;\n const totalToolCallCount = display.totalToolCallCount;\n const toolResultsLabel =\n totalToolCallCount === 0\n ? 'Tool results (0): (none)'\n : uniqueToolCount < totalToolCallCount\n ? `Tool results (${uniqueToolCount} unique / ${totalToolCallCount} calls, ~${msgTokens.toolTokens.toLocaleString()} tokens):`\n : `Tool results (${uniqueToolCount}, ~${msgTokens.toolTokens.toLocaleString()} tokens):`;\n\n const conversationLines: string[] =\n display.turnCount === 0\n ? []\n : [\n `User (${msgTokens.userCount}): ~${msgTokens.userTokens.toLocaleString()} tokens`,\n `Assistant (${msgTokens.assistantCount}): ~${msgTokens.assistantTokens.toLocaleString()} tokens`,\n ...(msgTokens.systemTokens > 0\n ? [`System messages: ~${msgTokens.systemTokens.toLocaleString()} tokens`]\n : []),\n totalToolCallCount > 0\n ? [toolResultsLabel, ...toolResultLines.map((l) => ` ${l}`)].join('\\n')\n : toolResultsLabel,\n ];\n\n const convSection =\n display.turnCount === 0\n ? `${convTurnLabel}:\\n (none)`\n : [`${convTurnLabel}:`, ...conversationLines.map((l) => ` ${l}`)].join('\\n');\n\n const message = [\n `Context: ${state.usedTokens.toLocaleString()} / ${state.maxTokens.toLocaleString()} tokens (${Math.round(state.usedPercentage)}%)`,\n formatAutoCompactLine(autoCompactThreshold, autoCompactThresholdSource),\n '',\n formatSection(\n 'System prompt (active every turn)',\n systemRefTokens,\n systemRefs.map(formatContextReferenceLine),\n ),\n '',\n convSection,\n '',\n formatSection('Manually added', manualTokens, manualRefs.map(formatContextReferenceLine)),\n '',\n formatSection(\n 'Prompt references (@-syntax)',\n promptRefTokens,\n promptRefs.map(formatContextReferenceLine),\n ),\n ].join('\\n');\n\n return {\n success: true,\n message,\n data: {\n references,\n history: { turnCount: display.turnCount, toolResults: display.toolResults },\n },\n };\n}\n","import { executeContextCommand } from './context-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createContextCommandEntry(): ICommand {\n return {\n name: 'context',\n displayName: 'Context References',\n description: 'Context window info, reference inventory, and auto-compact controls',\n source: 'context',\n modelInvocable: false,\n argumentHint: 'list | add <path> | remove <path> | clear | auto ...',\n subcommands: [\n { name: 'list', description: 'List loaded context references', source: 'context' },\n { name: 'add', description: 'Add a file to active context references', source: 'context' },\n { name: 'remove', description: 'Remove a context reference', source: 'context' },\n { name: 'clear', description: 'Clear context references', source: 'context' },\n { name: 'auto', description: 'Inspect or change auto-compact policy', source: 'context' },\n ],\n };\n}\n\nfunction createContextSystemCommand(): ISystemCommand {\n const entry = createContextCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n execute: executeContextCommand,\n };\n}\n\nexport class ContextCommandSource implements ICommandSource {\n readonly name = 'context';\n\n getCommands(): ICommand[] {\n return [createContextCommandEntry()];\n }\n}\n\nexport function createContextCommandModule(): ICommandModule {\n return {\n name: 'agent-command-context',\n commandSources: [new ContextCommandSource()],\n systemCommands: [createContextSystemCommand()],\n };\n}\n","/**\n * TERM-004: editor-selection seam. Resolves `$VISUAL` → `$EDITOR` → `vi` (POSIX-first; a Windows\n * default is a TERM-007 concern). Splits on whitespace so `\"code -w\"` / `\"subl -w\"` style values work.\n */\nexport interface IResolvedEditor {\n command: string;\n args: readonly string[];\n}\n\nexport function resolveEditor(): IResolvedEditor {\n const visual = process.env.VISUAL?.trim();\n const editor = process.env.EDITOR?.trim();\n const chosen =\n visual !== undefined && visual.length > 0\n ? visual\n : editor !== undefined && editor.length > 0\n ? editor\n : 'vi';\n const parts = chosen.split(/\\s+/).filter((p) => p.length > 0);\n return { command: parts[0] ?? 'vi', args: parts.slice(1) };\n}\n","/**\n * Pure-Node spawn with the real terminal inherited (interactive input + output). Used inside a\n * terminal-handoff `runWithTerminal(fn)` — the framework/transport own the suspend/restore; this just\n * runs the child attached to the real TTY and resolves with its exit code.\n */\nimport { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\n\nexport function spawnInherited(\n command: string,\n args: readonly string[],\n cwd: string,\n): Promise<number> {\n return new Promise<number>((resolve, reject) => {\n const child = spawn(command, [...args], { cwd, stdio: 'inherit', env: process.env });\n child.on('error', reject);\n child.on('exit', (code, signal) => {\n // RUNTIME-53: a signal-terminated child reports code=null; resolving 0 there is a false\n // success. Translate to the shell convention 128 + signal number so callers see the failure.\n if (code !== null) {\n resolve(code);\n return;\n }\n if (signal) {\n const signalNumber = constants.signals[signal as keyof typeof constants.signals];\n resolve(128 + (signalNumber ?? 0));\n return;\n }\n resolve(0);\n });\n });\n}\n","/**\n * TERM-004: `/editor` — compose a message/prompt in `$EDITOR` via the terminal-handoff capability,\n * then return the saved text. The temp file is pre-filled with any args and removed afterward.\n */\nimport { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { resolveEditor } from './resolve-editor.js';\nimport { spawnInherited } from '../shell/spawn-inherited.js';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport const EDITOR_COMMAND_DESCRIPTION =\n 'Compose a message in $EDITOR (optionally pre-filled with `/editor <text>`), then return it.';\n\nexport async function executeEditorCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n if (context.canHandoffTerminal?.() !== true || context.runWithTerminal === undefined) {\n return {\n message: 'An editor is unavailable here (no interactive terminal).',\n success: false,\n };\n }\n\n const editor = resolveEditor();\n const dir = mkdtempSync(join(tmpdir(), 'robota-editor-'));\n const file = join(dir, 'message.md');\n writeFileSync(file, args ?? '', 'utf8');\n\n try {\n const exitCode = await context.runWithTerminal(async () =>\n spawnInherited(editor.command, [...editor.args, file], context.getCwd()),\n );\n if (exitCode !== 0) {\n return {\n message: `Editor exited without saving (code ${exitCode}).`,\n success: false,\n data: { exitCode },\n };\n }\n const content = readFileSync(file, 'utf8').replace(/\\s+$/u, '');\n if (content.length === 0) {\n return { message: 'Editor closed with empty content; nothing composed.', success: false };\n }\n return { message: content, success: true, data: { content } };\n } finally {\n rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 20 });\n }\n}\n","/**\n * TERM-004: `/editor` command module — a framework-level consumer of the terminal-handoff capability.\n */\nimport { EDITOR_COMMAND_DESCRIPTION, executeEditorCommand } from './editor-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createEditorCommandEntry(): ICommand {\n return {\n name: 'editor',\n displayName: 'Editor',\n description: EDITOR_COMMAND_DESCRIPTION,\n source: 'editor',\n modelInvocable: false,\n };\n}\n\nfunction createEditorSystemCommand(): ISystemCommand {\n const entry = createEditorCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeEditorCommand,\n };\n}\n\nexport class EditorCommandSource implements ICommandSource {\n readonly name = 'editor';\n\n getCommands(): ICommand[] {\n return [createEditorCommandEntry()];\n }\n}\n\nexport function createEditorCommandModule(): ICommandModule {\n return {\n name: 'agent-command-editor',\n commandSources: [new EditorCommandSource()],\n systemCommands: [createEditorSystemCommand()],\n };\n}\n","import { confirmAction, isConfirmed } from '@robota-sdk/agent-core';\nimport { createSessionExitRequestedEffect } from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport async function executeExitCommand(\n context: ICommandHostContext,\n _args: string,\n): Promise<ICommandResult> {\n // Confirm only when an interactive renderer is attached. With no human (headless/automation) the\n // user explicitly invoked /exit, so proceed — the confirm is an interactive safety prompt, not a gate.\n const ui = context.getUserInteraction?.();\n if (ui) {\n const response = await ui.ask(confirmAction('exit', 'Exit the session?'));\n if (!isConfirmed(response)) {\n return { success: true, message: 'Exit cancelled.' };\n }\n }\n\n return {\n success: true,\n message: 'Exit requested.',\n effects: [createSessionExitRequestedEffect()],\n };\n}\n","import { EXIT_COMMAND_DESCRIPTION } from '@robota-sdk/agent-framework';\n\nimport { executeExitCommand } from './exit-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createExitCommandEntry(): ICommand {\n return {\n name: 'exit',\n displayName: 'Exit Session',\n description: EXIT_COMMAND_DESCRIPTION,\n source: 'exit',\n modelInvocable: false,\n };\n}\n\nfunction createExitSystemCommand(): ISystemCommand {\n const entry = createExitCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeExitCommand,\n };\n}\n\nexport class ExitCommandSource implements ICommandSource {\n readonly name = 'exit';\n\n getCommands(): ICommand[] {\n return [createExitCommandEntry()];\n }\n}\n\nexport function createExitCommandModule(): ICommandModule {\n return {\n name: 'agent-command-exit',\n commandSources: [new ExitCommandSource()],\n systemCommands: [createExitSystemCommand()],\n };\n}\n","/**\n * GOAL-001: the `/goal` slash command. Assigns an autonomous objective the agent pursues across\n * turns until satisfied or a bound fires. Delegates to the framework-owned goal controller via the\n * command host context; all loop logic lives in agent-framework.\n */\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult, IGoalState } from '@robota-sdk/agent-interface-transport';\n\nexport const GOAL_COMMAND_DESCRIPTION =\n 'Assign an autonomous goal the agent pursues across turns until satisfied.';\n\nconst GOAL_COMMAND_USAGE =\n 'Usage:\\n /goal <objective> assign a goal and pursue it autonomously\\n' +\n ' /goal status show the current goal and progress\\n' +\n ' /goal cancel stop the current goal';\n\nfunction formatGoalState(goal: IGoalState): string {\n const lines = [\n `Goal: ${goal.objective}`,\n `Status: ${goal.status}${goal.stopReason ? ` (${goal.stopReason})` : ''}`,\n `Iterations: ${goal.iterations} / ${goal.maxIterations}`,\n ];\n const last = goal.progress[goal.progress.length - 1];\n if (last?.reason) lines.push(`Latest: ${last.reason}`);\n return lines.join('\\n');\n}\n\nexport async function executeGoalCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n const trimmed = args.trim();\n const verb = trimmed.split(/\\s+/)[0]?.toLowerCase() ?? '';\n\n if (trimmed.length === 0 || verb === 'help') {\n return { message: GOAL_COMMAND_USAGE, success: true };\n }\n\n if (verb === 'status') {\n const goal = context.getGoalState?.() ?? null;\n return goal\n ? { message: formatGoalState(goal), success: true, data: { status: goal.status } }\n : { message: 'No goal is set.', success: true };\n }\n\n if (verb === 'cancel' || verb === 'stop') {\n const stopped = context.cancelGoal?.() ?? null;\n return stopped\n ? { message: `Goal cancelled: ${stopped.objective}`, success: true }\n : { message: 'No active goal to cancel.', success: false };\n }\n\n if (!context.setGoal) {\n return { message: 'Goal pursuit is not available in this session.', success: false };\n }\n\n let goal: IGoalState;\n try {\n goal = await context.setGoal(trimmed);\n } catch (error) {\n // allow-fallback: surface an invalid-objective error to the user as a failed command result, not a crash\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n return {\n message: `Goal set — pursuing autonomously (up to ${goal.maxIterations} iterations):\\n${goal.objective}`,\n success: true,\n data: { goalId: goal.id },\n };\n}\n","/**\n * GOAL-001: `/goal` command module registration.\n */\n\nimport { executeGoalCommand, GOAL_COMMAND_DESCRIPTION } from './goal-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createGoalCommandEntry(): ICommand {\n return {\n name: 'goal',\n displayName: 'Autonomous Goal',\n description: GOAL_COMMAND_DESCRIPTION,\n source: 'goal',\n modelInvocable: false,\n };\n}\n\nfunction createGoalSystemCommand(): ISystemCommand {\n const entry = createGoalCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeGoalCommand,\n };\n}\n\nexport class GoalCommandSource implements ICommandSource {\n readonly name = 'goal';\n\n getCommands(): ICommand[] {\n return [createGoalCommandEntry()];\n }\n}\n\nexport function createGoalCommandModule(): ICommandModule {\n return {\n name: 'agent-command-goal',\n commandSources: [new GoalCommandSource()],\n systemCommands: [createGoalSystemCommand()],\n };\n}\n","import { formatCommandHelpMessage } from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport function executeHelpCommand(context: ICommandHostContext, _args: string): ICommandResult {\n return {\n success: true,\n message: formatCommandHelpMessage(context),\n };\n}\n","import { HELP_COMMAND_DESCRIPTION } from '@robota-sdk/agent-framework';\n\nimport { executeHelpCommand } from './help-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createHelpCommandEntry(): ICommand {\n return {\n name: 'help',\n displayName: 'Help',\n description: HELP_COMMAND_DESCRIPTION,\n source: 'help',\n modelInvocable: false,\n };\n}\n\nfunction createHelpSystemCommand(): ISystemCommand {\n const entry = createHelpCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeHelpCommand,\n };\n}\n\nexport class HelpCommandSource implements ICommandSource {\n readonly name = 'help';\n\n getCommands(): ICommand[] {\n return [createHelpCommandEntry()];\n }\n}\n\nexport function createHelpCommandModule(): ICommandModule {\n return {\n name: 'agent-command-help',\n commandSources: [new HelpCommandSource()],\n systemCommands: [createHelpSystemCommand()],\n };\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport {\n buildLanguageCommandSubcommands,\n formatLanguageUsageMessage,\n parseLanguageArgument,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\n/**\n * Ask the user to pick a language (CMD-004 inline ask). Returns a validated language, or `undefined`\n * when no interactive renderer is attached or the user cancelled — the caller then shows usage.\n */\nasync function resolveLanguageViaAsk(context: ICommandHostContext): Promise<string | undefined> {\n const ui = context.getUserInteraction?.();\n if (!ui) return undefined;\n const options = buildLanguageCommandSubcommands().map((sub) => ({\n value: sub.name,\n label: sub.name,\n description: sub.description,\n }));\n const response = await ui.ask(selectAction('language', 'Select language', options));\n const picked = response.type === 'answer' ? response.values[0] : undefined;\n return picked === undefined ? undefined : parseLanguageArgument(picked);\n}\n\nexport async function executeLanguageCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n let language = parseLanguageArgument(args);\n\n if (language === undefined) {\n language = await resolveLanguageViaAsk(context);\n if (language === undefined) {\n return {\n message: formatLanguageUsageMessage(),\n success: false,\n };\n }\n }\n\n return {\n message: `Language set to \"${language}\".`,\n success: true,\n data: { language },\n effects: [{ type: 'language-change-requested', language }],\n };\n}\n","import {\n buildLanguageCommandSubcommands,\n LANGUAGE_COMMAND_ARGUMENT_HINT,\n LANGUAGE_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executeLanguageCommand } from './language-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createLanguageCommandEntry(): ICommand {\n return {\n name: 'language',\n displayName: 'Language',\n description: LANGUAGE_COMMAND_DESCRIPTION,\n source: 'language',\n argumentHint: LANGUAGE_COMMAND_ARGUMENT_HINT,\n subcommands: buildLanguageCommandSubcommands('language'),\n modelInvocable: false,\n };\n}\n\nfunction createLanguageSystemCommand(): ISystemCommand {\n const entry = createLanguageCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executeLanguageCommand,\n };\n}\n\nexport class LanguageCommandSource implements ICommandSource {\n readonly name = 'language';\n\n getCommands(): ICommand[] {\n return [createLanguageCommandEntry()];\n }\n}\n\nexport function createLanguageCommandModule(): ICommandModule {\n return {\n name: 'agent-command-language',\n commandSources: [new LanguageCommandSource()],\n systemCommands: [createLanguageSystemCommand()],\n };\n}\n","import {\n MEMORY_COMMAND_USAGE,\n createCommandMemoryStores,\n hasSensitiveCommandMemoryContent,\n isCommandMemoryType,\n listCommandUsedMemoryReferences,\n recordCommandMemoryEvent,\n} from '@robota-sdk/agent-framework';\n\nimport type {\n IAppendMemoryInput,\n ICommandHostContext,\n ICommandPendingMemoryStore,\n ICommandProjectMemoryStore,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult, IMemoryEvent } from '@robota-sdk/agent-interface-transport';\n\nconst SUBCOMMAND_INDEX = 0;\nconst TYPE_INDEX = 1;\nconst TOPIC_INDEX = 2;\nconst TEXT_START_INDEX = 3;\n\nfunction usage(): ICommandResult {\n return {\n message: MEMORY_COMMAND_USAGE,\n success: false,\n };\n}\n\nfunction formatError(error: Error | string): ICommandResult {\n return {\n message: error instanceof Error ? error.message : String(error),\n success: false,\n };\n}\n\nfunction formatList(store: ICommandProjectMemoryStore): ICommandResult {\n const summary = store.list();\n const topics =\n summary.topics.length > 0\n ? summary.topics.map((topic) => `- ${topic.name}: ${topic.path}`).join('\\n')\n : '(none)';\n\n return {\n message: [\n `Memory index: ${summary.indexPath}`,\n `Topics directory: ${summary.topicsPath}`,\n 'Topics:',\n topics,\n ].join('\\n'),\n success: true,\n data: {\n indexPath: summary.indexPath,\n topicsPath: summary.topicsPath,\n topicCount: summary.topics.length,\n },\n };\n}\n\nfunction formatShow(store: ICommandProjectMemoryStore, topic?: string): ICommandResult {\n if (!topic || topic === 'index') {\n const memory = store.loadStartupMemory();\n return {\n message: memory.content || '(empty memory index)',\n success: true,\n data: {\n path: memory.path,\n lineCount: memory.lineCount,\n truncated: memory.truncated,\n },\n };\n }\n\n const content = store.readTopic(topic);\n return {\n message: content || `(empty memory topic: ${topic})`,\n success: true,\n data: { topic },\n };\n}\n\nfunction parseAdd(args: readonly string[]): IAppendMemoryInput | undefined {\n const type = args[TYPE_INDEX];\n const topic = args[TOPIC_INDEX];\n const text = args.slice(TEXT_START_INDEX).join(' ').trim();\n\n if (!type || !isCommandMemoryType(type) || !topic || text.length === 0) return undefined;\n return { type, topic, text };\n}\n\nfunction formatPending(store: ICommandPendingMemoryStore): ICommandResult {\n const records = store.list('pending');\n const lines =\n records.length > 0\n ? records.map(\n (record) =>\n `- ${record.id} ${record.type}/${record.topic} confidence=${record.confidence}: ${record.text}`,\n )\n : ['(no pending memory candidates)'];\n\n return {\n message: ['Pending memory candidates:', ...lines].join('\\n'),\n success: true,\n data: { count: records.length },\n };\n}\n\nfunction recordEvent(context: ICommandHostContext, event: Omit<IMemoryEvent, 'at'>): void {\n recordCommandMemoryEvent(context, event);\n}\n\nfunction approvePending(\n context: ICommandHostContext,\n pendingStore: ICommandPendingMemoryStore,\n memoryStore: ICommandProjectMemoryStore,\n id: string | undefined,\n): ICommandResult {\n if (!id) return usage();\n try {\n const approved = pendingStore.mark(id, 'approved', 'approved-by-user');\n const saved = memoryStore.append(approved);\n const record = pendingStore.mark(id, 'saved', 'approved-and-saved');\n recordEvent(context, {\n type: 'memory_candidate_approved',\n candidateId: record.id,\n topic: record.topic,\n reason: 'approved-by-user',\n });\n recordEvent(context, {\n type: 'memory_candidate_saved',\n candidateId: record.id,\n topic: record.topic,\n reason: saved.deduplicated ? 'deduplicated' : 'approved-and-saved',\n });\n return {\n message: saved.deduplicated\n ? `Saved memory candidate ${id} was already present in ${saved.topicPath}`\n : `Saved memory candidate ${id} to ${saved.topicPath}`,\n success: true,\n data: {\n id,\n status: record.status,\n topic: saved.topic,\n topicPath: saved.topicPath,\n deduplicated: saved.deduplicated,\n },\n };\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nfunction rejectPending(\n context: ICommandHostContext,\n pendingStore: ICommandPendingMemoryStore,\n id: string | undefined,\n): ICommandResult {\n if (!id) return usage();\n try {\n const record = pendingStore.mark(id, 'rejected', 'rejected-by-user');\n recordEvent(context, {\n type: 'memory_candidate_rejected',\n candidateId: record.id,\n topic: record.topic,\n reason: 'rejected-by-user',\n });\n return {\n message: `Rejected memory candidate ${id}`,\n success: true,\n data: { id, status: record.status },\n };\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nfunction formatUsed(context: ICommandHostContext): ICommandResult {\n const references = listCommandUsedMemoryReferences(context);\n const lines =\n references.length > 0\n ? references.map((reference) => {\n const suffix = reference.truncated ? ' truncated=true' : '';\n return `- ${reference.topic} score=${reference.score}${suffix}: ${reference.path}`;\n })\n : ['(no memory used in current turn)'];\n\n return {\n message: ['Used memory references:', ...lines].join('\\n'),\n success: true,\n data: { count: references.length, references: [...references] },\n };\n}\n\nexport function executeMemoryCommand(\n context: ICommandHostContext,\n rawArgs: string,\n): ICommandResult {\n const args = rawArgs.trim().split(/\\s+/).filter(Boolean);\n const subcommand = args[SUBCOMMAND_INDEX] ?? 'list';\n const stores = createCommandMemoryStores(context);\n\n if (subcommand === 'list') return formatList(stores.project);\n if (subcommand === 'show') return formatShow(stores.project, args[TYPE_INDEX]);\n if (subcommand === 'pending') return formatPending(stores.pending);\n if (subcommand === 'approve')\n return approvePending(context, stores.pending, stores.project, args[TYPE_INDEX]);\n if (subcommand === 'reject') return rejectPending(context, stores.pending, args[TYPE_INDEX]);\n if (subcommand === 'used') return formatUsed(context);\n if (subcommand === 'add') {\n const input = parseAdd(args);\n if (!input) return usage();\n if (hasSensitiveCommandMemoryContent(input.text)) {\n return {\n message: 'Refusing to save sensitive memory content.',\n success: false,\n };\n }\n const result = stores.project.append(input);\n return {\n message: result.deduplicated\n ? `${input.type} memory already exists in ${result.topicPath}`\n : `Saved ${input.type} memory to ${result.topicPath}`,\n success: true,\n data: {\n indexPath: result.indexPath,\n topicPath: result.topicPath,\n topic: result.topic,\n deduplicated: result.deduplicated,\n },\n };\n }\n\n return usage();\n}\n","import {\n MEMORY_COMMAND_ARGUMENT_HINT,\n MEMORY_COMMAND_DESCRIPTION,\n buildMemoryCommandSubcommands,\n} from '@robota-sdk/agent-framework';\n\nimport { executeMemoryCommand } from './memory-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createMemoryCommandEntry(): ICommand {\n return {\n name: 'memory',\n displayName: 'Memory',\n description: MEMORY_COMMAND_DESCRIPTION,\n source: 'memory',\n argumentHint: MEMORY_COMMAND_ARGUMENT_HINT,\n modelInvocable: true,\n safety: 'write',\n subcommands: buildMemoryCommandSubcommands(),\n };\n}\n\nfunction createMemorySystemCommand(): ISystemCommand {\n const entry = createMemoryCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n subcommands: entry.subcommands,\n execute: executeMemoryCommand,\n };\n}\n\nexport class MemoryCommandSource implements ICommandSource {\n readonly name = 'memory';\n\n getCommands(): ICommand[] {\n return [createMemoryCommandEntry()];\n }\n}\n\nexport function createMemoryCommandModule(): ICommandModule {\n return {\n name: 'agent-command-memory',\n commandSources: [new MemoryCommandSource()],\n systemCommands: [createMemorySystemCommand()],\n };\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport {\n buildPermissionModeSubcommands,\n formatInvalidPermissionModeMessage,\n isPermissionMode,\n parsePermissionModeArgument,\n readCommandPermissionMode,\n writeCommandPermissionMode,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\n/**\n * Ask the user to pick a permission mode (CMD-004 inline ask). Returns the chosen mode name, or\n * `undefined` when no interactive renderer is attached or the user cancelled — the caller then reports\n * the current mode instead of changing it (never a silent guess).\n */\nasync function resolveModeViaAsk(context: ICommandHostContext): Promise<string | undefined> {\n const ui = context.getUserInteraction?.();\n if (!ui) return undefined;\n const options = buildPermissionModeSubcommands().map((sub) => ({\n value: sub.name,\n label: sub.name,\n description: sub.description,\n }));\n const response = await ui.ask(selectAction('mode', 'Select interaction mode', options));\n return response.type === 'answer' ? response.values[0] : undefined;\n}\n\nexport async function executeModeCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n let arg: string | undefined = parsePermissionModeArgument(args);\n\n if (arg === undefined) {\n arg = await resolveModeViaAsk(context);\n if (arg === undefined) {\n // No interactive answer — report the current mode without changing it.\n const mode = readCommandPermissionMode(context);\n return { message: `Current mode: ${mode}`, success: true, data: { mode } };\n }\n }\n\n if (!isPermissionMode(arg)) {\n return {\n message: formatInvalidPermissionModeMessage(),\n success: false,\n };\n }\n\n writeCommandPermissionMode(context, arg);\n return {\n message: `Permission mode set to: ${arg}`,\n success: true,\n data: { mode: arg },\n };\n}\n","import {\n buildPermissionModeSubcommands,\n PERMISSION_MODE_ARGUMENT_HINT,\n PERMISSION_MODE_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executeModeCommand } from './mode-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createModeCommandEntry(): ICommand {\n return {\n name: 'mode',\n displayName: 'Interaction Mode',\n description: PERMISSION_MODE_COMMAND_DESCRIPTION,\n source: 'mode',\n argumentHint: PERMISSION_MODE_ARGUMENT_HINT,\n subcommands: buildPermissionModeSubcommands('mode'),\n modelInvocable: false,\n };\n}\n\nfunction createModeSystemCommand(): ISystemCommand {\n const entry = createModeCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executeModeCommand,\n };\n}\n\nexport class ModeCommandSource implements ICommandSource {\n readonly name = 'mode';\n\n getCommands(): ICommand[] {\n return [createModeCommandEntry()];\n }\n}\n\nexport function createModeCommandModule(): ICommandModule {\n return {\n name: 'agent-command-mode',\n commandSources: [new ModeCommandSource()],\n systemCommands: [createModeSystemCommand()],\n };\n}\n","import {\n formatCommandPermissionsMessage,\n formatInvalidPermissionModeMessage,\n isPermissionMode,\n parsePermissionModeArgument,\n readCommandPermissionsState,\n writeCommandPermissionMode,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport function executePermissionsCommand(\n context: ICommandHostContext,\n args: string,\n): ICommandResult {\n const arg = parsePermissionModeArgument(args);\n if (arg !== undefined) {\n if (!isPermissionMode(arg)) {\n return {\n message: formatInvalidPermissionModeMessage(),\n success: false,\n };\n }\n\n writeCommandPermissionMode(context, arg);\n const state = readCommandPermissionsState(context);\n return {\n message: `Permission mode set to: ${arg}\\n${formatCommandPermissionsMessage(state)}`,\n success: true,\n data: {\n mode: state.mode,\n sessionAllowed: state.sessionAllowed,\n },\n };\n }\n\n const state = readCommandPermissionsState(context);\n return {\n message: formatCommandPermissionsMessage(state),\n success: true,\n data: {\n mode: state.mode,\n sessionAllowed: state.sessionAllowed,\n },\n };\n}\n","import {\n buildPermissionModeSubcommands,\n PERMISSION_MODE_ARGUMENT_HINT,\n PERMISSIONS_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executePermissionsCommand } from './permissions-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createPermissionsCommandEntry(): ICommand {\n return {\n name: 'permissions',\n displayName: 'Permissions',\n description: PERMISSIONS_COMMAND_DESCRIPTION,\n source: 'permissions',\n argumentHint: PERMISSION_MODE_ARGUMENT_HINT,\n subcommands: buildPermissionModeSubcommands('permissions'),\n modelInvocable: false,\n };\n}\n\nfunction createPermissionsSystemCommand(): ISystemCommand {\n const entry = createPermissionsCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executePermissionsCommand,\n };\n}\n\nexport class PermissionsCommandSource implements ICommandSource {\n readonly name = 'permissions';\n\n getCommands(): ICommand[] {\n return [createPermissionsCommandEntry()];\n }\n}\n\nexport function createPermissionsCommandModule(): ICommandModule {\n return {\n name: 'agent-command-permissions',\n commandSources: [new PermissionsCommandSource()],\n systemCommands: [createPermissionsSystemCommand()],\n };\n}\n","import {\n createPluginRegistryReloadRequestedEffect,\n createPluginTuiRequestedEffect,\n resolvePluginCommandAdapter,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandPluginAdapter, ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nfunction getSubcommandParts(args: string): { subcommand: string; subArgs: string } {\n const parts = args\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n return {\n subcommand: parts[0] ?? '',\n subArgs: parts.slice(1).join(' ').trim(),\n };\n}\n\nfunction usage(message: string): ICommandResult {\n return {\n success: false,\n message,\n };\n}\n\nfunction getPluginAdapter(context: ICommandHostContext): ICommandPluginAdapter | undefined {\n return resolvePluginCommandAdapter(context);\n}\n\nasync function executePluginOperation(\n context: ICommandHostContext,\n operation: (adapter: ICommandPluginAdapter) => Promise<string>,\n): Promise<ICommandResult> {\n const adapter = getPluginAdapter(context);\n if (adapter === undefined) {\n return {\n success: false,\n message: 'Plugin management is not available.',\n };\n }\n\n try {\n return {\n success: true,\n message: await operation(adapter),\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Plugin error: ${message}`,\n };\n }\n}\n\nasync function executeMarketplaceCommand(\n context: ICommandHostContext,\n subArgs: string,\n): Promise<ICommandResult> {\n const { subcommand, subArgs: marketplaceArgs } = getSubcommandParts(subArgs);\n\n if (subcommand === 'add' && marketplaceArgs.length > 0) {\n return executePluginOperation(context, async (adapter) => {\n const registeredName = await adapter.marketplaceAdd(marketplaceArgs);\n return `Added marketplace: \"${registeredName}\" (from ${marketplaceArgs})\\nInstall plugins with: /plugin install <name>@${registeredName}`;\n });\n }\n\n if (subcommand === 'remove' && marketplaceArgs.length > 0) {\n return executePluginOperation(context, async (adapter) => {\n await adapter.marketplaceRemove(marketplaceArgs);\n return `Removed marketplace \"${marketplaceArgs}\" and uninstalled its plugins.`;\n });\n }\n\n if (subcommand === 'update' && marketplaceArgs.length > 0) {\n return executePluginOperation(context, async (adapter) => {\n await adapter.marketplaceUpdate(marketplaceArgs);\n return `Updated marketplace \"${marketplaceArgs}\".`;\n });\n }\n\n if (subcommand === 'list') {\n return executePluginOperation(context, async (adapter) => {\n const sources = await adapter.marketplaceList();\n if (sources.length === 0) {\n return 'No marketplace sources configured.';\n }\n const lines = sources.map((source) => ` ${source.name} (${source.type})`);\n return `Marketplace sources:\\n${lines.join('\\n')}`;\n });\n }\n\n return usage('Usage: /plugin marketplace add <source> | remove <name> | update <name> | list');\n}\n\ntype TPluginIdOperation = (\n adapter: ICommandPluginAdapter,\n pluginId: string,\n) => Promise<string> | string;\n\nfunction executePluginIdOperation(\n context: ICommandHostContext,\n pluginId: string,\n usageMessage: string,\n operation: TPluginIdOperation,\n): Promise<ICommandResult> {\n if (pluginId.length === 0) {\n return Promise.resolve(usage(usageMessage));\n }\n return executePluginOperation(context, (adapter) =>\n Promise.resolve(operation(adapter, pluginId)),\n );\n}\n\nfunction executePluginManager(): ICommandResult {\n return {\n success: true,\n message: 'Opening plugin manager...',\n effects: [createPluginTuiRequestedEffect()],\n };\n}\n\nfunction executeInstallCommand(\n context: ICommandHostContext,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin install <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.install(targetPluginId);\n return `Installed plugin: ${targetPluginId}`;\n },\n );\n}\n\nfunction executeUninstallCommand(\n context: ICommandHostContext,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin uninstall <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.uninstall(targetPluginId);\n return `Uninstalled plugin: ${targetPluginId}`;\n },\n );\n}\n\nfunction executeEnableCommand(\n context: ICommandHostContext,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin enable <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.enable(targetPluginId);\n return `Enabled plugin: ${targetPluginId}`;\n },\n );\n}\n\nfunction executeDisableCommand(\n context: ICommandHostContext,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin disable <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.disable(targetPluginId);\n return `Disabled plugin: ${targetPluginId}`;\n },\n );\n}\n\nexport async function executePluginCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n const { subcommand, subArgs } = getSubcommandParts(args);\n switch (subcommand) {\n case '':\n case 'manage':\n return executePluginManager();\n case 'install':\n return executeInstallCommand(context, subArgs);\n case 'uninstall':\n return executeUninstallCommand(context, subArgs);\n case 'enable':\n return executeEnableCommand(context, subArgs);\n case 'disable':\n return executeDisableCommand(context, subArgs);\n case 'marketplace':\n return executeMarketplaceCommand(context, subArgs);\n default:\n return usage(`Unknown plugin subcommand: ${subcommand}`);\n }\n}\n\nexport async function executeReloadPluginsCommand(\n context: ICommandHostContext,\n _args: string,\n): Promise<ICommandResult> {\n return executePluginOperation(context, async (adapter) => {\n const result = await adapter.reloadPlugins();\n const suffix =\n result.loadedPluginCount === 1\n ? '1 plugin resource'\n : `${result.loadedPluginCount} plugin resources`;\n return `Reloaded ${suffix}.`;\n }).then((result) => {\n if (!result.success) return result;\n return {\n ...result,\n effects: [createPluginRegistryReloadRequestedEffect()],\n };\n });\n}\n","import {\n buildPluginCommandSubcommands,\n PLUGIN_COMMAND_ARGUMENT_HINT,\n PLUGIN_COMMAND_DESCRIPTION,\n RELOAD_PLUGINS_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executePluginCommand, executeReloadPluginsCommand } from './plugin-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createPluginCommandEntry(): ICommand {\n return {\n name: 'plugin',\n displayName: 'Plugins',\n description: PLUGIN_COMMAND_DESCRIPTION,\n source: 'plugin-manager',\n modelInvocable: false,\n argumentHint: PLUGIN_COMMAND_ARGUMENT_HINT,\n subcommands: buildPluginCommandSubcommands(),\n };\n}\n\nexport function createReloadPluginsCommandEntry(): ICommand {\n return {\n name: 'reload-plugins',\n displayName: 'Reload Plugins',\n description: RELOAD_PLUGINS_COMMAND_DESCRIPTION,\n source: 'plugin-manager',\n modelInvocable: false,\n };\n}\n\nfunction createPluginSystemCommand(): ISystemCommand {\n const entry = createPluginCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n subcommands: entry.subcommands,\n execute: executePluginCommand,\n };\n}\n\nfunction createReloadPluginsSystemCommand(): ISystemCommand {\n const entry = createReloadPluginsCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeReloadPluginsCommand,\n };\n}\n\nexport class PluginManagerCommandSource implements ICommandSource {\n readonly name = 'plugin-manager';\n\n getCommands(): ICommand[] {\n return [createPluginCommandEntry(), createReloadPluginsCommandEntry()];\n }\n}\n\nexport function createPluginCommandModule(): ICommandModule {\n return {\n name: 'agent-command-plugin',\n commandSources: [new PluginManagerCommandSource()],\n systemCommands: [createPluginSystemCommand(), createReloadPluginsSystemCommand()],\n };\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport { applyPresetToSession } from '@robota-sdk/agent-framework';\nimport { getPreset, listPresets, resolvePreset } from '@robota-sdk/agent-preset';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\n/** Default active preset id reported when the runtime has no recorded active preset. */\nconst DEFAULT_ACTIVE_PRESET_ID = 'default';\n\n/** Read the active preset id from the session, defaulting when the optional seam is absent. */\nfunction readActivePresetId(context: ICommandHostContext): string {\n return context.getSession().getActivePresetId?.() ?? DEFAULT_ACTIVE_PRESET_ID;\n}\n\n/** Build the `/preset` listing: one line per preset, marking the active one with a `*` prefix. */\nfunction formatPresetList(active: string): string {\n const lines = listPresets().map((preset) => {\n const marker = preset.id === active ? '* ' : ' ';\n return `${marker}${preset.id} — ${preset.title}: ${preset.description}`;\n });\n return ['Available presets:', ...lines].join('\\n');\n}\n\n/** Build the rejection message for an unknown preset id, listing the valid ids. */\nfunction formatUnknownPresetMessage(id: string): string {\n const ids = listPresets()\n .map((preset) => preset.id)\n .join(', ');\n return `Unknown preset: ${id}. Available: ${ids}`;\n}\n\n/** The `/preset` (or `/preset list`) listing result. */\nfunction presetListResult(context: ICommandHostContext): ICommandResult {\n const active = readActivePresetId(context);\n return {\n message: formatPresetList(active),\n success: true,\n data: { presets: listPresets(), active },\n };\n}\n\n/**\n * Ask the user to pick a preset (CMD-004 inline ask). Returns the chosen id, or `undefined` when no\n * interactive renderer is attached or the user cancelled — the caller then shows the preset list.\n */\nasync function resolvePresetViaAsk(context: ICommandHostContext): Promise<string | undefined> {\n const ui = context.getUserInteraction?.();\n if (!ui) return undefined;\n const options = listPresets().map((preset) => ({\n value: preset.id,\n label: preset.id,\n description: preset.description,\n }));\n const response = await ui.ask(selectAction('preset', 'Select a preset', options));\n return response.type === 'answer' ? response.values[0] : undefined;\n}\n\nexport async function executePresetCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n let id: string | undefined = args.trim().split(/\\s+/)[0];\n\n if (id === 'list') {\n return presetListResult(context);\n }\n\n if (id === undefined || id.length === 0) {\n id = await resolvePresetViaAsk(context);\n if (id === undefined) {\n return presetListResult(context);\n }\n }\n\n if (getPreset(id) === undefined) {\n return {\n message: formatUnknownPresetMessage(id),\n success: false,\n };\n }\n\n const resolved = resolvePreset(id);\n await applyPresetToSession(context, id, resolved);\n return {\n message: `Switched to preset: ${id}`,\n success: true,\n data: { preset: id },\n };\n}\n","import { listPresets } from '@robota-sdk/agent-preset';\n\nimport { executePresetCommand } from './preset-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nconst PRESET_COMMAND_DESCRIPTION = 'List presets or switch the active preset';\nconst PRESET_ARGUMENT_HINT = 'list | <preset-id>';\n\n/** Build one subcommand per registered preset id (mirrors the permission-mode subcommands). */\nfunction buildPresetSubcommands(source = 'preset'): ICommand[] {\n return listPresets().map((preset) => ({\n name: preset.id,\n description: preset.description,\n source,\n }));\n}\n\nexport function createPresetCommandEntry(): ICommand {\n return {\n name: 'preset',\n displayName: 'Agent Preset',\n description: PRESET_COMMAND_DESCRIPTION,\n source: 'preset',\n argumentHint: PRESET_ARGUMENT_HINT,\n subcommands: buildPresetSubcommands('preset'),\n modelInvocable: false,\n };\n}\n\nfunction createPresetSystemCommand(): ISystemCommand {\n const entry = createPresetCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executePresetCommand,\n };\n}\n\nexport class PresetCommandSource implements ICommandSource {\n readonly name = 'preset';\n\n getCommands(): ICommand[] {\n return [createPresetCommandEntry()];\n }\n}\n\nexport function createPresetCommandModule(): ICommandModule {\n return {\n name: 'agent-command-preset',\n commandSources: [new PresetCommandSource()],\n systemCommands: [createPresetSystemCommand()],\n };\n}\n","import { findProviderDefinition, formatSupportedProviderTypes } from '@robota-sdk/agent-core';\nimport { suggestProviderProfileName } from '@robota-sdk/agent-framework';\n\nimport type {\n IProviderDefinition,\n IProviderSetupHelpLink,\n IProviderSetupStepDefinition,\n TProviderSetupField,\n} from '@robota-sdk/agent-core';\nimport type { IProviderSetupInput } from '@robota-sdk/agent-framework';\n\nexport type TProviderSetupType = string;\nexport type TPromptInput = (label: string, masked?: boolean) => Promise<string>;\n\nexport interface IProviderSetupPromptStep extends IProviderSetupStepDefinition {\n key: TProviderSetupField;\n}\n\nexport interface IProviderSetupFlowState {\n type: TProviderSetupType;\n steps: readonly IProviderSetupPromptStep[];\n setupHelpLinks: readonly IProviderSetupHelpLink[];\n stepIndex: number;\n values: Partial<Record<TProviderSetupField, string>>;\n existingProfileNames: readonly string[];\n profileName?: string;\n setCurrent?: boolean;\n}\n\nexport interface IProviderSetupFlowOptions {\n existingProfileNames?: readonly string[];\n initialValues?: Partial<Record<TProviderSetupField, string>>;\n profileName?: string;\n setCurrent?: boolean;\n}\n\nexport type TProviderSetupFlowSubmitResult =\n | {\n status: 'next';\n state: IProviderSetupFlowState;\n }\n | {\n status: 'complete';\n input: IProviderSetupInput;\n }\n | {\n status: 'error';\n state: IProviderSetupFlowState;\n message: string;\n };\n\nexport function createProviderSetupFlow(\n type: TProviderSetupType,\n providerDefinitions: readonly IProviderDefinition[],\n options: IProviderSetupFlowOptions = {},\n): IProviderSetupFlowState {\n const definition = getProviderSetupDefinition(type, providerDefinitions);\n return {\n type,\n steps: applyProviderSetupInitialValues(\n getProviderSetupSteps(definition),\n options.initialValues,\n ),\n setupHelpLinks: definition.setupHelpLinks ?? [],\n stepIndex: 0,\n values: {},\n existingProfileNames: options.existingProfileNames ?? [],\n ...(options.profileName !== undefined ? { profileName: options.profileName } : {}),\n ...(options.setCurrent !== undefined ? { setCurrent: options.setCurrent } : {}),\n };\n}\n\nexport function formatProviderSetupSelectionPrompt(\n providerDefinitions: readonly IProviderDefinition[],\n): string {\n if (providerDefinitions.length === 0) {\n return ' No providers are available.';\n }\n const lines = [\n ' Select provider:',\n ...providerDefinitions.map(\n (definition, index) => ` ${index + 1}. ${formatProviderSetupChoiceLabel(definition)}`,\n ),\n ` Provider [1-${providerDefinitions.length}] (default: 1): `,\n ];\n return lines.join('\\n');\n}\n\nexport function resolveProviderSetupSelection(\n rawValue: string,\n providerDefinitions: readonly IProviderDefinition[],\n): TProviderSetupType {\n const value = rawValue.trim();\n const selectedValue = value.length > 0 ? value : '1';\n const index = parseProviderSelectionIndex(selectedValue);\n if (index !== undefined) {\n const definition = providerDefinitions[index];\n if (definition !== undefined) {\n return definition.type;\n }\n throw new Error(\n `Provider selection ${selectedValue} is out of range. Currently supported: ${formatSupportedProviderTypes(providerDefinitions)}`,\n );\n }\n const definition = findProviderDefinition(providerDefinitions, selectedValue);\n if (definition === undefined) {\n throw new Error(\n `Unknown provider: ${selectedValue}. Currently supported: ${formatSupportedProviderTypes(providerDefinitions)}`,\n );\n }\n return definition.type;\n}\n\nexport function getProviderSetupStep(state: IProviderSetupFlowState): IProviderSetupPromptStep {\n const step = state.steps[state.stepIndex];\n if (step === undefined) {\n throw new Error(`Provider setup step ${state.stepIndex} is out of range`);\n }\n return step;\n}\n\nexport function submitProviderSetupValue(\n state: IProviderSetupFlowState,\n rawValue: string,\n): TProviderSetupFlowSubmitResult {\n const step = getProviderSetupStep(state);\n const value = rawValue.trim() || step.defaultValue || '';\n const validationMessage = validateProviderSetupValue(step, value);\n if (validationMessage !== undefined) {\n return { status: 'error', state, message: validationMessage };\n }\n\n const nextState = {\n ...state,\n stepIndex: state.stepIndex + 1,\n values: { ...state.values, [step.key]: value },\n };\n if (nextState.stepIndex < state.steps.length) {\n return { status: 'next', state: nextState };\n }\n return { status: 'complete', input: buildProviderSetupInput(nextState) };\n}\n\nexport async function runProviderSetupPromptFlow(\n type: TProviderSetupType,\n promptInput: TPromptInput,\n providerDefinitions: readonly IProviderDefinition[],\n options: IProviderSetupFlowOptions = {},\n): Promise<IProviderSetupInput> {\n let state = createProviderSetupFlow(type, providerDefinitions, options);\n const stepCount = state.steps.length;\n while (state.stepIndex < stepCount) {\n const step = getProviderSetupStep(state);\n const value = await promptInput(\n formatProviderSetupPromptLabel(step, state.setupHelpLinks),\n step.masked === true,\n );\n const result = submitProviderSetupValue(state, value);\n if (result.status === 'complete') {\n return result.input;\n }\n if (result.status === 'error') {\n throw new Error(result.message);\n }\n state = result.state;\n }\n throw new Error('Provider setup flow ended without completion');\n}\n\nexport function formatProviderSetupPromptLabel(\n step: IProviderSetupPromptStep,\n setupHelpLinks: readonly IProviderSetupHelpLink[] = [],\n): string {\n const suffix = step.defaultValue !== undefined ? ` (default: ${step.defaultValue})` : '';\n const setupHelp = formatProviderSetupHelpLinks(setupHelpLinks);\n const prefix = setupHelp.length > 0 ? `${setupHelp}\\n` : '';\n return `${prefix} ${step.title}${suffix}: `;\n}\n\nconst CATEGORY_BADGES: Record<string, string> = {\n 'cloud-paid': '[Cloud/Paid]',\n 'cloud-free': '[Cloud/Free]',\n 'local-free': '[Local/Free]',\n};\n\nexport function formatProviderSetupChoiceLabel(definition: IProviderDefinition): string {\n const badge =\n definition.category !== undefined ? `${CATEGORY_BADGES[definition.category] ?? ''} ` : '';\n const name =\n definition.displayName !== undefined\n ? `${definition.displayName} (${definition.type})`\n : definition.type;\n const label = `${badge}${name}`;\n return definition.description !== undefined ? `${label} — ${definition.description}` : label;\n}\n\nexport function formatProviderSetupHelpLinks(\n setupHelpLinks: readonly IProviderSetupHelpLink[] = [],\n): string {\n if (setupHelpLinks.length === 0) {\n return '';\n }\n return setupHelpLinks\n .map(\n (link) =>\n ` Setup help: ${formatProviderSetupHelpLinkKind(link.kind)}: ${link.label} - ${link.url}`,\n )\n .join('\\n');\n}\n\nfunction parseProviderSelectionIndex(value: string): number | undefined {\n if (!/^\\d+$/.test(value)) {\n return undefined;\n }\n return Number(value) - 1;\n}\n\nexport function validateProviderSetupValue(\n step: IProviderSetupPromptStep,\n value: string,\n): string | undefined {\n if (step.required === true && value.length === 0) {\n return 'Required';\n }\n return undefined;\n}\n\nfunction getProviderSetupDefinition(\n type: TProviderSetupType,\n providerDefinitions: readonly IProviderDefinition[],\n): IProviderDefinition {\n const definition = findProviderDefinition(providerDefinitions, type);\n if (definition === undefined) {\n throw new Error(\n `Unknown provider: ${type}. Currently supported: ${formatSupportedProviderTypes(providerDefinitions)}`,\n );\n }\n return definition;\n}\n\nfunction getProviderSetupSteps(definition: IProviderDefinition): IProviderSetupPromptStep[] {\n if (definition.setupSteps !== undefined) {\n return [...definition.setupSteps];\n }\n\n const steps: IProviderSetupPromptStep[] = [\n {\n key: 'model',\n title: `${definition.type} model`,\n defaultValue: definition.defaults?.model,\n required: definition.defaults?.model === undefined,\n },\n ];\n if (definition.defaults?.baseURL !== undefined) {\n steps.unshift({\n key: 'baseURL',\n title: `${definition.type} base URL`,\n defaultValue: definition.defaults.baseURL,\n });\n }\n if (definition.requiresApiKey === true) {\n steps.push({\n key: 'apiKey',\n title: `${definition.type} API key`,\n defaultValue: definition.defaults?.apiKey,\n required: definition.defaults?.apiKey === undefined,\n masked: true,\n });\n }\n return steps;\n}\n\nfunction formatProviderSetupHelpLinkKind(kind: IProviderSetupHelpLink['kind']): string {\n if (kind === 'api-key') {\n return 'API key';\n }\n if (kind === 'console') {\n return 'Console';\n }\n return 'Official';\n}\n\nfunction applyProviderSetupInitialValues(\n steps: readonly IProviderSetupPromptStep[],\n initialValues: Partial<Record<TProviderSetupField, string>> | undefined,\n): IProviderSetupPromptStep[] {\n if (initialValues === undefined) {\n return [...steps];\n }\n return steps.map((step) => {\n const initialValue = initialValues[step.key];\n if (initialValue === undefined) {\n return step;\n }\n return {\n ...step,\n defaultValue: initialValue,\n required: false,\n };\n });\n}\n\nfunction buildProviderSetupInput(state: IProviderSetupFlowState): IProviderSetupInput {\n const profile =\n state.profileName ??\n suggestProviderProfileName(\n { type: state.type },\n { existingProfileNames: state.existingProfileNames },\n );\n const apiKey = state.values.apiKey;\n return {\n profile,\n type: state.type,\n model: state.values.model,\n ...(apiKey !== undefined && apiKey.length > 0 && { apiKey }),\n ...(state.values.baseURL !== undefined && { baseURL: state.values.baseURL }),\n setCurrent: state.setCurrent ?? true,\n };\n}\n","import { textAction } from '@robota-sdk/agent-core';\nimport { buildProviderSetupPatch, mergeProviderPatch } from '@robota-sdk/agent-framework';\n\nimport {\n createProviderSetupFlow,\n formatProviderSetupHelpLinks,\n getProviderSetupStep,\n submitProviderSetupValue,\n} from './provider-setup-flow.js';\n\nimport type { IProviderSetupFlowState } from './provider-setup-flow.js';\nimport type { IActionRequest, IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n IProviderCommandModuleOptions,\n IProviderSetupInput,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nconst PROVIDER_RESTART_EFFECT = {\n type: 'session-restart-requested',\n reason: 'other',\n} as const;\n\nexport function createSetupFlow(\n type: string,\n options: IProviderCommandModuleOptions,\n): IProviderSetupFlowState {\n return createProviderSetupFlow(type, options.providerDefinitions, {\n existingProfileNames: Object.keys(options.settings.readMergedSettings().providers ?? {}),\n });\n}\n\n/** Build the per-step `IActionRequest` for the current setup step (CMD-004 inline ask). */\nfunction toProviderSetupStepRequest(\n flow: IProviderSetupFlowState,\n errorMessage?: string,\n): IActionRequest {\n const step = getProviderSetupStep(flow);\n const placeholder =\n step.masked === true && step.defaultValue !== undefined ? '(unchanged)' : step.defaultValue;\n const helpLinks = formatProviderSetupHelpLinks(flow.setupHelpLinks);\n const description =\n [errorMessage, helpLinks.length > 0 ? helpLinks : undefined]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join('\\n') || undefined;\n return textAction(`provider-setup-${step.key}`, step.title, {\n description,\n placeholder,\n allowEmpty: step.defaultValue !== undefined,\n masked: step.masked,\n });\n}\n\n/**\n * Drive the setup-step engine through inline `ui.ask` calls (CMD-004), re-asking the same step when a\n * step fails validation (the error is surfaced in the request description). The `complete` sink differs\n * between the add and edit paths.\n */\nexport async function runProviderSetupAsk(\n ui: IUserInteraction,\n flow: IProviderSetupFlowState,\n complete: (input: IProviderSetupInput) => ICommandResult,\n cancelMessage: string,\n): Promise<ICommandResult> {\n let state = flow;\n let errorMessage: string | undefined;\n for (;;) {\n const response = await ui.ask(toProviderSetupStepRequest(state, errorMessage));\n if (response.type === 'cancelled') {\n return { message: cancelMessage, success: true };\n }\n const result = submitProviderSetupValue(state, response.text ?? '');\n if (result.status === 'error') {\n errorMessage = result.message;\n continue;\n }\n if (result.status === 'complete') {\n return complete(result.input);\n }\n state = result.state;\n errorMessage = undefined;\n }\n}\n\n/** Run the `/provider add` setup wizard inline. */\nexport function runProviderAddSetup(\n ui: IUserInteraction,\n flow: IProviderSetupFlowState,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n return runProviderSetupAsk(\n ui,\n flow,\n (input) => completeProviderSetup(input, options),\n 'Provider setup cancelled.',\n );\n}\n\nfunction completeProviderSetup(\n input: IProviderSetupInput,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const target = options.settings.readTargetSettings();\n const patch = buildProviderSetupPatch(input, {\n providerDefinitions: options.providerDefinitions,\n });\n options.settings.writeTargetSettings(mergeProviderPatch(target, patch));\n return {\n message: `Provider ${input.profile} configured. Restarting...`,\n success: true,\n effects: [{ ...PROVIDER_RESTART_EFFECT, message: 'Provider setup restart' }],\n };\n}\n","import {\n buildProviderSetupPatch,\n formatOrgPolicyViolationMessage,\n isApiKeyPlaintext,\n setCurrentProvider,\n upsertProviderProfile,\n} from '@robota-sdk/agent-framework';\n\nimport { runProviderSetupAsk } from './provider-command-setup.js';\nimport { createProviderSetupFlow } from './provider-setup-flow.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n IProviderSetupInput,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport function formatProviderChoiceLabel(\n name: string,\n profile: IProviderProfileSettings,\n currentProvider: string | undefined,\n): string {\n const marker = name === currentProvider ? '* ' : '';\n return `${marker}${name}: ${profile.type ?? 'unknown'} ${profile.model ?? '(no model)'}`;\n}\n\nexport function buildProviderSwitch(\n providers: Record<string, IProviderProfileSettings> | undefined,\n profileName: string | undefined,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n if (!profileName) {\n return { message: 'Usage: /provider switch <profile>', success: false };\n }\n if (!providers?.[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const { orgPolicy } = options;\n if (orgPolicy?.allowedProviders && !orgPolicy.allowedProviders.includes(profileName)) {\n return {\n message: formatOrgPolicyViolationMessage(\n `Provider \"${profileName}\" is not allowed by your organization policy. Allowed: ${orgPolicy.allowedProviders.join(', ')}.`,\n orgPolicy.adminContact,\n ),\n success: false,\n };\n }\n if (options.settings.readMergedSettings().currentProvider === profileName) {\n return { message: `Already using provider \"${profileName}\".`, success: true };\n }\n const profile = providers[profileName];\n const target = options.settings.readTargetSettings();\n const merged = options.settings.readMergedSettings();\n const next =\n target.providers?.[profileName] !== undefined || merged.providers?.[profileName] !== undefined\n ? { ...target, currentProvider: profileName }\n : setCurrentProvider(target, profileName);\n options.settings.writeTargetSettings(next);\n const modelLabel = profile.model ?? 'unknown model';\n return {\n message: `Switched to ${profileName} (${modelLabel}). History preserved.`,\n success: true,\n effects: [{ type: 'provider-hot-swap-requested', profileName }],\n };\n}\n\nexport async function buildProviderEdit(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n const profile = settings.providers?.[profileName];\n if (!profile) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n if (!profile.type) {\n return { message: `Provider profile \"${profileName}\" is missing type.`, success: false };\n }\n let flow;\n try {\n flow = createProviderSetupFlow(profile.type, options.providerDefinitions, {\n profileName,\n setCurrent: false,\n initialValues: getProviderProfileSetupValues(profile),\n });\n } catch (error) {\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n return runProviderSetupAsk(\n ui,\n flow,\n (input) => completeProviderEdit(input, profileName, options),\n 'Provider edit cancelled.',\n );\n}\n\nfunction getProviderProfileSetupValues(profile: IProviderProfileSettings): {\n model?: string;\n apiKey?: string;\n baseURL?: string;\n} {\n return {\n ...(typeof profile.model === 'string' ? { model: profile.model } : {}),\n ...(typeof profile.apiKey === 'string' ? { apiKey: profile.apiKey } : {}),\n ...(typeof profile.baseURL === 'string' ? { baseURL: profile.baseURL } : {}),\n };\n}\n\nfunction completeProviderEdit(\n input: IProviderSetupInput,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const merged = options.settings.readMergedSettings();\n const currentProfile = merged.providers?.[profileName];\n if (!currentProfile) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const { orgPolicy } = options;\n if (orgPolicy?.requireApiKeyFromEnv && isApiKeyPlaintext(input.apiKey)) {\n return {\n message: formatOrgPolicyViolationMessage(\n 'Your organization policy requires API keys to be stored as environment variable references ($ENV:VAR_NAME), not as plaintext.',\n orgPolicy.adminContact,\n ),\n success: false,\n };\n }\n const target = options.settings.readTargetSettings();\n const patch = buildProviderSetupPatch(input, {\n providerDefinitions: options.providerDefinitions,\n });\n const updatedProfile = patch.providers[profileName];\n if (!updatedProfile) {\n return { message: `Provider profile \"${profileName}\" was not updated.`, success: false };\n }\n options.settings.writeTargetSettings(\n upsertProviderProfile(target, profileName, { ...currentProfile, ...updatedProfile }),\n );\n const isCurrent = merged.currentProvider === profileName;\n return {\n message: isCurrent\n ? `Provider ${profileName} updated. Switching...`\n : `Provider ${profileName} updated.`,\n success: true,\n ...(isCurrent ? { effects: [{ type: 'provider-hot-swap-requested', profileName }] } : {}),\n };\n}\n","import { confirmAction, isConfirmed, selectAction, textAction } from '@robota-sdk/agent-core';\nimport {\n deleteProviderProfile,\n sanitizeProviderProfileName,\n upsertProviderProfile,\n} from '@robota-sdk/agent-framework';\n\nimport { formatProviderChoiceLabel } from './provider-command-profile-operations.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type { IProviderCommandModuleOptions } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nconst MAX_DUPLICATE_PROFILE_SUFFIX = 1000;\nconst PROVIDER_RESTART_EFFECT = {\n type: 'session-restart-requested',\n reason: 'other',\n} as const;\n\nexport async function buildProviderDuplicate(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n if (!settings.providers?.[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const defaultName = suggestDuplicateProfileName(profileName, Object.keys(settings.providers));\n let errorMessage: string | undefined;\n for (;;) {\n const response = await ui.ask(\n textAction('provider-duplicate', `Duplicate ${profileName} as`, {\n description: errorMessage,\n placeholder: defaultName,\n allowEmpty: true,\n }),\n );\n if (response.type === 'cancelled') {\n return { message: 'Provider duplicate cancelled.', success: true };\n }\n const value = response.text ?? '';\n // Re-ask on validation failure, surfacing the reason (CMD-004 re-ask loop replaces the closure).\n const validationMessage = validateDuplicateProfileName(value, defaultName, options);\n if (validationMessage !== undefined) {\n errorMessage = validationMessage;\n continue;\n }\n return completeProviderDuplicate(profileName, value, defaultName, options);\n }\n}\n\nfunction validateDuplicateProfileName(\n value: string,\n defaultName: string,\n options: IProviderCommandModuleOptions,\n): string | undefined {\n const name = normalizeProfileName(value, defaultName);\n if (name.length === 0) {\n return 'Required';\n }\n if (options.settings.readMergedSettings().providers?.[name] !== undefined) {\n return `Provider profile \"${name}\" already exists`;\n }\n return undefined;\n}\n\nfunction completeProviderDuplicate(\n profileName: string,\n value: string,\n defaultName: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const settings = options.settings.readMergedSettings();\n const sourceProfile = settings.providers?.[profileName];\n if (!sourceProfile) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const targetName = normalizeProfileName(value, defaultName);\n const validationMessage = validateDuplicateProfileName(targetName, defaultName, options);\n if (validationMessage !== undefined) {\n return { message: validationMessage, success: false };\n }\n options.settings.writeTargetSettings(\n upsertProviderProfile(options.settings.readTargetSettings(), targetName, { ...sourceProfile }),\n );\n return {\n message: `Provider profile duplicated: ${profileName} -> ${targetName}.`,\n success: true,\n };\n}\n\nexport async function buildProviderDelete(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n const providers = settings.providers ?? {};\n if (!providers[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n if (Object.keys(providers).length <= 1) {\n return { message: 'Cannot delete the only provider profile.', success: false };\n }\n if (options.settings.readTargetSettings().providers?.[profileName] === undefined) {\n return {\n message: `Provider profile \"${profileName}\" is not stored in the active write target; edit its source settings file or override it before deleting.`,\n success: false,\n };\n }\n const response = await ui.ask(\n confirmAction('provider-delete', `Delete provider profile ${profileName}?`),\n );\n if (!isConfirmed(response)) {\n return { message: 'Provider delete cancelled.', success: true };\n }\n return confirmProviderDelete(ui, profileName, options);\n}\n\nasync function confirmProviderDelete(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n if (settings.currentProvider !== profileName) {\n options.settings.writeTargetSettings(\n deleteProviderProfile(options.settings.readTargetSettings(), profileName),\n );\n return { message: `Provider profile deleted: ${profileName}.`, success: true };\n }\n const replacementOptions = Object.entries(settings.providers ?? {})\n .filter(([name]) => name !== profileName)\n .map(([name, profile]) => ({\n value: name,\n label: formatProviderChoiceLabel(name, profile, settings.currentProvider),\n }));\n const response = await ui.ask(\n selectAction(\n 'provider-delete-replacement',\n `Replacement provider for ${profileName}`,\n replacementOptions,\n {\n maxVisible: 8,\n },\n ),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider delete cancelled.', success: true };\n }\n return completeActiveProviderDelete(profileName, response.values[0], options);\n}\n\nfunction completeActiveProviderDelete(\n profileName: string,\n replacementName: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const settings = options.settings.readMergedSettings();\n if (settings.providers?.[replacementName] === undefined || replacementName === profileName) {\n return { message: `Provider profile \"${replacementName}\" was not found.`, success: false };\n }\n const target = deleteProviderProfile(options.settings.readTargetSettings(), profileName);\n options.settings.writeTargetSettings({ ...target, currentProvider: replacementName });\n return {\n message: `Provider profile deleted: ${profileName}. Restarting with ${replacementName}...`,\n success: true,\n effects: [{ ...PROVIDER_RESTART_EFFECT, message: 'Provider delete restart' }],\n };\n}\n\nfunction suggestDuplicateProfileName(\n profileName: string,\n existingProfileNames: readonly string[],\n): string {\n const base = sanitizeProviderProfileName(`${profileName}-copy`) ?? 'provider-copy';\n if (!existingProfileNames.includes(base)) {\n return base;\n }\n for (let index = 2; index < MAX_DUPLICATE_PROFILE_SUFFIX; index += 1) {\n const candidate = `${base}-${index}`;\n if (!existingProfileNames.includes(candidate)) {\n return candidate;\n }\n }\n return `${base}-${Date.now()}`;\n}\n\nfunction normalizeProfileName(value: string, defaultName: string): string {\n const raw = value.trim() || defaultName;\n return sanitizeProviderProfileName(raw) ?? '';\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport { testProviderProfileCommand } from '@robota-sdk/agent-framework';\n\nimport {\n buildProviderDelete,\n buildProviderDuplicate,\n} from './provider-command-profile-lifecycle.js';\nimport {\n buildProviderEdit,\n buildProviderSwitch,\n formatProviderChoiceLabel,\n} from './provider-command-profile-operations.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nconst ACTION_SWITCH = 'switch';\nconst ACTION_EDIT = 'edit';\nconst ACTION_TEST = 'test';\nconst ACTION_DUPLICATE = 'duplicate';\nconst ACTION_DELETE = 'delete';\nconst ACTION_CANCEL = 'cancel';\n\n/**\n * Ask the user to pick a provider profile, then drive its action menu (CMD-004 inline ask). Replaces\n * the former returned choice→submit continuation chain — the picker's own option list is the rendered\n * profile list, so the caller no longer prepends a separate list message.\n */\nexport async function askProviderProfileSelection(\n ui: IUserInteraction,\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const profileOptions = Object.entries(providers ?? {}).map(([name, profile]) => ({\n value: name,\n label: formatProviderChoiceLabel(name, profile, currentProvider),\n }));\n const response = await ui.ask(\n selectAction('provider-profile', 'Select provider profile', profileOptions, { maxVisible: 8 }),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider profile selection cancelled.', success: true };\n }\n return askProviderProfileAction(ui, response.values[0], options);\n}\n\nasync function askProviderProfileAction(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n if (!settings.providers?.[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const response = await ui.ask(\n selectAction('provider-profile-action', `Provider profile: ${profileName}`, [\n { value: ACTION_SWITCH, label: 'Switch' },\n { value: ACTION_EDIT, label: 'Edit' },\n { value: ACTION_TEST, label: 'Test' },\n { value: ACTION_DUPLICATE, label: 'Duplicate' },\n { value: ACTION_DELETE, label: 'Delete' },\n { value: ACTION_CANCEL, label: 'Cancel' },\n ]),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider profile action cancelled.', success: true };\n }\n return executeProviderProfileAction(ui, profileName, response.values[0], options);\n}\n\nasync function executeProviderProfileAction(\n ui: IUserInteraction,\n profileName: string,\n action: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n switch (action) {\n case ACTION_SWITCH:\n return buildProviderSwitch(settings.providers, profileName, options);\n case ACTION_EDIT:\n return buildProviderEdit(ui, profileName, options);\n case ACTION_TEST:\n return testProviderProfileCommand(\n settings.currentProvider,\n settings.providers,\n profileName,\n options,\n );\n case ACTION_DUPLICATE:\n return buildProviderDuplicate(ui, profileName, options);\n case ACTION_DELETE:\n return buildProviderDelete(ui, profileName, options);\n case ACTION_CANCEL:\n return { message: 'Provider profile action cancelled.', success: true };\n default:\n return { message: `Unknown provider profile action \"${action}\".`, success: false };\n }\n}\n","import {\n findProviderDefinition,\n formatSupportedProviderTypes,\n selectAction,\n} from '@robota-sdk/agent-core';\nimport { testProviderProfileCommand } from '@robota-sdk/agent-framework';\n\nimport { buildProviderSwitch } from './provider-command-profile-operations.js';\nimport { askProviderProfileSelection } from './provider-command-profile.js';\nimport { createSetupFlow, runProviderAddSetup } from './provider-command-setup.js';\nimport { formatProviderSetupChoiceLabel } from './provider-setup-flow.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n ICommandHostContext,\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport async function executeProviderCommand(\n context: ICommandHostContext,\n args: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const ui = context.getUserInteraction?.();\n const settings = options.settings.readMergedSettings();\n const trimmedArgs = args.trim();\n if (trimmedArgs.length === 0) {\n return buildProviderProfilePicker(ui, settings.currentProvider, settings.providers, options);\n }\n const [subcommand = 'current', profileArg] = trimmedArgs.split(/\\s+/);\n\n if (subcommand === 'list') {\n return buildProviderProfilePicker(ui, settings.currentProvider, settings.providers, options);\n }\n if (subcommand === 'current' || subcommand === '') {\n return {\n message: formatCurrentProvider(settings.currentProvider, settings.providers),\n success: true,\n };\n }\n if (subcommand === 'switch') {\n return buildProviderSwitch(settings.providers, profileArg, options);\n }\n if (subcommand === 'test') {\n return testProviderProfileCommand(\n settings.currentProvider,\n settings.providers,\n profileArg,\n options,\n );\n }\n if (subcommand === 'add') {\n return buildProviderSetup(ui, profileArg, options);\n }\n\n return {\n message: 'Usage: provider [current|list|switch <profile>|add <type>|test [profile]]',\n success: false,\n };\n}\n\n/**\n * List the provider profiles. With an interactive renderer attached, drive the inline profile picker\n * (CMD-004); without one (headless/automation) or with no profiles, return the formatted list as text.\n */\nfunction buildProviderProfilePicker(\n ui: IUserInteraction | undefined,\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> | ICommandResult {\n if (!ui || Object.keys(providers ?? {}).length === 0) {\n return { message: formatProviderList(currentProvider, providers), success: true };\n }\n return askProviderProfileSelection(ui, currentProvider, providers, options);\n}\n\nfunction formatProviderList(\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n): string {\n const entries = Object.entries(providers ?? {});\n if (entries.length === 0) {\n return 'No provider profiles configured.';\n }\n return entries\n .map(([name, profile]) => {\n const marker = name === currentProvider ? '*' : '-';\n return `${marker} ${name}: ${profile.type ?? 'unknown'} ${profile.model ?? '(no model)'}`;\n })\n .join('\\n');\n}\n\nfunction formatCurrentProvider(\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n): string {\n if (!currentProvider) {\n return 'No current provider configured.';\n }\n const profile = providers?.[currentProvider];\n if (!profile) {\n return `Current provider \"${currentProvider}\" was not found in providers.`;\n }\n return [\n `Current provider: ${currentProvider}`,\n `Type: ${profile.type ?? 'unknown'}`,\n `Model: ${profile.model ?? '(no model)'}`,\n ...(profile.baseURL ? [`Base URL: ${profile.baseURL}`] : []),\n ].join('\\n');\n}\n\n/**\n * Configure a provider profile. With an explicit `type`, run the setup wizard directly; without one,\n * ask the user to pick a provider type first (CMD-004). Without an interactive renderer, setup cannot\n * proceed — return usage text instead of a silent guess.\n */\nfunction buildProviderSetup(\n ui: IUserInteraction | undefined,\n type: string | undefined,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> | ICommandResult {\n if (type === undefined || type.length === 0) {\n if (!ui) {\n return {\n message: `Usage: provider add <type>. Supported: ${formatSupportedProviderTypes(options.providerDefinitions)}`,\n success: false,\n };\n }\n return askProviderSetupType(ui, options);\n }\n if (findProviderDefinition(options.providerDefinitions, type) === undefined) {\n return {\n message: `Usage: provider add <type>. Supported: ${formatSupportedProviderTypes(options.providerDefinitions)}`,\n success: false,\n };\n }\n if (!ui) {\n return {\n message: `Provider setup for \"${type}\" requires an interactive session.`,\n success: false,\n };\n }\n return runProviderAddSetup(ui, createSetupFlow(type, options), options);\n}\n\nasync function askProviderSetupType(\n ui: IUserInteraction,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const typeOptions = options.providerDefinitions.map((definition) => ({\n value: definition.type,\n label: formatProviderSetupChoiceLabel(definition),\n }));\n const response = await ui.ask(\n selectAction('provider-type', 'Select provider', typeOptions, { maxVisible: 6 }),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider setup cancelled.', success: true };\n }\n const type = response.values[0];\n if (findProviderDefinition(options.providerDefinitions, type) === undefined) {\n return {\n message: `Usage: provider add <type>. Supported: ${formatSupportedProviderTypes(options.providerDefinitions)}`,\n success: false,\n };\n }\n return runProviderAddSetup(ui, createSetupFlow(type, options), options);\n}\n","import { executeProviderCommand } from './provider-command-execution.js';\n\nimport type {\n ICommandModule as TCommandModule,\n IProviderCommandModuleOptions,\n IProviderCommandSettingsAdapter,\n ISystemCommand as TSystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\nexport type { IProviderCommandModuleOptions, IProviderCommandSettingsAdapter };\n\nfunction buildProviderSubcommands(): ICommand[] {\n return [\n { name: 'current', description: 'Show current provider', source: 'provider' },\n { name: 'list', description: 'List provider profiles', source: 'provider' },\n { name: 'switch', description: 'Hot-swap to another provider profile', source: 'provider' },\n { name: 'add', description: 'Configure a provider profile', source: 'provider' },\n { name: 'test', description: 'Test provider profile', source: 'provider' },\n ];\n}\n\nexport function createProviderCommandEntry(): ICommand {\n return {\n name: 'provider',\n displayName: 'Provider Setup',\n description: 'Manage provider profiles',\n source: 'provider',\n modelInvocable: false,\n argumentHint: 'current | list | switch <profile> | add [type] | test [profile]',\n subcommands: buildProviderSubcommands(),\n example: '/provider switch production',\n };\n}\n\nexport class ProviderCommandSource implements ICommandSource {\n readonly name = 'provider';\n\n getCommands(): ICommand[] {\n return [createProviderCommandEntry()];\n }\n}\n\nfunction createProviderSystemCommand(options: IProviderCommandModuleOptions): TSystemCommand {\n const entry = createProviderCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n example: entry.example,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: (context, args) => executeProviderCommand(context, args, options),\n };\n}\n\nexport function createProviderCommandModule(\n options: IProviderCommandModuleOptions,\n): TCommandModule {\n return {\n name: 'agent-command-provider',\n commandSources: [new ProviderCommandSource()],\n systemCommands: [createProviderSystemCommand(options)],\n };\n}\n","import type { TPromptInput } from './provider-setup-flow.js';\nimport type { ITerminalOutput } from '@robota-sdk/agent-core';\n\nexport type TOnboardingPath = 'has-key' | 'free-key' | 'local';\n\nexport interface IOnboardingResult {\n path: TOnboardingPath;\n preselectedType?: string;\n}\n\nconst ONBOARDING_PROMPT = `\n Do you have an API key for an AI provider?\n\n 1. Yes, I have an API key\n 2. No — get a free key (Google Gemini, takes ~2 min)\n 3. No — use a local model (LM Studio, no API key needed)\n\n Choose [1-3] (default: 1): `;\n\nconst GEMINI_GUIDE = `\n ── Get a free Gemini API key ────────────────────────────────────────────────\n\n 1. Open https://aistudio.google.com/apikey in your browser\n 2. Sign in with your Google account\n 3. Click \"Create API key\" (takes ~30 seconds)\n 4. Copy the key starting with \"AIza...\"\n\n ─────────────────────────────────────────────────────────────────────────────\n`;\n\nconst LOCAL_MODEL_GUIDE = `\n ── Set up a local model with LM Studio ──────────────────────────────────────\n\n 1. Download LM Studio from https://lmstudio.ai\n 2. Open LM Studio → search for a model (e.g. \"llama\" or \"phi\") → Download\n 3. Go to Developer tab → click Start Server\n (default address: http://localhost:1234)\n\n When the server is running, come back here and press Enter to continue.\n\n ─────────────────────────────────────────────────────────────────────────────\n`;\n\nexport async function runOnboardingBranch(\n promptInput: TPromptInput,\n terminal: ITerminalOutput,\n): Promise<IOnboardingResult> {\n const raw = await promptInput(ONBOARDING_PROMPT);\n const choice = raw.trim() || '1';\n\n if (choice === '2') {\n terminal.writeLine(GEMINI_GUIDE);\n await promptInput(' Press Enter when you have your API key: ');\n return { path: 'free-key', preselectedType: 'gemini' };\n }\n\n if (choice === '3') {\n terminal.writeLine(LOCAL_MODEL_GUIDE);\n await promptInput(' Press Enter when LM Studio server is running: ');\n return { path: 'local', preselectedType: 'gemma' };\n }\n\n return { path: 'has-key' };\n}\n","import { join } from 'node:path';\n\nimport {\n checkSettingsDocument,\n ProviderConfigError,\n readMergedProviderSettings,\n readSettings,\n writeSettings,\n resolveEnvDefaultProvider,\n resolveSettingsPathForScope,\n getProviderSettingsPaths,\n applyProviderConfiguration,\n} from '@robota-sdk/agent-framework';\n\nimport { runOnboardingBranch } from './provider-onboarding.js';\nimport {\n formatProviderSetupSelectionPrompt,\n resolveProviderSetupSelection,\n runProviderSetupPromptFlow,\n type TPromptInput,\n} from './provider-setup-flow.js';\n\nimport type { IProviderDefinition } from '@robota-sdk/agent-core';\nimport type { ITerminalOutput } from '@robota-sdk/agent-core';\nimport type { TSettingsScope } from '@robota-sdk/agent-framework';\n\nexport interface IProviderStartupContext {\n provider?: string;\n settingsScope?: TSettingsScope;\n}\n\nexport interface IEnsureProviderConfigOptions {\n formatError: (defs: readonly IProviderDefinition[]) => string;\n isInteractive?: () => boolean;\n /** Environment map for env-default synthesis (test seam, default: process.env). */\n env?: Record<string, string | undefined>;\n}\n\nexport async function runProviderStartupSetup(\n cwd: string,\n ctx: IProviderStartupContext,\n promptInput: TPromptInput,\n terminal: ITerminalOutput,\n providerDefinitions: readonly IProviderDefinition[],\n): Promise<void> {\n const onboarding = await runOnboardingBranch(promptInput, terminal);\n const existingProfileNames = Object.keys(readMergedProviderSettings(cwd).providers ?? {});\n const settingsPath = resolveSettingsPathForScope(cwd, ctx.settingsScope);\n\n let type: string;\n if (onboarding.preselectedType !== undefined) {\n type = onboarding.preselectedType;\n } else {\n const providerChoice = await promptInput(\n formatProviderSetupSelectionPrompt(providerDefinitions),\n );\n type = resolveProviderSetupSelection(providerChoice, providerDefinitions);\n }\n\n const input = await runProviderSetupPromptFlow(type, promptInput, providerDefinitions, {\n existingProfileNames,\n });\n applyProviderConfiguration(settingsPath, input, { providerDefinitions });\n const language = await promptInput(' Response language (ko/en/ja/zh, default: en): ');\n if (language) {\n const settings = readSettings(settingsPath);\n settings.language = language;\n writeSettings(settingsPath, settings);\n }\n terminal.writeLine(`\\n Config saved to ${settingsPath}\\n`);\n}\n\nexport async function ensureProviderConfig(\n cwd: string,\n ctx: IProviderStartupContext,\n promptInput: TPromptInput,\n terminal: ITerminalOutput,\n providerDefinitions: readonly IProviderDefinition[],\n options: IEnsureProviderConfigOptions,\n): Promise<void> {\n const merged = readMergedProviderSettings(cwd);\n const selectedSettings =\n ctx.provider !== undefined ? { ...merged, currentProvider: ctx.provider } : merged;\n if (checkSettingsDocument(selectedSettings, providerDefinitions) === 'valid') {\n return;\n }\n // Zero-config startup: a recognized provider env key with complete definition defaults\n // makes setup unnecessary — resolution will synthesize an env-default config.\n if (\n ctx.provider === undefined &&\n resolveEnvDefaultProvider(providerDefinitions, options.env) !== undefined\n ) {\n return;\n }\n const checkInteractive = options.isInteractive ?? (() => false);\n if (!checkInteractive()) {\n throw new ProviderConfigError(options.formatError(providerDefinitions));\n }\n await runProviderStartupSetup(\n cwd,\n selectStartupContext(cwd, ctx),\n promptInput,\n terminal,\n providerDefinitions,\n );\n const updated = readMergedProviderSettings(cwd);\n const updatedSettings =\n ctx.provider !== undefined ? { ...updated, currentProvider: ctx.provider } : updated;\n if (checkSettingsDocument(updatedSettings, providerDefinitions) !== 'valid') {\n throw new ProviderConfigError(options.formatError(providerDefinitions));\n }\n}\n\nfunction selectStartupContext(cwd: string, ctx: IProviderStartupContext): IProviderStartupContext {\n if (ctx.settingsScope !== undefined || ctx.provider !== undefined) return ctx;\n const currentProviderPath = findHighestPriorityCurrentProviderPath(getProviderSettingsPaths(cwd));\n if (currentProviderPath === undefined) return ctx;\n const projectSettingsPath = join(cwd, '.robota', 'settings.json');\n const projectLocalSettingsPath = join(cwd, '.robota', 'settings.local.json');\n if (\n currentProviderPath === projectSettingsPath ||\n currentProviderPath === projectLocalSettingsPath\n ) {\n return { ...ctx, settingsScope: 'project-local' };\n }\n return ctx;\n}\n\nfunction findHighestPriorityCurrentProviderPath(\n settingsPaths: readonly string[],\n): string | undefined {\n for (let index = settingsPaths.length - 1; index >= 0; index -= 1) {\n const settingsPath = settingsPaths[index];\n if (settingsPath === undefined) continue;\n const settings = readSettings(settingsPath);\n if (typeof settings.currentProvider === 'string') {\n return settingsPath;\n }\n }\n return undefined;\n}\n","import type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport function executeResetCommand(_context: ICommandHostContext, _args: string): ICommandResult {\n return {\n success: true,\n message: 'Reset requested.',\n data: { resetRequested: true },\n effects: [{ type: 'settings-reset-requested' }],\n };\n}\n","import { executeResetCommand } from './reset-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nconst RESET_COMMAND_DESCRIPTION = 'Delete settings';\n\nexport function createResetCommandEntry(): ICommand {\n return {\n name: 'reset',\n displayName: 'Reset Settings',\n description: RESET_COMMAND_DESCRIPTION,\n source: 'reset',\n modelInvocable: false,\n };\n}\n\nfunction createResetSystemCommand(): ISystemCommand {\n const entry = createResetCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeResetCommand,\n };\n}\n\nexport class ResetCommandSource implements ICommandSource {\n readonly name = 'reset';\n\n getCommands(): ICommand[] {\n return [createResetCommandEntry()];\n }\n}\n\nexport function createResetCommandModule(): ICommandModule {\n return {\n name: 'agent-command-reset',\n commandSources: [new ResetCommandSource()],\n systemCommands: [createResetSystemCommand()],\n };\n}\n","import {\n inspectCommandEditCheckpoint,\n listCommandEditCheckpoints,\n restoreCommandEditCheckpoint,\n rollbackCommandEditCheckpoint,\n} from '@robota-sdk/agent-framework';\n\nimport type {\n ICommandHostContext,\n IEditCheckpointInspection,\n IEditCheckpointRestoreResult,\n IEditCheckpointSummary,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nconst SUBCOMMAND_INDEX = 0;\nconst CHECKPOINT_ID_INDEX = 1;\nconst PROMPT_PREVIEW_LENGTH = 120;\nconst ELLIPSIS_LENGTH = 3;\n\nfunction usage(): ICommandResult {\n return {\n message:\n 'Usage: rewind [list] | rewind inspect <checkpoint-id> | rewind restore <checkpoint-id> | rewind code <checkpoint-id> | rewind rollback <checkpoint-id>',\n success: false,\n };\n}\n\nfunction formatPrompt(prompt: string): string {\n const compact = prompt.replace(/\\s+/g, ' ').trim();\n if (compact.length <= PROMPT_PREVIEW_LENGTH) return compact;\n return `${compact.slice(0, PROMPT_PREVIEW_LENGTH - ELLIPSIS_LENGTH)}...`;\n}\n\nfunction formatList(checkpoints: readonly IEditCheckpointSummary[]): ICommandResult {\n const lines =\n checkpoints.length > 0\n ? checkpoints.map(\n (checkpoint) =>\n `- ${checkpoint.id} files=${checkpoint.fileCount} ${checkpoint.createdAt} ${formatPrompt(\n checkpoint.prompt,\n )}`,\n )\n : ['(no edit checkpoints)'];\n\n return {\n message: ['Edit checkpoints:', ...lines].join('\\n'),\n success: true,\n data: { count: checkpoints.length, checkpoints: [...checkpoints] },\n };\n}\n\nfunction formatCheckpointIds(ids: readonly string[]): string {\n return ids.length > 0 ? ids.join(', ') : '(none)';\n}\n\nfunction formatInspection(inspection: IEditCheckpointInspection): ICommandResult {\n const fileLines =\n inspection.capturedFiles.length > 0\n ? inspection.capturedFiles.map((file) => {\n const size =\n file.snapshotSizeBytes === undefined ? '' : ` size=${file.snapshotSizeBytes}B`;\n return `- ${file.relativePath} action=${file.restoreAction} snapshot=${String(\n file.snapshotAvailable,\n )}${size}`;\n })\n : ['(no files captured)'];\n\n return {\n message: [\n `Checkpoint ${inspection.target.id}`,\n `Prompt: ${formatPrompt(inspection.target.prompt)}`,\n 'Captured files:',\n ...fileLines,\n `Restore later checkpoints: files=${inspection.restoreToCheckpoint.fileCount} checkpoints=${formatCheckpointIds(\n inspection.restoreToCheckpoint.checkpointIds,\n )}`,\n `Rollback through checkpoint: files=${inspection.rollbackThroughCheckpoint.fileCount} checkpoints=${formatCheckpointIds(\n inspection.rollbackThroughCheckpoint.checkpointIds,\n )}`,\n ].join('\\n'),\n success: true,\n data: { inspection },\n };\n}\n\nfunction formatRestoreResult(result: IEditCheckpointRestoreResult): ICommandResult {\n return {\n message: [\n `Restored code to ${result.target.id}.`,\n `Restored files: ${result.restoredFileCount}`,\n `Rolled back checkpoints: ${result.restoredCheckpointCount}`,\n ].join('\\n'),\n success: true,\n data: {\n target: result.target,\n restoredCheckpointCount: result.restoredCheckpointCount,\n restoredFileCount: result.restoredFileCount,\n removedCheckpointCount: result.removedCheckpointCount,\n },\n };\n}\n\nfunction formatRollbackResult(result: IEditCheckpointRestoreResult): ICommandResult {\n return {\n message: [\n `Rolled back code through ${result.target.id}.`,\n `Restored files: ${result.restoredFileCount}`,\n `Removed checkpoints: ${result.removedCheckpointCount}`,\n ].join('\\n'),\n success: true,\n data: {\n target: result.target,\n restoredCheckpointCount: result.restoredCheckpointCount,\n restoredFileCount: result.restoredFileCount,\n removedCheckpointCount: result.removedCheckpointCount,\n },\n };\n}\n\nfunction formatError(error: Error | string): ICommandResult {\n return {\n message: error instanceof Error ? error.message : String(error),\n success: false,\n };\n}\n\nfunction inspect(context: ICommandHostContext, checkpointId: string | undefined): ICommandResult {\n if (!checkpointId) return usage();\n try {\n return formatInspection(inspectCommandEditCheckpoint(context, checkpointId));\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nasync function restore(\n context: ICommandHostContext,\n checkpointId: string | undefined,\n): Promise<ICommandResult> {\n if (!checkpointId) return usage();\n try {\n return formatRestoreResult(await restoreCommandEditCheckpoint(context, checkpointId));\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nasync function rollback(\n context: ICommandHostContext,\n checkpointId: string | undefined,\n): Promise<ICommandResult> {\n if (!checkpointId) return usage();\n try {\n return formatRollbackResult(await rollbackCommandEditCheckpoint(context, checkpointId));\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nexport async function executeRewindCommand(\n context: ICommandHostContext,\n rawArgs: string,\n): Promise<ICommandResult> {\n const args = rawArgs.trim().split(/\\s+/).filter(Boolean);\n const subcommand = args[SUBCOMMAND_INDEX] ?? 'list';\n\n if (subcommand === 'list') {\n return formatList(listCommandEditCheckpoints(context));\n }\n\n if (subcommand === 'inspect') {\n return inspect(context, args[CHECKPOINT_ID_INDEX]);\n }\n\n if (subcommand === 'restore' || subcommand === 'code') {\n return restore(context, args[CHECKPOINT_ID_INDEX]);\n }\n\n if (subcommand === 'rollback') {\n return rollback(context, args[CHECKPOINT_ID_INDEX]);\n }\n\n return usage();\n}\n","import {\n REWIND_COMMAND_ARGUMENT_HINT,\n REWIND_COMMAND_DESCRIPTION,\n buildRewindCommandSubcommands,\n} from '@robota-sdk/agent-framework';\n\nimport { executeRewindCommand } from './rewind-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createRewindCommandEntry(): ICommand {\n return {\n name: 'rewind',\n displayName: 'Rewind History',\n description: REWIND_COMMAND_DESCRIPTION,\n source: 'rewind',\n argumentHint: REWIND_COMMAND_ARGUMENT_HINT,\n modelInvocable: false,\n safety: 'write',\n subcommands: buildRewindCommandSubcommands(),\n };\n}\n\nfunction createRewindSystemCommand(): ISystemCommand {\n const entry = createRewindCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n argumentHint: entry.argumentHint,\n userInvocable: true,\n modelInvocable: false,\n safety: 'write',\n subcommands: entry.subcommands,\n execute: executeRewindCommand,\n };\n}\n\nexport class RewindCommandSource implements ICommandSource {\n readonly name = 'rewind';\n\n getCommands(): ICommand[] {\n return [createRewindCommandEntry()];\n }\n}\n\nexport function createRewindCommandModule(): ICommandModule {\n return {\n name: 'agent-command-rewind',\n commandSources: [new RewindCommandSource()],\n systemCommands: [createRewindSystemCommand()],\n };\n}\n","/**\n * FLOW-005: parse the `<when>` portion of `/schedule` into a cron expression croner accepts.\n *\n * Two forms:\n * in <N><unit> <instruction> — one-shot, fires once at now + duration (s|m|h|d)\n * cron \"<expr>\" <instruction> — recurring, a standard cron expression\n */\n\nexport interface IScheduleSpec {\n cronExpression: string;\n instruction: string;\n recurring: boolean;\n}\n\nexport type TScheduleParseResult = { ok: true; spec: IScheduleSpec } | { ok: false; error: string };\n\nconst DURATION_MS: Record<string, number> = {\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\nconst USAGE =\n 'Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron \"<expr>\" <instruction>';\n\nexport function parseScheduleSpec(args: string, now: number): TScheduleParseResult {\n const trimmed = args.trim();\n if (trimmed.length === 0) return { ok: false, error: USAGE };\n\n if (trimmed.startsWith('in ')) {\n const rest = trimmed.slice(3).trim();\n const spaceIdx = rest.indexOf(' ');\n if (spaceIdx === -1) return { ok: false, error: `Missing instruction. ${USAGE}` };\n const durationToken = rest.slice(0, spaceIdx);\n const instruction = rest.slice(spaceIdx + 1).trim();\n const match = /^(\\d+)(s|m|h|d)$/.exec(durationToken);\n if (!match) return { ok: false, error: `Invalid duration \"${durationToken}\". ${USAGE}` };\n if (instruction.length === 0) return { ok: false, error: `Missing instruction. ${USAGE}` };\n const ms = parseInt(match[1]!, 10) * DURATION_MS[match[2]!]!;\n return {\n ok: true,\n spec: {\n cronExpression: new Date(now + ms).toISOString(),\n instruction,\n recurring: false,\n },\n };\n }\n\n if (trimmed.startsWith('cron ')) {\n const rest = trimmed.slice(5).trim();\n const quoted = /^[\"']([^\"']+)[\"']\\s+(.+)$/.exec(rest);\n if (!quoted) {\n return { ok: false, error: `cron form needs a quoted expression. ${USAGE}` };\n }\n const instruction = quoted[2]!.trim();\n if (instruction.length === 0) return { ok: false, error: `Missing instruction. ${USAGE}` };\n return {\n ok: true,\n spec: { cronExpression: quoted[1]!.trim(), instruction, recurring: true },\n };\n }\n\n return { ok: false, error: USAGE };\n}\n","/**\n * FLOW-005: `/schedule` and `/monitor` command executors — create agent-wake background tasks.\n */\n\nimport { parseScheduleSpec } from './schedule-spec-parser.js';\n\nimport type { IAgentJobHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nconst MAX_LABEL_LENGTH = 48;\n\nfunction labelFor(prefix: string, instruction: string): string {\n const snippet = instruction.slice(0, MAX_LABEL_LENGTH);\n return `${prefix}: ${snippet}${instruction.length > MAX_LABEL_LENGTH ? '…' : ''}`;\n}\n\nexport async function executeScheduleCommand(\n host: IAgentJobHostContext,\n args: string,\n now: number = Date.now(),\n): Promise<ICommandResult> {\n const parsed = parseScheduleSpec(args, now);\n if (!parsed.ok) return { message: parsed.error, success: false };\n\n const { cronExpression, instruction, recurring } = parsed.spec;\n const task = await host.spawnScheduledWake({\n label: labelFor('Scheduled', instruction),\n cronExpression,\n agentInstruction: instruction,\n });\n\n const when = recurring ? `cron \\`${cronExpression}\\`` : `once at ${cronExpression}`;\n return {\n message: `Scheduled wake (${when}): \"${instruction}\" — task ${task.id}.`,\n success: true,\n data: { taskId: task.id, cronExpression, recurring },\n };\n}\n\nconst MONITOR_USAGE = 'Usage: /monitor \"<command>\" \"<pattern>\" <instruction>';\n\n/** Parse `\"<command>\" \"<pattern>\" <instruction>` (quotes may be single or double). */\nfunction parseMonitorArgs(\n args: string,\n): { command: string; matchPattern: string; instruction: string } | null {\n const match = /^[\"']([^\"']+)[\"']\\s+[\"']([^\"']+)[\"']\\s+(.+)$/.exec(args.trim());\n if (!match) return null;\n const instruction = match[3]!.trim();\n if (instruction.length === 0) return null;\n return { command: match[1]!, matchPattern: match[2]!, instruction };\n}\n\nexport async function executeMonitorCommand(\n host: IAgentJobHostContext,\n args: string,\n): Promise<ICommandResult> {\n const parsed = parseMonitorArgs(args);\n if (!parsed) return { message: MONITOR_USAGE, success: false };\n\n const task = await host.spawnMonitorWake({\n label: labelFor('Monitor', parsed.instruction),\n command: parsed.command,\n matchPattern: parsed.matchPattern,\n agentInstruction: parsed.instruction,\n });\n\n return {\n message: `Monitoring \\`${parsed.command}\\` for /${parsed.matchPattern}/ — task ${task.id}.`,\n success: true,\n data: { taskId: task.id, matchPattern: parsed.matchPattern },\n };\n}\n","/**\n * FLOW-005: the `/schedule` + `/monitor` command module — surfaces agent-wake scheduling\n * and process monitoring to users (and the model as tools).\n */\n\nimport { executeMonitorCommand, executeScheduleCommand } from './schedule-command.js';\n\nimport type {\n IAgentJobHostContext,\n ICommandHostContext,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type {\n ICommand,\n ICommandResult,\n ICommandSource,\n} from '@robota-sdk/agent-interface-transport';\n\nfunction getAgentHostContext(context: ICommandHostContext): IAgentJobHostContext {\n const cap = context.getAgentJobCapability?.();\n if (!cap) throw new Error('Scheduling requires an active agent runtime.');\n return cap;\n}\n\nconst SCHEDULE_DESCRIPTION =\n 'Schedule the agent to wake and run an instruction on a timer (one-shot or cron).';\nconst SCHEDULE_ARGUMENT_HINT = 'in <N><s|m|h|d> <instruction> | cron \"<expr>\" <instruction>';\nconst MONITOR_DESCRIPTION =\n 'Watch a process’s output and wake the agent when a line matches a pattern.';\nconst MONITOR_ARGUMENT_HINT = '\"<command>\" \"<pattern>\" <instruction>';\n\nexport function createScheduleCommandEntry(): ICommand {\n return {\n name: 'schedule',\n displayName: 'Schedule Wake',\n description: SCHEDULE_DESCRIPTION,\n source: 'schedule',\n argumentHint: SCHEDULE_ARGUMENT_HINT,\n modelInvocable: true,\n };\n}\n\nexport function createMonitorCommandEntry(): ICommand {\n return {\n name: 'monitor',\n displayName: 'Monitor Process',\n description: MONITOR_DESCRIPTION,\n source: 'schedule',\n argumentHint: MONITOR_ARGUMENT_HINT,\n modelInvocable: true,\n };\n}\n\nfunction createScheduleSystemCommand(): ISystemCommand {\n const entry = createScheduleCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n execute: (context, args): Promise<ICommandResult> =>\n executeScheduleCommand(getAgentHostContext(context), args),\n };\n}\n\nfunction createMonitorSystemCommand(): ISystemCommand {\n const entry = createMonitorCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n execute: (context, args): Promise<ICommandResult> =>\n executeMonitorCommand(getAgentHostContext(context), args),\n };\n}\n\nexport class ScheduleCommandSource implements ICommandSource {\n readonly name = 'schedule';\n\n getCommands(): ICommand[] {\n return [createScheduleCommandEntry(), createMonitorCommandEntry()];\n }\n}\n\nexport function createScheduleCommandModule(): ICommandModule {\n return {\n name: 'agent-command-schedule',\n commandSources: [new ScheduleCommandSource()],\n systemCommands: [createScheduleSystemCommand(), createMonitorSystemCommand()],\n sessionRequirements: ['agent-runtime'],\n };\n}\n","import { calculateModelCost } from '@robota-sdk/agent-core';\n\n/**\n * Returns USD cost, or undefined if the model is not in the pricing table.\n * Delegates to the agent-core pricing SSOT (`calculateModelCost`); this package owns only the\n * command-facing display helpers below.\n */\nexport function calculateCost(\n modelId: string,\n inputTokens: number,\n outputTokens: number,\n): number | undefined {\n return calculateModelCost(modelId, inputTokens, outputTokens);\n}\n\n/** Format a USD amount for display (e.g. \"$0.0043\"). */\nexport function formatUsd(amount: number): string {\n if (amount < 0.01) return `$${amount.toFixed(4)}`;\n if (amount < 1) return `$${amount.toFixed(3)}`;\n return `$${amount.toFixed(2)}`;\n}\n\n/** Format a token count with comma separators (e.g. \"45,000\"). */\nexport function formatTokens(count: number): string {\n return count.toLocaleString('en-US');\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { confirmAction, isConfirmed } from '@robota-sdk/agent-core';\nimport {\n RENAME_COMMAND_USAGE,\n clearConversationHistory,\n createSessionPickerRequestedEffect,\n createSessionRenamedEffect,\n formatCommandSessionReplayValidationReport,\n parseSessionNameArgument,\n readCommandSessionInfo,\n validateCommandSessionReplayLog,\n} from '@robota-sdk/agent-framework';\n\nimport { calculateCost, formatTokens, formatUsd } from './model-pricing.js';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport const CLEAR_COMMAND_MESSAGE = 'Conversation cleared.';\n\nexport async function executeClearCommand(\n context: ICommandHostContext,\n _args: string,\n): Promise<ICommandResult> {\n // Confirm only when an interactive renderer is attached; with no human the explicit /clear proceeds.\n const ui = context.getUserInteraction?.();\n if (ui) {\n const response = await ui.ask(confirmAction('clear', 'Clear conversation history?'));\n if (!isConfirmed(response)) {\n return { success: true, message: 'Clear cancelled.' };\n }\n }\n\n clearConversationHistory(context);\n return {\n success: true,\n message: CLEAR_COMMAND_MESSAGE,\n effects: [{ type: 'conversation-history-cleared' }],\n };\n}\n\nexport function executeRenameCommand(_context: ICommandHostContext, args: string): ICommandResult {\n const name = parseSessionNameArgument(args);\n if (name === undefined) {\n return { success: false, message: RENAME_COMMAND_USAGE };\n }\n\n return {\n success: true,\n message: `Session renamed to \"${name}\".`,\n data: { name },\n effects: [createSessionRenamedEffect(name)],\n };\n}\n\nexport function executeResumeCommand(_context: ICommandHostContext, _args: string): ICommandResult {\n return {\n success: true,\n message: 'Opening session picker...',\n data: { triggerResumePicker: true },\n effects: [createSessionPickerRequestedEffect()],\n };\n}\n\nconst BUDGET_FILE = '.robota/budget.json';\n\ninterface IBudgetConfig {\n monthly: number;\n}\n\nfunction readBudget(cwd: string): IBudgetConfig | undefined {\n const file = join(cwd, BUDGET_FILE);\n if (!existsSync(file)) return undefined;\n let raw: string;\n try {\n raw = readFileSync(file, 'utf-8');\n } catch {\n // allow-fallback: budget file read failure disables feature gracefully\n return undefined;\n }\n try {\n return JSON.parse(raw) as IBudgetConfig;\n } catch {\n // allow-fallback: malformed budget JSON treated as no budget set\n return undefined;\n }\n}\n\nfunction writeBudget(cwd: string, config: IBudgetConfig): void {\n const dir = join(cwd, '.robota');\n mkdirSync(dir, { recursive: true });\n writeFileSync(join(cwd, BUDGET_FILE), JSON.stringify(config, null, 2));\n}\n\nfunction clearBudget(cwd: string): void {\n const file = join(cwd, BUDGET_FILE);\n if (existsSync(file)) {\n writeFileSync(file, '{}');\n }\n}\n\nfunction buildCostOutput(context: ICommandHostContext): {\n lines: string[];\n data: Record<string, unknown>;\n} {\n const session = context.getSession();\n const sessionInfo = readCommandSessionInfo(context);\n const tokenUsage = session.getSessionTokenUsage?.();\n const modelId = session.getModelId?.();\n const lines: string[] = [\n `Session: ${sessionInfo.sessionId}`,\n `Messages: ${sessionInfo.messageCount}`,\n ];\n const data: Record<string, unknown> = {\n sessionId: sessionInfo.sessionId,\n messageCount: sessionInfo.messageCount,\n };\n\n if (tokenUsage) {\n lines.push(\n `Tokens: ${formatTokens(tokenUsage.inputTokens)} input / ${formatTokens(tokenUsage.outputTokens)} output`,\n );\n data.inputTokens = tokenUsage.inputTokens;\n data.outputTokens = tokenUsage.outputTokens;\n\n if (modelId) {\n const cost = calculateCost(modelId, tokenUsage.inputTokens, tokenUsage.outputTokens);\n if (cost !== undefined) {\n lines.push(`Cost: ${formatUsd(cost)} (${modelId})`);\n data.estimatedCostUsd = cost;\n\n const budget = readBudget(context.getCwd());\n if (budget?.monthly) {\n const remaining = budget.monthly - cost;\n const pct = Math.min(100, Math.round((cost / budget.monthly) * 100));\n lines.push(\n `Budget: ${formatUsd(remaining)} remaining of ${formatUsd(budget.monthly)}/mo (${pct}% used)`,\n );\n data.budgetMonthly = budget.monthly;\n data.budgetRemainingUsd = remaining;\n }\n }\n }\n } else {\n lines.push('Tokens: not yet available (no turns completed)');\n }\n\n return { lines, data };\n}\n\nexport function executeCostCommand(context: ICommandHostContext, args: string): ICommandResult {\n const trimmed = args.trim();\n\n if (trimmed.startsWith('budget')) {\n const budgetArg = trimmed.slice('budget'.length).trim();\n\n if (budgetArg === 'clear') {\n clearBudget(context.getCwd());\n return { success: true, message: 'Monthly budget cleared.' };\n }\n\n if (budgetArg === '') {\n const current = readBudget(context.getCwd());\n if (!current?.monthly) {\n return {\n success: true,\n message: 'No budget set. Use: /cost budget <amount>',\n };\n }\n return { success: true, message: `Monthly budget: ${formatUsd(current.monthly)}` };\n }\n\n const amount = parseFloat(budgetArg);\n if (!Number.isFinite(amount) || amount <= 0) {\n return {\n success: false,\n message: 'Usage: /cost budget <amount> (e.g. /cost budget 5.00)',\n };\n }\n writeBudget(context.getCwd(), { monthly: amount });\n return { success: true, message: `Monthly budget set to ${formatUsd(amount)}.` };\n }\n\n const { lines, data } = buildCostOutput(context);\n return { success: true, message: lines.join('\\n'), data };\n}\n\nexport function executeValidateSessionCommand(\n context: ICommandHostContext,\n _args: string,\n): ICommandResult {\n const report = validateCommandSessionReplayLog(context);\n return {\n success: report.validation.ok,\n message: formatCommandSessionReplayValidationReport(report),\n data: {\n logFile: report.logFile,\n entryCount: report.entryCount,\n issueCount: report.validation.issues.length,\n ok: report.validation.ok,\n },\n };\n}\n","import {\n CLEAR_COMMAND_DESCRIPTION,\n COST_COMMAND_DESCRIPTION,\n RENAME_COMMAND_DESCRIPTION,\n RESUME_COMMAND_DESCRIPTION,\n VALIDATE_SESSION_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport {\n executeClearCommand,\n executeCostCommand,\n executeRenameCommand,\n executeResumeCommand,\n executeValidateSessionCommand,\n} from './session-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createClearCommandEntry(): ICommand {\n return {\n name: 'clear',\n displayName: 'Clear History',\n description: CLEAR_COMMAND_DESCRIPTION,\n source: 'session',\n modelInvocable: false,\n };\n}\n\nexport function createRenameCommandEntry(): ICommand {\n return {\n name: 'rename',\n displayName: 'Rename Session',\n description: RENAME_COMMAND_DESCRIPTION,\n source: 'session',\n modelInvocable: false,\n };\n}\n\nexport function createResumeCommandEntry(): ICommand {\n return {\n name: 'resume',\n displayName: 'Resume Session',\n description: RESUME_COMMAND_DESCRIPTION,\n source: 'session',\n modelInvocable: false,\n };\n}\n\nexport function createCostCommandEntry(): ICommand {\n return {\n name: 'cost',\n displayName: 'Session Cost',\n description: COST_COMMAND_DESCRIPTION,\n source: 'session',\n modelInvocable: false,\n };\n}\n\nexport function createValidateSessionCommandEntry(): ICommand {\n return {\n name: 'validate-session',\n displayName: 'Validate Session',\n description: VALIDATE_SESSION_COMMAND_DESCRIPTION,\n source: 'session',\n modelInvocable: false,\n };\n}\n\nfunction createClearSystemCommand(): ISystemCommand {\n const entry = createClearCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeClearCommand,\n };\n}\n\nfunction createRenameSystemCommand(): ISystemCommand {\n const entry = createRenameCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeRenameCommand,\n };\n}\n\nfunction createResumeSystemCommand(): ISystemCommand {\n const entry = createResumeCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeResumeCommand,\n };\n}\n\nfunction createCostSystemCommand(): ISystemCommand {\n const entry = createCostCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeCostCommand,\n };\n}\n\nfunction createValidateSessionSystemCommand(): ISystemCommand {\n const entry = createValidateSessionCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeValidateSessionCommand,\n };\n}\n\nexport class SessionCommandSource implements ICommandSource {\n readonly name = 'session';\n\n getCommands(): ICommand[] {\n return [\n createClearCommandEntry(),\n createRenameCommandEntry(),\n createResumeCommandEntry(),\n createCostCommandEntry(),\n createValidateSessionCommandEntry(),\n ];\n }\n}\n\nexport function createSessionCommandModule(): ICommandModule {\n return {\n name: 'agent-command-session',\n commandSources: [new SessionCommandSource()],\n systemCommands: [\n createClearSystemCommand(),\n createRenameSystemCommand(),\n createResumeSystemCommand(),\n createCostSystemCommand(),\n createValidateSessionSystemCommand(),\n ],\n };\n}\n","import type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createSettingsCommandEntry(): ICommand {\n return {\n name: 'settings',\n displayName: 'Settings',\n description: 'Open transport settings — enable/disable transports and configure options',\n source: 'settings',\n modelInvocable: false,\n };\n}\n\nfunction createSettingsSystemCommand(): ISystemCommand {\n const entry = createSettingsCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: async () => ({\n success: true,\n message: 'Opening settings...',\n effects: [{ type: 'settings-tui-requested' as const }],\n }),\n };\n}\n\nexport class SettingsCommandSource implements ICommandSource {\n readonly name = 'settings';\n\n getCommands(): ICommand[] {\n return [createSettingsCommandEntry()];\n }\n}\n\nexport function createSettingsCommandModule(): ICommandModule {\n return {\n name: 'agent-command-settings',\n commandSources: [new SettingsCommandSource()],\n systemCommands: [createSettingsSystemCommand()],\n };\n}\n","/**\n * TERM-003 shell-selection seam, now backed by the cross-platform SSOT resolver in agent-core\n * (TERM-008). Keep all shell choice behind this function so the call sites never change; the\n * per-platform logic (POSIX `$SHELL`/`sh`, Windows PowerShell) lives once in `resolvePlatformShell`.\n */\nimport { resolvePlatformShell } from '@robota-sdk/agent-core';\n\nexport interface IResolvedShell {\n /** Executable to spawn. */\n command: string;\n /** Args for an interactive shell session (drop-to-shell). */\n interactiveArgs: readonly string[];\n /** Args to run a single command string non-interactively. */\n commandArgs(command: string): readonly string[];\n}\n\n/** Resolve the interactive shell for the current platform via the agent-core SSOT resolver. */\nexport function resolveShell(): IResolvedShell {\n const shell = resolvePlatformShell();\n return {\n command: shell.command,\n interactiveArgs: shell.interactiveArgs,\n commandArgs: (cmd: string) => shell.commandArgs(cmd),\n };\n}\n","/**\n * TERM-003: `/shell` — hand the real terminal to an interactive subshell (or run a single command\n * interactively), then return to the agent session. Uses the framework terminal-handoff capability;\n * the shell choice goes through the `resolveShell()` seam (macOS/Linux first).\n */\nimport { resolveShell } from './resolve-shell.js';\nimport { spawnInherited } from './spawn-inherited.js';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport const SHELL_COMMAND_DESCRIPTION =\n 'Drop to an interactive shell (or run `/shell <command>` interactively), then return to the agent.';\n\nexport async function executeShellCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n if (context.canHandoffTerminal?.() !== true || context.runWithTerminal === undefined) {\n return {\n message: 'An interactive shell is unavailable here (no interactive terminal).',\n success: false,\n };\n }\n\n const shell = resolveShell();\n const cwd = context.getCwd();\n const command = args.trim();\n\n const exitCode = await context.runWithTerminal(async () =>\n command.length > 0\n ? spawnInherited(shell.command, shell.commandArgs(command), cwd)\n : spawnInherited(shell.command, shell.interactiveArgs, cwd),\n );\n\n return {\n message:\n command.length > 0\n ? `Command exited (code ${exitCode}).`\n : `Shell session ended (code ${exitCode}).`,\n success: exitCode === 0,\n data: { exitCode },\n };\n}\n","/**\n * TERM-003: `/shell` command module — a framework-level consumer of the terminal-handoff capability.\n */\nimport { executeShellCommand, SHELL_COMMAND_DESCRIPTION } from './shell-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createShellCommandEntry(): ICommand {\n return {\n name: 'shell',\n displayName: 'Shell',\n description: SHELL_COMMAND_DESCRIPTION,\n source: 'shell',\n modelInvocable: false,\n };\n}\n\nfunction createShellSystemCommand(): ISystemCommand {\n const entry = createShellCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeShellCommand,\n };\n}\n\nexport class ShellCommandSource implements ICommandSource {\n readonly name = 'shell';\n\n getCommands(): ICommand[] {\n return [createShellCommandEntry()];\n }\n}\n\nexport function createShellCommandModule(): ICommandModule {\n return {\n name: 'agent-command-shell',\n commandSources: [new ShellCommandSource()],\n systemCommands: [createShellSystemCommand()],\n };\n}\n","import type { ICommandHostContext, ICommandSkillListEntry } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport const SKILLS_COMMAND_DESCRIPTION =\n '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\".';\n\ninterface IParsedSkillsArgs {\n readonly action: 'list' | 'activate';\n readonly skillName?: string;\n readonly skillArgs: string;\n}\n\nfunction formatSkillFlags(skill: ICommandSkillListEntry): string {\n const flags: string[] = [];\n if (!skill.modelInvocable) flags.push('model-disabled');\n if (!skill.userInvocable) flags.push('model-only');\n if (skill.context) flags.push(`context:${skill.context}`);\n if (skill.agent) flags.push(`agent:${skill.agent}`);\n return flags.length > 0 ? ` [${flags.join(', ')}]` : '';\n}\n\nfunction formatSkillLine(skill: ICommandSkillListEntry): string {\n const hint = skill.argumentHint ? ` ${skill.argumentHint}` : '';\n return `- ${skill.name}${hint}: ${skill.description}${formatSkillFlags(skill)}`;\n}\n\nfunction formatSkillsMessage(skills: readonly ICommandSkillListEntry[]): string {\n if (skills.length === 0) {\n return [\n 'No skills are registered for this session.',\n '',\n 'Skills are metadata until activated. Do not invent or imitate a skill workflow when no matching registered skill exists.',\n ].join('\\n');\n }\n\n return [\n 'Registered skills:',\n ...skills.map(formatSkillLine),\n '',\n 'Activation contract:',\n '- Use /skills <skill-name> [args] to activate a matching skill.',\n '- Treat /<skill-name> as a virtual alias for /skills <skill-name>.',\n '- The system prompt Skills section is skill selection metadata.',\n '- Treat descriptions as selection metadata only, not as loaded SKILL.md content.',\n '- Do not answer by merely naming, recommending, or imitating a matching skill.',\n '- If no listed skill matches the task, continue without claiming a skill was activated.',\n ].join('\\n');\n}\n\nfunction parseSkillsArgs(args: string): IParsedSkillsArgs {\n const trimmed = args.trim();\n if (trimmed.length === 0 || trimmed === 'list') {\n return { action: 'list', skillArgs: '' };\n }\n\n const [skillName = '', ...rest] = trimmed.split(/\\s+/);\n if (skillName.length === 0) {\n return { action: 'list', skillArgs: '' };\n }\n\n return {\n action: 'activate',\n skillName,\n skillArgs: rest.join(' '),\n };\n}\n\nexport async function executeSkillsCommand(\n context: ICommandHostContext,\n args = '',\n): Promise<ICommandResult> {\n const parsed = parseSkillsArgs(args);\n if (parsed.action === 'activate' && parsed.skillName !== undefined) {\n if (!context.executeSkillCommandByName) {\n return {\n success: false,\n message: 'Skill activation is not available in this session.',\n };\n }\n const displayInput = `/${parsed.skillName}${parsed.skillArgs ? ` ${parsed.skillArgs}` : ''}`;\n const result = await context.executeSkillCommandByName(parsed.skillName, parsed.skillArgs, {\n invocationSource: context.getCommandInvocationSource?.() ?? 'user',\n displayInput,\n rawInput: displayInput,\n });\n return (\n result ?? {\n success: false,\n message: `Unknown skill: ${parsed.skillName}`,\n }\n );\n }\n\n const skills = context.listSkills?.() ?? [];\n return {\n success: true,\n message: formatSkillsMessage(skills),\n data: {\n skills,\n activationContract: {\n activateWith: '/skills <skill-name> [args]',\n activationRequiredBeforeWorkflow: true,\n metadataIsNotSkillContent: true,\n },\n },\n };\n}\n","import { SkillCommandSource } from '@robota-sdk/agent-framework';\n\nimport { executeSkillsCommand, SKILLS_COMMAND_DESCRIPTION } from './skills-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport interface ISkillsCommandModuleOptions {\n readonly cwd: string;\n}\n\nexport function createSkillsCommandEntry(): ICommand {\n return {\n name: 'skills',\n displayName: 'Skills',\n description: SKILLS_COMMAND_DESCRIPTION,\n source: 'skills',\n modelInvocable: true,\n userInvocable: true,\n argumentHint: '[list | <skill-name> [args]]',\n safety: 'read-only',\n };\n}\n\nfunction createSkillsSystemCommand(): ISystemCommand {\n const entry = createSkillsCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n lifecycle: 'inline',\n execute: executeSkillsCommand,\n };\n}\n\nexport class SkillsCommandSource implements ICommandSource {\n readonly name = 'skills';\n\n getCommands(): ICommand[] {\n return [createSkillsCommandEntry()];\n }\n}\n\nexport function createSkillsCommandModule(options: ISkillsCommandModuleOptions): ICommandModule {\n const commandSources: ICommandSource[] = [new SkillsCommandSource()];\n commandSources.push(new SkillCommandSource(options.cwd));\n\n return {\n name: 'agent-command-skills',\n commandSources,\n systemCommands: [createSkillsSystemCommand()],\n };\n}\n","import { DEFAULT_STATUS_LINE_COMMAND_SETTINGS } from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type {\n ICommandResult,\n TStatusLineCommandSettingsPatch,\n} from '@robota-sdk/agent-interface-transport';\n\ninterface IStatusLineCommandSuccessAction {\n success: true;\n message: string;\n patch: TStatusLineCommandSettingsPatch;\n}\n\ninterface IStatusLineCommandFailureAction {\n success: false;\n message: string;\n}\n\ntype TStatusLineCommandAction = IStatusLineCommandSuccessAction | IStatusLineCommandFailureAction;\n\nexport const STATUSLINE_USAGE = [\n 'Usage: /statusline on | off | reset | git on | git off',\n 'Fields: model, context, permission mode, message count, session name, thinking state, git branch.',\n].join('\\n');\n\nfunction parseStatusLineArgs(args: string): TStatusLineCommandAction {\n const parts = args\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n const [first, second] = parts;\n\n if (first === 'on' && second === undefined) {\n return { success: true, message: 'Status line enabled.', patch: { enabled: true } };\n }\n if (first === 'off' && second === undefined) {\n return { success: true, message: 'Status line disabled.', patch: { enabled: false } };\n }\n if (first === 'reset' && second === undefined) {\n return {\n success: true,\n message: 'Status line settings reset.',\n patch: { ...DEFAULT_STATUS_LINE_COMMAND_SETTINGS },\n };\n }\n if (first === 'git' && second === 'on' && parts.length === 2) {\n return {\n success: true,\n message: 'Status line git branch shown.',\n patch: { gitBranch: true },\n };\n }\n if (first === 'git' && second === 'off' && parts.length === 2) {\n return {\n success: true,\n message: 'Status line git branch hidden.',\n patch: { gitBranch: false },\n };\n }\n\n return { success: false, message: STATUSLINE_USAGE };\n}\n\nexport function executeStatusLineCommand(\n _context: ICommandHostContext,\n args: string,\n): ICommandResult {\n const action = parseStatusLineArgs(args);\n if (!action.success) {\n return { success: false, message: action.message };\n }\n\n return {\n success: true,\n message: action.message,\n effects: [{ type: 'statusline-settings-patch', patch: action.patch }],\n };\n}\n","import {\n buildStatusLineCommandSubcommands,\n STATUSLINE_COMMAND_ARGUMENT_HINT,\n STATUSLINE_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executeStatusLineCommand } from './statusline-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createStatusLineCommandEntry(): ICommand {\n return {\n name: 'statusline',\n displayName: 'Status Line',\n description: STATUSLINE_COMMAND_DESCRIPTION,\n source: 'statusline',\n argumentHint: STATUSLINE_COMMAND_ARGUMENT_HINT,\n subcommands: buildStatusLineCommandSubcommands('statusline'),\n modelInvocable: false,\n };\n}\n\nfunction createStatusLineSystemCommand(): ISystemCommand {\n const entry = createStatusLineCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executeStatusLineCommand,\n };\n}\n\nexport class StatusLineCommandSource implements ICommandSource {\n readonly name = 'statusline';\n\n getCommands(): ICommand[] {\n return [createStatusLineCommandEntry()];\n }\n}\n\nexport function createStatusLineCommandModule(): ICommandModule {\n return {\n name: 'agent-command-statusline',\n commandSources: [new StatusLineCommandSource()],\n systemCommands: [createStatusLineSystemCommand()],\n };\n}\n","export const USER_LOCAL_COMMAND_DESCRIPTION = 'Inspect Robota user-local storage and memory state.';\nexport const USER_LOCAL_COMMAND_ARGUMENT_HINT =\n 'storage list [--format json] | memory set/list/inspect/disable/delete';\nexport const USER_LOCAL_COMMAND_USAGE =\n '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>';\n","import {\n deleteUserLocalMemoryItem,\n disableUserLocalMemoryItem,\n inspectUserLocalMemoryItem,\n listUserLocalMemoryItems,\n setUserLocalMemoryItem,\n} from '@robota-sdk/agent-framework';\n\nimport { USER_LOCAL_COMMAND_USAGE } from './user-local-command-constants.js';\n\nimport type { TUserLocalMemoryCategory } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport interface IUserLocalMemoryCommandArgs {\n readonly action?: string;\n readonly positional: readonly string[];\n readonly format: 'text' | 'json';\n readonly summary?: string;\n readonly source?: string;\n}\n\nfunction formatMemoryListText(\n items: readonly { category: string; key: string; enabled: boolean }[],\n): string {\n if (items.length === 0) {\n return 'No user-local memory items.';\n }\n return items\n .map((item) => `- ${item.category}/${item.key} (${item.enabled ? 'enabled' : 'disabled'})`)\n .join('\\n');\n}\n\nfunction parseMemoryCategory(value: string | undefined): TUserLocalMemoryCategory {\n if (value === undefined) {\n throw new Error('User-local memory category is required.');\n }\n return value as TUserLocalMemoryCategory;\n}\n\nasync function executeMemoryListCommand(\n activeRepositoryRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const list = await listUserLocalMemoryItems({ activeRepositoryRoot });\n return {\n message:\n parsed.format === 'json' ? JSON.stringify(list, null, 2) : formatMemoryListText(list.items),\n success: true,\n data: { list },\n };\n}\n\nasync function executeMemorySetCommand(\n activeRepositoryRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key, value] = parsed.positional;\n const item = await setUserLocalMemoryItem({\n activeRepositoryRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n value: value ?? '',\n summary: parsed.summary ?? '',\n source: parsed.source ?? '',\n });\n return {\n message: `Stored user-local memory item ${item.category}/${item.key} at ${item.storageLocation}`,\n success: true,\n data: { item },\n };\n}\n\nasync function executeMemoryInspectCommand(\n activeRepositoryRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key] = parsed.positional;\n const item = await inspectUserLocalMemoryItem({\n activeRepositoryRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n });\n return {\n message:\n parsed.format === 'json'\n ? JSON.stringify(item, null, 2)\n : `${item.category}/${item.key}: ${item.summary}`,\n success: true,\n data: { item },\n };\n}\n\nasync function executeMemoryDisableCommand(\n activeRepositoryRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key] = parsed.positional;\n const item = await disableUserLocalMemoryItem({\n activeRepositoryRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n });\n return {\n message: `Disabled user-local memory item ${item.category}/${item.key}`,\n success: true,\n data: { item },\n };\n}\n\nasync function executeMemoryDeleteCommand(\n activeRepositoryRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key] = parsed.positional;\n const result = await deleteUserLocalMemoryItem({\n activeRepositoryRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n });\n return {\n message: `Deleted user-local memory item ${result.category}/${result.key}`,\n success: true,\n data: { result },\n };\n}\n\nexport async function executeMemoryCommand(\n cwd: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n if ((parsed.action ?? 'list') === 'list') {\n return executeMemoryListCommand(cwd, parsed);\n }\n if (parsed.action === 'set') {\n return executeMemorySetCommand(cwd, parsed);\n }\n if (parsed.action === 'inspect') {\n return executeMemoryInspectCommand(cwd, parsed);\n }\n if (parsed.action === 'disable') {\n return executeMemoryDisableCommand(cwd, parsed);\n }\n if (parsed.action === 'delete') {\n return executeMemoryDeleteCommand(cwd, parsed);\n }\n return {\n message: USER_LOCAL_COMMAND_USAGE,\n success: false,\n };\n}\n","import { inspectUserLocalStorage } from '@robota-sdk/agent-framework';\n\nimport { USER_LOCAL_COMMAND_USAGE } from './user-local-command-constants.js';\nimport { executeMemoryCommand } from './user-local-memory-command.js';\n\nimport type { ICommandHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-transport';\nexport {\n USER_LOCAL_COMMAND_ARGUMENT_HINT,\n USER_LOCAL_COMMAND_DESCRIPTION,\n USER_LOCAL_COMMAND_USAGE,\n} from './user-local-command-constants.js';\n\ntype TUserLocalOutputFormat = 'text' | 'json';\n\nexport interface IUserLocalDirectCommandOptions {\n readonly cwd: string;\n readonly argv: readonly string[];\n readonly format?: string;\n readonly summary?: string;\n readonly source?: string;\n}\n\ninterface IParsedUserLocalCommand {\n readonly target?: string;\n readonly action?: string;\n readonly positional: readonly string[];\n readonly format: TUserLocalOutputFormat;\n readonly summary?: string;\n readonly source?: string;\n}\n\ninterface IParsedUserLocalOption {\n readonly format?: string;\n readonly summary?: string;\n readonly source?: string;\n readonly nextIndex: number;\n}\n\nfunction parseOutputFormat(value: string | undefined): TUserLocalOutputFormat {\n if (value === undefined || value === 'text') {\n return 'text';\n }\n if (value === 'json') {\n return 'json';\n }\n throw new Error(`Unsupported user-local output format: ${value}`);\n}\n\nfunction parseUserLocalOption(\n arg: string,\n argv: readonly string[],\n index: number,\n): IParsedUserLocalOption | null {\n if (arg === '--format') {\n return { format: argv[index + 1], nextIndex: index + 1 };\n }\n if (arg.startsWith('--format=')) {\n return { format: arg.slice('--format='.length), nextIndex: index };\n }\n if (arg === '--summary') {\n return { summary: argv[index + 1], nextIndex: index + 1 };\n }\n if (arg.startsWith('--summary=')) {\n return { summary: arg.slice('--summary='.length), nextIndex: index };\n }\n if (arg === '--source') {\n return { source: argv[index + 1], nextIndex: index + 1 };\n }\n if (arg.startsWith('--source=')) {\n return { source: arg.slice('--source='.length), nextIndex: index };\n }\n return null;\n}\n\nfunction parseUserLocalArgs(\n argv: readonly string[],\n directOptions: {\n readonly format?: string;\n readonly summary?: string;\n readonly source?: string;\n } = {},\n): IParsedUserLocalCommand {\n let format = directOptions.format;\n let summary = directOptions.summary;\n let source = directOptions.source;\n const positional: string[] = [];\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n const option = parseUserLocalOption(arg, argv, index);\n if (option !== null) {\n format = option.format ?? format;\n summary = option.summary ?? summary;\n source = option.source ?? source;\n index = option.nextIndex;\n continue;\n }\n positional.push(arg);\n }\n\n return {\n target: positional[0],\n action: positional[1],\n positional: positional.slice(2),\n format: parseOutputFormat(format),\n summary,\n source,\n };\n}\n\nfunction splitRawArgs(rawArgs: string): readonly string[] {\n return rawArgs.trim().split(/\\s+/).filter(Boolean);\n}\n\nfunction formatStorageInspectionText(\n root: string,\n categories: readonly { category: string }[],\n): string {\n const categoryLines = categories.map((item) => `- ${item.category}`);\n return [`User-local storage root: ${root}`, 'Categories:', ...categoryLines].join('\\n');\n}\n\nasync function executeStorageCommand(\n cwd: string,\n parsed: IParsedUserLocalCommand,\n): Promise<ICommandResult> {\n if ((parsed.action ?? 'list') !== 'list') {\n return {\n message: USER_LOCAL_COMMAND_USAGE,\n success: false,\n };\n }\n\n const inspection = await inspectUserLocalStorage({ activeRepositoryRoot: cwd });\n return {\n message:\n parsed.format === 'json'\n ? JSON.stringify(inspection, null, 2)\n : formatStorageInspectionText(inspection.root, inspection.categories),\n success: true,\n data: {\n root: inspection.root,\n categories: inspection.categories,\n inspection,\n },\n };\n}\n\nasync function executeParsedUserLocalCommand(\n cwd: string,\n parsed: IParsedUserLocalCommand,\n): Promise<ICommandResult> {\n if (parsed.target === 'storage') {\n return executeStorageCommand(cwd, parsed);\n }\n if (parsed.target === 'memory') {\n return executeMemoryCommand(cwd, parsed);\n }\n return {\n message: USER_LOCAL_COMMAND_USAGE,\n success: false,\n };\n}\n\nfunction formatCommandErrorMessage(errorMessage: string): string {\n if (errorMessage.includes('ENOENT')) {\n return 'User-local memory item not found.';\n }\n return errorMessage;\n}\n\nexport async function executeUserLocalDirectCommand(\n options: IUserLocalDirectCommandOptions,\n): Promise<ICommandResult> {\n try {\n return await executeParsedUserLocalCommand(\n options.cwd,\n parseUserLocalArgs(options.argv, {\n format: options.format,\n summary: options.summary,\n source: options.source,\n }),\n );\n } catch (error) {\n return {\n message: formatCommandErrorMessage(error instanceof Error ? error.message : String(error)),\n success: false,\n };\n }\n}\n\nexport async function executeUserLocalCommand(\n context: ICommandHostContext,\n rawArgs: string,\n): Promise<ICommandResult> {\n try {\n return await executeParsedUserLocalCommand(\n context.getCwd(),\n parseUserLocalArgs(splitRawArgs(rawArgs)),\n );\n } catch (error) {\n return {\n message: formatCommandErrorMessage(error instanceof Error ? error.message : String(error)),\n success: false,\n };\n }\n}\n","import {\n USER_LOCAL_COMMAND_ARGUMENT_HINT,\n USER_LOCAL_COMMAND_DESCRIPTION,\n executeUserLocalCommand,\n} from './user-local-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-transport';\n\nexport function createUserLocalCommandEntry(): ICommand {\n return {\n name: 'user-local',\n displayName: 'User Config',\n description: USER_LOCAL_COMMAND_DESCRIPTION,\n source: 'user-local',\n argumentHint: USER_LOCAL_COMMAND_ARGUMENT_HINT,\n modelInvocable: false,\n safety: 'read-only',\n subcommands: [\n {\n name: 'storage',\n description: 'Inspect user-local storage categories',\n source: 'user-local',\n },\n {\n name: 'memory',\n description: 'Inspect and manage user-local memory items',\n source: 'user-local',\n },\n ],\n };\n}\n\nfunction createUserLocalSystemCommand(): ISystemCommand {\n const entry = createUserLocalCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n subcommands: entry.subcommands,\n execute: executeUserLocalCommand,\n };\n}\n\nexport class UserLocalCommandSource implements ICommandSource {\n readonly name = 'user-local';\n\n getCommands(): ICommand[] {\n return [createUserLocalCommandEntry()];\n }\n}\n\nexport function createUserLocalCommandModule(): ICommandModule {\n return {\n name: 'agent-command-user-local',\n commandSources: [new UserLocalCommandSource()],\n systemCommands: [createUserLocalSystemCommand()],\n };\n}\n","import { createAgentCommandModule } from '../agent/index.js';\nimport { createBackgroundCommandModule } from '../background/index.js';\nimport { createCompactCommandModule } from '../compact/index.js';\nimport { createContextCommandModule } from '../context/index.js';\nimport { createEditorCommandModule } from '../editor/index.js';\nimport { createExitCommandModule } from '../exit/index.js';\nimport { createGoalCommandModule } from '../goal/index.js';\nimport { createHelpCommandModule } from '../help/index.js';\nimport { createLanguageCommandModule } from '../language/index.js';\nimport { createMemoryCommandModule } from '../memory/index.js';\nimport { createModeCommandModule } from '../mode/index.js';\nimport { createPermissionsCommandModule } from '../permissions/index.js';\nimport { createPluginCommandModule } from '../plugin/index.js';\nimport { createPresetCommandModule } from '../preset/index.js';\nimport { createProviderCommandModule } from '../provider/index.js';\nimport { createResetCommandModule } from '../reset/index.js';\nimport { createRewindCommandModule } from '../rewind/index.js';\nimport { createScheduleCommandModule } from '../schedule/index.js';\nimport { createSessionCommandModule } from '../session/index.js';\nimport { createSettingsCommandModule } from '../settings/index.js';\nimport { createShellCommandModule } from '../shell/index.js';\nimport { createSkillsCommandModule } from '../skills/index.js';\nimport { createStatusLineCommandModule } from '../statusline/index.js';\nimport { createUserLocalCommandModule } from '../user-local/index.js';\n\nimport type { IProviderDefinition } from '@robota-sdk/agent-core';\nimport type { ICommandModule, IProviderCommandSettingsAdapter } from '@robota-sdk/agent-framework';\n\nexport interface IDefaultCommandModulesOptions {\n cwd: string;\n providerDefinitions: readonly IProviderDefinition[];\n providerSettingsAdapter: IProviderCommandSettingsAdapter;\n /**\n * Whitelist of module `name`s to keep. When provided, only modules whose `name`\n * appears here survive. Omitted → all modules kept (no-regression).\n */\n enabledCommandModules?: readonly string[];\n /**\n * Blacklist of module `name`s to remove. Applied after the whitelist, so a name\n * present in both is removed (deny > allow). Omitted → no modules removed.\n */\n disabledCommandModules?: readonly string[];\n}\n\n/**\n * Apply the preset module-selection delta to the default module set.\n *\n * Rules: if `enabled` is provided, keep only modules whose `name` is in it; then\n * remove any module whose `name` is in `disabled` (deny > allow). Neither given →\n * the full default set is returned unchanged (no-regression).\n */\nfunction applyModuleSelection(\n modules: readonly ICommandModule[],\n enabled: readonly string[] | undefined,\n disabled: readonly string[] | undefined,\n): readonly ICommandModule[] {\n let selected = modules;\n if (enabled !== undefined) {\n const allow = new Set(enabled);\n selected = selected.filter((module) => allow.has(module.name));\n }\n if (disabled !== undefined) {\n const deny = new Set(disabled);\n selected = selected.filter((module) => !deny.has(module.name));\n }\n return selected;\n}\n\nexport function createDefaultCommandModules({\n cwd,\n providerDefinitions,\n providerSettingsAdapter,\n enabledCommandModules,\n disabledCommandModules,\n}: IDefaultCommandModulesOptions): readonly ICommandModule[] {\n const modules: readonly ICommandModule[] = [\n createSkillsCommandModule({ cwd }),\n createHelpCommandModule(),\n createAgentCommandModule(),\n createPermissionsCommandModule(),\n createModeCommandModule(),\n createPresetCommandModule(),\n createLanguageCommandModule(),\n createBackgroundCommandModule(),\n createGoalCommandModule(),\n createShellCommandModule(),\n createEditorCommandModule(),\n createMemoryCommandModule(),\n createUserLocalCommandModule(),\n createCompactCommandModule(),\n createContextCommandModule(),\n createExitCommandModule(),\n createSessionCommandModule(),\n createResetCommandModule(),\n createRewindCommandModule(),\n createScheduleCommandModule(),\n createStatusLineCommandModule(),\n createPluginCommandModule(),\n createSettingsCommandModule(),\n createProviderCommandModule({\n providerDefinitions,\n settings: providerSettingsAdapter,\n }),\n ];\n return applyModuleSelection(modules, enabledCommandModules, disabledCommandModules);\n}\n","import { execSync } from 'node:child_process';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nimport {\n BundlePluginInstaller,\n BundlePluginLoader,\n MarketplaceClient,\n PluginSettingsStore,\n} from '@robota-sdk/agent-framework';\n\nimport type { IMarketplaceManifest } from '@robota-sdk/agent-framework';\nimport type {\n ICommandAvailablePlugin,\n ICommandInstalledPlugin,\n ICommandMarketplaceSource,\n ICommandPluginAdapter,\n TPluginInstallScope,\n} from '@robota-sdk/agent-interface-transport';\n\ninterface IPluginServices {\n cwd: string;\n marketplace: MarketplaceClient;\n installer: BundlePluginInstaller;\n loader: BundlePluginLoader;\n settingsStore: PluginSettingsStore;\n}\n\nfunction createPluginServices(cwd: string): IPluginServices {\n const home = homedir();\n const pluginsDir = join(home, '.robota', 'plugins');\n const userSettingsPath = join(home, '.robota', 'settings.json');\n\n const exec = (command: string, options: { timeout: number; stdio?: string }): Buffer =>\n execSync(command, {\n timeout: options.timeout,\n stdio: (options.stdio ?? 'pipe') as 'pipe' | 'inherit' | 'ignore',\n });\n\n const settingsStore = new PluginSettingsStore(userSettingsPath);\n const marketplace = new MarketplaceClient({ pluginsDir, exec });\n const installer = new BundlePluginInstaller({\n pluginsDir,\n settingsStore,\n marketplaceClient: marketplace,\n exec,\n });\n const loader = new BundlePluginLoader(pluginsDir);\n\n return {\n cwd,\n marketplace,\n installer,\n loader,\n settingsStore,\n };\n}\n\nasync function listInstalledPlugins(\n services: IPluginServices,\n): Promise<readonly ICommandInstalledPlugin[]> {\n const plugins = await services.loader.loadAll();\n const enabledMap = services.settingsStore.getEnabledPlugins();\n return plugins.map((plugin) => {\n const parts = plugin.pluginDir.split('/');\n const cacheIdx = parts.indexOf('cache');\n const marketplaceName = cacheIdx >= 0 ? (parts[cacheIdx + 1] ?? '') : '';\n const fullId = marketplaceName\n ? `${plugin.manifest.name}@${marketplaceName}`\n : plugin.manifest.name;\n return {\n name: fullId,\n description: plugin.manifest.description,\n enabled: enabledMap[fullId] !== false && enabledMap[plugin.manifest.name] !== false,\n };\n });\n}\n\nasync function listAvailablePlugins(\n services: IPluginServices,\n marketplaceName: string,\n): Promise<readonly ICommandAvailablePlugin[]> {\n let manifest: IMarketplaceManifest;\n try {\n manifest = services.marketplace.fetchManifest(marketplaceName);\n } catch {\n // allow-fallback: marketplace manifest fetch failure is non-fatal — return empty list\n return [];\n }\n const installed = services.installer.getInstalledPlugins();\n const installedNames = new Set(Object.values(installed).map((record) => record.pluginName));\n return manifest.plugins.map((plugin) => ({\n name: plugin.name,\n description: plugin.description,\n installed: installedNames.has(plugin.name),\n }));\n}\n\nasync function installPlugin(\n services: IPluginServices,\n pluginId: string,\n scope?: TPluginInstallScope,\n): Promise<void> {\n const [name, marketplaceName] = pluginId.split('@');\n if (!name || !marketplaceName) {\n throw new Error('Plugin ID must be in format: name@marketplace');\n }\n if (scope === 'project') {\n const projectPluginsDir = join(services.cwd, '.robota', 'plugins');\n const projectExec = (command: string, options: { timeout: number; stdio?: string }): Buffer =>\n execSync(command, {\n timeout: options.timeout,\n stdio: (options.stdio ?? 'pipe') as 'pipe' | 'inherit' | 'ignore',\n });\n const projectInstaller = new BundlePluginInstaller({\n pluginsDir: projectPluginsDir,\n settingsStore: services.settingsStore,\n marketplaceClient: services.marketplace,\n exec: projectExec,\n });\n await projectInstaller.install(name, marketplaceName);\n return;\n }\n await services.installer.install(name, marketplaceName);\n}\n\nasync function removeMarketplace(services: IPluginServices, name: string): Promise<void> {\n const installedFromMarketplace = services.installer.getPluginsByMarketplace(name);\n for (const record of installedFromMarketplace) {\n await services.installer.uninstall(`${record.pluginName}@${record.marketplace}`);\n }\n services.marketplace.removeMarketplace(name);\n}\n\nfunction listMarketplaces(services: IPluginServices): readonly ICommandMarketplaceSource[] {\n return services.marketplace.listMarketplaces().map((marketplaceEntry) => ({\n name: marketplaceEntry.name,\n type: marketplaceEntry.source.type,\n }));\n}\n\nexport function createDefaultPluginCommandAdapter(cwd: string): ICommandPluginAdapter {\n const services = createPluginServices(cwd);\n return {\n listInstalled: () => listInstalledPlugins(services),\n listAvailablePlugins: (marketplaceName) => listAvailablePlugins(services, marketplaceName),\n install: (pluginId, scope) => installPlugin(services, pluginId, scope),\n uninstall: async (pluginId) => services.installer.uninstall(pluginId),\n enable: async (pluginId) => services.installer.enable(pluginId),\n disable: async (pluginId) => services.installer.disable(pluginId),\n marketplaceAdd: async (source) => {\n if (source.includes('/') && !source.includes(':')) {\n return services.marketplace.addMarketplace({ type: 'github', repo: source });\n }\n return services.marketplace.addMarketplace({ type: 'git', url: source });\n },\n marketplaceRemove: (name) => removeMarketplace(services, name),\n marketplaceUpdate: async (name) => services.marketplace.updateMarketplace(name),\n marketplaceList: async () => listMarketplaces(services),\n reloadPlugins: async () => ({\n loadedPluginCount: (await services.loader.loadAll()).length,\n }),\n };\n}\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { BundlePluginLoader, PluginCommandSource } from '@robota-sdk/agent-framework';\n\nimport type { CommandRegistry } from '@robota-sdk/agent-framework';\n\nconst PLUGIN_SOURCE_NAME = 'plugin';\n\nfunction getHomeDir(): string {\n return process.env.HOME ?? homedir();\n}\n\nexport function reloadPluginCommandSource(registry: CommandRegistry): number {\n const pluginsDir = join(getHomeDir(), '.robota', 'plugins');\n const loader = new BundlePluginLoader(pluginsDir);\n try {\n // allow-fallback: plugin load failure is non-fatal — clear source and return empty\n const plugins = loader.loadPluginsSync();\n if (plugins.length === 0) {\n registry.replaceSource(PLUGIN_SOURCE_NAME);\n return 0;\n }\n registry.replaceSource(PLUGIN_SOURCE_NAME, new PluginCommandSource(plugins));\n return plugins.length;\n } catch {\n // allow-fallback: plugin load failure is non-fatal — clear source and return empty\n registry.replaceSource(PLUGIN_SOURCE_NAME);\n return 0;\n }\n}\n"],"mappings":"u2IAEA,MAAM,EAAqB,kBAoB3B,SAAgB,GAAa,EAAwB,CACnD,IAAM,EAAmB,CAAC,EACtB,EAAU,GACV,EACA,EAAU,GAEd,IAAK,IAAM,KAAQ,EAAM,CACvB,GAAI,EAAS,CACX,GAAW,EACX,EAAU,GACV,QACF,CACA,GAAI,GAAS,IAAS,KAAM,CAC1B,EAAU,GACV,QACF,CACA,GAAI,EAAO,CACL,IAAS,EAAO,EAAQ,IA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AAK,CAAO,CAAC,EAEzE,kBAAoB,GAAS,GAAkB,EAAU,CAAI,EAC7D,kBAAmB,KAAO,IAAS,EAAS,YAAY,kBAAkB,CAAI,EAC9E,gBAAiB,SAAY,GAAiB,CAAQ,EACtD,cAAe,UAAa,CAC1B,mBAAoB,MAAM,EAAS,OAAO,QAAQ,EAAA,CAAG,MACvD,EACF,CACF,CC5JA,MAAM,GAAqB,SAE3B,SAAS,IAAqB,CAC5B,OAAO,QAAQ,IAAI,MAAQ,GAAQ,CACrC,CAEA,SAAgB,GAA0B,EAAmC,CAE3E,IAAM,EAAS,IAAI,EADA,EAAK,GAAW,EAAG,UAAW,SACF,CAAC,EAChD,GAAI,CAEF,IAAM,EAAU,EAAO,gBAAgB,EAMvC,OALI,EAAQ,SAAW,GACrB,EAAS,cAAc,EAAkB,EAClC,IAET,EAAS,cAAc,GAAoB,IAAI,GAAoB,CAAO,CAAC,EACpE,EAAQ,OACjB,MAAQ,CAGN,OADA,EAAS,cAAc,EAAkB,EAClC,CACT,CACF"}
1
+ {"version":3,"file":"index.js","names":["formatError","executeSend","getAgentHostContext","PERCENT","USAGE","USAGE","formatList","constants","formatError","constants","usage","USAGE","listResult","SUBCOMMAND_INDEX","usage","formatError","formatList","listResult","usage","PROVIDER_RESTART_ACTION","MAX_LABEL_LENGTH","USAGE","executeMemoryCommand","executeMemoryCommand"],"sources":["../../src/agent/agent-command-parser.ts","../../src/agent/agent-command.ts","../../src/agent/agent-command-module.ts","../../src/background/background-command.ts","../../src/background/background-command-module.ts","../../src/compact/compact-command.ts","../../src/compact/compact-command-module.ts","../../src/context/auto-compact-format.ts","../../src/context/context-breakdown.ts","../../src/context/context-command.ts","../../src/command-module-utils.ts","../../src/context/context-command-module.ts","../../src/devices/devices-command-module.ts","../../src/doctor/doctor-node-deps.ts","../../src/doctor/doctor-render.ts","../../src/doctor/doctor-redaction.ts","../../src/doctor/doctor-settings-probe.ts","../../src/doctor/doctor-storage-probe.ts","../../src/doctor/doctor-repair.ts","../../src/doctor/doctor-extensions-probe.ts","../../src/doctor/doctor-runner.ts","../../src/doctor/doctor-command-module.ts","../../src/editor/resolve-editor.ts","../../src/shell/spawn-inherited.ts","../../src/editor/editor-command.ts","../../src/editor/editor-command-module.ts","../../src/advisor/advisor-command.ts","../../src/advisor/advisor-command-module.ts","../../src/effort/effort-command.ts","../../src/effort/effort-command-module.ts","../../src/exit/exit-command.ts","../../src/exit/exit-command-module.ts","../../src/fork/fork-command.ts","../../src/fork/fork-command-module.ts","../../src/git/git-process.ts","../../src/git/git-status.ts","../../src/git/git-commit.ts","../../src/git/git-diff.ts","../../src/git/git-command-module.ts","../../src/goal/goal-command.ts","../../src/goal/goal-command-module.ts","../../src/handoff/handoff-command.ts","../../src/handoff/handoff-command-module.ts","../../src/help/help-command.ts","../../src/help/help-command-module.ts","../../src/keybindings/keybindings-command-module.ts","../../src/language/language-command.ts","../../src/language/language-command-module.ts","../../src/mcp-activation/mcp-model-notice.ts","../../src/mcp-activation/mcp-model-status.ts","../../src/mcp-activation/mcp-activation-command.ts","../../src/mcp-activation/mcp-activation-command-module.ts","../../src/memory/memory-command.ts","../../src/memory/memory-command-module.ts","../../src/permissions/permissions-command.ts","../../src/mode/mode-command.ts","../../src/mode/mode-command-module.ts","../../src/sandbox/sandbox-command.ts","../../src/sandbox/sandbox-command-module.ts","../../src/output-style/output-style-command-module.ts","../../src/peers/peers-command.ts","../../src/peers/peers-command-module.ts","../../src/permissions/permissions-command-module.ts","../../src/plan/plan-command.ts","../../src/plan/plan-command-module.ts","../../src/plugin/plugin-command.ts","../../src/plugin/plugin-command-module.ts","../../src/preset/preset-command.ts","../../src/preset/preset-command-module.ts","../../src/provider/provider-setup-flow.ts","../../src/provider/provider-command-setup.ts","../../src/provider/provider-command-profile-operations.ts","../../src/provider/provider-command-profile-lifecycle.ts","../../src/provider/provider-command-profile.ts","../../src/provider/provider-command-execution.ts","../../src/provider/provider-command-module.ts","../../src/provider/provider-onboarding.ts","../../src/provider/provider-startup.ts","../../src/remote-control/remote-control-command.ts","../../src/remote-control/remote-control-command-module.ts","../../src/reset/reset-command.ts","../../src/reset/reset-command-module.ts","../../src/rewind/rewind-command.ts","../../src/rewind/rewind-command-module.ts","../../src/schedule/loop-jitter.ts","../../src/schedule/loop-command.ts","../../src/schedule/schedule-spec-parser.ts","../../src/schedule/schedule-command.ts","../../src/schedule/schedule-command-module.ts","../../src/session/model-pricing.ts","../../src/session/session-command.ts","../../src/session/session-command-module.ts","../../src/settings/settings-command-module.ts","../../src/shell/resolve-shell.ts","../../src/shell/shell-command.ts","../../src/shell/shell-command-module.ts","../../src/skills/skills-command.ts","../../src/skills/skills-command-module.ts","../../src/statusline/statusline-command.ts","../../src/statusline/statusline-command-module.ts","../../src/theme/theme-command-module.ts","../../src/user-local/user-local-command-constants.ts","../../src/user-local/user-local-memory-command.ts","../../src/user-local/user-local-command.ts","../../src/user-local/user-local-command-module.ts","../../src/default/default-command-modules.ts"],"sourcesContent":["import type { TBackgroundTaskIsolation } from '@robota-sdk/agent-interface-execution';\n\nconst DEFAULT_AGENT_TYPE = 'general-purpose';\n\nexport type TAgentMode = 'background';\n\nexport interface IAgentRunRequest {\n readonly agentType: string;\n readonly label: string;\n readonly mode: TAgentMode;\n readonly prompt: string;\n readonly model?: string;\n readonly isolation?: TBackgroundTaskIsolation;\n}\n\ninterface IParsedAgentOptions {\n readonly agentType?: string;\n readonly model?: string;\n readonly isolation?: TBackgroundTaskIsolation;\n readonly positional: string[];\n}\n\nexport function tokenizeArgs(args: string): string[] {\n const tokens: string[] = [];\n let current = '';\n let quote: '\"' | \"'\" | undefined;\n let escaped = false;\n\n for (const char of args) {\n if (escaped) {\n current += char;\n escaped = false;\n continue;\n }\n if (quote && char === '\\\\') {\n escaped = true;\n continue;\n }\n if (quote) {\n if (char === quote) quote = undefined;\n else current += char;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n if (/\\s/.test(char)) {\n if (current.length > 0) {\n tokens.push(current);\n current = '';\n }\n continue;\n }\n current += char;\n }\n\n if (current.length > 0) tokens.push(current);\n return tokens;\n}\n\nfunction parseOptions(tokens: readonly string[]): IParsedAgentOptions {\n const positional: string[] = [];\n let agentType: string | undefined;\n let model: string | undefined;\n let isolation: TBackgroundTaskIsolation | undefined;\n\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index];\n if (token === '--background') {\n continue;\n }\n if (token === '--agent' || token === '--type' || token === '-a') {\n agentType = tokens[index + 1];\n index += 1;\n continue;\n }\n if (token === '--model') {\n model = tokens[index + 1];\n index += 1;\n continue;\n }\n if (token === '--isolation') {\n const value = tokens[index + 1];\n if (value === 'none' || value === 'worktree') isolation = value;\n index += 1;\n continue;\n }\n if (token !== undefined) positional.push(token);\n }\n\n return {\n positional,\n ...(agentType ? { agentType } : {}),\n ...(model ? { model } : {}),\n ...(isolation ? { isolation } : {}),\n };\n}\n\nfunction createRequest(\n options: IParsedAgentOptions,\n agentType: string,\n label: string,\n prompt: string,\n): IAgentRunRequest {\n return {\n agentType,\n label,\n mode: 'background',\n prompt,\n ...(options.model ? { model: options.model } : {}),\n ...(options.isolation ? { isolation: options.isolation } : {}),\n };\n}\n\nexport function parseRunRequest(\n tokens: readonly string[],\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest | undefined {\n const options = parseOptions(tokens);\n const [first, ...rest] = options.positional;\n let agentType = options.agentType ?? DEFAULT_AGENT_TYPE;\n let promptParts = options.positional;\n\n if (!options.agentType && first && availableAgentNames.has(first)) {\n agentType = first;\n promptParts = rest;\n }\n\n const prompt = promptParts.join(' ').trim();\n if (!prompt) return undefined;\n return createRequest(options, agentType, agentType, prompt);\n}\n\nexport function parseParallelRequests(\n tokens: readonly string[],\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest[] {\n const options = parseOptions(tokens);\n return options.positional\n .map((token) => parseAgentJobToken(token, options, availableAgentNames))\n .filter((job): job is IAgentRunRequest => job !== undefined);\n}\n\nfunction parseAgentJobToken(\n token: string,\n options: IParsedAgentOptions,\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest | undefined {\n const equalsIndex = token.indexOf('=');\n if (equalsIndex > 0) {\n const label = token.slice(0, equalsIndex);\n const spec = token.slice(equalsIndex + 1);\n return parseAgentPromptSpec(label, spec, options, availableAgentNames);\n }\n\n const colonIndex = token.indexOf(':');\n if (colonIndex <= 0 || colonIndex === token.length - 1) return undefined;\n const head = token.slice(0, colonIndex);\n const prompt = token.slice(colonIndex + 1);\n const agentType =\n options.agentType ?? (availableAgentNames.has(head) ? head : DEFAULT_AGENT_TYPE);\n return createRequest(options, agentType, head, prompt);\n}\n\nfunction parseAgentPromptSpec(\n label: string,\n spec: string,\n options: IParsedAgentOptions,\n availableAgentNames: ReadonlySet<string>,\n): IAgentRunRequest | undefined {\n const colonIndex = spec.indexOf(':');\n if (colonIndex === -1) {\n const agentType =\n options.agentType ?? (availableAgentNames.has(label) ? label : DEFAULT_AGENT_TYPE);\n return createRequest(options, agentType, label, spec);\n }\n if (colonIndex === 0 || colonIndex === spec.length - 1) return undefined;\n return createRequest(options, spec.slice(0, colonIndex), label, spec.slice(colonIndex + 1));\n}\n","import { summarizeBackgroundJobGroup } from '@robota-sdk/agent-framework';\n\nimport { parseParallelRequests, parseRunRequest, tokenizeArgs } from './agent-command-parser.js';\n\nimport type { IAgentRunRequest } from './agent-command-parser.js';\nimport type { IAgentJobHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { ISubagentJobState } from '@robota-sdk/agent-interface-execution';\n\nfunction formatError<TError>(error: TError): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction getAvailableAgentNames(session: IAgentJobHostContext): ReadonlySet<string> {\n return new Set(session.listAgentDefinitions().map((agent) => agent.name));\n}\n\nfunction validateAgentType(\n session: IAgentJobHostContext,\n agentType: string,\n): ICommandResult | undefined {\n const agents = session.listAgentDefinitions();\n if (agents.some((agent) => agent.name === agentType)) return undefined;\n return {\n message: `Unknown agent type: ${agentType}\\nAvailable agents: ${agents.map((agent) => agent.name).join(', ')}`,\n success: false,\n };\n}\n\nasync function spawnAgentJob(\n session: IAgentJobHostContext,\n request: IAgentRunRequest,\n): Promise<ICommandResult | { state: ISubagentJobState }> {\n const invalid = validateAgentType(session, request.agentType);\n if (invalid) return invalid;\n try {\n return { state: await session.spawnAgentJob(request) };\n } catch (error) {\n return { message: formatError(error), success: false };\n }\n}\n\nfunction executeOpenSwitcher(): ICommandResult {\n return { message: '', uiIntents: [{ type: 'show-agent-switcher' }], success: true };\n}\n\nasync function executeList(session: IAgentJobHostContext): Promise<ICommandResult> {\n const agents = session.listAgentDefinitions();\n const jobs = session.listAgentJobs();\n const lines = [\n 'Available agents:',\n ...agents.map((agent) => ` ${agent.name} - ${agent.description}`),\n '',\n jobs.length === 0 ? 'No active agent jobs.' : 'Agent jobs:',\n ...jobs.map((job) => ` ${formatAgentJobLine(job)}`),\n ];\n return {\n message: lines.join('\\n'),\n success: true,\n data: { agents: agents.length, jobs: jobs.length },\n };\n}\n\nfunction formatAgentJobLine(job: ISubagentJobState): string {\n const worktree = [\n job.worktreePath ? `worktree=${job.worktreePath}` : undefined,\n job.branchName ? `branch=${job.branchName}` : undefined,\n ].filter((segment): segment is string => segment !== undefined);\n const metadata = worktree.length > 0 ? ` ${worktree.join(' ')}` : '';\n return `${job.id} [${job.status}${metadata}] ${job.label} - ${job.promptPreview}`;\n}\n\nasync function executeRun(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const request = parseRunRequest(tokens, getAvailableAgentNames(session));\n if (!request) {\n return {\n message: 'Usage: agent run [AGENT_NAME] [--agent AGENT_NAME] PROMPT',\n success: false,\n };\n }\n\n const spawned = await spawnAgentJob(session, request);\n if ('success' in spawned) return spawned;\n const { state } = spawned;\n\n return {\n message: `Started agent job: ${state.id}`,\n success: true,\n data: { agentId: state.id, status: state.status },\n };\n}\n\nasync function executeParallel(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const wait = tokens.includes('--wait') || !tokens.includes('--detach');\n const commandTokens = tokens.filter((token) => token !== '--wait' && token !== '--detach');\n const jobs = parseParallelRequests(commandTokens, getAvailableAgentNames(session));\n\n if (jobs.length === 0) {\n return {\n message: 'Usage: agent parallel [--wait|--detach] LABEL:\"PROMPT\" [LABEL=AGENT_NAME:\"PROMPT\"]',\n success: false,\n };\n }\n\n const invalid = jobs\n .map((job) => validateAgentType(session, job.agentType))\n .find((result): result is ICommandResult => result !== undefined);\n if (invalid) return invalid;\n\n let states: ISubagentJobState[];\n try {\n states = await Promise.all(jobs.map((job) => session.spawnAgentJob(job)));\n } catch (error) {\n return { message: formatError(error), success: false };\n }\n const group = session.createBackgroundJobGroup({\n waitPolicy: 'wait_all',\n taskIds: states.map((state) => state.id),\n label: 'agent parallel',\n });\n\n if (wait) {\n const completed = await session.waitBackgroundJobGroup(group.id);\n const summary = summarizeBackgroundJobGroup(completed);\n return {\n message: formatGroupSummary(summary),\n success: true,\n data: { agentIds: states.map((state) => state.id), groupId: group.id, summary },\n };\n }\n\n return {\n message: ['Started agent jobs:', ...states.map((state) => `${state.label}: ${state.id}`)].join(\n '\\n',\n ),\n success: true,\n data: { agentIds: states.map((state) => state.id), groupId: group.id },\n };\n}\n\nasync function executeWait(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [groupId] = tokens;\n if (!groupId) return { message: 'Usage: agent wait GROUP_ID', success: false };\n const completed = await session.waitBackgroundJobGroup(groupId);\n const summary = summarizeBackgroundJobGroup(completed);\n return {\n message: formatGroupSummary(summary),\n success: true,\n data: { groupId, summary },\n };\n}\n\nasync function executeRead(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId, offset] = tokens;\n if (!agentId) return { message: 'Usage: agent read AGENT_ID [OFFSET]', success: false };\n const cursor = offset ? { offset: Number.parseInt(offset, 10) } : undefined;\n const page = await session.readBackgroundTaskLog(agentId, cursor);\n const next = page.nextCursor ? `\\nNext offset: ${page.nextCursor.offset}` : '';\n return {\n message: page.lines.length > 0 ? `${page.lines.join('\\n')}${next}` : `No log lines: ${agentId}`,\n success: true,\n data: { agentId, nextOffset: page.nextCursor?.offset },\n };\n}\n\nasync function executeSend(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId, ...promptParts] = tokens;\n const prompt = promptParts.join(' ').trim();\n if (!agentId || !prompt) {\n return { message: 'Usage: agent send AGENT_ID PROMPT', success: false };\n }\n await session.sendAgentJob(agentId, prompt);\n return { message: `Sent input to agent job: ${agentId}`, success: true, data: { agentId } };\n}\n\nasync function executeStop(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId, ...reasonParts] = tokens;\n if (!agentId) return { message: 'Usage: agent stop AGENT_ID [REASON]', success: false };\n await session.cancelAgentJob(agentId, reasonParts.join(' ') || undefined);\n return { message: `Agent job stopped: ${agentId}`, success: true, data: { agentId } };\n}\n\nasync function executeClose(\n session: IAgentJobHostContext,\n tokens: readonly string[],\n): Promise<ICommandResult> {\n const [agentId] = tokens;\n if (!agentId) return { message: 'Usage: agent close AGENT_ID', success: false };\n await session.closeAgentJob(agentId);\n return { message: `Agent job closed: ${agentId}`, success: true, data: { agentId } };\n}\n\nexport async function executeAgentCommand(\n session: IAgentJobHostContext,\n args: string,\n): Promise<ICommandResult> {\n try {\n if (args.trim() === '') return executeOpenSwitcher();\n const [action = 'list', ...tokens] = tokenizeArgs(args);\n if (action === 'list' && tokens.length === 0) return executeList(session);\n if (action === 'run') return executeRun(session, tokens);\n if (action === 'parallel') return executeParallel(session, tokens);\n if (action === 'wait') return executeWait(session, tokens);\n if (action === 'read' || action === 'open') return executeRead(session, tokens);\n if (action === 'send') return executeSend(session, tokens);\n if (action === 'stop' || action === 'cancel') return executeStop(session, tokens);\n if (action === 'close') return executeClose(session, tokens);\n return executeRun(session, [action, ...tokens]);\n } catch (error) {\n return { message: formatError(error), success: false };\n }\n}\n\nfunction formatGroupSummary(summary: ReturnType<typeof summarizeBackgroundJobGroup>): string {\n const header = `Background job group ${summary.groupId}: ${summary.status} (${summary.completed}/${summary.total} completed, ${summary.failed} failed, ${summary.cancelled} cancelled, ${summary.pending} pending)`;\n return [header, ...summary.lines].join('\\n');\n}\n","import { executeAgentCommand } from './agent-command.js';\n\nimport type {\n IAgentJobHostContext,\n ICommandHostAgentJobs,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nfunction getAgentHostContext(context: ICommandHostAgentJobs): IAgentJobHostContext {\n const cap = context.getAgentJobCapability();\n if (!cap) throw new Error('Agent job capability is not available in this context.');\n return cap;\n}\n\nfunction createAgentSubcommands(): ICommand[] {\n return [\n { name: 'list', description: 'List available agents and active jobs', source: 'agent' },\n { name: 'run', description: 'Start one background agent job', source: 'agent' },\n { name: 'parallel', description: 'Run multiple agents in parallel', source: 'agent' },\n { name: 'wait', description: 'Wait for a background agent group summary', source: 'agent' },\n { name: 'read', description: 'Read an agent job log page', source: 'agent' },\n { name: 'send', description: 'Send follow-up input to an agent job', source: 'agent' },\n { name: 'stop', description: 'Cancel a running agent job', source: 'agent' },\n { name: 'close', description: 'Dismiss a terminal agent job', source: 'agent' },\n { name: 'open', description: 'Read an agent job log page (alias for read)', source: 'agent' },\n ];\n}\n\nexport function createAgentCommandEntry(): ICommand {\n return {\n name: 'agent',\n displayName: 'Agent Jobs',\n description: 'Start and manage background subagent jobs',\n // Model-invocable: delegating work to subagents is the model's own decision, and each job runs\n // under the session's permissions, so starting one widens nothing.\n modelDescription: [\n 'Start and manage background subagent jobs.',\n 'Natural-language arguments start one background agent job.',\n '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.',\n 'If the target item is unspecified, include target selection inside the agent prompt instead of delaying execution.',\n 'The parallel form starts multiple background agent jobs as a wait_all group and returns a consolidated group summary unless --detach is present.',\n 'list, wait, read, send, stop, close, and open manage existing agent jobs.',\n 'Returns the started job id (or group summary), the job list, or the requested log page.',\n ].join(' '),\n source: 'agent',\n modelInvocable: true,\n argumentHint:\n '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',\n safety: 'background-agent',\n subcommands: createAgentSubcommands(),\n };\n}\n\nexport function createAgentSystemCommand(): ISystemCommand {\n const entry = createAgentCommandEntry();\n return {\n name: entry.name,\n semanticRole: 'subagentSpawn',\n ...(entry.displayName !== undefined ? { displayName: entry.displayName } : {}),\n description: entry.description,\n requiresPermission: false,\n execute: (context, args) => executeAgentCommand(getAgentHostContext(context), args),\n ...(entry.modelInvocable !== undefined ? { modelInvocable: entry.modelInvocable } : {}),\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n ...(entry.userInvocable !== undefined ? { userInvocable: entry.userInvocable } : {}),\n ...(entry.argumentHint !== undefined ? { argumentHint: entry.argumentHint } : {}),\n ...(entry.safety !== undefined ? { safety: entry.safety } : {}),\n ...(entry.subcommands !== undefined ? { subcommands: entry.subcommands } : {}),\n };\n}\n\nexport class AgentCommandSource implements ICommandSource {\n readonly name = 'agent';\n\n getCommands(): ICommand[] {\n return [createAgentCommandEntry()];\n }\n}\n\nexport function createAgentCommandModule(): ICommandModule {\n return {\n name: 'agent-command-agent',\n commandSources: [new AgentCommandSource()],\n systemCommands: [createAgentSystemCommand()],\n sessionRequirements: ['agent-runtime'],\n };\n}\n","import {\n BACKGROUND_COMMAND_USAGE,\n cancelCommandBackgroundTask,\n closeCommandBackgroundTask,\n formatCommandBackgroundTaskList,\n listCommandBackgroundTasks,\n parseCommandBackgroundLogCursor,\n readCommandBackgroundTaskLog,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostBackgroundTasks } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nfunction parseCommandParts(args: string): string[] {\n return args.trim().split(/\\s+/).filter(Boolean);\n}\n\nexport async function executeBackgroundCommand(\n context: ICommandHostBackgroundTasks,\n args: string,\n): Promise<ICommandResult> {\n const [action = 'list', taskId, ...reasonParts] = parseCommandParts(args);\n if (action === 'list') {\n const tasks = listCommandBackgroundTasks(context);\n return {\n message: formatCommandBackgroundTaskList(tasks),\n success: true,\n data: { count: tasks.length },\n };\n }\n\n if (!taskId) {\n return {\n message: BACKGROUND_COMMAND_USAGE,\n success: false,\n };\n }\n\n if (action === 'read' || action === 'log' || action === 'open') {\n const page = await readCommandBackgroundTaskLog(\n context,\n taskId,\n parseCommandBackgroundLogCursor(reasonParts[0]),\n );\n const next = page.nextCursor ? `\\nNext offset: ${page.nextCursor.offset}` : '';\n return {\n message:\n page.lines.length > 0 ? `${page.lines.join('\\n')}${next}` : `No log lines: ${taskId}`,\n success: true,\n data: { taskId, nextOffset: page.nextCursor?.offset },\n };\n }\n\n if (action === 'cancel' || action === 'stop') {\n await cancelCommandBackgroundTask(context, taskId, reasonParts.join(' ') || undefined);\n return { message: `Background task cancelled: ${taskId}`, success: true, data: { taskId } };\n }\n\n if (action === 'close' || action === 'dismiss') {\n await closeCommandBackgroundTask(context, taskId);\n return { message: `Background task closed: ${taskId}`, success: true, data: { taskId } };\n }\n\n return { message: `Unknown background action: ${action}`, success: false };\n}\n","import {\n BACKGROUND_COMMAND_DESCRIPTION,\n buildBackgroundCommandSubcommands,\n} from '@robota-sdk/agent-framework';\n\nimport { executeBackgroundCommand } from './background-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createBackgroundCommandEntry(): ICommand {\n return {\n name: 'background',\n displayName: 'Background Tasks',\n description: BACKGROUND_COMMAND_DESCRIPTION,\n source: 'background',\n // User-only: a view onto the user's job panel; the model manages its own jobs through `agent`.\n modelInvocable: false,\n subcommands: buildBackgroundCommandSubcommands(),\n };\n}\n\nfunction createBackgroundSystemCommand(): ISystemCommand {\n const entry = createBackgroundCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n subcommands: entry.subcommands,\n execute: executeBackgroundCommand,\n };\n}\n\nexport class BackgroundCommandSource implements ICommandSource {\n readonly name = 'background';\n\n getCommands(): ICommand[] {\n return [createBackgroundCommandEntry()];\n }\n}\n\nexport function createBackgroundCommandModule(): ICommandModule {\n return {\n name: 'agent-command-background',\n commandSources: [new BackgroundCommandSource()],\n systemCommands: [createBackgroundSystemCommand()],\n };\n}\n","import { compactCommandContext } from '@robota-sdk/agent-framework';\n\nimport type {\n ICommandHostContextWindow,\n ICommandHostSessionAccess,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nfunction parseInstructions(args: string): string | undefined {\n const instructions = args.trim();\n return instructions.length > 0 ? instructions : undefined;\n}\n\nexport async function executeCompactCommand(\n context: ICommandHostContextWindow & ICommandHostSessionAccess,\n args: string,\n): Promise<ICommandResult> {\n const result = await compactCommandContext(context, parseInstructions(args));\n const { before, after, beforeMessageCount, afterMessageCount } = result;\n const removedMessages = beforeMessageCount - afterMessageCount;\n const removedPercent =\n beforeMessageCount > 0 ? Math.round((removedMessages / beforeMessageCount) * 100) : 0;\n const message = [\n 'Context compacted.',\n ` Removed messages: ${removedMessages} (${removedPercent}% of total)`,\n ` Context: ${Math.round(before.usedPercentage)}% → ${Math.round(after.usedPercentage)}%`,\n ].join('\\n');\n return {\n message,\n success: true,\n data: { before, after, beforeMessageCount, afterMessageCount },\n };\n}\n","import { executeCompactCommand } from './compact-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createCompactCommandEntry(): ICommand {\n return {\n name: 'compact',\n displayName: 'Compact Context',\n description: 'Compress context window',\n // Model-invocable: compaction only summarizes the model's own context, and the model is the one\n // that notices when it is running out of room.\n modelDescription:\n 'Summarize older conversation turns to free context-window space. Use it when the context is ' +\n 'nearly full (check with the context command) or before starting a large new task; optional ' +\n 'instructions say what the summary must keep. Returns how many messages were removed and the ' +\n 'context usage before and after.',\n source: 'compact',\n modelInvocable: true,\n argumentHint: '[instructions]',\n safety: 'write',\n example: '/compact Summarize the current context',\n };\n}\n\nfunction createCompactSystemCommand(): ISystemCommand {\n const entry = createCompactCommandEntry();\n return {\n name: entry.name,\n semanticRole: 'contextReduction',\n displayName: entry.displayName,\n description: entry.description,\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n example: entry.example,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: entry.modelInvocable,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n lifecycle: 'blocking',\n execute: executeCompactCommand,\n };\n}\n\nexport class CompactCommandSource implements ICommandSource {\n readonly name = 'compact';\n\n getCommands(): ICommand[] {\n return [createCompactCommandEntry()];\n }\n}\n\nexport function createCompactCommandModule(): ICommandModule {\n return {\n name: 'agent-command-compact',\n commandSources: [new CompactCommandSource()],\n systemCommands: [createCompactSystemCommand()],\n };\n}\n","/**\n * Leaf formatting helpers for the auto-compact threshold line. Split out of `context-command.ts`\n * so `context-breakdown.ts` can use {@link formatAutoCompactLine} without importing back from\n * `context-command.ts`, which previously created an import cycle between the two.\n */\nimport type { TAutoCompactThreshold, TAutoCompactThresholdSource } from '@robota-sdk/agent-framework';\n\nconst PERCENT = 100;\n\nexport function formatThreshold(threshold: TAutoCompactThreshold): string {\n if (threshold === false) {\n return 'disabled';\n }\n return `${Math.round(threshold * PERCENT)}%`;\n}\n\nexport function formatAutoCompactLine(\n threshold: TAutoCompactThreshold,\n source: TAutoCompactThresholdSource,\n): string {\n if (threshold === false) {\n return `Auto compact: disabled (${source})`;\n }\n return `Auto compact: ${formatThreshold(threshold)} (${source})`;\n}\n","/**\n * The `/context` transcript breakdown: token accounting over the history plus its rendering.\n *\n * Split out of `context-command.ts` when that file passed its size floor. The seam is a real one and\n * the role ports named it: this half only READS (`TContextReadHost`), while the command surface it\n * came from dispatches subcommands and writes thresholds and references.\n */\n\nimport { CONTEXT_ESTIMATE_CHARS_PER_TOKEN, estimateToolSchemaTokens } from '@robota-sdk/agent-core';\nimport {\n listCommandContextReferences,\n readAutoCompactThreshold,\n readAutoCompactThresholdSource,\n readCommandContextState,\n} from '@robota-sdk/agent-framework';\n\nimport { formatAutoCompactLine } from './auto-compact-format.js';\n\nimport type { IHistoryEntry, TUniversalMessage } from '@robota-sdk/agent-core';\nimport type {\n ICommandHostContextReferences,\n ICommandHostContextWindow,\n ICommandHostSessionAccess,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IContextReferenceItem } from '@robota-sdk/agent-interface-session';\n\n/** What the breakdown reads — no adapter role, no writes. */\ntype TContextReadHost = ICommandHostContextReferences &\n ICommandHostContextWindow &\n ICommandHostSessionAccess;\n\nconst TOOL_ARG_MAX_LEN = 60;\n\nfunction estimateTokens(charLength: number): number {\n return Math.ceil(charLength / CONTEXT_ESTIMATE_CHARS_PER_TOKEN);\n}\n\nexport function formatContextReferenceLine(reference: IContextReferenceItem): string {\n return [\n reference.relativePath,\n `[${reference.loadType}, ${reference.status}]`,\n `~${estimateTokens(reference.byteLength).toLocaleString()} tokens`,\n ].join(' ');\n}\n\n// ── History analysis ────────────────────────────────────────────────────────\n\ninterface IToolResultSummary {\n toolName: string;\n displayArg: string;\n}\n\ninterface IMessageTokensByRole {\n systemTokens: number;\n userTokens: number;\n userCount: number;\n assistantTokens: number;\n assistantCount: number;\n toolTokens: number;\n toolCallCount: number;\n totalTokens: number;\n}\n\ninterface IToolDisplayList {\n turnCount: number;\n toolResults: IToolResultSummary[];\n totalToolCallCount: number;\n}\n\nfunction parseToolCallArgs(argsJson: string): Record<string, unknown> | null {\n try {\n return JSON.parse(argsJson) as Record<string, unknown>;\n } catch {\n // allow-fallback: tool call arguments JSON may be malformed; display-only degradation, not a terminal path\n return null;\n }\n}\n\nfunction extractFirstToolArg(argsJson: string): string {\n const parsed = parseToolCallArgs(argsJson);\n if (parsed === null) return '';\n const first = Object.values(parsed)[0];\n const raw = typeof first === 'string' ? first : JSON.stringify(first);\n return raw.length > TOOL_ARG_MAX_LEN ? `${raw.slice(0, TOOL_ARG_MAX_LEN)}…` : raw;\n}\n\nfunction computeMessageTokensByRole(rawMessages: TUniversalMessage[]): IMessageTokensByRole {\n let systemTokens = 0;\n let userTokens = 0;\n let userCount = 0;\n let assistantTokens = 0;\n let assistantCount = 0;\n let toolTokens = 0;\n let toolCallCount = 0;\n\n for (const msg of rawMessages) {\n const t = Math.ceil(JSON.stringify(msg).length / CONTEXT_ESTIMATE_CHARS_PER_TOKEN);\n if (msg.role === 'system') {\n systemTokens += t;\n } else if (msg.role === 'user') {\n userTokens += t;\n userCount++;\n } else if (msg.role === 'assistant') {\n assistantTokens += t;\n assistantCount++;\n } else if (msg.role === 'tool') {\n toolTokens += t;\n toolCallCount++;\n }\n }\n\n return {\n systemTokens,\n userTokens,\n userCount,\n assistantTokens,\n assistantCount,\n toolTokens,\n toolCallCount,\n totalTokens: systemTokens + userTokens + assistantTokens + toolTokens,\n };\n}\n\n/** One conversation item as the display reads it: its role and its message payload. */\ninterface IChatItem {\n readonly type: string;\n readonly data: unknown;\n}\n\n/** Every chat entry of the full history, including turns compaction has since summarized away. */\nexport function buildToolDisplayList(history: IHistoryEntry[]): IToolDisplayList {\n return buildDisplayList(\n history\n .filter((entry) => entry.category === 'chat')\n .map((entry) => ({ type: entry.type, data: entry.data })),\n );\n}\n\n/** Only what the model still has in context — what `/context list` accounts for. */\nexport function buildLiveToolDisplayList(messages: readonly TUniversalMessage[]): IToolDisplayList {\n return buildDisplayList(messages.map((message) => ({ type: message.role, data: message })));\n}\n\nfunction buildDisplayList(items: readonly IChatItem[]): IToolDisplayList {\n type TToolCallEntry = { name: string; firstArg: string };\n const toolCallMap = new Map<string, TToolCallEntry>();\n\n for (const entry of items) {\n if (entry.type !== 'assistant') continue;\n const data = entry.data as {\n toolCalls?: Array<{ id: string; function: { name: string; arguments: string } }>;\n };\n for (const tc of data.toolCalls ?? []) {\n toolCallMap.set(tc.id, {\n name: tc.function.name,\n firstArg: extractFirstToolArg(tc.function.arguments),\n });\n }\n }\n\n let turnCount = 0;\n let totalToolCallCount = 0;\n const toolDisplayMap = new Map<string, IToolResultSummary>();\n\n for (const entry of items) {\n if (entry.type === 'user') {\n turnCount++;\n } else if (entry.type === 'tool') {\n const data = entry.data as { toolCallId?: string };\n const tc = toolCallMap.get(data.toolCallId ?? '');\n const toolName = tc?.name ?? 'tool';\n const displayArg = tc?.firstArg ?? '';\n totalToolCallCount++;\n toolDisplayMap.set(`${toolName}:${displayArg}`, { toolName, displayArg });\n }\n }\n\n return {\n turnCount,\n toolResults: [...toolDisplayMap.values()],\n totalToolCallCount,\n };\n}\n\n// ── Full context breakdown (for /context list) ──────────────────────────────\n\nfunction formatSection(title: string, tokens: number, lines: string[]): string {\n const tokenLabel = tokens > 0 ? ` — ~${tokens.toLocaleString()} tokens` : '';\n const header = `${title}${tokenLabel}:`;\n return lines.length === 0\n ? `${header}\\n (none)`\n : [header, ...lines.map((l) => ` ${l}`)].join('\\n');\n}\n\nexport function formatFullContextBreakdown(context: TContextReadHost): ICommandResult {\n const state = readCommandContextState(context);\n const autoCompactThreshold = readAutoCompactThreshold(context);\n const autoCompactThresholdSource = readAutoCompactThresholdSource(context);\n const rawMessages = context.getSession().getHistory();\n const msgTokens = computeMessageTokensByRole(rawMessages);\n // CLI-1990: what the TOOL SCHEMAS cost on every request — the offered set, so a deferred tool that\n // has not been loaded is not counted, because it is not sent. Until now nothing separated this\n // from the system prompt it is billed alongside, so the saving deferral produces had no observable.\n const offeredToolSchemas = context.getSession().getOfferedToolSchemas();\n const toolSchemaTokens = estimateToolSchemaTokens(offeredToolSchemas);\n // The live messages, like the token counts beside it: a turn compaction summarized away is no\n // longer in context, so listing its tool results would describe a context the model does not have.\n const display = buildLiveToolDisplayList(rawMessages);\n const references = listCommandContextReferences(context);\n\n const systemRefs = references.filter((r) => r.loadType === 'system');\n const manualRefs = references.filter((r) => r.loadType === 'manual');\n const promptRefs = references.filter((r) => r.loadType === 'prompt-reference');\n\n const systemRefTokens = systemRefs.reduce((s, r) => s + estimateTokens(r.byteLength), 0);\n const manualTokens = manualRefs.reduce((s, r) => s + estimateTokens(r.byteLength), 0);\n const promptRefTokens = promptRefs.reduce((s, r) => s + estimateTokens(r.byteLength), 0);\n\n const convTurnLabel =\n display.turnCount === 0\n ? 'Conversation history — 0 turns'\n : `Conversation history — ${display.turnCount} turn${display.turnCount !== 1 ? 's' : ''} | ~${msgTokens.totalTokens.toLocaleString()} tokens`;\n\n const toolResultLines = display.toolResults.map(\n (t) => `${t.toolName}${t.displayArg ? `: ${t.displayArg}` : ''}`,\n );\n\n const uniqueToolCount = display.toolResults.length;\n const totalToolCallCount = display.totalToolCallCount;\n const toolResultsLabel =\n totalToolCallCount === 0\n ? 'Tool results (0): (none)'\n : uniqueToolCount < totalToolCallCount\n ? `Tool results (${uniqueToolCount} unique / ${totalToolCallCount} calls, ~${msgTokens.toolTokens.toLocaleString()} tokens):`\n : `Tool results (${uniqueToolCount}, ~${msgTokens.toolTokens.toLocaleString()} tokens):`;\n\n const conversationLines: string[] =\n display.turnCount === 0\n ? []\n : [\n `User (${msgTokens.userCount}): ~${msgTokens.userTokens.toLocaleString()} tokens`,\n `Assistant (${msgTokens.assistantCount}): ~${msgTokens.assistantTokens.toLocaleString()} tokens`,\n ...(msgTokens.systemTokens > 0\n ? [`System messages: ~${msgTokens.systemTokens.toLocaleString()} tokens`]\n : []),\n totalToolCallCount > 0\n ? [toolResultsLabel, ...toolResultLines.map((l) => ` ${l}`)].join('\\n')\n : toolResultsLabel,\n ];\n\n const convSection =\n display.turnCount === 0\n ? `${convTurnLabel}:\\n (none)`\n : [`${convTurnLabel}:`, ...conversationLines.map((l) => ` ${l}`)].join('\\n');\n\n const message = [\n `Context: ${state.usedTokens.toLocaleString()} / ${state.maxTokens.toLocaleString()} tokens (${Math.round(state.usedPercentage)}%)`,\n formatAutoCompactLine(autoCompactThreshold, autoCompactThresholdSource),\n '',\n formatSection(\n 'System prompt (active every turn)',\n systemRefTokens,\n systemRefs.map(formatContextReferenceLine),\n ),\n '',\n formatSection(\n 'Tool schemas (sent every turn)',\n toolSchemaTokens,\n offeredToolSchemas.map((schema) => schema.name),\n ),\n '',\n convSection,\n '',\n formatSection('Manually added', manualTokens, manualRefs.map(formatContextReferenceLine)),\n '',\n formatSection(\n 'Prompt references (@-syntax)',\n promptRefTokens,\n promptRefs.map(formatContextReferenceLine),\n ),\n ].join('\\n');\n\n return {\n success: true,\n message,\n data: {\n references,\n history: { turnCount: display.turnCount, toolResults: display.toolResults },\n // CLI-1990: machine-readable beside the rendered line, so a caller can compare the figure\n // across configurations rather than parsing the message back out.\n toolSchemaTokens,\n },\n };\n}\n","import {\n addCommandContextReference,\n clearCommandContextReferences,\n DEFAULT_AUTO_COMPACT_THRESHOLD,\n listCommandContextReferences,\n readAutoCompactThreshold,\n readAutoCompactThresholdSource,\n readCommandContextState,\n removeCommandContextReference,\n resetAutoCompactThresholdSetting,\n setCommandAutoCompactThreshold,\n writeAutoCompactThresholdSetting,\n} from '@robota-sdk/agent-framework';\n\nimport {\n buildToolDisplayList,\n formatContextReferenceLine,\n formatFullContextBreakdown,\n} from './context-breakdown.js';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostContextReferences,\n ICommandHostContextWindow,\n ICommandHostSessionAccess,\n TAutoCompactThreshold,\n TAutoCompactThresholdSource,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IContextReferenceItem } from '@robota-sdk/agent-interface-session';\n\nimport { formatAutoCompactLine, formatThreshold } from './auto-compact-format.js';\n\nexport { formatAutoCompactLine } from './auto-compact-format.js';\n\nconst PERCENT = 100;\nconst USAGE = [\n 'Usage: /context [list] | add <path> | remove <path> | clear | auto on | off | <percent> | reset',\n 'Examples: /context list, /context add AGENTS.md, /context remove AGENTS.md, /context auto 85%',\n].join('\\n');\n\nfunction formatPersistenceSuffix(persisted: boolean): string {\n return persisted ? 'settings' : 'current session only';\n}\n\n/** The roles the `/context` surface reads. Named once so five signatures do not restate it. */\ntype TContextCommandHost = ICommandHostAdapterAccess &\n ICommandHostContextReferences &\n ICommandHostContextWindow &\n ICommandHostSessionAccess;\n\n/** The subset the threshold operations need — no context-reference role. */\ntype TContextThresholdHost = ICommandHostAdapterAccess &\n ICommandHostContextWindow &\n ICommandHostSessionAccess;\n\nexport async function executeContextCommand(\n context: TContextCommandHost,\n args: string,\n): Promise<ICommandResult> {\n const parts = args\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n\n if (parts.length > 0) {\n return executeContextSubcommand(context, parts);\n }\n\n const state = readCommandContextState(context);\n const autoCompactThreshold = readAutoCompactThreshold(context);\n const autoCompactThresholdSource = readAutoCompactThresholdSource(context);\n const history = context.getSession().getFullHistory();\n const display = buildToolDisplayList(history);\n const references = listCommandContextReferences(context);\n return {\n message: [\n `Context: ${state.usedTokens.toLocaleString()} / ${state.maxTokens.toLocaleString()} tokens (${Math.round(state.usedPercentage)}%)`,\n formatAutoCompactLine(autoCompactThreshold, autoCompactThresholdSource),\n formatContextReferenceSummary(references),\n `History: ${display.turnCount} turn${display.turnCount !== 1 ? 's' : ''}`,\n ].join('\\n'),\n success: true,\n data: {\n usedTokens: state.usedTokens,\n maxTokens: state.maxTokens,\n percentage: state.usedPercentage,\n autoCompactThreshold,\n autoCompactThresholdSource,\n references,\n },\n };\n}\n\nasync function executeContextSubcommand(\n context: TContextCommandHost,\n parts: readonly string[],\n): Promise<ICommandResult> {\n const [subcommand, ...rest] = parts;\n if (subcommand === 'list') {\n if (rest.length > 0) return { success: false, message: USAGE };\n return formatFullContextBreakdown(context);\n }\n if (subcommand === 'add') {\n return executeAddContextReference(context, rest);\n }\n if (subcommand === 'remove') {\n return executeRemoveContextReference(context, rest);\n }\n if (subcommand === 'clear') {\n if (rest.length > 0) return { success: false, message: USAGE };\n const result = clearCommandContextReferences(context);\n return {\n success: true,\n message: `Context references cleared: ${result.removed.length} removed.`,\n data: { removed: result.removed },\n };\n }\n if (subcommand !== 'auto') {\n return { success: false, message: USAGE };\n }\n return executeAutoContextSubcommand(context, rest);\n}\n\nfunction executeAutoContextSubcommand(\n context: TContextThresholdHost,\n parts: readonly string[],\n): ICommandResult {\n const [action, extra] = parts;\n if (extra !== undefined) return { success: false, message: USAGE };\n if (action === undefined) {\n const threshold = readAutoCompactThreshold(context);\n const source = readAutoCompactThresholdSource(context);\n return {\n success: true,\n message: [formatAutoCompactLine(threshold, source), USAGE].join('\\n'),\n data: { autoCompactThreshold: threshold, autoCompactThresholdSource: source },\n };\n }\n\n if (action === 'on') {\n return applyAutoCompactThreshold(context, DEFAULT_AUTO_COMPACT_THRESHOLD, 'enabled');\n }\n if (action === 'off') {\n return applyAutoCompactThreshold(context, false, 'disabled');\n }\n if (action === 'reset') {\n const persisted = resetAutoCompactThresholdSetting(context);\n setCommandAutoCompactThreshold(context, DEFAULT_AUTO_COMPACT_THRESHOLD, 'default');\n return {\n success: true,\n message: `Auto compact reset to default: ${formatThreshold(DEFAULT_AUTO_COMPACT_THRESHOLD)} (${formatPersistenceSuffix(persisted)}).`,\n data: {\n autoCompactThreshold: DEFAULT_AUTO_COMPACT_THRESHOLD,\n autoCompactThresholdSource: 'default',\n persisted,\n },\n };\n }\n\n const parsed = parseThreshold(action);\n if (!parsed.success) {\n return { success: false, message: `${parsed.message}\\n${USAGE}` };\n }\n return applyAutoCompactThreshold(context, parsed.threshold, 'threshold set');\n}\n\nasync function executeAddContextReference(\n context: ICommandHostContextReferences,\n args: readonly string[],\n): Promise<ICommandResult> {\n const path = args.join(' ').trim();\n if (!path) return { success: false, message: USAGE };\n\n const result = await addCommandContextReference(context, path);\n if (!result.reference) {\n return {\n success: false,\n message: result.diagnostics.join('\\n') || `Context reference not found: ${path}`,\n data: { diagnostics: result.diagnostics },\n };\n }\n\n return {\n success: true,\n message: [\n `Context reference added: ${formatContextReferenceLine(result.reference)}.`,\n ...(result.evicted.length > 0\n ? [`Evicted ${result.evicted.length} older context reference(s).`]\n : []),\n ].join('\\n'),\n data: { reference: result.reference, evicted: result.evicted },\n };\n}\n\nfunction executeRemoveContextReference(\n context: ICommandHostContextReferences,\n args: readonly string[],\n): ICommandResult {\n const path = args.join(' ').trim();\n if (!path) return { success: false, message: USAGE };\n\n const result = removeCommandContextReference(context, path);\n if (!result.removed) {\n return {\n success: false,\n message: `Context reference not found: ${path}`,\n };\n }\n\n return {\n success: true,\n message: `Context reference removed: ${formatContextReferenceLine(result.removed)}.`,\n data: { removed: result.removed },\n };\n}\n\nfunction applyAutoCompactThreshold(\n context: TContextThresholdHost,\n threshold: TAutoCompactThreshold,\n action: 'enabled' | 'disabled' | 'threshold set',\n): ICommandResult {\n const persisted = writeAutoCompactThresholdSetting(context, threshold);\n const source: TAutoCompactThresholdSource = persisted ? 'settings' : 'session';\n setCommandAutoCompactThreshold(context, threshold, source);\n\n return {\n success: true,\n message: formatApplyMessage(action, threshold, persisted),\n data: {\n autoCompactThreshold: threshold,\n autoCompactThresholdSource: source,\n persisted,\n },\n };\n}\n\nfunction formatApplyMessage(\n action: 'enabled' | 'disabled' | 'threshold set',\n threshold: TAutoCompactThreshold,\n persisted: boolean,\n): string {\n const suffix = formatPersistenceSuffix(persisted);\n if (action === 'disabled') {\n return `Auto compact disabled (${suffix}).`;\n }\n if (action === 'enabled') {\n return `Auto compact enabled at ${formatThreshold(threshold)} (${suffix}).`;\n }\n return `Auto compact threshold set to ${formatThreshold(threshold)} (${suffix}).`;\n}\n\ntype TParseThresholdResult =\n { success: true; threshold: number } | { success: false; message: string };\n\nfunction parseThreshold(raw: string): TParseThresholdResult {\n if (raw.endsWith('%')) {\n const percent = Number(raw.slice(0, -1));\n if (!Number.isFinite(percent) || percent <= 0 || percent > PERCENT) {\n return {\n success: false,\n message: 'Auto compact percentage must be greater than 0% and at most 100%.',\n };\n }\n return { success: true, threshold: percent / PERCENT };\n }\n\n if (raw.includes('.')) {\n const fraction = Number(raw);\n if (!Number.isFinite(fraction) || fraction <= 0 || fraction > 1) {\n return {\n success: false,\n message: 'Auto compact fraction must be greater than 0 and at most 1.',\n };\n }\n return { success: true, threshold: fraction };\n }\n\n return {\n success: false,\n message: 'Use a percentage such as 85% or a fraction such as 0.85.',\n };\n}\n\nfunction formatContextReferenceSummary(references: readonly IContextReferenceItem[]): string {\n const active = references.filter((reference) => reference.status === 'active').length;\n const observed = references.filter((reference) => reference.status === 'observed').length;\n return `References: ${active} active, ${observed} observed`;\n}\n\n// 1 token ≈ 4 chars — sourced from the agent-core estimation SSOT.\n","import type { ICommand, ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { ICommandHostContext, ISystemCommand } from '@robota-sdk/agent-framework';\n\n/** Build executable metadata from the palette entry so user and model views cannot drift. */\nexport function createSystemCommandFromEntry(\n entry: ICommand,\n behavior: {\n lifecycle: NonNullable<ISystemCommand['lifecycle']>;\n requiresPermission: boolean;\n execute: (\n context: ICommandHostContext,\n args: string,\n ) => ICommandResult | Promise<ICommandResult>;\n semanticRole?: ISystemCommand['semanticRole'];\n },\n): ISystemCommand {\n return {\n name: entry.name,\n ...(entry.displayName !== undefined ? { displayName: entry.displayName } : {}),\n description: entry.description,\n ...(entry.example !== undefined ? { example: entry.example } : {}),\n ...(entry.modelInvocable !== undefined ? { modelInvocable: entry.modelInvocable } : {}),\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n ...(entry.userInvocable !== undefined ? { userInvocable: entry.userInvocable } : {}),\n ...(entry.argumentHint !== undefined ? { argumentHint: entry.argumentHint } : {}),\n ...(entry.safety !== undefined ? { safety: entry.safety } : {}),\n ...(entry.subcommands !== undefined ? { subcommands: entry.subcommands } : {}),\n ...(behavior.semanticRole !== undefined ? { semanticRole: behavior.semanticRole } : {}),\n lifecycle: behavior.lifecycle,\n requiresPermission: behavior.requiresPermission,\n execute: behavior.execute,\n };\n}\n","import { executeContextCommand } from './context-command.js';\nimport { createSystemCommandFromEntry } from '../command-module-utils.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createContextCommandEntry(): ICommand {\n return {\n name: 'context',\n displayName: 'Context References',\n description: 'Context window info, reference inventory, and auto-compact controls',\n // Model-invocable for the read-only views only: knowing how full the context is lets the model\n // decide when to compact. Pinning, unpinning and clearing references and the auto-compact\n // policy are the user's curation and preference, so they stay user-only.\n modelDescription:\n 'Inspect the context window. Use it before a large task or before deciding to compact, or to ' +\n 'see which files the user pinned into context. Bare returns used/max tokens and percentage, ' +\n 'the auto-compact threshold, the pinned-reference summary and the turn count; `list` returns ' +\n 'the per-category token breakdown and every pinned reference.',\n source: 'context',\n modelInvocable: true,\n userInvocable: true,\n argumentHint: 'list | add <path> | remove <path> | clear | auto ...',\n subcommands: [\n {\n name: 'list',\n description: 'List loaded context references',\n source: 'context',\n modelInvocable: true,\n },\n {\n name: 'add',\n description: 'Add a file to active context references',\n source: 'context',\n modelInvocable: false,\n },\n {\n name: 'remove',\n description: 'Remove a context reference',\n source: 'context',\n modelInvocable: false,\n },\n {\n name: 'clear',\n description: 'Clear context references',\n source: 'context',\n modelInvocable: false,\n },\n {\n name: 'auto',\n description: 'Inspect or change auto-compact policy',\n source: 'context',\n modelInvocable: false,\n },\n ],\n };\n}\n\nfunction createContextSystemCommand(): ISystemCommand {\n const entry = createContextCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: executeContextCommand,\n });\n}\n\nexport class ContextCommandSource implements ICommandSource {\n readonly name = 'context';\n\n getCommands(): ICommand[] {\n return [createContextCommandEntry()];\n }\n}\n\nexport function createContextCommandModule(): ICommandModule {\n return {\n name: 'agent-command-context',\n commandSources: [new ContextCommandSource()],\n systemCommands: [createContextSystemCommand()],\n };\n}\n","/**\n * `/devices` — this device's place in the user's device identity: list the roster, create the\n * identity, revoke a device, recover from the recovery phrase.\n *\n * Operator-only, twice over: the command is not model-invocable, and it refuses any invocation that\n * is not the operator's own (a remote surface, the model). Every verb that touches a secret or\n * asks for a confirmation runs inside the terminal handoff, so what is typed goes to the host's\n * terminal and never through the session's input, prompt history or conversation. Without an\n * interactive terminal those verbs refuse rather than fall back to anything else.\n */\nimport { createSystemCommandFromEntry } from '../command-module-utils.js';\n\nimport type {\n IDevicesCommandPort,\n IDevicesView,\n TDevicesOutcome,\n TDevicesRefusal,\n} from './devices-command-port.js';\nimport type {\n ICommandHostContext,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandResult, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nconst SHORT_ID_CHARS = 10;\nconst USAGE = 'Usage: /devices [list|init [name]|revoke <device-id>|recover]';\n\nexport function createDevicesCommandEntry(): ICommand {\n return {\n name: 'devices',\n displayName: 'Devices',\n description:\n \"Manage this device's identity among the user's devices: list the roster, create the identity and its recovery phrase, revoke a device, or rotate the signing key from the phrase. Operator-only; the phrase is handled on the terminal and results carry only device ids and names.\",\n source: 'devices',\n modelInvocable: false,\n userInvocable: true,\n argumentHint: '[list|init [name]|revoke <device-id>|recover]',\n subcommands: [\n { name: 'list', description: 'List your devices', source: 'devices' },\n {\n name: 'init',\n description: 'Create your device identity and recovery phrase',\n source: 'devices',\n argumentHint: '[name]',\n },\n {\n name: 'revoke',\n description: 'Revoke a device with the signing key',\n source: 'devices',\n argumentHint: '<device-id>',\n },\n {\n name: 'recover',\n description: 'Rotate the signing key from your recovery phrase',\n source: 'devices',\n },\n ],\n };\n}\n\nconst REFUSALS: Readonly<Record<TDevicesRefusal, string>> = {\n 'no-terminal': 'This needs an interactive terminal; the recovery phrase is never shown or read anywhere else.',\n 'not-initialized': 'This device has no identity yet. Run `/devices init` first.',\n 'already-initialized': 'This device already has an identity. Use `/devices recover` to rotate its signing key.',\n cancelled: 'Cancelled. Nothing was changed.',\n 'confirmation-failed': 'The confirmation did not match. Nothing was changed.',\n 'phrase-invalid': 'That is not a valid recovery phrase. Nothing was changed.',\n 'phrase-mismatch':\n 'That phrase (with that passphrase) belongs to a different identity than this device. Nothing was changed.',\n 'no-signing-key': 'This device does not hold the signing key. Revoke from a device that does, or `/devices recover`.',\n 'signing-key-expired': 'The signing key on this device has expired. Run `/devices recover` to issue a new one.',\n 'unknown-device': 'No device in the roster has that id.',\n 'ambiguous-device': 'More than one device starts with that id; give more of it.',\n 'self-revocation': 'This device cannot revoke itself. Revoke it from another device, or `/devices recover`.',\n 'changed-concurrently':\n 'The device identity changed in another session while this was waiting. Nothing was changed; try again.',\n};\n\nfunction short(id: string): string {\n return id.slice(0, SHORT_ID_CHARS);\n}\n\nfunction day(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\nfunction refused(reason: TDevicesRefusal): ICommandResult {\n return { success: false, message: REFUSALS[reason] };\n}\n\nfunction formatList(view: IDevicesView | undefined): ICommandResult {\n if (view === undefined) return { success: true, message: REFUSALS['not-initialized'] };\n const lines = view.devices.map((device) => {\n const notes = [\n ...(device.thisDevice ? ['this device'] : []),\n ...(device.holdsSigningKey ? ['holds the signing key'] : []),\n ];\n const suffix = notes.length > 0 ? ` (${notes.join(', ')})` : '';\n return ` ${short(device.deviceId)} ${device.name}${suffix} certificate expires ${day(device.certificateExpiresAt)}`;\n });\n return {\n success: true,\n message: [\n `Devices of user ${short(view.userId)}:`,\n ...lines,\n `${view.revokedDeviceCount} revoked. Roster and revocation list valid until ${new Date(view.listsExpireAt).toISOString()}.`,\n ].join('\\n'),\n };\n}\n\nfunction isOperator(context: ICommandHostContext): boolean {\n return context.getCommandInvocationSource() === 'user';\n}\n\n/** Run a terminal-bound port call; a refusal or a thrown error becomes a failed result. */\nasync function onTerminal<T>(\n context: ICommandHostContext,\n run: () => Promise<TDevicesOutcome<T>>,\n done: (value: T) => string,\n): Promise<ICommandResult> {\n if (!context.canHandoffTerminal()) return refused('no-terminal');\n try {\n const outcome = await context.runWithTerminal(run);\n return outcome.ok ? { success: true, message: done(outcome.value) } : refused(outcome.reason);\n } catch (error) {\n return {\n success: false,\n message: `Device identity operation failed: ${error instanceof Error ? error.message : 'unknown error'}`,\n };\n }\n}\n\nexport async function executeDevicesCommand(\n port: IDevicesCommandPort,\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n if (!isOperator(context)) {\n return {\n success: false,\n message: '`/devices` runs only for the operator at this terminal, never from a remote surface or the model.',\n };\n }\n const trimmed = args.trim();\n const spaceAt = trimmed.indexOf(' ');\n const verb = (spaceAt === -1 ? trimmed : trimmed.slice(0, spaceAt)).toLowerCase();\n // Device ids are case-sensitive base64url, so the remainder keeps its case.\n const rest = spaceAt === -1 ? '' : trimmed.slice(spaceAt + 1).trim();\n\n switch (verb) {\n case '':\n case 'list':\n try {\n return formatList(await port.list());\n } catch (error) {\n return {\n success: false,\n message: `Device identity could not be read: ${error instanceof Error ? error.message : 'unknown error'}`,\n };\n }\n case 'init':\n return onTerminal(\n context,\n () => port.init(rest.length > 0 ? { name: rest } : {}),\n (value) =>\n [\n `Device identity created. This device: ${short(value.deviceId)}; user ${short(value.userId)}.`,\n `It holds signing key ${short(value.signingKeyId)}.`,\n ...(value.keyStorage !== undefined ? [`Private keys are kept in: ${value.keyStorage}.`] : []),\n 'Keep the recovery phrase offline; it is the only way to recover this identity.',\n ].join('\\n'),\n );\n case 'recover':\n return onTerminal(\n context,\n () => port.recover(),\n (value) =>\n [\n `Recovered. New signing key ${short(value.signingKeyId)}; ${value.revokedSigningKeyCount} old signing key(s) revoked.`,\n `This device (${short(value.deviceId)}) is certified again.`,\n ...(value.droppedDeviceCount > 0\n ? [`${value.droppedDeviceCount} other device(s) were certified by a retired signing key and must enrol again.`]\n : []),\n ].join('\\n'),\n );\n case 'revoke':\n if (rest.length === 0) return { success: false, message: 'Usage: /devices revoke <device-id>' };\n return onTerminal(\n context,\n () => port.revoke(rest),\n (value) => `Revoked ${value.name} (${short(value.deviceId)}). A new roster and revocation list were issued.`,\n );\n case 'add':\n case 'join':\n return {\n success: false,\n message: `\\`/devices ${verb}\\` is not available yet: enrolling another device needs the device connection, which is not built yet.`,\n };\n default:\n return { success: false, message: `Unknown argument \"${verb}\". ${USAGE}` };\n }\n}\n\nexport class DevicesCommandSource implements ICommandSource {\n readonly name = 'devices';\n\n getCommands(): ICommand[] {\n return [createDevicesCommandEntry()];\n }\n}\n\nexport function createDevicesCommandModule(port: IDevicesCommandPort): ICommandModule {\n const command: ISystemCommand = createSystemCommandFromEntry(createDevicesCommandEntry(), {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: (context, args) => executeDevicesCommand(port, context, args),\n });\n return {\n name: 'agent-command-devices',\n commandSources: [new DevicesCommandSource()],\n systemCommands: [command],\n };\n}\n","/** Node defaults for {@link IDoctorDeps}: a TCP connect probe and read-only filesystem facts. */\nimport { accessSync, constants, existsSync, statSync } from 'node:fs';\nimport { createConnection } from 'node:net';\nimport { delimiter, isAbsolute, join } from 'node:path';\n\nimport { ownerOnlyGuarantee } from '@robota-sdk/agent-core/node';\n\nimport type { IDoctorDeps, IDoctorEndpointProbeResult, IDoctorPathFacts } from './doctor-types.js';\n\nconst NETWORK_CHECK_TIMEOUT_MS = 3000;\nconst MS_PER_SECOND = 1000;\nconst MODE_BITS = 0o777;\n\n/** TCP connect with a bounded timeout; a refusal or a timeout is a result, never a throw. */\nexport function probeEndpointViaSocket(\n host: string,\n port: number,\n): Promise<IDoctorEndpointProbeResult> {\n return new Promise((resolve) => {\n const start = Date.now();\n const socket = createConnection({ host, port });\n const timeout = setTimeout(() => {\n socket.destroy();\n resolve({\n reachable: false,\n error: `timeout (${NETWORK_CHECK_TIMEOUT_MS / MS_PER_SECOND}s)`,\n });\n }, NETWORK_CHECK_TIMEOUT_MS);\n socket.on('connect', () => {\n clearTimeout(timeout);\n socket.destroy();\n resolve({ reachable: true, elapsedMs: Date.now() - start });\n });\n socket.on('error', (error) => {\n clearTimeout(timeout);\n resolve({ reachable: false, error: error.message });\n });\n });\n}\n\n/** Existence, directory-ness, `W_OK` and mode — probed without writing. */\nexport function inspectPathFacts(path: string): IDoctorPathFacts {\n if (!existsSync(path)) return { exists: false, isDirectory: false, writable: false };\n let isDirectory = false;\n let mode: number | undefined;\n try {\n const stat = statSync(path);\n isDirectory = stat.isDirectory();\n mode = stat.mode & MODE_BITS;\n } catch {\n // allow-fallback: a path that exists but cannot be stat'ed is reported as not a writable directory\n return { exists: true, isDirectory: false, writable: false };\n }\n let writable = false;\n try {\n accessSync(path, constants.W_OK);\n writable = true;\n } catch {\n // allow-fallback: W_OK refused IS the fact being reported\n writable = false;\n }\n return { exists: true, isDirectory, writable, ...(mode === undefined ? {} : { mode }) };\n}\n\n/** A bare command resolves through `PATH`; a path-form command must exist as given. */\nexport function resolveCommandOnPath(\n command: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n const executable = command.trim().split(/\\s+/)[0];\n if (executable === undefined || executable.length === 0) return false;\n if (isAbsolute(executable) || executable.includes('/')) return existsSync(executable);\n const extensions = process.platform === 'win32' ? ['', '.exe', '.cmd', '.bat'] : [''];\n return (env.PATH ?? '')\n .split(delimiter)\n .filter((dir) => dir.length > 0)\n .some((dir) => extensions.some((ext) => existsSync(join(dir, executable + ext))));\n}\n\nexport function createNodeDoctorDeps(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): IDoctorDeps {\n return {\n probeEndpoint: probeEndpointViaSocket,\n inspectPath: inspectPathFacts,\n resolveCommand: (command) => resolveCommandOnPath(command, env),\n ownerOnlyGuarantee: () => ownerOnlyGuarantee(),\n };\n}\n","/** Plain-text rendering of a doctor report — the same lines for the shell route and `/doctor`. */\nimport type { IDoctorCheck, IDoctorReport, TDoctorCheckStatus } from './doctor-types.js';\n\nconst ICON: Record<TDoctorCheckStatus, string> = {\n ok: '✓',\n warn: '⚠',\n fail: '✗',\n 'not-configured': '○',\n 'not-probed': '–',\n};\n\n/** Optional product wording supplied by the host; omission keeps diagnostics product-neutral. */\nexport interface IDoctorDisplayVocabulary {\n readonly title?: string;\n readonly productName?: string;\n readonly formatRepairCommand?: (checkId: string) => string;\n readonly repairOffer?: string;\n}\n\nfunction renderCheck(check: IDoctorCheck, display: IDoctorDisplayVocabulary): string[] {\n const head = ` ${ICON[check.status]} ${check.label} [${check.id}] ${check.status}${check.cause === undefined ? '' : `: ${check.cause}`}`;\n const lines = [head];\n if (check.path !== undefined) lines.push(` path: ${check.path}`);\n for (const line of check.detail ?? []) lines.push(` ${line}`);\n if (check.repair !== undefined) {\n const repairAction = display.formatRepairCommand?.(check.repair);\n lines.push(\n ` repair: ${repairAction ?? `request repair for ${check.repair} through your host`}`,\n );\n }\n return lines;\n}\n\nfunction summary(report: IDoctorReport, display: IDoctorDisplayVocabulary): string {\n const productName = display.productName?.trim();\n if (report.failCount === 0 && report.warnCount === 0)\n return productName\n ? `✓ All checks passed. ${productName} is ready to use.`\n : '✓ All checks passed.';\n if (report.failCount > 0)\n return productName\n ? `✗ ${report.failCount} issue(s) found. Fix the items above to use ${productName}.`\n : `✗ ${report.failCount} issue(s) found. Fix the items above before use.`;\n return productName\n ? `⚠ ${report.warnCount} warning(s). ${productName} may work but check the items above.`\n : `⚠ ${report.warnCount} warning(s). Check the items above.`;\n}\n\n/** Render the report as lines: a title, every check, then the summary and the repair offers. */\nexport function renderDoctorReport(\n report: IDoctorReport,\n title = 'Doctor',\n display: IDoctorDisplayVocabulary = {},\n): string[] {\n const lines = [\n '',\n title,\n '',\n ...report.checks.flatMap((check) => renderCheck(check, display)),\n '',\n summary(report, display),\n ];\n if (report.repairable.length > 0) {\n lines.push(\n ` repairable: ${report.repairable.join(', ')} — ${display.repairOffer ?? 'ask your host to apply a repair'}`,\n );\n }\n lines.push('');\n return lines;\n}\n","/**\n * The doctor's single rendering boundary for secrets (OBSERVABILITY-1991).\n *\n * Defence in depth, not the first line: the inspection APIs the probes read already return facts\n * (states, paths, issue paths, env KEY names) rather than file content. This pass exists for the\n * text the doctor cannot prevent from carrying a value — an owner error message, a URL a user typed\n * a credential into — and for the case the structural layer cannot see: a literal that IS a secret\n * because the settings layers or the environment say so.\n */\n\nimport { SettingsParseError } from '@robota-sdk/agent-framework';\n\nimport type { TSettings } from '@robota-sdk/agent-framework';\n\nconst REDACTED = '[redacted]';\n\n/**\n * `scheme://user:pass@host` → `scheme://[redacted]@host`. The scheme is bounded: an unbounded run,\n * retried from every word start, was quadratic on long text that never reaches `://`.\n */\nconst URL_USERINFO = /(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^\\s/@]+)@/gi;\n/** `Bearer <token>` in any casing. */\nconst BEARER_TOKEN = /\\b(bearer)\\s+[A-Za-z0-9._~+/=-]{8,}/gi;\n/** Vendor-key shapes: `sk-…`, `sk-ant-…`, `AIza…`, `ghp_…`, `xox?-…`. */\nconst KEY_SHAPES =\n /\\b(?:sk-[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{20,}|ghp_[A-Za-z0-9]{20,}|xox[abprs]-[A-Za-z0-9-]{10,})\\b/g;\n\nconst MIN_SECRET_LENGTH = 4;\n/** The quoted excerpt of the input a JSON parser embeds in its message: `...\"<snippet>\"...`. */\nconst PARSER_SNIPPET = /\\.\\.\\.\"[^\"]*\"\\.\\.\\./g;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Mask every known secret value and every credential-shaped token in `text`.\n *\n * `secrets` are literal values the doctor learned from its inputs — the resolved credential, every\n * literal `apiKey` in any settings layer (active or not), every value a `$ENV:` reference names,\n * every `env` map value. Values shorter than four characters are not masked: they cannot be\n * credentials and masking them would shred ordinary words.\n */\nexport function redactDiagnosticText(text: string, secrets: Iterable<string> = []): string {\n let out = text;\n const seen = new Set<string>();\n for (const secret of secrets) {\n if (typeof secret !== 'string' || secret.length < MIN_SECRET_LENGTH || seen.has(secret))\n continue;\n seen.add(secret);\n out = out.replace(new RegExp(escapeRegExp(secret), 'g'), REDACTED);\n }\n out = out.replace(URL_USERINFO, `$1${REDACTED}@`);\n out = out.replace(BEARER_TOKEN, `$1 ${REDACTED}`);\n out = out.replace(KEY_SHAPES, REDACTED);\n return out;\n}\n\n/**\n * An owner error as the doctor may show it. A parse error is named by its class and file only —\n * its message quotes the file around the fault, which is exactly the content a broken settings\n * layer never had a chance to contribute to the secret list. Any other message loses a parser\n * snippet it may carry; the redactor still runs over the result.\n */\nexport function describeDiagnosticError(error: Error): string {\n if (error instanceof SettingsParseError) {\n return `${error.name}: ${error.filePath} is not valid JSON (see the settings check)`;\n }\n return `${error.name}: ${error.message.replace(PARSER_SNIPPET, '…')}`;\n}\n\n/**\n * Collect the literal secrets a set of parsed settings layers and the environment expose:\n * `providers.*.apiKey`, `provider.apiKey` (literal, or the value of a `$ENV:` reference), and\n * every `env` map value. The doctor never RENDERS any of these; they feed the redactor so that a\n * value which nonetheless reaches a message is masked.\n */\nexport function collectSettingsSecrets(\n layers: ReadonlyArray<TSettings | undefined>,\n env: Readonly<Record<string, string | undefined>>,\n): string[] {\n const secrets = new Set<string>();\n const addKey = (value: string | undefined): void => {\n if (value === undefined) return;\n if (value.startsWith('$ENV:')) {\n const resolved = env[value.slice('$ENV:'.length).trim()];\n if (resolved !== undefined) secrets.add(resolved);\n return;\n }\n secrets.add(value);\n };\n for (const layer of layers) {\n if (layer === undefined) continue;\n addKey(layer.provider?.apiKey);\n for (const profile of Object.values(layer.providers ?? {})) addKey(profile.apiKey);\n for (const value of Object.values(layer.env ?? {})) secrets.add(value);\n }\n return [...secrets];\n}\n","/**\n * Settings and provider probes (OBSERVABILITY-1991).\n *\n * Every fact here comes from an owner API — `inspectSettingsLayers` for the layers and their\n * provenance, `readProviderSettings` for the runtime-equivalent provider resolution. The probe adds\n * no reader of its own; that is the CLI-067 discipline the old `diagnose` command broke three times.\n */\nimport { basename, dirname } from 'node:path';\n\nimport { findProviderDefinition } from '@robota-sdk/agent-core';\nimport { inspectSettingsLayers, readProviderSettings } from '@robota-sdk/agent-framework';\n\nimport { describeDiagnosticError } from './doctor-redaction.js';\n\nimport type { IDoctorCheck, IDoctorDeps, IDoctorInputs } from './doctor-types.js';\nimport type { IProviderDefinitionConfig } from '@robota-sdk/agent-core';\nimport type {\n ISettingsInspection,\n ISettingsLayerInspection,\n TSettingsSource,\n} from '@robota-sdk/agent-framework';\n\nconst HTTP_PORT = 80;\nconst HTTPS_PORT = 443;\n\n/**\n * `settings.<scope>.<family>` — the id a user types into `--repair`. The family is the name of the\n * directory the file lives in, without its leading dot, so the id follows whatever layout the host\n * composed rather than a product name written here.\n */\nexport function settingsCheckId(source: TSettingsSource): string {\n const path = source.kind === 'host' ? source.path : source.relativePath;\n const family = basename(dirname(path)).replace(/^\\./, '');\n return `settings.${source.scope}.${family}`;\n}\n\n/** The check id of the host's own user settings file — the settings repair target. */\nexport function userSettingsCheckId(inputs: IDoctorInputs): string | undefined {\n const source = inputs.settingsSources.find(\n (candidate) => candidate.kind === 'host' && candidate.path === inputs.userSettingsPath,\n );\n return source === undefined ? undefined : settingsCheckId(source);\n}\n\nfunction layerCause(layer: ISettingsLayerInspection): string {\n const cause = layer.cause;\n if (cause === undefined) return layer.state;\n switch (cause.state) {\n case 'unreadable':\n return cause.errno === undefined ? 'unreadable' : `unreadable (${cause.errno})`;\n case 'invalid-json':\n return cause.offset === undefined ? 'invalid-json' : `invalid-json at offset ${cause.offset}`;\n case 'schema-invalid':\n return `schema-invalid: ${(cause.issues ?? []).map((issue) => `${issue.path} (${issue.code})`).join(', ')}`;\n default:\n return cause.state;\n }\n}\n\n/** Only the host's own user settings file, and only when it is empty, is a settings repair target. */\nexport function isRepairableSettingsLayer(\n layer: ISettingsLayerInspection,\n inputs: IDoctorInputs,\n): boolean {\n return (\n layer.source.kind === 'host' &&\n layer.source.path === inputs.userSettingsPath &&\n layer.state === 'empty'\n );\n}\n\nfunction layerCheck(layer: ISettingsLayerInspection, inputs: IDoctorInputs): IDoctorCheck {\n const id = settingsCheckId(layer.source);\n const path = layer.source.kind === 'host' ? layer.source.path : layer.source.relativePath;\n if (layer.state === 'absent') {\n return { id, label: 'Settings layer', status: 'not-configured', path, cause: 'absent' };\n }\n if (layer.state === 'ok') return { id, label: 'Settings layer', status: 'ok', path, cause: 'ok' };\n const repairable = isRepairableSettingsLayer(layer, inputs);\n return {\n id,\n label: 'Settings layer',\n status: 'fail',\n path,\n cause: layerCause(layer),\n detail: repairable\n ? ['The file exists but holds nothing; rewriting it as {} loses no content.']\n : ['Session start will refuse this configuration. Fix the file at the named path.'],\n ...(repairable ? { repair: id } : {}),\n };\n}\n\nfunction provenanceCheck(inspection: ISettingsInspection): IDoctorCheck {\n const lines = [\n ...inspection.provenance.map(\n (entry) => `${entry.key}: ${entry.rule} ← ${entry.contributors.join(' → ')}`,\n ),\n ...inspection.hookSources.map(\n (hook, index) => `settings hook ${index + 1}: ${hook.event}/${hook.type} ← ${hook.source}`,\n ),\n ];\n if (inspection.partial) {\n return {\n id: 'settings.merge',\n label: 'Merged settings',\n status: 'warn',\n cause: 'partial — a present layer is broken; session start will refuse this configuration',\n detail: lines.length === 0 ? ['(no key declared by a healthy layer)'] : lines,\n };\n }\n return {\n id: 'settings.merge',\n label: 'Merged settings',\n status: 'ok',\n cause: `${inspection.provenance.length} key(s) from ${inspection.layers.filter((l) => l.state === 'ok').length} layer(s)`,\n detail: lines.length === 0 ? ['(no settings declared)'] : lines,\n };\n}\n\nexport interface ISettingsProbeResult {\n readonly inspection: ISettingsInspection;\n readonly checks: readonly IDoctorCheck[];\n}\n\n/** Every layer in precedence order, then the merged view with its provenance. */\nexport function probeSettings(inputs: IDoctorInputs): ISettingsProbeResult {\n const inspection = inspectSettingsLayers(inputs.settingsSources);\n return {\n inspection,\n checks: [\n ...inspection.layers.map((layer) => layerCheck(layer, inputs)),\n provenanceCheck(inspection),\n ],\n };\n}\n\nfunction resolutionCheck(config: IProviderDefinitionConfig): IDoctorCheck {\n const source =\n config.source === 'env-default'\n ? `env-default via ${config.sourceEnvVar ?? 'environment'}`\n : 'settings profile';\n return {\n id: 'provider.resolution',\n label: 'Provider',\n status: 'ok',\n cause: `${config.name} (${config.model}) — ${source}`,\n };\n}\n\nfunction endpointOf(\n config: IProviderDefinitionConfig,\n inputs: IDoctorInputs,\n): { host: string; port: number; origin: string } | undefined {\n const definition = findProviderDefinition(inputs.providerDefinitions, config.name);\n const baseURL = config.baseURL ?? definition?.defaults?.baseURL;\n if (baseURL !== undefined) {\n try {\n const url = new URL(baseURL);\n const port =\n url.port === '' ? (url.protocol === 'http:' ? HTTP_PORT : HTTPS_PORT) : Number(url.port);\n return {\n host: url.hostname,\n port,\n origin: config.baseURL === undefined ? 'definition defaults.baseURL' : 'profile baseURL',\n };\n } catch {\n // allow-fallback: an unparseable baseURL is reported by the caller as a warn, never guessed\n return undefined;\n }\n }\n const endpoint = definition?.endpoint;\n return endpoint === undefined ? undefined : { ...endpoint, origin: 'definition endpoint' };\n}\n\nasync function reachabilityCheck(\n config: IProviderDefinitionConfig,\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n): Promise<IDoctorCheck> {\n const endpoint = endpointOf(config, inputs);\n if (endpoint === undefined) {\n return {\n id: 'provider.reachability',\n label: 'Provider reachability',\n status: 'warn',\n cause: `not checked: ${config.name} declares no endpoint (no profile baseURL, defaults.baseURL or definition endpoint)`,\n };\n }\n const result = await deps.probeEndpoint(endpoint.host, endpoint.port);\n const target = `${endpoint.host}:${endpoint.port} (${endpoint.origin})`;\n return result.reachable\n ? {\n id: 'provider.reachability',\n label: 'Provider reachability',\n status: 'ok',\n cause: `${target} reachable in ${result.elapsedMs ?? 0}ms`,\n }\n : {\n id: 'provider.reachability',\n label: 'Provider reachability',\n status: 'warn',\n cause: `${target} unreachable: ${result.error ?? 'connection failed'}`,\n detail: ['Check proxy settings, firewall, or the profile baseURL.'],\n };\n}\n\n/** Runtime-equivalent resolution, then TCP reachability of the host the resolved profile implies. */\nexport async function probeProvider(\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n): Promise<{ readonly checks: readonly IDoctorCheck[]; readonly resolvedApiKey?: string }> {\n let config: IProviderDefinitionConfig;\n try {\n config = readProviderSettings(inputs.settingsSources, {\n providerDefinitions: inputs.providerDefinitions,\n env: { ...inputs.env },\n });\n } catch (error) {\n // allow-fallback: resolution failure IS the finding; it is reported, never defaulted\n return {\n checks: [\n {\n id: 'provider.resolution',\n label: 'Provider',\n status: 'fail',\n cause: describeDiagnosticError(error instanceof Error ? error : new Error(String(error))),\n detail: [\n inputs.diagnosticGuidance?.providerResolution ??\n 'Configure a provider or set its API key environment variable.',\n ],\n },\n ],\n };\n }\n return {\n checks: [resolutionCheck(config), await reachabilityCheck(config, inputs, deps)],\n ...(config.apiKey === undefined ? {} : { resolvedApiKey: config.apiKey }),\n };\n}\n","/**\n * Storage, workspace-trust and provider-security probes (OBSERVABILITY-1991). Read-only: existence,\n * `W_OK` access and mode bits are inspected, never written.\n */\nimport type { IDoctorCheck, IDoctorDeps, IDoctorInputs } from './doctor-types.js';\nimport type { ISettingsInspection } from '@robota-sdk/agent-framework';\n\nconst FORBIDDEN_MODE_BITS = 0o077;\n\nexport type TUserStorageState = 'ok' | 'missing' | 'unwritable' | 'too-open' | 'mode-not-probed';\n\n/** The state the repair allowlist re-reads immediately before writing. */\nexport function userStorageState(inputs: IDoctorInputs, deps: IDoctorDeps): TUserStorageState {\n const { root, sessions } = inputs.userStorage;\n const facts = [deps.inspectPath(root), deps.inspectPath(sessions)];\n if (facts.some((f) => !f.exists)) return 'missing';\n if (facts.some((f) => !f.isDirectory || !f.writable)) return 'unwritable';\n if (deps.ownerOnlyGuarantee() !== 'posix-mode') return 'mode-not-probed';\n return facts.some((f) => f.mode !== undefined && (f.mode & FORBIDDEN_MODE_BITS) !== 0)\n ? 'too-open'\n : 'ok';\n}\n\nfunction userStorageCheck(inputs: IDoctorInputs, deps: IDoctorDeps): IDoctorCheck {\n const { root, sessions } = inputs.userStorage;\n const base = { id: 'storage.user', label: 'User storage', path: root } as const;\n switch (userStorageState(inputs, deps)) {\n case 'missing':\n return {\n ...base,\n status: 'warn',\n cause: 'not initialized (created on first write)',\n detail: [root, sessions],\n repair: 'storage.user',\n };\n case 'unwritable':\n return {\n ...base,\n status: 'fail',\n cause: 'exists but is not a writable directory',\n detail: [root, sessions],\n };\n case 'too-open':\n return {\n ...base,\n status: 'warn',\n cause: 'not owner-only (mode allows group/other access)',\n detail: [root, sessions],\n repair: 'storage.user',\n };\n case 'mode-not-probed':\n return {\n ...base,\n status: 'not-probed',\n cause: 'owner-only mode is not asserted on this platform (windows-acl)',\n };\n default:\n return { ...base, status: 'ok', cause: 'writable, owner-only' };\n }\n}\n\nfunction projectStorageCheck(inputs: IDoctorInputs, deps: IDoctorDeps): IDoctorCheck {\n const access = inputs.projectAccess;\n if (access.status !== 'trusted') {\n return {\n id: 'storage.project',\n label: 'Project storage',\n status: 'not-configured',\n cause: 'project sources are disabled in an untrusted workspace',\n };\n }\n const root = inputs.projectStorageRoot;\n if (root === undefined) {\n return {\n id: 'storage.project',\n label: 'Project storage',\n status: 'not-configured',\n cause: 'the host names no project state root',\n };\n }\n const facts = deps.inspectPath(root);\n if (!facts.exists) {\n return {\n id: 'storage.project',\n label: 'Project storage',\n status: 'not-configured',\n path: root,\n cause: 'absent (created on first write)',\n };\n }\n return facts.isDirectory && facts.writable\n ? {\n id: 'storage.project',\n label: 'Project storage',\n status: 'ok',\n path: root,\n cause: 'writable',\n }\n : {\n id: 'storage.project',\n label: 'Project storage',\n status: 'fail',\n path: root,\n cause: 'exists but is not a writable directory',\n };\n}\n\nfunction trustCheck(inputs: IDoctorInputs): IDoctorCheck {\n const access = inputs.projectAccess;\n if (access.status === 'trusted') {\n return {\n id: 'workspace.trust',\n label: 'Workspace trust',\n status: 'ok',\n path: access.identity.displayPath,\n cause: 'trusted',\n };\n }\n const cause =\n access.cause === undefined\n ? access.trustState\n : `${access.trustState}: ${access.cause.name}: ${access.cause.message}`;\n return {\n id: 'workspace.trust',\n label: 'Workspace trust',\n status:\n access.trustState === 'store-unavailable' || access.trustState === 'identity-unavailable'\n ? 'fail'\n : 'warn',\n ...(access.displayPath === undefined ? {} : { path: access.displayPath }),\n cause,\n detail: [\n inputs.diagnosticGuidance?.projectTrust ??\n 'Project sources are disabled. Approve this workspace with the host.',\n ],\n };\n}\n\n/**\n * The credential-quarantine report `robota diagnose` already shipped (CLI-067), over the inspection's\n * parsed layers instead of a private re-read: a lower-trust layer that changed a profile's `baseURL`\n * without supplying its own key had the inherited key removed. Neither key is ever shown.\n */\nfunction providerSecurityCheck(settings: ISettingsInspection): IDoctorCheck | undefined {\n const seen = new Map<string, { baseURL?: string; apiKey?: string }>();\n let quarantined = false;\n for (const layer of settings.layers) {\n for (const [name, profile] of Object.entries(layer.settings?.providers ?? {})) {\n const previous = seen.get(name);\n if (\n previous?.apiKey !== undefined &&\n profile.baseURL !== undefined &&\n profile.baseURL !== previous.baseURL &&\n profile.apiKey === undefined\n ) {\n quarantined = true;\n }\n seen.set(name, {\n baseURL: profile.baseURL ?? previous?.baseURL,\n apiKey: profile.apiKey ?? previous?.apiKey,\n });\n }\n }\n return quarantined\n ? {\n id: 'provider.security',\n label: 'Provider security',\n status: 'warn',\n cause: 'provider endpoint quarantined; inherited credential removed (credential redacted)',\n }\n : undefined;\n}\n\n/** Workspace trust, storage, then the provider-security report. */\nexport function probeStorageAndTrust(\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n settings: ISettingsInspection,\n): IDoctorCheck[] {\n const security = providerSecurityCheck(settings);\n return [\n trustCheck(inputs),\n userStorageCheck(inputs, deps),\n projectStorageCheck(inputs, deps),\n ...(security === undefined ? [] : [security]),\n ];\n}\n","/**\n * The doctor's closed repair allowlist (OBSERVABILITY-1991).\n *\n * Two entries, both existing idempotent writers, both gated on the state being re-read IMMEDIATELY\n * before the write (the report a user read a minute ago is not the state on disk now):\n * - the host's own user settings file (id `settings.user.<family>`) exists but holds nothing\n * (`empty`); rewriting it as `{}` through `writeSettings` loses no content and changes neither\n * onboarding (`isFirstRun` keys on a separate marker) nor provider setup (which keys on document\n * content).\n * - `storage.user` — the host's user store root or its sessions directory is missing or not\n * owner-only; `ensureOwnerOnlyDirectory` creates and tightens both.\n * Anything else — an unknown id, a state that is not the repairable one, an already-clean check —\n * is refused with no write.\n */\nimport { ensureOwnerOnlyDirectory } from '@robota-sdk/agent-core/node';\nimport { inspectSettingsLayers, writeSettings } from '@robota-sdk/agent-framework';\n\nimport {\n isRepairableSettingsLayer,\n settingsCheckId,\n userSettingsCheckId,\n} from './doctor-settings-probe.js';\nimport { userStorageState } from './doctor-storage-probe.js';\n\nimport type { IDoctorDeps, IDoctorInputs } from './doctor-types.js';\n\nexport const STORAGE_REPAIR_ID = 'storage.user';\n\n/** The closed allowlist for this composition: the host's user settings layer id and `storage.user`. */\nexport function doctorRepairAllowlist(inputs: IDoctorInputs): readonly string[] {\n const settings = userSettingsCheckId(inputs);\n return settings === undefined ? [STORAGE_REPAIR_ID] : [settings, STORAGE_REPAIR_ID];\n}\n\nexport interface IDoctorRepairPlan {\n readonly id: string;\n /** What the writer will do, for the confirmation prompt. */\n readonly description: string;\n readonly path: string;\n}\n\nexport type TDoctorRepairPlanResult =\n | { readonly ok: true; readonly plan: IDoctorRepairPlan }\n | { readonly ok: false; readonly reason: string };\n\nexport type TDoctorRepairOutcome =\n | { readonly applied: true; readonly plan: IDoctorRepairPlan }\n | { readonly applied: false; readonly reason: string };\n\nexport function isDoctorRepairId(id: string, inputs: IDoctorInputs): boolean {\n return doctorRepairAllowlist(inputs).includes(id);\n}\n\nfunction planSettingsRepair(id: string, inputs: IDoctorInputs): TDoctorRepairPlanResult {\n const layer = inspectSettingsLayers(inputs.settingsSources).layers.find(\n (candidate) => settingsCheckId(candidate.source) === id,\n );\n if (layer === undefined || layer.source.kind !== 'host') {\n return { ok: false, reason: `${id}: no user settings layer in this composition` };\n }\n if (!isRepairableSettingsLayer(layer, inputs)) {\n return { ok: false, reason: `${id}: state is ${layer.state}; only an empty file is rewritten` };\n }\n return {\n ok: true,\n plan: {\n id,\n description: 'rewrite the empty user settings file as {}',\n path: layer.source.path,\n },\n };\n}\n\nfunction planStorageRepair(inputs: IDoctorInputs, deps: IDoctorDeps): TDoctorRepairPlanResult {\n const state = userStorageState(inputs, deps);\n const { root } = inputs.userStorage;\n if (state !== 'missing' && state !== 'too-open') {\n return {\n ok: false,\n reason: `storage.user: state is ${state}; only a missing or too-open directory is repaired`,\n };\n }\n return {\n ok: true,\n plan: {\n id: 'storage.user',\n description:\n 'create the user store root and its sessions directory as owner-only directories',\n path: root,\n },\n };\n}\n\n/** Re-read the state now and decide whether `id` is repairable in it. Never writes. */\nexport function planDoctorRepair(\n id: string,\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n): TDoctorRepairPlanResult {\n if (!isDoctorRepairId(id, inputs)) {\n return {\n ok: false,\n reason: `${id}: not a repairable check (allowlist: ${doctorRepairAllowlist(inputs).join(', ')})`,\n };\n }\n return id === STORAGE_REPAIR_ID\n ? planStorageRepair(inputs, deps)\n : planSettingsRepair(id, inputs);\n}\n\n/**\n * Plan, confirm, re-plan, write. `confirm` is the host's prompt (`--yes` supplies `() => true`); a\n * refusal or an absent prompt writes nothing. The plan is recomputed after confirmation so a state\n * that changed while the user was deciding is refused rather than overwritten.\n */\nexport async function applyDoctorRepair(\n id: string,\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n confirm: (plan: IDoctorRepairPlan) => Promise<boolean>,\n): Promise<TDoctorRepairOutcome> {\n const first = planDoctorRepair(id, inputs, deps);\n if (!first.ok) return { applied: false, reason: first.reason };\n if (!(await confirm(first.plan)))\n return { applied: false, reason: `${id}: repair not confirmed; nothing written` };\n const current = planDoctorRepair(id, inputs, deps);\n if (!current.ok)\n return { applied: false, reason: `${current.reason} (state changed before the write)` };\n if (current.plan.id === STORAGE_REPAIR_ID) {\n const { root, sessions } = inputs.userStorage;\n ensureOwnerOnlyDirectory(sessions, { withinRoot: root });\n } else {\n writeSettings(current.plan.path, {});\n }\n return { applied: true, plan: current.plan };\n}\n","/**\n * Plugin, skill, hook and MCP probes (OBSERVABILITY-1991) — each over the owner's inspection API.\n *\n * Statuses follow the spec: a plugin the user installed that cannot load is `fail`; a hooks.json the\n * schema refuses is `warn` (report-only — the loader still loads it); an MCP structural fault is\n * `warn` until the CLI has an MCP consumer; MCP connection and hook execution are the enumerated\n * `not-probed` exclusions of a read-only doctor.\n */\nimport {\n inspectSkillSources,\n loadHostBundlePluginInspectionFromScopes,\n} from '@robota-sdk/agent-framework';\n\nimport type { IDoctorCheck, IDoctorDeps, IDoctorInputs } from './doctor-types.js';\nimport type {\n IBundlePluginInspection,\n IBundlePluginMcpServer,\n ISettingsInspection,\n} from '@robota-sdk/agent-framework';\n\nconst SKIP_CAUSE: Record<string, string> = {\n 'manifest-unreadable': 'manifest could not be parsed',\n 'manifest-invalid': 'manifest is not a valid plugin.json (name, version, description required)',\n 'load-failed': 'plugin assets could not be loaded',\n};\n\nfunction pluginChecks(inspections: readonly IBundlePluginInspection[]): IDoctorCheck[] {\n const checks: IDoctorCheck[] = [];\n const loaded = inspections.reduce((n, i) => n + i.loaded.length, 0);\n const present = inspections.filter((i) => i.cacheDirPresent);\n checks.push(\n present.length === 0\n ? {\n id: 'plugins',\n label: 'Plugins',\n status: 'not-configured',\n cause: 'no plugin cache directory',\n detail: inspections.map((i) => i.pluginsDir),\n }\n : {\n id: 'plugins',\n label: 'Plugins',\n status: 'ok',\n cause: `${loaded} plugin(s) loaded`,\n detail: present.map(\n (i) => `${i.pluginsDir}: ${i.loaded.length} loaded, ${i.skipped.length} skipped`,\n ),\n },\n );\n for (const inspection of inspections) {\n for (const skip of inspection.skipped) {\n if (skip.reason === 'disabled') continue;\n checks.push({\n id: `plugin.${skip.pluginId}`,\n label: 'Plugin',\n status: 'fail',\n path: skip.manifestPath,\n cause: SKIP_CAUSE[skip.reason] ?? skip.reason,\n ...(skip.detail === undefined ? {} : { detail: [skip.detail] }),\n });\n }\n for (const issue of inspection.hookIssues) {\n checks.push({\n id: `plugin.${issue.pluginId}.hooks`,\n label: 'Plugin hooks',\n status: 'warn',\n path: issue.hooksPath,\n cause: `hooks.json fails the hooks schema: ${issue.issues.map((i) => `${i.path} (${i.code})`).join(', ')}`,\n detail: ['Report-only: the plugin still loads; these hooks may not run.'],\n });\n }\n }\n return checks;\n}\n\nfunction skillChecks(inputs: IDoctorInputs): IDoctorCheck[] {\n const inspection = inspectSkillSources(inputs.contributionSources, inputs.skillRoots);\n const present = inspection.roots.filter((root) => root.present);\n const discovered = present.reduce((n, root) => n + root.discovered.length, 0);\n const checks: IDoctorCheck[] = [\n present.length === 0\n ? {\n id: 'skills',\n label: 'Skills and commands',\n status: 'not-configured',\n cause: 'no skill or command root present',\n }\n : {\n id: 'skills',\n label: 'Skills and commands',\n status: 'ok',\n cause: `${discovered} discovered`,\n detail: present.map(\n (root) => `${root.sourceDisplayName}: ${root.root} (${root.discovered.length})`,\n ),\n },\n ];\n for (const root of present) {\n for (const skip of root.skipped) {\n // A value the parser refuses ends session discovery with a throw; every other skip is tolerated.\n checks.push({\n id: `skill.${skip.path}`,\n label: 'Skill definition',\n status: skip.reason === 'frontmatter-invalid' ? 'fail' : 'warn',\n path: `${root.sourceDisplayName}: ${skip.path}`,\n cause: skip.reason,\n ...(skip.detail === undefined ? {} : { detail: [skip.detail] }),\n });\n }\n }\n return checks;\n}\n\n/** The shape of a hook group as both settings layers and plugin `hooks.json` carry it. */\ninterface IHookGroupLike {\n readonly hooks?: ReadonlyArray<{ readonly type?: string; readonly command?: string }>;\n}\n\nfunction commandHooks(\n settings: ISettingsInspection,\n plugins: readonly IBundlePluginInspection[],\n): string[] {\n const commands: string[] = [];\n const collect = (hooks: object | undefined): void => {\n if (hooks === undefined) return;\n for (const groups of Object.values(\n hooks as Record<string, readonly IHookGroupLike[] | undefined>,\n )) {\n for (const group of groups ?? []) {\n for (const hook of group.hooks ?? []) {\n if (hook.type === 'command' && typeof hook.command === 'string')\n commands.push(hook.command);\n }\n }\n }\n };\n collect(settings.merged.hooks);\n for (const inspection of plugins) for (const plugin of inspection.loaded) collect(plugin.hooks);\n return commands;\n}\n\nfunction hookChecks(\n settings: ISettingsInspection,\n plugins: readonly IBundlePluginInspection[],\n deps: IDoctorDeps,\n): IDoctorCheck[] {\n const commands = commandHooks(settings, plugins);\n const missing = commands.filter((command) => !deps.resolveCommand(command));\n return [\n commands.length === 0\n ? {\n id: 'hooks',\n label: 'Hooks',\n status: 'not-configured',\n cause: 'no command hooks configured',\n }\n : missing.length === 0\n ? {\n id: 'hooks',\n label: 'Hooks',\n status: 'ok',\n cause: `${commands.length} command hook(s); every executable resolves`,\n }\n : {\n id: 'hooks',\n label: 'Hooks',\n status: 'warn',\n cause: `${missing.length} command hook executable(s) not found on PATH`,\n detail: missing.map((command) => command.split(/\\s+/)[0] ?? command),\n },\n {\n id: 'hooks.execution',\n label: 'Hook execution',\n status: 'not-probed',\n cause: 'the doctor does not run hooks',\n },\n ];\n}\n\nfunction mcpServerCheck(server: IBundlePluginMcpServer, deps: IDoctorDeps): IDoctorCheck {\n const id = `mcp.plugin.${server.pluginId}.${server.name}`;\n if (server.transport === 'stdio' && server.command !== undefined) {\n return deps.resolveCommand(server.command)\n ? {\n id,\n label: 'MCP server (plugin)',\n status: 'ok',\n path: server.mcpPath,\n cause: `stdio command ${server.command} resolves`,\n }\n : {\n id,\n label: 'MCP server (plugin)',\n status: 'warn',\n path: server.mcpPath,\n cause: `stdio command ${server.command} not found on PATH`,\n detail: server.envKeys.length === 0 ? [] : [`env keys: ${server.envKeys.join(', ')}`],\n };\n }\n if (server.transport === 'http' && server.url !== undefined) {\n try {\n new URL(server.url);\n return {\n id,\n label: 'MCP server (plugin)',\n status: 'ok',\n path: server.mcpPath,\n cause: `url ${server.url}`,\n };\n } catch {\n // allow-fallback: an unparseable url is the finding\n return {\n id,\n label: 'MCP server (plugin)',\n status: 'warn',\n path: server.mcpPath,\n cause: 'url is not parseable',\n };\n }\n }\n return {\n id,\n label: 'MCP server (plugin)',\n status: 'warn',\n path: server.mcpPath,\n cause: 'neither command nor url declared',\n };\n}\n\nfunction mcpChecks(\n inputs: IDoctorInputs,\n plugins: readonly IBundlePluginInspection[],\n deps: IDoctorDeps,\n): IDoctorCheck[] {\n const checks: IDoctorCheck[] = [];\n if (inputs.mcpActivation === undefined) {\n checks.push({\n id: 'mcp.activation',\n label: 'MCP activation',\n status: 'not-configured',\n cause: 'this CLI composes no MCP activation adapter',\n });\n } else {\n const summaries = inputs.mcpActivation.list();\n checks.push({\n id: 'mcp.activation',\n label: 'MCP activation',\n status: 'ok',\n cause: `${summaries.length} server(s) known`,\n });\n for (const summary of summaries) {\n checks.push({\n id: `mcp.${summary.serverId}`,\n label: 'MCP server',\n status: summary.allowed ? 'ok' : 'warn',\n cause: `${summary.status} (${summary.source}): ${summary.reason}`,\n });\n }\n }\n for (const inspection of plugins) {\n for (const server of inspection.mcpServers) checks.push(mcpServerCheck(server, deps));\n for (const fault of inspection.mcpFaults) {\n checks.push({\n id: `mcp.plugin.${fault.pluginId}`,\n label: 'MCP declaration (plugin)',\n status: 'warn',\n path: fault.mcpPath,\n cause: `.mcp.json ${fault.reason}`,\n });\n }\n }\n checks.push({\n id: 'mcp.connection',\n label: 'MCP connection',\n status: 'not-probed',\n cause: 'the doctor does not connect to MCP servers',\n });\n return checks;\n}\n\n/** Plugins, skills, hooks and MCP — in that order. */\nexport function probeExtensions(\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n settings: ISettingsInspection,\n): IDoctorCheck[] {\n // Enablement is read the way the session loader reads it — from the user settings file through the\n // plugin settings store — so the doctor and the session agree even where that store's own policy is\n // a separate open item (recorded on #2670).\n const plugins = loadHostBundlePluginInspectionFromScopes(inputs.pluginsDirs, {\n settingsPath: inputs.userSettingsPath,\n });\n return [\n ...pluginChecks(plugins),\n ...skillChecks(inputs),\n ...hookChecks(settings, plugins, deps),\n ...mcpChecks(inputs, plugins, deps),\n ];\n}\n","/**\n * The doctor runner (OBSERVABILITY-1991): one pass over every probe, one redaction boundary, one\n * exit-code aggregation. Reachable without a session — it constructs no provider, no preset and no\n * session; the host supplies what it composed and the checks only it can make.\n */\nimport { probeExtensions } from './doctor-extensions-probe.js';\nimport {\n collectSettingsSecrets,\n describeDiagnosticError,\n redactDiagnosticText,\n} from './doctor-redaction.js';\nimport { probeProvider, probeSettings } from './doctor-settings-probe.js';\nimport { probeStorageAndTrust } from './doctor-storage-probe.js';\n\nimport type { ISettingsProbeResult } from './doctor-settings-probe.js';\nimport type { IDoctorCheck, IDoctorDeps, IDoctorInputs, IDoctorReport } from './doctor-types.js';\n\n/** A probe that throws is a `fail` check carrying the owner's error class — never a default value. */\nfunction probeFailure(id: string, label: string, error: Error): IDoctorCheck {\n return { id, label, status: 'fail', cause: describeDiagnosticError(error) };\n}\n\nasync function guarded<T>(\n id: string,\n label: string,\n probe: () => Promise<T> | T,\n onValue: (value: T) => readonly IDoctorCheck[],\n): Promise<readonly IDoctorCheck[]> {\n try {\n return onValue(await probe());\n } catch (error) {\n // allow-fallback: the probe's own failure is reported as a check, per the fallback declaration\n return [probeFailure(id, label, error instanceof Error ? error : new Error(String(error)))];\n }\n}\n\nfunction redactCheck(check: IDoctorCheck, secrets: readonly string[]): IDoctorCheck {\n const redact = (text: string): string => redactDiagnosticText(text, secrets);\n return {\n ...check,\n label: redact(check.label),\n ...(check.path === undefined ? {} : { path: redact(check.path) }),\n ...(check.cause === undefined ? {} : { cause: redact(check.cause) }),\n ...(check.detail === undefined ? {} : { detail: check.detail.map(redact) }),\n };\n}\n\n/** Aggregate checks into the report; `fail` alone raises the exit code (CLI-067). */\nexport function buildDoctorReport(checks: readonly IDoctorCheck[]): IDoctorReport {\n const failCount = checks.filter((check) => check.status === 'fail').length;\n const warnCount = checks.filter((check) => check.status === 'warn').length;\n return {\n checks,\n failCount,\n warnCount,\n repairable: checks.flatMap((check) => (check.repair === undefined ? [] : [check.repair])),\n exitCode: failCount === 0 ? 0 : 1,\n };\n}\n\n/** The settings probe under its own boundary: its failure is a `fail` check and later probes run without layers. */\nfunction guardedSettings(inputs: IDoctorInputs): {\n checks: readonly IDoctorCheck[];\n result?: ISettingsProbeResult;\n} {\n try {\n const result = probeSettings(inputs);\n return { checks: result.checks, result };\n } catch (error) {\n // allow-fallback: the settings probe's own failure is a `fail` check; later probes run without layers\n const cause = error instanceof Error ? error : new Error(String(error));\n return { checks: [probeFailure('settings', 'Settings', cause)] };\n }\n}\n\n/** Run every probe and return the redacted report. */\nexport async function runDoctor(inputs: IDoctorInputs, deps: IDoctorDeps): Promise<IDoctorReport> {\n const checks: IDoctorCheck[] = [...inputs.hostChecks];\n if (inputs.compositionFailure !== undefined) checks.push(inputs.compositionFailure);\n\n const settings = guardedSettings(inputs);\n checks.push(...settings.checks);\n const inspection = settings.result?.inspection;\n\n const secrets = collectSettingsSecrets(\n (inspection?.layers ?? []).map((layer) => layer.settings),\n inputs.env,\n );\n\n checks.push(\n ...(await guarded(\n 'provider',\n 'Provider',\n () => probeProvider(inputs, deps),\n (provider) => {\n if (provider.resolvedApiKey !== undefined) secrets.push(provider.resolvedApiKey);\n return provider.checks;\n },\n )),\n );\n\n if (inspection !== undefined) {\n checks.push(\n ...(await guarded(\n 'storage',\n 'Storage',\n () => probeStorageAndTrust(inputs, deps, inspection),\n (c) => c,\n )),\n );\n checks.push(\n ...(await guarded(\n 'extensions',\n 'Extensions',\n () => probeExtensions(inputs, deps, inspection),\n (c) => c,\n )),\n );\n }\n\n return buildDoctorReport(checks.map((check) => redactCheck(check, secrets)));\n}\n","import { createSystemCommandFromEntry } from '../command-module-utils.js';\n/**\n * `/doctor` — the interactive surface of the same runner the shell route uses (OBSERVABILITY-1991).\n *\n * `/doctor` renders the report; `/doctor repair <check-id>` confirms through the host's user\n * interaction port and treats an absent port or a cancelled answer as \"nothing written\". Neither\n * form creates a provider turn or submits user input: the command reads and, on explicit\n * confirmation, runs one allowlisted writer.\n */\nimport { confirmAction } from '@robota-sdk/agent-core';\n\nimport { createNodeDoctorDeps } from './doctor-node-deps.js';\nimport { renderDoctorReport } from './doctor-render.js';\nimport { applyDoctorRepair } from './doctor-repair.js';\nimport { runDoctor } from './doctor-runner.js';\n\nimport type { IDoctorRepairPlan } from './doctor-repair.js';\nimport type { IDoctorDisplayVocabulary } from './doctor-render.js';\nimport type { IDoctorDeps, IDoctorInputs } from './doctor-types.js';\nimport type {\n ICommandHostUserInteraction,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandResult, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createDoctorCommandEntry(): ICommand {\n return {\n name: 'doctor',\n displayName: 'Doctor',\n description:\n 'Diagnose configuration and runtime readiness; `repair <check-id>` applies an allowlisted fix',\n source: 'doctor',\n // User-only: install diagnostics and confirmed repairs that write settings are the user's.\n modelInvocable: false,\n userInvocable: true,\n argumentHint: '[repair <check-id>]',\n };\n}\n\nexport class DoctorCommandSource implements ICommandSource {\n readonly name = 'doctor';\n\n getCommands(): ICommand[] {\n return [createDoctorCommandEntry()];\n }\n}\n\nasync function confirmThroughHost(\n context: ICommandHostUserInteraction,\n plan: IDoctorRepairPlan,\n): Promise<boolean> {\n const ui = context.getUserInteraction();\n if (ui === undefined) return false;\n const response = await ui.ask(\n confirmAction(`doctor-repair:${plan.id}`, `Repair ${plan.id}?`, {\n description: `${plan.description} (${plan.path})`,\n defaultYes: false,\n }),\n );\n return response.type === 'answer' && response.values[0] === 'yes';\n}\n\nasync function executeRepair(\n id: string,\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n context: ICommandHostUserInteraction,\n display: IDoctorDisplayVocabulary,\n): Promise<ICommandResult> {\n const outcome = await applyDoctorRepair(id, inputs, deps, (plan) =>\n confirmThroughHost(context, plan),\n );\n if (!outcome.applied) {\n return { success: false, message: outcome.reason, data: { repair: id, applied: false } };\n }\n const report = await runDoctor(inputs, deps);\n const check = report.checks.find((candidate) => candidate.id === id);\n return {\n success: true,\n message: [\n `Repaired ${id}: ${outcome.plan.description}.`,\n ...renderDoctorReport(report, `${display.title ?? 'Doctor'} (after repair)`, display),\n ].join('\\n'),\n data: { repair: id, applied: true, status: check?.status, exitCode: report.exitCode },\n };\n}\n\nasync function executeDoctorCommand(\n inputs: IDoctorInputs,\n deps: IDoctorDeps,\n context: ICommandHostUserInteraction,\n args: string,\n display: IDoctorDisplayVocabulary,\n): Promise<ICommandResult> {\n const [verb, target] = args.trim().split(/\\s+/);\n if (verb === 'repair') {\n if (target === undefined || target.length === 0) {\n return { success: false, message: 'Usage: /doctor repair <check-id>' };\n }\n return executeRepair(target, inputs, deps, context, display);\n }\n const report = await runDoctor(inputs, deps);\n return {\n success: report.failCount === 0,\n message: renderDoctorReport(report, display.title, display).join('\\n'),\n data: {\n failCount: report.failCount,\n warnCount: report.warnCount,\n repairable: [...report.repairable],\n },\n };\n}\n\n/** Register `/doctor` over the host-composed inputs; the host decides whether to supply them. */\nexport function createDoctorCommandModule(\n inputs: IDoctorInputs,\n deps: IDoctorDeps = createNodeDoctorDeps({ ...inputs.env }),\n display: IDoctorDisplayVocabulary = {},\n): ICommandModule {\n const entry = createDoctorCommandEntry();\n const command: ISystemCommand = createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: (context, args) => executeDoctorCommand(inputs, deps, context, args, display),\n });\n return {\n name: 'agent-command-doctor',\n commandSources: [new DoctorCommandSource()],\n systemCommands: [command],\n };\n}\n","/**\n * TERM-004: editor-selection seam. Resolves `$VISUAL` → `$EDITOR` → `vi` (POSIX-first; a Windows\n * default is a TERM-007 concern). Splits on whitespace so `\"code -w\"` / `\"subl -w\"` style values work.\n */\nexport interface IResolvedEditor {\n command: string;\n args: readonly string[];\n}\n\nexport function resolveEditor(): IResolvedEditor {\n const visual = process.env.VISUAL?.trim();\n const editor = process.env.EDITOR?.trim();\n const chosen =\n visual !== undefined && visual.length > 0\n ? visual\n : editor !== undefined && editor.length > 0\n ? editor\n : 'vi';\n const parts = chosen.split(/\\s+/).filter((p) => p.length > 0);\n return { command: parts[0] ?? 'vi', args: parts.slice(1) };\n}\n","/**\n * Pure-Node spawn with the real terminal inherited (interactive input + output). Used inside a\n * terminal-handoff `runWithTerminal(fn)` — the framework/transport own the suspend/restore; this just\n * runs the child attached to the real TTY and resolves with its exit code.\n */\nimport { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\n\nexport function spawnInherited(\n command: string,\n args: readonly string[],\n cwd: string,\n): Promise<number> {\n return new Promise<number>((resolve, reject) => {\n const child = spawn(command, [...args], { cwd, stdio: 'inherit', env: process.env });\n child.on('error', reject);\n child.on('exit', (code, signal) => {\n // RUNTIME-53: a signal-terminated child reports code=null; resolving 0 there is a false\n // success. Translate to the shell convention 128 + signal number so callers see the failure.\n if (code !== null) {\n resolve(code);\n return;\n }\n if (signal) {\n const signalNumber = constants.signals[signal as keyof typeof constants.signals];\n resolve(128 + (signalNumber ?? 0));\n return;\n }\n resolve(0);\n });\n });\n}\n","/**\n * TERM-004: `/editor` — compose a message/prompt in `$EDITOR` via the terminal-handoff capability,\n * then return the saved text. The temp file is pre-filled with any args and removed afterward.\n */\nimport { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { resolveEditor } from './resolve-editor.js';\nimport { spawnInherited } from '../shell/spawn-inherited.js';\n\nimport type {\n ICommandHostTerminalHandoff,\n ICommandHostWorkspace,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport const EDITOR_COMMAND_DESCRIPTION =\n 'Compose a message in $EDITOR (optionally pre-filled with `/editor <text>`), then return it.';\nexport const DEFAULT_EDITOR_TEMPORARY_DIRECTORY_PREFIX = 'agent-editor-';\n\nexport async function executeEditorCommand(\n context: ICommandHostTerminalHandoff & ICommandHostWorkspace,\n args: string,\n temporaryDirectoryPrefix: string = DEFAULT_EDITOR_TEMPORARY_DIRECTORY_PREFIX,\n): Promise<ICommandResult> {\n if (!context.canHandoffTerminal()) {\n return {\n message: 'An editor is unavailable here (no interactive terminal).',\n success: false,\n };\n }\n\n const editor = resolveEditor();\n const dir = mkdtempSync(join(tmpdir(), temporaryDirectoryPrefix));\n const file = join(dir, 'message.md');\n writeFileSync(file, args ?? '', 'utf8');\n\n try {\n const exitCode = await context.runWithTerminal(async () =>\n spawnInherited(editor.command, [...editor.args, file], context.getCwd()),\n );\n if (exitCode !== 0) {\n return {\n message: `Editor exited without saving (code ${exitCode}).`,\n success: false,\n data: { exitCode },\n };\n }\n const content = readFileSync(file, 'utf8').replace(/\\s+$/u, '');\n if (content.length === 0) {\n return { message: 'Editor closed with empty content; nothing composed.', success: false };\n }\n return { message: content, success: true, data: { content } };\n } finally {\n rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 20 });\n }\n}\n","/**\n * TERM-004: `/editor` command module — a framework-level consumer of the terminal-handoff capability.\n */\nimport { EDITOR_COMMAND_DESCRIPTION, executeEditorCommand } from './editor-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createEditorCommandEntry(): ICommand {\n return {\n name: 'editor',\n displayName: 'Editor',\n description: EDITOR_COMMAND_DESCRIPTION,\n source: 'editor',\n // User-only: opens the user's terminal editor; UI-only.\n modelInvocable: false,\n };\n}\n\nfunction createEditorSystemCommand(temporaryDirectoryPrefix?: string): ISystemCommand {\n const entry = createEditorCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: (context, args) => executeEditorCommand(context, args, temporaryDirectoryPrefix),\n };\n}\n\nexport class EditorCommandSource implements ICommandSource {\n readonly name = 'editor';\n\n getCommands(): ICommand[] {\n return [createEditorCommandEntry()];\n }\n}\n\nexport function createEditorCommandModule(temporaryDirectoryPrefix?: string): ICommandModule {\n return {\n name: 'agent-command-editor',\n commandSources: [new EditorCommandSource()],\n systemCommands: [createEditorSystemCommand(temporaryDirectoryPrefix)],\n };\n}\n","import type {\n IAdvisorStatus,\n ICommandHostAdapterAccess,\n ICommandHostWorkspace,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\n/** The user-settings key `/advisor` saves the default advisor under. */\nexport const ADVISOR_SETTING_KEY = 'advisorModel';\n\nfunction describeStatus(status: IAdvisorStatus): string {\n if (status.killSwitch) return 'Advisor: disabled by the environment kill switch.';\n if (status.target === undefined || !status.enabled) {\n return 'Advisor: off. Set one with /advisor <profile> or /advisor <profile>:<model>.';\n }\n const availability = status.registered\n ? `${status.sessionCalls}/${status.maxCallsPerSession} calls used this session`\n : 'available from the next session';\n return `Advisor: ${status.target} (${availability}).`;\n}\n\n/**\n * `/advisor` — show the advisor, set it (`<profile>` or `<profile>:<model>`), or turn it off. A\n * change the user makes is also saved as the default for later sessions.\n */\nexport async function executeAdvisorCommand(\n context: ICommandHostAdapterAccess & ICommandHostWorkspace,\n args: string,\n): Promise<ICommandResult> {\n const adapters = context.getCommandHostAdapters?.() ?? {};\n const advisor = adapters.advisor;\n if (advisor === undefined) {\n return { success: false, message: 'The advisor is not available in this environment.' };\n }\n const value = args.trim();\n if (value.length === 0) {\n const status = advisor.status();\n return { success: true, message: describeStatus(status), data: { advisor: { ...status } } };\n }\n const result = advisor.set(value);\n if (!result.success || result.saved === undefined) {\n return { success: result.success, message: result.message };\n }\n const settings = adapters.settings;\n if (settings !== undefined && context.getCommandInvocationSource() === 'user') {\n const current = settings.read();\n if (result.saved === 'off') {\n const { [ADVISOR_SETTING_KEY]: _removed, ...rest } = current;\n settings.write(rest);\n } else {\n settings.write({ ...current, [ADVISOR_SETTING_KEY]: result.saved });\n }\n }\n return { success: true, message: result.message, data: { advisor: { ...advisor.status() } } };\n}\n","import { executeAdvisorCommand } from './advisor-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createAdvisorCommandEntry(): ICommand {\n return {\n name: 'advisor',\n displayName: 'Advisor',\n description: 'Show, set, or turn off the model the main model can consult for advice',\n source: 'advisor',\n argumentHint: '<profile> | <profile>:<model> | off',\n // User-only: choosing a second model changes cost and what sees the conversation; the user decides.\n modelInvocable: false,\n };\n}\n\nfunction createAdvisorSystemCommand(): ISystemCommand {\n const entry = createAdvisorCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n execute: executeAdvisorCommand,\n };\n}\n\nexport class AdvisorCommandSource implements ICommandSource {\n readonly name = 'advisor';\n\n getCommands(): ICommand[] {\n return [createAdvisorCommandEntry()];\n }\n}\n\nexport function createAdvisorCommandModule(): ICommandModule {\n return {\n name: 'agent-command-advisor',\n commandSources: [new AdvisorCommandSource()],\n systemCommands: [createAdvisorSystemCommand()],\n };\n}\n","import { MODEL_EFFORT_VALUES, selectAction } from '@robota-sdk/agent-core';\nimport { parseModelEffort, resolveModelEffort } from '@robota-sdk/agent-framework';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostAdapters,\n ICommandHostSessionAccess,\n ICommandHostUserInteraction,\n ICommandHostWorkspace,\n IModelEffortResolution,\n TEffortSelection,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nconst EFFORT_SELECTIONS: readonly TEffortSelection[] = ['auto', ...MODEL_EFFORT_VALUES];\n\nfunction formatEffortMessage(resolution: {\n requested: TEffortSelection;\n effective: string;\n source: string;\n disposition: string;\n}): string {\n return `Model effort: requested=${resolution.requested}, effective=${resolution.effective}, source=${resolution.source}, disposition=${resolution.disposition}.`;\n}\n\nasync function askForEffort(\n context: ICommandHostUserInteraction,\n): Promise<TEffortSelection | undefined> {\n const interaction = context.getUserInteraction();\n if (interaction === undefined) return undefined;\n const response = await interaction.ask(\n selectAction(\n 'effort',\n 'Select model effort',\n EFFORT_SELECTIONS.map((value) => ({ value, label: value })),\n ),\n );\n const selected = response.type === 'answer' ? response.values[0] : undefined;\n return parseModelEffort(selected, '/effort');\n}\n\nfunction readCurrentResolution(\n context: ICommandHostAdapterAccess & ICommandHostSessionAccess,\n): IModelEffortResolution {\n const adapter = context.getCommandHostAdapters?.().effort;\n if (adapter !== undefined) return adapter.getResolution();\n const selection = context.getSession().getModelEffort();\n return resolveModelEffort({\n command: selection,\n modelDefault: selection === 'auto' ? 'high' : selection,\n });\n}\n\nfunction readAdapters(context: ICommandHostAdapterAccess): ICommandHostAdapters {\n return context.getCommandHostAdapters?.() ?? {};\n}\n\nfunction persistEffortSelection(\n context: ICommandHostAdapterAccess,\n selection: TEffortSelection,\n): void {\n const settings = readAdapters(context).settings;\n if (settings === undefined || selection === 'max') return;\n const current = settings.read();\n if (selection === 'auto') {\n const { effort: _effort, ...withoutEffort } = current;\n settings.write(withoutEffort);\n return;\n }\n settings.write({ ...current, effort: selection });\n}\n\nexport async function executeEffortCommand(\n context: ICommandHostAdapterAccess &\n ICommandHostSessionAccess &\n ICommandHostUserInteraction &\n ICommandHostWorkspace,\n args: string,\n): Promise<ICommandResult> {\n let selection: TEffortSelection | undefined;\n try {\n selection = parseModelEffort(args.trim() || undefined, '/effort');\n if (selection === undefined) selection = await askForEffort(context);\n } catch (error) {\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n\n const current = readCurrentResolution(context);\n if (selection === undefined) {\n return {\n message: formatEffortMessage(current),\n success: true,\n data: { effort: current },\n };\n }\n\n const adapter = readAdapters(context).effort;\n let resolution;\n try {\n resolution =\n adapter === undefined\n ? resolveModelEffort({ command: selection, modelDefault: current.effective })\n : await adapter.apply(selection, context.getSession());\n if (adapter === undefined) {\n await context.getSession().applyModelOptions({ effort: selection });\n }\n if (context.getCommandInvocationSource() === 'user') {\n persistEffortSelection(context, selection);\n }\n } catch (error) {\n return {\n message: `Model effort was not applied: ${error instanceof Error ? error.message : String(error)}`,\n success: false,\n };\n }\n\n return {\n message: formatEffortMessage(resolution),\n success: true,\n data: { effort: resolution },\n };\n}\n","import { MODEL_EFFORT_VALUES } from '@robota-sdk/agent-core';\n\nimport { executeEffortCommand } from './effort-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nconst EFFORT_ARGUMENT_HINT = `auto | ${MODEL_EFFORT_VALUES.join(' | ')}`;\n\nexport function createEffortCommandEntry(): ICommand {\n return {\n name: 'effort',\n displayName: 'Model Effort',\n description: 'Show or change the model effort level',\n source: 'effort',\n argumentHint: EFFORT_ARGUMENT_HINT,\n // User-only: the effort tier is the user's cost/latency preference.\n modelInvocable: false,\n };\n}\n\nfunction createEffortSystemCommand(): ISystemCommand {\n const entry = createEffortCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n execute: executeEffortCommand,\n };\n}\n\nexport class EffortCommandSource implements ICommandSource {\n readonly name = 'effort';\n\n getCommands(): ICommand[] {\n return [createEffortCommandEntry()];\n }\n}\n\nexport function createEffortCommandModule(): ICommandModule {\n return {\n name: 'agent-command-effort',\n commandSources: [new EffortCommandSource()],\n systemCommands: [createEffortSystemCommand()],\n };\n}\n","import { confirmAction, isConfirmed } from '@robota-sdk/agent-core';\nimport { createSessionExitHostAction } from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostUserInteraction } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport async function executeExitCommand(\n context: ICommandHostUserInteraction,\n _args: string,\n): Promise<ICommandResult> {\n // Confirm only when an interactive renderer is attached. With no human (headless/automation) the\n // user explicitly invoked /exit, so proceed — the confirm is an interactive safety prompt, not a gate.\n const ui = context.getUserInteraction();\n if (ui) {\n const response = await ui.ask(confirmAction('exit', 'Exit the session?'));\n if (!isConfirmed(response)) {\n return { success: true, message: 'Exit cancelled.' };\n }\n }\n\n return {\n success: true,\n message: 'Exit requested.',\n hostActions: [createSessionExitHostAction()],\n };\n}\n","import { EXIT_COMMAND_DESCRIPTION } from '@robota-sdk/agent-framework';\n\nimport { executeExitCommand } from './exit-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createExitCommandEntry(): ICommand {\n return {\n name: 'exit',\n displayName: 'Exit Session',\n description: EXIT_COMMAND_DESCRIPTION,\n source: 'exit',\n // User-only: ending the session is the user's decision.\n modelInvocable: false,\n };\n}\n\nfunction createExitSystemCommand(): ISystemCommand {\n const entry = createExitCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeExitCommand,\n };\n}\n\nexport class ExitCommandSource implements ICommandSource {\n readonly name = 'exit';\n\n getCommands(): ICommand[] {\n return [createExitCommandEntry()];\n }\n}\n\nexport function createExitCommandModule(): ICommandModule {\n return {\n name: 'agent-command-exit',\n commandSources: [new ExitCommandSource()],\n systemCommands: [createExitSystemCommand()],\n };\n}\n","/**\n * `/fork [name] [--same-dir]` (CLI-1994, issue #1994) — copy this conversation into a background\n * session and keep working here.\n *\n * The two halves are deliberately separate calls to two different capabilities, because they are two\n * different facts. `forkSession` writes a COPY of the live conversation as a new session record: the\n * messages, the parent's assembled system message, the tool schemas and the transcript, under a\n * fresh id and a name that is not the parent's. Spawning then starts a background agent job that\n * carries ONLY that id — the conversation never rides on the request, so it never crosses the\n * child-process wire (ARCH-044); the child reads the record from the session store, exactly as the\n * startup `--fork-session` does.\n *\n * A fork is a copy, not a branch of one live thing: from the moment the record is written, work in\n * the fork and work here are two histories that never rejoin. Attaching to the fork later (the\n * background panel's `attach` control) switches the terminal's VIEW to that session; it does not\n * merge anything back.\n */\n\nimport type { ICommandHostAgentJobs, ICommandHostSessionAccess } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { TBackgroundTaskIsolation } from '@robota-sdk/agent-interface-execution';\n\n/** What `/fork` needs from its host: the copy-writer and the job dispatcher. */\nexport type TForkCommandContext = ICommandHostSessionAccess & ICommandHostAgentJobs;\n\n/**\n * The fork runs in its own worktree by DEFAULT.\n *\n * A spawned job inherits the parent's cwd, so a fork that keeps working in the same directory writes\n * over the files the parent is still editing — the \"work in it does not affect the original\"\n * property lost through the filesystem rather than through the conversation. `--same-dir` is the\n * explicit opt-out for a fork that is meant to read and think rather than to edit.\n */\nconst DEFAULT_ISOLATION: TBackgroundTaskIsolation = 'worktree';\nconst SAME_DIR_ISOLATION: TBackgroundTaskIsolation = 'none';\nconst SAME_DIR_FLAG = '--same-dir';\n\n/** The agent a forked conversation continues under — the general one, since the fork IS the context. */\nconst FORK_AGENT_TYPE = 'general-purpose';\n\n/**\n * The fork's first turn input.\n *\n * A fork inherits the parent's whole conversation and its assembled system message, so there is\n * nothing left to brief it about — this is a minimal continuation cue, deliberately NOT a prompt.\n * § Solution 5 asked for an empty string; a turn with no user content is rejected by providers, and\n * one word is the smallest thing that is not — the divergence is recorded in the spec beside it. Anything longer would be this neutral command layer\n * deciding how a forked agent should behave, which is the product layer's call\n * (`scan-prompt-prose` is the mechanical form of that rule).\n */\nconst FORK_FIRST_TURN = 'Continue.';\n\nexport interface IParsedForkArgs {\n readonly name: string | undefined;\n readonly isolation: TBackgroundTaskIsolation;\n}\n\n/** A rejected argument string, kept distinct from a parse so neither can be read as the other. */\nexport interface IForkArgsError {\n readonly error: string;\n}\n\n/**\n * `--same-dir` may appear anywhere; everything else is the name.\n *\n * An unrecognised `--flag` is REFUSED rather than folded into the name: a mistyped `--same-dr` that\n * became a session called \"--same-dr\" would silently give the operator a worktree they asked not to\n * have, and the name is the one field they will later use to find the fork.\n */\nexport function parseForkArgs(args: string): IParsedForkArgs | IForkArgsError {\n const tokens = args\n .trim()\n .split(/\\s+/)\n .filter((token) => token.length > 0);\n const unknownFlag = tokens.find((token) => token.startsWith('--') && token !== SAME_DIR_FLAG);\n if (unknownFlag !== undefined) {\n return { error: `Unknown option: ${unknownFlag}\\nUsage: /fork [name] [${SAME_DIR_FLAG}]` };\n }\n const nameTokens = tokens.filter((token) => token !== SAME_DIR_FLAG);\n return {\n name: nameTokens.length > 0 ? nameTokens.join(' ') : undefined,\n isolation: tokens.includes(SAME_DIR_FLAG) ? SAME_DIR_ISOLATION : DEFAULT_ISOLATION,\n };\n}\n\nfunction formatError<TError>(error: TError): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction describeFork(name: string, taskId: string, isolation: TBackgroundTaskIsolation): string {\n const where = isolation === SAME_DIR_ISOLATION ? 'in this directory' : 'in its own worktree';\n return [\n `Forked this conversation into \"${name}\" (${taskId}), running ${where}.`,\n 'The fork is a copy: this session keeps going, and the two are separate records.',\n 'See its progress with /background list. Attaching from the background panel points this',\n \"terminal at the copy as it was forked; the fork's own turns stay in its task transcript.\",\n ].join('\\n');\n}\n\n/**\n * The copy is on disk and the job is not. Both facts are reported, because the record is still\n * resumable by name and an operator told only \"failed\" would not know that.\n */\nfunction describeSpawnFailure(\n fork: { sessionId: string; name: string },\n reason: string,\n formatResumeCommand?: (sessionId: string) => string,\n): string {\n const resumeHint = formatResumeCommand?.(fork.sessionId);\n return (\n `The fork \"${fork.name}\" was written (${fork.sessionId}) but its background job could not ` +\n `start: ${reason}\\n${resumeHint === undefined ? 'Resume the saved session through your host.' : `Resume it in a new terminal with: ${resumeHint}`}`\n );\n}\n\nexport async function executeForkCommand(\n context: TForkCommandContext,\n args = '',\n formatResumeCommand?: (sessionId: string) => string,\n): Promise<ICommandResult> {\n const parsed = parseForkArgs(args);\n if ('error' in parsed) return { message: parsed.error, success: false };\n\n const jobs = context.getAgentJobCapability();\n if (!jobs) {\n return {\n message: 'This session cannot start background jobs, so it cannot run a fork.',\n success: false,\n };\n }\n\n // The copy is written FIRST, and a failure here is reported without spawning: a job that resumes a\n // record which was never written is a child that fails on its own far side, out of the operator's\n // sight.\n let fork: { sessionId: string; name: string };\n try {\n fork = await context.forkSession(parsed.name !== undefined ? { name: parsed.name } : {});\n } catch (error) {\n return { message: `Could not fork this session: ${formatError(error)}`, success: false };\n }\n\n try {\n const state = await jobs.spawnAgentJob({\n agentType: FORK_AGENT_TYPE,\n label: fork.name,\n mode: 'background',\n prompt: FORK_FIRST_TURN,\n isolation: parsed.isolation,\n resumeSessionId: fork.sessionId,\n });\n return {\n message: describeFork(fork.name, state.id, parsed.isolation),\n success: true,\n data: { sessionId: fork.sessionId, name: fork.name, taskId: state.id },\n };\n } catch (error) {\n return {\n message: describeSpawnFailure(fork, formatError(error), formatResumeCommand),\n success: false,\n };\n }\n}\n","import { executeForkCommand } from './fork-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createForkCommandEntry(): ICommand {\n return {\n name: 'fork',\n displayName: 'Fork Session',\n description:\n 'Copy this conversation into a new background session and keep working here. ' +\n 'The fork inherits the whole conversation and the assembled system prompt; it is a copy, ' +\n 'so nothing it does reaches this session and it never merges back.',\n source: 'fork',\n // The model does not decide to duplicate the operator's conversation. Forking spends a second\n // session's budget and creates a second worktree, both of which are the operator's call.\n // User-only: starts a separate session the user owns and attaches to.\n modelInvocable: false,\n argumentHint: '[name] [--same-dir]',\n };\n}\n\nfunction createForkSystemCommand(\n formatResumeCommand?: (sessionId: string) => string,\n): ISystemCommand {\n const entry = createForkCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n ...(entry.argumentHint !== undefined ? { argumentHint: entry.argumentHint } : {}),\n // `ICommandHostContext` aggregates both role ports `/fork` declares, so the narrowing is the\n // parameter's own type — no assertion, and a role the command stops satisfying is a build error.\n execute: (context, args) => executeForkCommand(context, args, formatResumeCommand),\n };\n}\n\nexport class ForkCommandSource implements ICommandSource {\n readonly name = 'fork';\n\n getCommands(): ICommand[] {\n return [createForkCommandEntry()];\n }\n}\n\nexport function createForkCommandModule(\n formatResumeCommand?: (sessionId: string) => string,\n): ICommandModule {\n return {\n name: 'agent-command-fork',\n commandSources: [new ForkCommandSource()],\n systemCommands: [createForkSystemCommand(formatResumeCommand)],\n // A fork is a background agent job resuming a session record; a host with no agent runtime has\n // neither half, so the command is not offered rather than offered and refused.\n sessionRequirements: ['agent-runtime'],\n };\n}\n","/**\n * BEHAVIOR-2437: the one seam every `/git` verb runs git through.\n *\n * argv only — `execFile` with `shell: false`, so no user token is ever parsed as shell syntax; stdin\n * is closed at once, so a hook that reads it sees EOF instead of hanging; output is capped, the child\n * is bounded by a timeout, and every way a run can end is a typed outcome rather than a throw. Exit\n * codes are DATA: `diff --cached --quiet` answers with 1, and that is an answer, not an error.\n */\nimport { execFile } from 'node:child_process';\nimport { constants } from 'node:os';\n\nimport type { ExecFileException } from 'node:child_process';\n\nexport const GIT_DEFAULT_TIMEOUT_MS = 120_000;\nconst BYTES_PER_KIB = 1024;\nconst OUTPUT_CAP_MIB = 16;\nexport const GIT_MAX_OUTPUT_BYTES = OUTPUT_CAP_MIB * BYTES_PER_KIB * BYTES_PER_KIB;\n/** The shell convention for a signal-terminated child: 128 + the signal number. */\nconst SIGNAL_EXIT_BASE = 128;\n\n/**\n * Variables that redirect a git child to ANOTHER repository. Git exports them into hooks, so a\n * `/git` run started from inside a hook (or from any process that inherited one) would otherwise\n * operate on the wrong tree. Identity and configuration variables are deliberately NOT here — the\n * user's `GIT_CONFIG_GLOBAL`, `GIT_AUTHOR_*`, `GPG_TTY`, `SSH_AUTH_SOCK` … are what make the commit\n * theirs.\n */\nexport const GIT_ENV_DENYLIST: readonly string[] = [\n 'GIT_DIR',\n 'GIT_WORK_TREE',\n 'GIT_INDEX_FILE',\n 'GIT_OBJECT_DIRECTORY',\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES',\n 'GIT_COMMON_DIR',\n 'GIT_PREFIX',\n 'GIT_NAMESPACE',\n];\n\nexport interface IGitProcessRunOptions {\n cwd: string;\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\n/**\n * `not-found` covers every spawn failure — ENOENT, EACCES, ENOTDIR, … — with the code in `detail`;\n * the other three are the run's own bounds.\n */\nexport type TGitProcessFailureReason = 'not-found' | 'timeout' | 'aborted' | 'output-too-large';\n\nexport type TGitProcessOutcome =\n | { kind: 'exited'; stdout: string; stderr: string; exitCode: number }\n | { kind: 'failed'; reason: TGitProcessFailureReason; detail: string };\n\nexport interface IGitProcessPort {\n run(args: readonly string[], options: IGitProcessRunOptions): Promise<TGitProcessOutcome>;\n}\n\nexport interface ICreateGitProcessOptions {\n /** The executable to run; `git` on PATH by default. */\n executable?: string;\n /** The environment to derive the child's from; the live process environment by default. */\n env?: NodeJS.ProcessEnv;\n}\n\n/** The child's environment: `source` minus the repository-redirecting variables. */\nexport function gitEnvironment(source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(source)) {\n if (!GIT_ENV_DENYLIST.includes(key)) env[key] = value;\n }\n return env;\n}\n\nfunction failed(reason: TGitProcessFailureReason, detail: string): TGitProcessOutcome {\n return { kind: 'failed', reason, detail };\n}\n\nfunction signalNumber(signal: NodeJS.Signals): number {\n return constants.signals[signal] ?? 0;\n}\n\nfunction toOutcome(\n error: ExecFileException | null,\n stdout: string,\n stderr: string,\n context: { executable: string; timeoutMs: number; signal: AbortSignal | undefined },\n): TGitProcessOutcome {\n if (error === null) return { kind: 'exited', stdout, stderr, exitCode: 0 };\n if (context.signal?.aborted === true || error.name === 'AbortError') {\n return failed('aborted', 'the run was aborted before git exited');\n }\n if (error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {\n return failed(\n 'output-too-large',\n `git produced more than ${OUTPUT_CAP_MIB} MiB of output and was stopped`,\n );\n }\n // Our own kill wins over whatever exit the child managed on the way down (a shell trap exiting\n // 143 is still a timeout).\n if (error.killed === true) {\n return failed('timeout', `git did not exit within ${context.timeoutMs} ms and was stopped`);\n }\n if (typeof error.code === 'number')\n return { kind: 'exited', stdout, stderr, exitCode: error.code };\n if (error.signal) {\n // RUNTIME-53 convention: a signal-terminated child reports 128 + the signal number.\n return {\n kind: 'exited',\n stdout,\n stderr,\n exitCode: SIGNAL_EXIT_BASE + signalNumber(error.signal),\n };\n }\n return failed(\n 'not-found',\n `${context.executable} could not be run (${String(error.code ?? error.message)})`,\n );\n}\n\n/** The production port: argv-only `execFile`, stdin closed, output capped, timeout bounded. */\nexport function createGitProcess(options: ICreateGitProcessOptions = {}): IGitProcessPort {\n const executable = options.executable ?? 'git';\n return {\n run(args, runOptions) {\n const timeoutMs = runOptions.timeoutMs ?? GIT_DEFAULT_TIMEOUT_MS;\n const env = gitEnvironment(options.env ?? process.env);\n return new Promise<TGitProcessOutcome>((resolve) => {\n const child = execFile(\n executable,\n [...args],\n {\n cwd: runOptions.cwd,\n env,\n shell: false,\n encoding: 'utf8',\n timeout: timeoutMs,\n maxBuffer: GIT_MAX_OUTPUT_BYTES,\n windowsHide: true,\n ...(runOptions.signal ? { signal: runOptions.signal } : {}),\n },\n (error, stdout, stderr) =>\n resolve(\n toOutcome(error, stdout, stderr, {\n executable,\n timeoutMs,\n signal: runOptions.signal,\n }),\n ),\n );\n // stdin is a pipe by default; closing it at once turns a hook's read into EOF.\n child.stdin?.end();\n });\n },\n };\n}\n\n/**\n * The reason a run did not produce a usable answer, for the verbs where a non-zero exit IS a failure.\n * `undefined` when the child exited 0.\n */\nexport function gitFailureMessage(verb: string, outcome: TGitProcessOutcome): string | undefined {\n if (outcome.kind === 'failed') return `git ${verb} failed: ${outcome.detail}`;\n if (outcome.exitCode === 0) return undefined;\n const stderr = outcome.stderr.trim();\n return stderr.length > 0\n ? `git ${verb} failed (exit ${outcome.exitCode}): ${stderr}`\n : `git ${verb} failed (exit ${outcome.exitCode})`;\n}\n","/**\n * BEHAVIOR-2437: `/git status` — `git status --porcelain=v2 -z --branch`, parsed into the branch and\n * the staged, unstaged, untracked (and, when present, conflicted) path sets.\n *\n * `-z` is what makes a path with a space, a quote, a newline or a non-ASCII character ONE element,\n * and it is why a `2` (rename/copy) record is read as TWO NUL-terminated fields — `path`, then\n * `origPath` — so the pair stays a pair.\n */\nimport { gitFailureMessage } from './git-process.js';\n\nimport type { IGitProcessPort } from './git-process.js';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport const GIT_STATUS_ARGS: readonly string[] = ['status', '--porcelain=v2', '-z', '--branch'];\n\nexport interface IGitStatusSummary {\n /** `branch.head`; `(detached)` when detached; `undefined` when git printed no branch header. */\n branch: string | undefined;\n /** `branch.oid` is `(initial)` on an unborn branch. */\n unborn: boolean;\n staged: readonly string[];\n unstaged: readonly string[];\n untracked: readonly string[];\n conflicted: readonly string[];\n}\n\nconst ORDINARY = /^1 (\\S\\S) \\S+ \\S+ \\S+ \\S+ \\S+ \\S+ ([^]*)$/;\nconst RENAMED = /^2 (\\S\\S) \\S+ \\S+ \\S+ \\S+ \\S+ \\S+ \\S+ ([^]*)$/;\nconst UNMERGED = /^u \\S\\S \\S+ \\S+ \\S+ \\S+ \\S+ \\S+ \\S+ \\S+ ([^]*)$/;\n\ninterface IStatusAccumulator {\n branch: string | undefined;\n unborn: boolean;\n staged: string[];\n unstaged: string[];\n untracked: string[];\n conflicted: string[];\n}\n\nfunction classify(acc: IStatusAccumulator, xy: string, display: string): void {\n if (xy[0] !== '.') acc.staged.push(display);\n if (xy[1] !== '.') acc.unstaged.push(display);\n}\n\nfunction readHeader(acc: IStatusAccumulator, record: string): void {\n if (record.startsWith('# branch.head ')) acc.branch = record.slice('# branch.head '.length);\n else if (record.startsWith('# branch.oid ')) {\n acc.unborn = record.slice('# branch.oid '.length) === '(initial)';\n }\n}\n\n/** Reads one record; returns how many EXTRA NUL-terminated fields it consumed (1 for a rename). */\nfunction readRecord(acc: IStatusAccumulator, record: string, next: string | undefined): number {\n if (record.startsWith('# ')) {\n readHeader(acc, record);\n return 0;\n }\n if (record.startsWith('? ')) {\n acc.untracked.push(record.slice(2));\n return 0;\n }\n if (record.startsWith('1 ')) {\n const match = ORDINARY.exec(record);\n if (match) classify(acc, match[1] ?? '..', match[2] ?? '');\n return 0;\n }\n if (record.startsWith('2 ')) {\n // The original path is the NEXT NUL-terminated field.\n const match = RENAMED.exec(record);\n if (match) classify(acc, match[1] ?? '..', `${match[2] ?? ''} (from ${next ?? ''})`);\n return 1;\n }\n if (record.startsWith('u ')) {\n const match = UNMERGED.exec(record);\n if (match) acc.conflicted.push(match[1] ?? '');\n }\n return 0;\n}\n\nexport function parseStatusPorcelainV2(stdout: string): IGitStatusSummary {\n const fields = stdout.split('\\0');\n const acc: IStatusAccumulator = {\n branch: undefined,\n unborn: false,\n staged: [],\n unstaged: [],\n untracked: [],\n conflicted: [],\n };\n for (let index = 0; index < fields.length; index += 1) {\n const record = fields[index] ?? '';\n if (record.length === 0) continue;\n index += readRecord(acc, record, fields[index + 1]);\n }\n return acc;\n}\n\nfunction group(label: string, paths: readonly string[]): string {\n return `${label} (${paths.length}):${paths.length > 0 ? ` ${paths.join(', ')}` : ''}`;\n}\n\nexport function formatGitStatus(summary: IGitStatusSummary): string {\n const head =\n summary.branch === undefined\n ? 'No branch information'\n : summary.branch === '(detached)'\n ? 'HEAD detached'\n : `On branch ${summary.branch}${summary.unborn ? ' (no commits yet)' : ''}`;\n const lines = [\n head,\n group('staged', summary.staged),\n group('unstaged', summary.unstaged),\n group('untracked', summary.untracked),\n ];\n if (summary.conflicted.length > 0) lines.push(group('conflicted', summary.conflicted));\n return lines.join('\\n');\n}\n\nexport async function executeGitStatus(\n port: IGitProcessPort,\n cwd: string,\n): Promise<ICommandResult> {\n const outcome = await port.run(GIT_STATUS_ARGS, { cwd });\n const failure = gitFailureMessage('status', outcome);\n if (failure !== undefined || outcome.kind !== 'exited') {\n return { success: false, message: failure ?? 'git status failed' };\n }\n const summary = parseStatusPorcelainV2(outcome.stdout);\n return {\n success: true,\n message: formatGitStatus(summary),\n data: { git: 'status', ...summary },\n };\n}\n","/**\n * BEHAVIOR-2437: `/git commit [<subject>]` — the staged set, and only ever the staged set.\n *\n * No `-a`, no `add`, no paths. Nothing staged is answered with guidance that says why; the subject\n * is held to the Conventional Commits v1.0.0 MUST rules and nothing more (the commitlint conventions\n * are warnings, never refusals); the confirmation lists the message and exactly the files\n * `git diff --cached --name-status` reports; an absent `IUserInteraction` is a cancellation — the\n * `/doctor repair` precedent — never a guess. Only after \"Yes\" does `git commit -m <subject>` run.\n */\nimport { confirmAction, isConfirmed, textAction } from '@robota-sdk/agent-core';\n\nimport { gitFailureMessage } from './git-process.js';\nimport { parseStatusPorcelainV2, GIT_STATUS_ARGS } from './git-status.js';\n\nimport type { IGitProcessPort } from './git-process.js';\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nconst GIT_COMMIT_CONVENTIONAL_TYPES: readonly string[] = [\n 'build',\n 'chore',\n 'ci',\n 'docs',\n 'feat',\n 'fix',\n 'perf',\n 'refactor',\n 'revert',\n 'style',\n 'test',\n];\nconst GIT_COMMIT_SUBJECT_LIMIT = 72;\n\nexport type TConventionalSubjectCheck =\n { ok: true; warnings: readonly string[] } | { ok: false; reason: string };\n\n/** `<type>[(scope)][!]: <description>` — the MUST rules, and only those. */\nconst CONVENTIONAL_SUBJECT = /^([^\\s():!]+)(\\(([^\\s()]+)\\))?(!)?: (.*)$/;\n\nexport function validateConventionalSubject(subject: string): TConventionalSubjectCheck {\n if (subject.trim().length === 0) return { ok: false, reason: 'the subject is empty' };\n const separator = subject.indexOf(': ');\n if (separator === -1) {\n return {\n ok: false,\n reason:\n 'the subject has no `: ` type separator — the form is `<type>[(scope)][!]: <description>`',\n };\n }\n const match = CONVENTIONAL_SUBJECT.exec(subject);\n if (!match) {\n return {\n ok: false,\n reason:\n 'the part before `: ` must be a type word with an optional `(scope)` and `!` — the form is `<type>[(scope)][!]: <description>`',\n };\n }\n const type = match[1] ?? '';\n const description = match[5] ?? '';\n if (description.trim().length === 0) {\n return { ok: false, reason: 'the description after `: ` is empty' };\n }\n const warnings: string[] = [];\n if (!GIT_COMMIT_CONVENTIONAL_TYPES.includes(type)) {\n warnings.push(\n `type \"${type}\" is not one of the conventional types (${GIT_COMMIT_CONVENTIONAL_TYPES.join(', ')})`,\n );\n }\n if (subject.length > GIT_COMMIT_SUBJECT_LIMIT) {\n warnings.push(\n `the subject is ${subject.length} characters; ${GIT_COMMIT_SUBJECT_LIMIT} is the conventional limit`,\n );\n }\n if (subject.endsWith('.')) warnings.push('the subject ends with a period');\n return { ok: true, warnings };\n}\n\n/** The inline subject: an optional leading `-m`, then one matching pair of outer quotes stripped. */\nexport function normalizeCommitSubject(args: string): string {\n let subject = args.trim();\n if (subject === '-m') return '';\n if (subject.startsWith('-m ')) subject = subject.slice('-m '.length).trim();\n if (\n subject.length >= 2 &&\n (subject.startsWith('\"') || subject.startsWith(\"'\")) &&\n subject.endsWith(subject[0] ?? '')\n ) {\n subject = subject.slice(1, -1).trim();\n }\n return subject;\n}\n\nfunction cancelled(message: string): ICommandResult {\n return { success: false, message, data: { git: 'commit', committed: false } };\n}\n\nasync function askSubject(ui: IUserInteraction): Promise<string | undefined> {\n const response = await ui.ask(\n textAction('git-commit-subject', 'Commit message', {\n description: 'Conventional Commits form: <type>[(scope)][!]: <description>',\n placeholder: 'feat: describe the change',\n }),\n );\n if (response.type !== 'answer') return undefined;\n const text = response.text ?? response.values[0] ?? '';\n return normalizeCommitSubject(text);\n}\n\ntype TStagedCheck = { staged: true } | { staged: false; result: ICommandResult };\n\n/** Step 1 — the staged set decides everything; exit 1 means something is staged. */\nasync function checkStaged(port: IGitProcessPort, cwd: string): Promise<TStagedCheck> {\n const staged = await port.run(['diff', '--cached', '--quiet'], { cwd });\n if (staged.kind === 'failed' || (staged.exitCode !== 0 && staged.exitCode !== 1)) {\n return {\n staged: false,\n result: {\n success: false,\n message: gitFailureMessage('diff --cached', staged) ?? 'git failed',\n },\n };\n }\n if (staged.exitCode === 1) return { staged: true };\n const status = await port.run(GIT_STATUS_ARGS, { cwd });\n const failure = gitFailureMessage('status', status);\n if (failure !== undefined || status.kind !== 'exited') {\n return { staged: false, result: { success: false, message: failure ?? 'git status failed' } };\n }\n const summary = parseStatusPorcelainV2(status.stdout);\n return {\n staged: false,\n result: {\n success: false,\n message: `Nothing is staged (${summary.unstaged.length} unstaged, ${summary.untracked.length} untracked). Stage files with \\`git add\\` or \\`/shell git add ...\\` and run \\`/git commit\\` again.`,\n data: {\n git: 'commit',\n committed: false,\n unstaged: summary.unstaged.length,\n untracked: summary.untracked.length,\n },\n },\n };\n}\n\ntype TSubjectResolution = { subject: string } | { result: ICommandResult };\n\n/** Step 2 — the subject: inline, or asked for as free text; then the MUST rules. */\nasync function resolveSubject(\n args: string,\n ui: IUserInteraction | undefined,\n): Promise<TSubjectResolution> {\n let subject = normalizeCommitSubject(args);\n if (subject.length === 0) {\n if (ui === undefined) {\n return {\n result: cancelled(\n 'Commit cancelled: a commit message was needed and none could be asked for (no interactive session). Run `/git commit <subject>`.',\n ),\n };\n }\n const asked = await askSubject(ui);\n if (asked === undefined || asked.length === 0)\n return { result: cancelled('Commit cancelled.') };\n subject = asked;\n }\n return { subject };\n}\n\n/** Step 3 — what is confirmed is what is committed: the listing comes from git, not from a guess. */\nasync function confirmCommit(\n port: IGitProcessPort,\n cwd: string,\n subject: string,\n warnings: readonly string[],\n ui: IUserInteraction | undefined,\n): Promise<\n { confirmed: true; files: readonly string[] } | { confirmed: false; result: ICommandResult }\n> {\n if (ui === undefined) {\n return {\n confirmed: false,\n result: cancelled(\n 'Commit cancelled: a confirmation was needed and none could be asked for (no interactive session).',\n ),\n };\n }\n const listing = await port.run(['diff', '--cached', '--name-status'], { cwd });\n const listingFailure = gitFailureMessage('diff --cached --name-status', listing);\n if (listingFailure !== undefined || listing.kind !== 'exited') {\n return {\n confirmed: false,\n result: { success: false, message: listingFailure ?? 'git failed' },\n };\n }\n const files = listing.stdout\n .split('\\n')\n .filter((line) => line.length > 0)\n .map((line) => line.replace(/\\t/g, ' '));\n const description = [\n `Message: ${subject}`,\n ...warnings.map((warning) => `Warning: ${warning}`),\n `Staged (${files.length}):`,\n ...files.map((file) => ` ${file}`),\n ].join('\\n');\n const response = await ui.ask(\n confirmAction('git-commit', `Commit ${files.length} staged file(s)?`, {\n description,\n defaultYes: false,\n }),\n );\n if (!isConfirmed(response)) return { confirmed: false, result: cancelled('Commit cancelled.') };\n return { confirmed: true, files };\n}\n\nexport async function executeGitCommit(\n port: IGitProcessPort,\n cwd: string,\n args: string,\n ui: IUserInteraction | undefined,\n): Promise<ICommandResult> {\n const staged = await checkStaged(port, cwd);\n if (!staged.staged) return staged.result;\n\n const resolved = await resolveSubject(args, ui);\n if (!('subject' in resolved)) return resolved.result;\n const { subject } = resolved;\n const check = validateConventionalSubject(subject);\n if (!check.ok) {\n return {\n success: false,\n message: `Commit refused: ${check.reason}.`,\n data: { git: 'commit', committed: false, subject },\n };\n }\n\n const confirmation = await confirmCommit(port, cwd, subject, check.warnings, ui);\n if (!confirmation.confirmed) return confirmation.result;\n\n // Step 4 — exactly `commit -m <subject>`: never `-a`, never `add`.\n const commit = await port.run(['commit', '-m', subject], { cwd });\n const failure = gitFailureMessage('commit', commit);\n if (failure !== undefined || commit.kind !== 'exited') {\n return { success: false, message: failure ?? 'git commit failed' };\n }\n const firstLine = commit.stdout.split('\\n').find((line) => line.trim().length > 0) ?? '';\n return {\n success: true,\n message: `Committed: ${firstLine.length > 0 ? firstLine : subject}`,\n data: { git: 'commit', committed: true, subject, files: confirmation.files },\n };\n}\n","/**\n * BEHAVIOR-2437: `/git diff` — a closed grammar, not a pass-through for git flags.\n *\n * `/git diff` (unstaged) · `/git diff --staged` (index vs HEAD) · `/git diff <rev>` (worktree vs rev)\n * · `/git diff <a>..<b>` (two revisions), each optionally followed by `-- <path>…`. Every revision is\n * verified with `rev-parse --verify --quiet --end-of-options <rev>^{commit}` before any diff runs;\n * any other `-` token is refused, because a flag is exactly how an argv element becomes an option.\n * In the argv git receives, `--end-of-options` precedes every user revision and `--` every path.\n */\nimport { gitFailureMessage } from './git-process.js';\n\nimport type { IGitProcessPort } from './git-process.js';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport const GIT_DIFF_USAGE =\n 'Usage: /git diff [--staged | <rev> | <a>..<b>] [-- <path> ...] — other git flags are not accepted here.';\n\nexport type TGitDiffTarget =\n | { kind: 'worktree' }\n | { kind: 'staged' }\n | { kind: 'revision'; revision: string }\n | { kind: 'range'; from: string; to: string };\n\nexport interface IGitDiffArgs {\n target: TGitDiffTarget;\n paths: readonly string[];\n}\n\nexport type TParseGitDiffArgs = { ok: true; args: IGitDiffArgs } | { ok: false; message: string };\n\nfunction refuse(reason: string): TParseGitDiffArgs {\n return { ok: false, message: `${reason}\\n${GIT_DIFF_USAGE}` };\n}\n\nexport function parseGitDiffArgs(tokens: readonly string[]): TParseGitDiffArgs {\n const separator = tokens.indexOf('--');\n const head = separator === -1 ? tokens : tokens.slice(0, separator);\n const paths = separator === -1 ? [] : tokens.slice(separator + 1);\n if (separator !== -1 && paths.length === 0) return refuse('`--` must be followed by a path.');\n\n const flag = head.find((token) => token.startsWith('-') && token !== '--staged');\n if (flag !== undefined) return refuse(`\\`${flag}\\` is not accepted.`);\n if (head.length > 1) return refuse(`Too many arguments: ${head.join(' ')}.`);\n\n const token = head[0];\n if (token === undefined) return { ok: true, args: { target: { kind: 'worktree' }, paths } };\n if (token === '--staged') return { ok: true, args: { target: { kind: 'staged' }, paths } };\n if (token.includes('..')) {\n if (token.includes('...')) return refuse(`\\`${token}\\` is not a \\`<a>..<b>\\` range.`);\n const parts = token.split('..');\n const [from, to] = parts;\n if (parts.length !== 2 || !from || !to) {\n return refuse(`\\`${token}\\` is not a \\`<a>..<b>\\` range.`);\n }\n return { ok: true, args: { target: { kind: 'range', from, to }, paths } };\n }\n return { ok: true, args: { target: { kind: 'revision', revision: token }, paths } };\n}\n\n/** The revisions a target names, in the order they are verified. */\nfunction revisionsOf(target: TGitDiffTarget): readonly string[] {\n switch (target.kind) {\n case 'revision':\n return [target.revision];\n case 'range':\n return [target.from, target.to];\n default:\n return [];\n }\n}\n\n/** The `diff` argv for a parsed target, `--end-of-options` before revisions and `--` before paths. */\nexport function gitDiffArgv(args: IGitDiffArgs): readonly string[] {\n const argv = ['diff'];\n switch (args.target.kind) {\n case 'staged':\n argv.push('--staged');\n break;\n case 'revision':\n argv.push('--end-of-options', args.target.revision);\n break;\n case 'range':\n argv.push('--end-of-options', `${args.target.from}..${args.target.to}`);\n break;\n default:\n break;\n }\n if (args.paths.length > 0) argv.push('--', ...args.paths);\n return argv;\n}\n\nfunction gitRevParseArgv(revision: string): readonly string[] {\n return ['rev-parse', '--verify', '--quiet', '--end-of-options', `${revision}^{commit}`];\n}\n\nfunction tokenizeGitArgs(args: string): string[] {\n return args.split(/\\s+/).filter((token) => token.length > 0);\n}\n\nexport async function executeGitDiff(\n port: IGitProcessPort,\n cwd: string,\n args: string,\n): Promise<ICommandResult> {\n const parsed = parseGitDiffArgs(tokenizeGitArgs(args));\n if (!parsed.ok) return { success: false, message: parsed.message };\n\n for (const revision of revisionsOf(parsed.args.target)) {\n const outcome = await port.run(gitRevParseArgv(revision), { cwd });\n if (outcome.kind === 'failed') {\n return { success: false, message: gitFailureMessage('rev-parse', outcome) ?? 'git failed' };\n }\n if (outcome.exitCode !== 0) {\n return { success: false, message: `Unknown revision: ${revision}` };\n }\n }\n\n const outcome = await port.run(gitDiffArgv(parsed.args), { cwd });\n const failure = gitFailureMessage('diff', outcome);\n if (failure !== undefined || outcome.kind !== 'exited') {\n return { success: false, message: failure ?? 'git diff failed' };\n }\n const diff = outcome.stdout.replace(/\\n$/, '');\n return {\n success: true,\n message: diff.length > 0 ? diff : 'No differences.',\n data: { git: 'diff', target: parsed.args.target, paths: parsed.args.paths },\n };\n}\n","/**\n * BEHAVIOR-2437: `/git` — one command whose `execute` parses its verb (`status` | `diff` | `commit`),\n * with the three verbs on `subcommands` for `/help` and autocomplete. Host-only (`modelInvocable:\n * false`); the confirmation lives in the `commit` verb, because `requiresPermission` is not enforced\n * on the user path (`SystemCommandExecutor.executeCommand` calls `execute` directly).\n */\nimport { executeGitCommit } from './git-commit.js';\nimport { executeGitDiff } from './git-diff.js';\nimport { createGitProcess } from './git-process.js';\nimport { executeGitStatus } from './git-status.js';\n\nimport type { IGitProcessPort } from './git-process.js';\nimport type {\n ICommandHostUserInteraction,\n ICommandHostWorkspace,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandResult, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport const GIT_COMMAND_DESCRIPTION =\n 'Show the git status, view a diff, or commit the staged changes after confirming';\nexport const GIT_COMMAND_ARGUMENT_HINT =\n 'status | diff [--staged | <rev> | <a>..<b>] [-- <path> ...] | commit [<subject>]';\nexport const GIT_COMMAND_USAGE =\n 'Usage: /git status | /git diff [--staged | <rev> | <a>..<b>] [-- <path> ...] | /git commit [<subject>]';\n\nconst SOURCE = 'git';\n\nfunction verbEntry(name: string, description: string, argumentHint?: string): ICommand {\n return {\n name,\n description,\n source: SOURCE,\n modelInvocable: false,\n ...(argumentHint ? { argumentHint } : {}),\n };\n}\n\nexport function createGitCommandEntry(): ICommand {\n return {\n name: 'git',\n displayName: 'Git',\n description: GIT_COMMAND_DESCRIPTION,\n source: SOURCE,\n modelInvocable: false,\n argumentHint: GIT_COMMAND_ARGUMENT_HINT,\n subcommands: [\n verbEntry('status', 'Show the branch and the staged, unstaged and untracked paths'),\n verbEntry(\n 'diff',\n 'Show the unstaged diff, the staged diff, or a diff against one or two revisions',\n '[--staged | <rev> | <a>..<b>] [-- <path> ...]',\n ),\n verbEntry(\n 'commit',\n 'Commit the staged changes with a Conventional Commits subject, after confirming',\n '[<subject>]',\n ),\n ],\n };\n}\n\n/** What the verbs need from the host: the working directory and the ask-the-user port. */\nexport type TGitCommandContext = Pick<ICommandHostWorkspace, 'getCwd'> &\n ICommandHostUserInteraction;\n\nexport async function executeGitCommand(\n context: TGitCommandContext,\n args: string,\n port: IGitProcessPort = createGitProcess(),\n): Promise<ICommandResult> {\n const trimmed = args.trim();\n const split = trimmed.search(/\\s/);\n const verb = split === -1 ? trimmed : trimmed.slice(0, split);\n const rest = split === -1 ? '' : trimmed.slice(split + 1).trim();\n const cwd = context.getCwd();\n\n switch (verb) {\n case 'status':\n if (rest.length > 0) {\n return {\n success: false,\n message: `\\`/git status\\` takes no arguments.\\n${GIT_COMMAND_USAGE}`,\n };\n }\n return executeGitStatus(port, cwd);\n case 'diff':\n return executeGitDiff(port, cwd, rest);\n case 'commit':\n return executeGitCommit(port, cwd, rest, context.getUserInteraction());\n default:\n return {\n success: false,\n message:\n verb.length === 0\n ? GIT_COMMAND_USAGE\n : `Unknown /git verb \"${verb}\".\\n${GIT_COMMAND_USAGE}`,\n };\n }\n}\n\nfunction createGitSystemCommand(port: IGitProcessPort): ISystemCommand {\n const entry = createGitCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n argumentHint: entry.argumentHint,\n example: '/git status',\n subcommands: entry.subcommands,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'blocking',\n execute: (context, args) => executeGitCommand(context, args, port),\n };\n}\n\nexport class GitCommandSource implements ICommandSource {\n readonly name = SOURCE;\n\n getCommands(): ICommand[] {\n return [createGitCommandEntry()];\n }\n}\n\nexport interface IGitCommandModuleOptions {\n /** The process seam; the production `createGitProcess()` by default, injectable for tests. */\n port?: IGitProcessPort;\n}\n\nexport function createGitCommandModule(options: IGitCommandModuleOptions = {}): ICommandModule {\n return {\n name: 'agent-command-git',\n commandSources: [new GitCommandSource()],\n systemCommands: [createGitSystemCommand(options.port ?? createGitProcess())],\n };\n}\n","/**\n * GOAL-001: the `/goal` slash command. Assigns an autonomous objective the agent pursues across\n * turns until satisfied or a bound fires. Delegates to the framework-owned goal controller via the\n * command host context; all loop logic lives in agent-framework.\n */\n\nimport type { ICommandHostGoal } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IGoalState } from '@robota-sdk/agent-interface-session';\n\nexport const GOAL_COMMAND_DESCRIPTION =\n 'Assign an autonomous goal the agent pursues across turns until satisfied.';\n\nconst GOAL_COMMAND_USAGE =\n 'Usage:\\n /goal <objective> assign a goal and pursue it autonomously\\n' +\n ' /goal status show the current goal and progress\\n' +\n ' /goal cancel stop the current goal';\n\nfunction formatGoalState(goal: IGoalState): string {\n const lines = [\n `Goal: ${goal.objective}`,\n `Status: ${goal.status}${goal.stopReason ? ` (${goal.stopReason})` : ''}`,\n `Iterations: ${goal.iterations} / ${goal.maxIterations}`,\n ];\n const last = goal.progress[goal.progress.length - 1];\n if (last?.reason) lines.push(`Latest: ${last.reason}`);\n return lines.join('\\n');\n}\n\nexport async function executeGoalCommand(\n context: ICommandHostGoal,\n args: string,\n): Promise<ICommandResult> {\n const trimmed = args.trim();\n const verb = trimmed.split(/\\s+/)[0]?.toLowerCase() ?? '';\n\n if (trimmed.length === 0 || verb === 'help') {\n return { message: GOAL_COMMAND_USAGE, success: true };\n }\n\n if (verb === 'status') {\n const goal = context.getGoalState();\n return goal\n ? { message: formatGoalState(goal), success: true, data: { status: goal.status } }\n : { message: 'No goal is set.', success: true };\n }\n\n if (verb === 'cancel' || verb === 'stop') {\n const stopped = context.cancelGoal();\n return stopped\n ? { message: `Goal cancelled: ${stopped.objective}`, success: true }\n : { message: 'No active goal to cancel.', success: false };\n }\n\n let goal: IGoalState;\n try {\n goal = await context.setGoal(trimmed);\n } catch (error) {\n // allow-fallback: surface an invalid-objective error to the user as a failed command result, not a crash\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n return {\n message: `Goal set — pursuing autonomously (up to ${goal.maxIterations} iterations):\\n${goal.objective}`,\n success: true,\n data: { goalId: goal.id },\n };\n}\n","/**\n * GOAL-001: `/goal` command module registration.\n */\n\nimport { executeGoalCommand, GOAL_COMMAND_DESCRIPTION } from './goal-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createGoalCommandEntry(): ICommand {\n return {\n name: 'goal',\n displayName: 'Autonomous Goal',\n description: GOAL_COMMAND_DESCRIPTION,\n source: 'goal',\n // User-only: assigning an autonomous goal widens what the agent pursues without asking; the user sets it.\n modelInvocable: false,\n };\n}\n\nfunction createGoalSystemCommand(): ISystemCommand {\n const entry = createGoalCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeGoalCommand,\n };\n}\n\nexport class GoalCommandSource implements ICommandSource {\n readonly name = 'goal';\n\n getCommands(): ICommand[] {\n return [createGoalCommandEntry()];\n }\n}\n\nexport function createGoalCommandModule(): ICommandModule {\n return {\n name: 'agent-command-goal',\n commandSources: [new GoalCommandSource()],\n systemCommands: [createGoalSystemCommand()],\n };\n}\n","import type {\n ICommandHostAdapterAccess,\n ICommandHostAdapters,\n ICommandHostUserInteraction,\n IHandoffProgress,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\n/**\n * `/handoff` (HANDOFF-001, issue #1864) — move this session to another machine.\n *\n * The command holds no protocol. It reads an injected adapter and touches no transport, for the same\n * reason `/peers` does not: the carrier, the wire composition and the device identity are\n * composition-root concerns and must have one owner.\n *\n * ## What it is FOR, which is the consent\n *\n * A hand-off loses things on purpose — uncommitted working-tree changes and running subprocesses\n * stay on this machine, because moving them would make this a file-sync product and a process cannot\n * migrate at all. Those are the operator's to lose, so they are named in the prompt BEFORE the\n * question, not reported afterwards. A confirmation that did not mention them is not consent.\n *\n * ## The sentence it always ends on\n *\n * Every outcome that is not `done` says the session is still on this machine. That is not\n * reassurance: it is the one invariant the whole design exists to preserve, and the operator is the\n * person who has to know whether to keep typing here or walk to the other computer.\n */\n\ntype THandoffHost = ICommandHostAdapterAccess & Partial<ICommandHostUserInteraction>;\n\n/** The line that answers \"where is my session?\" — printed on every path, success included. */\nfunction whereIsIt(progress: IHandoffProgress): string {\n return progress.stillMine\n ? 'This session is still on this machine, and still yours to use.'\n : 'This session now belongs to the destination. This copy is read-only.';\n}\n\nfunction describeDestinations(\n destinations: readonly { readonly deviceId: string; readonly name?: string }[],\n): string {\n return destinations.map((d) => ` ${d.deviceId}${d.name ? ` ${d.name}` : ''}`).join('\\n');\n}\n\nfunction usage(): ICommandResult {\n return {\n success: true,\n message: [\n 'Usage:',\n ' /handoff list the machines this session could move to',\n ' /handoff <device-id> move it there, after confirming what stays behind',\n ].join('\\n'),\n };\n}\n\nexport async function executeHandoffCommand(\n context: THandoffHost,\n args: string,\n): Promise<ICommandResult> {\n const adapter: ICommandHostAdapters['handoff'] = context.getCommandHostAdapters?.().handoff;\n if (adapter === undefined) {\n // Said plainly rather than offered and then failed. A host with no carrier cannot move a\n // session, and a command that took the request anyway would spend the operator's attention\n // before telling them.\n return {\n success: false,\n message:\n 'This session has no hand-off carrier, so it cannot be moved to another machine. ' +\n 'Nothing changed — the session is still here.',\n };\n }\n\n const target = args.trim();\n if (target === '' || target === 'help') {\n const destinations = await adapter.destinations();\n if (destinations.length === 0) {\n return {\n success: true,\n message:\n 'No other machine is reachable for a hand-off right now.\\n' + whereIsIt(adapter.status()),\n };\n }\n return {\n success: true,\n message: [\n 'This session could move to:',\n describeDestinations(destinations),\n '',\n usage().message ?? '',\n ].join('\\n'),\n };\n }\n\n const destinations = await adapter.destinations();\n if (!destinations.some((d) => d.deviceId === target)) {\n return {\n success: false,\n message:\n `No reachable machine is called '${target}'.\\n` +\n (destinations.length > 0\n ? `Reachable now:\\n${describeDestinations(destinations)}`\n : 'None are reachable right now.') +\n `\\n${whereIsIt(adapter.status())}`,\n };\n }\n\n const staying = await adapter.staysBehind();\n const consequences = [\n staying.uncommittedChanges\n ? ' - uncommitted changes in the working tree stay on THIS machine'\n : null,\n staying.subprocesses > 0\n ? ` - ${staying.subprocesses} running process(es) stay on THIS machine and will not be reachable there`\n : null,\n ' - the destination uses ITS OWN provider credential; credentials are never transferred',\n ].filter((line): line is string => line !== null);\n\n const ask = context.getUserInteraction?.();\n if (ask === undefined) {\n // No human is attached. Refused, never guessed: a hand-off is irreversible from the source's\n // side, and \"nobody was there to say no\" is not a yes.\n return {\n success: false,\n message:\n 'A hand-off needs a person to confirm what stays behind, and no interactive session is ' +\n `attached.\\n${whereIsIt(adapter.status())}`,\n };\n }\n\n const answer = await ask.ask({\n id: `handoff:${target}`,\n title: `Move this session to ${target}?`,\n description: ['What will NOT travel:', ...consequences].join('\\n'),\n options: [\n { value: 'move', label: `Move it to ${target}` },\n { value: 'stay', label: 'Keep it here' },\n ],\n });\n if (answer.type !== 'answer' || !answer.values.includes('move')) {\n return {\n success: true,\n message: `Hand-off cancelled.\\n${whereIsIt(adapter.status())}`,\n };\n }\n\n const progressLines: string[] = [];\n const final = await adapter.transfer(target, (progress) => {\n progressLines.push(renderProgress(progress, target));\n });\n\n return {\n success: final.state === 'done',\n message: [\n ...progressLines,\n final.state === 'done'\n ? `Hand-off complete. ${target} is running this session now.`\n : `Hand-off stopped: ${final.reason ?? 'no reason was reported'}.`,\n whereIsIt(final),\n ].join('\\n'),\n };\n}\n\n/**\n * One progress line, in the operator's vocabulary.\n *\n * `awaiting-confirmation` is spelled out rather than shortened because it is the phase the operator\n * is most likely to interrupt: the payload is on the other machine and this one has not yet heard\n * that it is on disk there. Quitting here is safe, and the wording is what says so.\n */\nfunction renderProgress(progress: IHandoffProgress, target: string): string {\n // Exhaustive by construction: the default returns nothing rather than a plausible-looking line, so\n // a new state added to the contract shows up as a blank line in a test instead of as a wrong one.\n switch (progress.state) {\n case 'offered':\n return `Offering the session to ${target}...`;\n case 'sending':\n return 'Sending the session...';\n case 'awaiting-confirmation':\n return `Sent. Waiting for ${target} to confirm it has the session on disk — until it does, this machine keeps it.`;\n case 'done':\n return `${target} confirmed it has the session.`;\n case 'stopped':\n return `Stopped: ${progress.reason ?? 'no reason was reported'}.`;\n default:\n return '';\n }\n}\n","import { executeHandoffCommand } from './handoff-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createHandoffCommandEntry(): ICommand {\n return {\n name: 'handoff',\n displayName: 'Hand off',\n description: 'Move this session to another machine, after confirming what stays behind',\n source: 'handoff',\n // The model does not decide to give this session away. A hand-off moves AUTHORITY over the\n // operator's work to a different computer — it is a decision about where the person is sitting,\n // which is a fact about them and not about the task.\n // User-only: moves the session to another machine; the user decides where it lives.\n modelInvocable: false,\n };\n}\n\nfunction createHandoffSystemCommand(): ISystemCommand {\n const entry = createHandoffCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: (context, args) => executeHandoffCommand(context, args),\n };\n}\n\nexport class HandoffCommandSource implements ICommandSource {\n readonly name = 'handoff';\n\n getCommands(): ICommand[] {\n return [createHandoffCommandEntry()];\n }\n}\n\nexport function createHandoffCommandModule(): ICommandModule {\n return {\n name: 'agent-command-handoff',\n commandSources: [new HandoffCommandSource()],\n systemCommands: [createHandoffSystemCommand()],\n };\n}\n","import { formatCommandHelpMessage } from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostCatalog } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport function executeHelpCommand(context: ICommandHostCatalog, _args: string): ICommandResult {\n return {\n success: true,\n message: formatCommandHelpMessage(context),\n };\n}\n","import { HELP_COMMAND_DESCRIPTION } from '@robota-sdk/agent-framework';\n\nimport { executeHelpCommand } from './help-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createHelpCommandEntry(): ICommand {\n return {\n name: 'help',\n displayName: 'Help',\n description: HELP_COMMAND_DESCRIPTION,\n source: 'help',\n // User-only: a listing for the user; the model already sees the commands it may run.\n modelInvocable: false,\n };\n}\n\nfunction createHelpSystemCommand(): ISystemCommand {\n const entry = createHelpCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeHelpCommand,\n };\n}\n\nexport class HelpCommandSource implements ICommandSource {\n readonly name = 'help';\n\n getCommands(): ICommand[] {\n return [createHelpCommandEntry()];\n }\n}\n\nexport function createHelpCommandModule(): ICommandModule {\n return {\n name: 'agent-command-help',\n commandSources: [new HelpCommandSource()],\n systemCommands: [createHelpSystemCommand()],\n };\n}\n","import { resolveEditor } from '../editor/resolve-editor.js';\nimport { spawnInherited } from '../shell/spawn-inherited.js';\n\nimport type {\n ICommandHostTerminalHandoff,\n ICommandHostWorkspace,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandResult, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport interface IKeybindingsFilePort {\n ensureFile(): Promise<string>;\n}\n\nexport function createKeybindingsCommandEntry(): ICommand {\n return {\n name: 'keybindings',\n displayName: 'Keybindings',\n description: 'Open the contextual terminal keybindings file in $EDITOR',\n source: 'keybindings',\n // User-only: UI preference.\n modelInvocable: false,\n };\n}\n\nasync function executeKeybindingsCommand(\n file: IKeybindingsFilePort,\n context: ICommandHostTerminalHandoff & ICommandHostWorkspace,\n): Promise<ICommandResult> {\n if (!context.canHandoffTerminal()) {\n return { success: false, message: 'Keybindings editor is unavailable here.' };\n }\n const path = await file.ensureFile();\n const editor = resolveEditor();\n const exitCode = await context.runWithTerminal(() =>\n spawnInherited(editor.command, [...editor.args, path], context.getCwd()),\n );\n if (exitCode !== 0) {\n return {\n success: false,\n message: `Keybindings editor exited with code ${exitCode}.`,\n data: { path, exitCode },\n };\n }\n return { success: true, message: `Opened keybindings: ${path}`, data: { path } };\n}\n\nexport class KeybindingsCommandSource implements ICommandSource {\n readonly name = 'keybindings';\n\n getCommands(): ICommand[] {\n return [createKeybindingsCommandEntry()];\n }\n}\n\nexport function createKeybindingsCommandModule(file: IKeybindingsFilePort): ICommandModule {\n const entry = createKeybindingsCommandEntry();\n const command: ISystemCommand = {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: (context) => executeKeybindingsCommand(file, context),\n };\n return {\n name: 'agent-command-keybindings',\n commandSources: [new KeybindingsCommandSource()],\n systemCommands: [command],\n };\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport {\n buildLanguageCommandSubcommands,\n formatLanguageUsageMessage,\n parseLanguageArgument,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostUserInteraction } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\n/**\n * Ask the user to pick a language (CMD-004 inline ask). Returns a validated language, or `undefined`\n * when no interactive renderer is attached or the user cancelled — the caller then shows usage.\n */\nasync function resolveLanguageViaAsk(\n context: ICommandHostUserInteraction,\n): Promise<string | undefined> {\n const ui = context.getUserInteraction();\n if (!ui) return undefined;\n const options = buildLanguageCommandSubcommands().map((sub) => ({\n value: sub.name,\n label: sub.name,\n description: sub.description,\n }));\n const response = await ui.ask(selectAction('language', 'Select language', options));\n const picked = response.type === 'answer' ? response.values[0] : undefined;\n return picked === undefined ? undefined : parseLanguageArgument(picked);\n}\n\nexport async function executeLanguageCommand(\n context: ICommandHostUserInteraction,\n args: string,\n): Promise<ICommandResult> {\n let language = parseLanguageArgument(args);\n\n if (language === undefined) {\n language = await resolveLanguageViaAsk(context);\n if (language === undefined) {\n return {\n message: formatLanguageUsageMessage(),\n success: false,\n };\n }\n }\n\n return {\n message: `Language set to \"${language}\".`,\n success: true,\n data: { language },\n hostActions: [{ type: 'language-change', language }],\n };\n}\n","import {\n buildLanguageCommandSubcommands,\n LANGUAGE_COMMAND_ARGUMENT_HINT,\n LANGUAGE_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executeLanguageCommand } from './language-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createLanguageCommandEntry(): ICommand {\n return {\n name: 'language',\n displayName: 'Language',\n description: LANGUAGE_COMMAND_DESCRIPTION,\n source: 'language',\n argumentHint: LANGUAGE_COMMAND_ARGUMENT_HINT,\n subcommands: buildLanguageCommandSubcommands('language'),\n // User-only: the user's response-language preference.\n modelInvocable: false,\n };\n}\n\nfunction createLanguageSystemCommand(): ISystemCommand {\n const entry = createLanguageCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executeLanguageCommand,\n };\n}\n\nexport class LanguageCommandSource implements ICommandSource {\n readonly name = 'language';\n\n getCommands(): ICommand[] {\n return [createLanguageCommandEntry()];\n }\n}\n\nexport function createLanguageCommandModule(): ICommandModule {\n return {\n name: 'agent-command-language',\n commandSources: [new LanguageCommandSource()],\n systemCommands: [createLanguageSystemCommand()],\n };\n}\n","/**\n * What the MODEL is told about an MCP server it cannot use, and which user command fixes it.\n *\n * Fixed words only. A server's name comes from a definition a repository may write, so it is named\n * only when it is safe to paste into any shell; otherwise the notice stays generic and points at\n * `/mcp status`, where the user sees the name. Nothing a server or its definition returned — reason\n * text, endpoint, header or token — ever reaches these strings.\n *\n * The actions themselves (approving a server, signing in, trusting a workspace) are the user's: the\n * model can only suggest the command.\n */\n\nimport { shellArgumentForDisplay } from '@robota-sdk/agent-core';\n\n/** Why a server's tools are unavailable, as a user action that would fix it. */\nexport type TMCPUserAction = 'approve' | 'sign-in' | 'trust-workspace';\n\n/**\n * Where the user can act: `session` is an interactive session they can type a `/mcp` command into;\n * `terminal` is a run with no such prompt (print, serve), where sign-in is the terminal command.\n */\nexport type TMCPUserActionSurface = 'session' | 'terminal';\n\n/** The command the user runs for `action`; `<server>` stands for a name that cannot be shown. */\nexport function mcpUserActionCommand(\n serverId: string,\n action: TMCPUserAction,\n surface: TMCPUserActionSurface = 'session',\n): string {\n const name = shellArgumentForDisplay(serverId) ?? '<server>';\n switch (action) {\n case 'approve':\n return `/mcp approve ${name}`;\n case 'sign-in':\n return surface === 'terminal' ? `robota mcp login ${name}` : `/mcp login ${name}`;\n case 'trust-workspace':\n return 'robota trust';\n }\n}\n\nconst NEED: Record<TMCPUserAction, string> = {\n approve: 'is waiting for the user’s approval',\n 'sign-in': 'needs the user to sign in',\n 'trust-workspace': 'needs the user to trust this workspace',\n};\n\nfunction subject(serverId: string): string {\n const name = shellArgumentForDisplay(serverId);\n return name === undefined\n ? 'An MCP server (its name cannot be shown here; `/mcp status` lists it)'\n : `MCP server \"${name}\"`;\n}\n\n/** One server's notice: what is missing and the exact command to suggest. */\nexport function mcpUserActionNotice(\n serverId: string,\n action: TMCPUserAction,\n surface: TMCPUserActionSurface = 'session',\n): string {\n const inTerminal =\n action === 'trust-workspace' || (action === 'sign-in' && surface === 'terminal');\n const where = inTerminal ? ' in a terminal, then restart the session' : '';\n return (\n `${subject(serverId)} ${NEED[action]}, so its tools are unavailable. You cannot do this ` +\n `yourself; ask the user to run \\`${mcpUserActionCommand(serverId, action, surface)}\\`${where}.`\n );\n}\n\n/**\n * The notice for every server that could not start for a reason the user can fix, or `undefined`\n * when there is none. Meant for the model's context at session start.\n */\nexport function mcpUnavailableServersNotice(\n servers: ReadonlyMap<string, TMCPUserAction>,\n): string | undefined {\n if (servers.size === 0) return undefined;\n const lines = [...servers].map(\n ([serverId, action]) => `- ${mcpUserActionNotice(serverId, action)}`,\n );\n return [\n 'MCP servers that did not start this session. Mention this only when the user needs one of ' +\n 'these servers or its tools:',\n ...lines,\n ].join('\\n');\n}\n","/**\n * `/mcp status` as the MODEL receives it: names, states and the user command that would fix a\n * server — nothing else.\n *\n * The user's view carries each definition's reason text, source, provenance, fingerprint and\n * security identity. None of that helps the model decide what to suggest, and some of it is\n * definition-derived text a repository wrote, so the model's view is rebuilt from fixed words\n * rather than filtered from the user's. A name that is not safe to show is replaced, never quoted.\n */\n\nimport { shellArgumentForDisplay } from '@robota-sdk/agent-core';\n\nimport { mcpUserActionCommand } from './mcp-model-notice.js';\n\nimport type { TMCPUserAction, TMCPUserActionSurface } from './mcp-model-notice.js';\nimport type {\n ICommandMCPActivationAdapter,\n ICommandMCPActivationSummary,\n ICommandMCPOAuthStatus,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\ntype TOAuthState = ICommandMCPOAuthStatus['state'];\n\nfunction userActionFor(\n status: ICommandMCPActivationSummary['status'],\n oauth: TOAuthState | undefined,\n): TMCPUserAction | undefined {\n if (status === 'pending' || status === 'stale') return 'approve';\n if (status === 'untrusted') return 'trust-workspace';\n if (status === 'approved' && (oauth === 'sign-in-required' || oauth === 'signed-out')) {\n return 'sign-in';\n }\n // `rejected` and `revoked` are decisions the user already made; there is nothing to suggest.\n return undefined;\n}\n\ninterface IModelServerView {\n readonly name?: string;\n readonly status: ICommandMCPActivationSummary['status'];\n readonly oauth?: TOAuthState;\n readonly suggestCommand?: string;\n}\n\nfunction toModelView(\n summary: ICommandMCPActivationSummary,\n oauth: TOAuthState | undefined,\n surface: TMCPUserActionSurface,\n): IModelServerView {\n const name = shellArgumentForDisplay(summary.serverId);\n const action = userActionFor(summary.status, oauth);\n return {\n ...(name === undefined ? {} : { name }),\n status: summary.status,\n ...(oauth === undefined ? {} : { oauth }),\n ...(action === undefined\n ? {}\n : { suggestCommand: mcpUserActionCommand(summary.serverId, action, surface) }),\n };\n}\n\nfunction formatLine(view: IModelServerView): string {\n const name = view.name ?? '(name not shown)';\n const signIn = view.oauth === undefined ? '' : ` — sign-in: ${view.oauth}`;\n const suggest =\n view.suggestCommand === undefined ? '' : ` — ask the user to run \\`${view.suggestCommand}\\``;\n return ` ${name} — ${view.status}${signIn}${suggest}`;\n}\n\nexport async function mcpModelStatusResult(\n mcp: ICommandMCPActivationAdapter | undefined,\n): Promise<ICommandResult> {\n if (!mcp) {\n return { message: 'MCP is not available in this environment.', success: true };\n }\n const oauthStates = new Map(\n ((await mcp.oauthStatus?.()) ?? []).map((status) => [status.serverId, status.state]),\n );\n const servers = mcp\n .list()\n .map((summary) =>\n toModelView(summary, oauthStates.get(summary.serverId), mcp.userActionSurface ?? 'session'),\n );\n const unreadableSources = (mcp.sourceProblems?.() ?? []).length;\n const lines =\n servers.length === 0\n ? ['No MCP servers are configured.']\n : ['MCP servers:', ...servers.map(formatLine)];\n if (unreadableSources > 0) {\n lines.push(\n `${unreadableSources} MCP configuration source(s) could not be read; the user can see which with \\`/mcp status\\`.`,\n );\n }\n return {\n message: lines.join('\\n'),\n success: true,\n data: { servers, unreadableSources },\n };\n}\n","import { shellArgumentForDisplay } from '@robota-sdk/agent-core';\n\nimport { mcpModelStatusResult } from './mcp-model-status.js';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostSessionAccess,\n ICommandHostUserInteraction,\n ICommandHostWorkspace,\n ICommandMCPActivationAdapter,\n ICommandMCPActivationSummary,\n ICommandMCPOAuthLoginRequest,\n ICommandMCPOAuthLoginResult,\n ICommandMCPOAuthLogoutResult,\n ICommandMCPOAuthStatus,\n ICommandMCPSourceProblem,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nfunction adapter(context: ICommandHostAdapterAccess): ICommandMCPActivationAdapter | undefined {\n return context.getCommandHostAdapters?.().mcpActivation;\n}\n\nconst OAUTH_STATE_LABEL: Record<ICommandMCPOAuthStatus['state'], string> = {\n 'signed-in': 'signed in',\n 'expired-refreshable': 'token expired, will refresh',\n 'sign-in-required': 'sign-in required',\n 'signed-out': 'signed out',\n};\n\nconst TOKEN_LABEL = { refresh_token: 'refresh token', access_token: 'access token' } as const;\n\n/** What revocation did, by fixed words and reasons only. */\nfunction revocationText(result: ICommandMCPOAuthLogoutResult): string {\n const failure = result.revocationFailure ?? 'revocation-failed';\n switch (result.revocation) {\n case 'revoked':\n return 'the tokens were revoked';\n case 'not-attempted':\n return 'there were no tokens to revoke';\n case 'unsupported':\n return 'the authorization server offers no token revocation; the tokens stay valid until they expire';\n case 'failed':\n return `token revocation failed (${failure}); the tokens stay valid until they expire`;\n case 'partial':\n return (result.tokens ?? [])\n .map((token) =>\n token.revoked\n ? `the ${TOKEN_LABEL[token.token]} was revoked`\n : `the ${TOKEN_LABEL[token.token]} was not (${token.failure ?? 'revocation-failed'}) and stays valid until it expires`,\n )\n .join('; ');\n }\n}\n\nconst USAGE =\n 'Usage: /mcp [status] | /mcp <approve|reject|revoke|logout> <serverId> | /mcp login <serverId> [--no-browser]';\nconst LOGIN_USAGE = 'Usage: /mcp login <serverId> [--no-browser]';\n\n/**\n * A server's name as a command argument. It comes from a definition a repository may write, so it\n * is shown only when it is safe to paste into any shell; otherwise `<server>` stands in for it.\n */\nfunction serverArgument(serverId: string): string {\n return shellArgumentForDisplay(serverId) ?? '<server>';\n}\n\n/** How to sign in to one server: in this session, or from a terminal. */\nfunction signInHint(serverId: string): string {\n const argument = serverArgument(serverId);\n const how = `run /mcp login ${argument}, or robota mcp login ${argument} in a terminal`;\n return shellArgumentForDisplay(serverId) === undefined\n ? ` (${how}; its name cannot be shown safely here)`\n : ` (${how})`;\n}\n\nfunction formatSummary(\n summary: ICommandMCPActivationSummary,\n oauth: ICommandMCPOAuthStatus['state'] | undefined,\n): string {\n const label = summary.displayName ? ` (${summary.displayName})` : '';\n // A fixed word per state: nothing token-derived ever reaches this line.\n const signIn =\n oauth === undefined\n ? ''\n : ` — OAuth: ${OAUTH_STATE_LABEL[oauth]}${oauth === 'sign-in-required' || oauth === 'signed-out' ? signInHint(summary.serverId) : ''}`;\n return ` ${summary.serverId}${label} — ${summary.status} — ${summary.source} — ${summary.reason}${signIn}`;\n}\n\n/**\n * Issue #2794: a source that produced no server names at all — \"which file could not be read\".\n *\n * `blockedServerNames` (PR #3076 review): a managed-tier problem also blocked every lower-tier\n * server that would otherwise have resolved — those names never appear in `list()` above (an\n * `unresolved` entry is never an activation candidate), so this line is the ONLY place `/mcp status`\n * says they exist at all and why they are not active.\n */\nfunction formatSourceProblem(problem: ICommandMCPSourceProblem): string {\n const blocked = problem.blockedServerNames ?? [];\n const blockedNote = blocked.length === 0 ? '' : ` Blocked until fixed: ${blocked.join(', ')}.`;\n return ` ${problem.source} (${problem.origin}) could not be read: ${problem.reason}.${blockedNote}`;\n}\n\nasync function oauthStates(\n mcp: ICommandMCPActivationAdapter,\n): Promise<ReadonlyMap<string, ICommandMCPOAuthStatus['state']>> {\n const states = (await mcp.oauthStatus?.()) ?? [];\n return new Map(states.map((status) => [status.serverId, status.state]));\n}\n\nasync function listResult(mcp: ICommandMCPActivationAdapter | undefined): Promise<ICommandResult> {\n if (!mcp) {\n return {\n message: 'MCP activation management is not available in this environment.',\n success: true,\n };\n }\n const entries = mcp.list();\n const oauth = await oauthStates(mcp);\n // A source-scoped problem (issue #2794) names no server, so it never appears in `entries` — it is\n // reported beside them rather than folded into the \"no servers\" branch, which would otherwise say\n // nothing while a managed policy sits unreadable.\n const sourceProblems = mcp.sourceProblems?.() ?? [];\n const sourceProblemLines =\n sourceProblems.length === 0\n ? []\n : [`MCP source problems:\\n${sourceProblems.map(formatSourceProblem).join('\\n')}`];\n\n if (entries.length === 0) {\n return {\n message:\n sourceProblemLines.length === 0\n ? 'No MCP definitions are registered.'\n : sourceProblemLines[0]!,\n success: true,\n data: { servers: [], sourceProblems },\n };\n }\n return {\n message: [\n `MCP activation status:\\n${entries\n .map((entry) => formatSummary(entry, oauth.get(entry.serverId)))\n .join('\\n')}`,\n ...sourceProblemLines,\n ].join('\\n\\n'),\n success: true,\n data: {\n servers: entries.map((entry) => ({\n serverId: entry.serverId,\n source: entry.source,\n status: entry.status,\n allowed: entry.allowed,\n provenanceId: entry.provenanceId,\n definitionFingerprint: entry.definitionFingerprint,\n securityIdentity: entry.securityIdentity,\n ...(oauth.has(entry.serverId) ? { oauth: oauth.get(entry.serverId) } : {}),\n })),\n sourceProblems,\n },\n };\n}\n\n/** What `/mcp` reaches: its port, and — to sign in — the live session and the user. */\nexport type TMCPActivationCommandContext = ICommandHostAdapterAccess &\n Pick<ICommandHostSessionAccess, 'getSession'> &\n ICommandHostUserInteraction &\n Partial<Pick<ICommandHostWorkspace, 'getCommandInvocationSource'>>;\n\nexport async function executeMCPActivationCommand(\n context: TMCPActivationCommandContext,\n args: string,\n): Promise<ICommandResult> {\n const trimmed = args.trim();\n const spaceAt = trimmed.indexOf(' ');\n const verb = (spaceAt === -1 ? trimmed : trimmed.slice(0, spaceAt)).toLowerCase();\n const serverId = spaceAt === -1 ? '' : trimmed.slice(spaceAt + 1).trim();\n\n if (verb === '' || verb === 'status' || verb === 'list') {\n // The full view only for a caller known to be a person; an unknown caller gets the model's view.\n const source = context.getCommandInvocationSource?.();\n return source === 'user' || source === 'remote'\n ? listResult(adapter(context))\n : mcpModelStatusResult(adapter(context));\n }\n if (verb === 'login') return loginResult(context, serverId);\n\n if (verb !== 'approve' && verb !== 'reject' && verb !== 'revoke' && verb !== 'logout') {\n return { message: `Unknown argument. ${USAGE}`, success: false };\n }\n if (!serverId) {\n return {\n message: `Usage: /mcp ${verb} <serverId>`,\n success: false,\n };\n }\n\n const mcp = adapter(context);\n if (!mcp) {\n return {\n message: 'MCP activation management is not available in this environment.',\n success: true,\n };\n }\n if (verb === 'logout') return logoutResult(mcp, serverId);\n\n try {\n const result = await mcp[verb](serverId);\n return {\n message: `MCP server ${serverId} is now ${result.status}. ${result.reason}`,\n success:\n result.status === 'approved' || result.status === 'rejected' || result.status === 'revoked',\n data: {\n serverId: result.serverId,\n status: result.status,\n allowed: result.allowed,\n source: result.source,\n provenanceId: result.provenanceId,\n definitionFingerprint: result.definitionFingerprint,\n securityIdentity: result.securityIdentity,\n },\n };\n } catch (error) {\n return {\n message: error instanceof Error ? error.message : String(error),\n success: false,\n };\n }\n}\n\nasync function logoutResult(\n mcp: ICommandMCPActivationAdapter,\n serverId: string,\n): Promise<ICommandResult> {\n if (mcp.oauthLogout === undefined || (await oauthStates(mcp)).get(serverId) === undefined) {\n return { message: `MCP server ${serverId} does not declare OAuth.`, success: false };\n }\n let result: ICommandMCPOAuthLogoutResult;\n try {\n result = await mcp.oauthLogout(serverId);\n } catch {\n return { message: `Signing out of MCP server ${serverId} failed.`, success: false };\n }\n const signedOut = result.removed\n ? `Signed out of MCP server ${serverId}`\n : `MCP server ${serverId} was not signed in`;\n return {\n message: `${signedOut}; ${revocationText(result)}.`,\n success: true,\n data: { ...result },\n };\n}\n\nlet loginPrompts = 0;\n\n/** Before the browser opens: the URL it will show, and the choice to paste or cancel instead. */\nfunction browserConfirmer(\n context: ICommandHostUserInteraction,\n serverId: string,\n): ICommandMCPOAuthLoginRequest['confirmBrowser'] {\n const ui = context.getUserInteraction();\n if (ui === undefined) return undefined;\n return async (prompt) => {\n loginPrompts += 1;\n const answer = await ui.ask({\n id: `mcp-login-browser-${loginPrompts}`,\n title: `Sign in to MCP server ${serverArgument(serverId)}`,\n description:\n `Your browser will open this URL; if it does not, open it yourself:\\n${prompt.authorizationUrl}\\n\\n` +\n 'The sign-in completes on its own once you approve in the browser.',\n options: [\n { value: 'open', label: 'Open my browser' },\n { value: 'paste', label: 'Paste the redirect instead (browser on another machine)' },\n { value: 'cancel', label: 'Cancel' },\n ],\n maxSelect: 1,\n default: { values: ['open'] },\n });\n if (answer.type !== 'answer') return 'cancel';\n const choice = answer.values[0];\n return choice === 'open' || choice === 'paste' ? choice : 'cancel';\n };\n}\n\n/** Asks, through the session's own prompt, for the redirect URL the user's browser was sent to. */\nfunction redirectReader(\n context: ICommandHostUserInteraction,\n serverId: string,\n): ICommandMCPOAuthLoginRequest['readRedirect'] {\n const ui = context.getUserInteraction();\n if (ui === undefined) return undefined;\n return async (prompt) => {\n loginPrompts += 1;\n const answer = await ui.ask({\n id: `mcp-login-redirect-${loginPrompts}`,\n title: `Sign in to MCP server ${serverArgument(serverId)}`,\n description:\n `Open this URL in a browser:\\n${prompt.authorizationUrl}\\n\\n` +\n `After you approve, the browser is sent to ${prompt.redirectUri}, which may not load. ` +\n 'Copy the full address from its address bar and paste it here.',\n allowFreeText: true,\n masked: true,\n placeholder: 'Redirect URL (not shown)',\n });\n if (answer.type !== 'answer' || answer.text === undefined || answer.text.trim() === '') {\n throw new Error('No redirect URL was pasted.');\n }\n return answer.text;\n };\n}\n\n/** Why a sign-in did not complete, and what to run instead, by fixed words only. */\nfunction loginFailureText(result: ICommandMCPOAuthLoginResult): string {\n const { serverId, failure } = result;\n const argument = serverArgument(serverId);\n switch (failure) {\n case 'not-oauth':\n return `MCP server ${serverId} does not declare OAuth; there is nothing to sign in to.`;\n case 'url-unset':\n return `MCP server ${serverId} has an unset variable in its url.`;\n case 'sign-in-in-progress':\n return `A sign-in to MCP server ${serverId} is already in progress.`;\n case 'prompt-unavailable':\n return (\n 'Signing in without a browser needs the redirect URL pasted here, and nothing here can ask ' +\n `for it; run robota mcp login ${argument} --no-browser in a terminal.`\n );\n case 'browser-failed':\n return (\n `Sign-in to MCP server ${serverId} failed (browser-failed): no browser could be opened. ` +\n `Run /mcp login ${argument} --no-browser to paste the redirect instead.`\n );\n default: {\n const secret =\n failure === 'token-exchange-failed' && result.preRegisteredClient\n ? ` If its pre-registered client needs a secret, run robota mcp login ${argument} --client-secret in a terminal.`\n : '';\n return `Sign-in to MCP server ${serverId} failed (${failure ?? 'unexpected-error'}); nothing was changed.${secret}`;\n }\n }\n}\n\n/** What a completed sign-in did to this session. */\nfunction loginSuccessText(\n serverId: string,\n connection: ICommandMCPOAuthLoginResult['connection'],\n added: number,\n): string {\n switch (connection) {\n case 'connected':\n return added === 0\n ? `Signed in to MCP server ${serverId}; it is connected and offers no new tools.`\n : `Signed in to MCP server ${serverId}; ${added} of its tools ${added === 1 ? 'is' : 'are'} available from your next message.`;\n case 'recovered':\n return `Signed in to MCP server ${serverId}; its tools work again.`;\n case 'not-admitted':\n return `Signed in to MCP server ${serverId}, but it is not approved for this session (see /mcp status).`;\n default:\n return `Signed in to MCP server ${serverId}, but it could not connect in this session; the next session connects it.`;\n }\n}\n\nasync function loginResult(\n context: TMCPActivationCommandContext,\n rest: string,\n): Promise<ICommandResult> {\n const words = rest.split(/\\s+/).filter((word) => word !== '');\n const noBrowser = words.includes('--no-browser');\n const withSecret = words.includes('--client-secret');\n const positional = words.filter((word) => word !== '--no-browser' && word !== '--client-secret');\n const serverId = positional[0];\n if (positional.length !== 1 || serverId === undefined || serverId.startsWith('-')) {\n return { message: LOGIN_USAGE, success: false };\n }\n const argument = serverArgument(serverId);\n if (withSecret) {\n // A secret typed here would become part of the conversation; it is asked for only in a terminal.\n return {\n message:\n 'A client secret is never typed into a session. Run robota mcp login ' +\n `${argument} --client-secret in a terminal.`,\n success: false,\n };\n }\n const mcp = adapter(context);\n if (!mcp) {\n return {\n message: 'MCP activation management is not available in this environment.',\n success: true,\n };\n }\n if (mcp.oauthLogin === undefined) {\n return {\n message: `Signing in is not available in this session; run robota mcp login ${argument} in a terminal.`,\n success: false,\n };\n }\n // A dismissed prompt cancels the sign-in itself, not only the read it was for.\n const cancel = new AbortController();\n const readRedirect = redirectReader(context, serverId);\n const confirmBrowser = noBrowser ? undefined : browserConfirmer(context, serverId);\n const result = await mcp.oauthLogin({\n serverId,\n noBrowser,\n signal: cancel.signal,\n ...(readRedirect === undefined\n ? {}\n : {\n readRedirect: (prompt, signal) =>\n readRedirect(prompt, signal).catch((error: unknown) => {\n cancel.abort();\n throw error;\n }),\n }),\n ...(confirmBrowser === undefined\n ? {}\n : {\n confirmBrowser: async (prompt, signal) => {\n const choice = await confirmBrowser(prompt, signal);\n if (choice === 'cancel') cancel.abort();\n return choice;\n },\n }),\n });\n if (result.failure !== undefined) {\n return {\n message: loginFailureText(result),\n success: false,\n data: { serverId, failure: result.failure },\n };\n }\n const added = result.tools.length === 0 ? [] : await context.getSession().addTools(result.tools);\n if (result.tools.length > 0) mcp.oauthToolsAdded?.(serverId, added);\n const dropped = result.tools.length - added.length;\n const droppedText =\n dropped === 0\n ? ''\n : ` ${dropped} of its tools ${dropped === 1 ? 'was' : 'were'} left out: the session already has a tool by that name.`;\n return {\n message: `${loginSuccessText(serverId, result.connection, added.length)}${droppedText}`,\n success: true,\n data: {\n serverId,\n connection: result.connection ?? 'not-connected',\n tools: [...added],\n ...(dropped === 0 ? {} : { dropped }),\n },\n };\n}\n","import { executeMCPActivationCommand } from './mcp-activation-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createMCPActivationCommandEntry(): ICommand {\n return {\n name: 'mcp',\n displayName: 'MCP activation',\n description:\n \"Show each MCP server's trust approval and OAuth sign-in state, or change one server: \" +\n 'approve, reject or revoke its trust; sign in to it (login, which connects it in this ' +\n 'session) or out of it (logout). Use when an MCP server is not approved, needs a sign-in, or ' +\n 'should stop being used. Returns the status list, or what the one action did.',\n // Model-invocable for `status` only: when an MCP server's tools are missing or failing, the\n // model can see why and name the command the user should run. Approving, rejecting and revoking\n // a server are trust decisions and signing in or out is a credential action, so those stay\n // user-only — the model's `status` view also omits everything but names and states.\n modelDescription:\n 'Show which MCP servers are configured and why any of them is unavailable. Use it when an MCP ' +\n 'server or its tools are missing, a tool call reports that a server needs sign-in or approval, ' +\n 'or the user asks about MCP servers. Returns one line per server: its name, activation state, ' +\n 'sign-in state, and the command to suggest to the user when the server needs their approval, ' +\n 'sign-in or workspace trust. You cannot approve, sign in or sign out yourself.',\n argumentHint:\n '[status] | <approve|reject|revoke|logout> <server> | login <server> [--no-browser]',\n source: 'mcp-activation',\n modelInvocable: true,\n // The bare `/mcp` shows the status view, so choosing it from a menu runs it.\n runsBare: true,\n subcommands: [\n {\n name: 'status',\n description: 'Show every MCP server’s name, activation state and sign-in state',\n source: 'mcp-activation',\n modelInvocable: true,\n },\n ...(['approve', 'reject', 'revoke', 'login', 'logout'] as const).map((verb) => ({\n name: verb,\n description: USER_ONLY_VERB_DESCRIPTION[verb],\n argumentHint: verb === 'login' ? '<server> [--no-browser]' : '<server>',\n source: 'mcp-activation',\n modelInvocable: false,\n })),\n ],\n };\n}\n\nconst USER_ONLY_VERB_DESCRIPTION = {\n approve: 'Trust and activate an MCP server',\n reject: 'Refuse an MCP server',\n revoke: 'Withdraw an earlier approval',\n login: 'Sign in to an OAuth MCP server and connect it in this session',\n logout: 'Sign out of an OAuth MCP server and revoke its tokens',\n} as const;\n\nfunction createMCPActivationSystemCommand(): ISystemCommand {\n const entry = createMCPActivationCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n argumentHint: entry.argumentHint,\n ...(entry.subcommands !== undefined ? { subcommands: entry.subcommands } : {}),\n // Approve/reject/revoke/login/logout change trust or credentials, so the command is never read-only\n // for the user or a remote policy. The model can reach only `status` (its subcommand\n // allowlist), a read-only view, so its call needs no prompt.\n requiresPermission: true,\n modelRequiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n lifecycle: 'inline',\n execute: executeMCPActivationCommand,\n };\n}\n\nexport class MCPActivationCommandSource implements ICommandSource {\n readonly name = 'mcp-activation';\n\n getCommands(): ICommand[] {\n return [createMCPActivationCommandEntry()];\n }\n}\n\nexport function createMCPActivationCommandModule(): ICommandModule {\n return {\n name: 'agent-command-mcp-activation',\n commandSources: [new MCPActivationCommandSource()],\n systemCommands: [createMCPActivationSystemCommand()],\n };\n}\n","import {\n MEMORY_COMMAND_USAGE,\n approvePendingMemoryCandidate,\n createCommandMemoryStores,\n hasSensitiveCommandMemoryContent,\n isCommandMemoryType,\n listCommandUsedMemoryReferences,\n recordCommandMemoryEvent,\n} from '@robota-sdk/agent-framework';\n\nimport type {\n IAppendMemoryInput,\n ICommandHostMemory,\n ICommandHostWorkspace,\n IMemoryStore,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IMemoryEvent } from '@robota-sdk/agent-interface-session';\n\nconst SUBCOMMAND_INDEX = 0;\nconst TYPE_INDEX = 1;\nconst TOPIC_INDEX = 2;\nconst TEXT_START_INDEX = 3;\n\nfunction usage(): ICommandResult {\n return {\n message: MEMORY_COMMAND_USAGE,\n success: false,\n };\n}\n\nfunction formatError(error: Error | string): ICommandResult {\n return {\n message: error instanceof Error ? error.message : String(error),\n success: false,\n };\n}\n\nasync function formatList(store: IMemoryStore): Promise<ICommandResult> {\n const summary = await store.list();\n const topics =\n summary.topics.length > 0\n ? summary.topics.map((topic) => `- ${topic.name}: ${topic.path}`).join('\\n')\n : '(none)';\n\n return {\n message: [\n `Memory index: ${summary.indexPath}`,\n `Topics directory: ${summary.topicsPath}`,\n 'Topics:',\n topics,\n ].join('\\n'),\n success: true,\n data: {\n indexPath: summary.indexPath,\n topicsPath: summary.topicsPath,\n topicCount: summary.topics.length,\n },\n };\n}\n\nasync function formatShow(store: IMemoryStore, topic?: string): Promise<ICommandResult> {\n if (!topic || topic === 'index') {\n const memory = await store.loadStartupMemory();\n return {\n message: memory.content || '(empty memory index)',\n success: true,\n data: {\n path: memory.path,\n lineCount: memory.lineCount,\n truncated: memory.truncated,\n },\n };\n }\n\n const content = await store.readTopic(topic);\n return {\n message: content || `(empty memory topic: ${topic})`,\n success: true,\n data: { topic },\n };\n}\n\nfunction parseAdd(args: readonly string[]): IAppendMemoryInput | undefined {\n const type = args[TYPE_INDEX];\n const topic = args[TOPIC_INDEX];\n const text = args.slice(TEXT_START_INDEX).join(' ').trim();\n\n if (!type || !isCommandMemoryType(type) || !topic || text.length === 0) return undefined;\n return { type, topic, text };\n}\n\nasync function formatPending(store: IMemoryStore): Promise<ICommandResult> {\n const records = await store.listPending('pending');\n const lines =\n records.length > 0\n ? records.map(\n (record) =>\n `- ${record.id} ${record.type}/${record.topic} confidence=${record.confidence}: ${record.text}`,\n )\n : ['(no pending memory candidates)'];\n\n return {\n message: ['Pending memory candidates:', ...lines].join('\\n'),\n success: true,\n data: { count: records.length },\n };\n}\n\nfunction recordEvent(context: ICommandHostMemory, event: Omit<IMemoryEvent, 'at'>): void {\n recordCommandMemoryEvent(context, event);\n}\n\nasync function approvePending(\n context: ICommandHostMemory,\n store: IMemoryStore,\n id: string | undefined,\n): Promise<ICommandResult> {\n if (!id) return usage();\n try {\n const { record, saved } = await approvePendingMemoryCandidate(store, id);\n recordEvent(context, {\n type: 'memory_candidate_approved',\n candidateId: record.id,\n topic: record.topic,\n reason: 'approved-by-user',\n });\n recordEvent(context, {\n type: 'memory_candidate_saved',\n candidateId: record.id,\n topic: record.topic,\n reason: saved.deduplicated ? 'deduplicated' : 'approved-and-saved',\n });\n return {\n message: saved.deduplicated\n ? `Saved memory candidate ${id} was already present in ${saved.topicPath}`\n : `Saved memory candidate ${id} to ${saved.topicPath}`,\n success: true,\n data: {\n id,\n status: record.status,\n topic: saved.topic,\n topicPath: saved.topicPath,\n deduplicated: saved.deduplicated,\n },\n };\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nasync function rejectPending(\n context: ICommandHostMemory,\n store: IMemoryStore,\n id: string | undefined,\n): Promise<ICommandResult> {\n if (!id) return usage();\n try {\n const record = await store.markPending(id, 'rejected', 'rejected-by-user');\n recordEvent(context, {\n type: 'memory_candidate_rejected',\n candidateId: record.id,\n topic: record.topic,\n reason: 'rejected-by-user',\n });\n return {\n message: `Rejected memory candidate ${id}`,\n success: true,\n data: { id, status: record.status },\n };\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nfunction formatUsed(context: ICommandHostMemory): ICommandResult {\n const references = listCommandUsedMemoryReferences(context);\n const lines =\n references.length > 0\n ? references.map((reference) => {\n const suffix = reference.truncated ? ' truncated=true' : '';\n return `- ${reference.topic} score=${reference.score}${suffix}: ${reference.path}`;\n })\n : ['(no memory used in current turn)'];\n\n return {\n message: ['Used memory references:', ...lines].join('\\n'),\n success: true,\n data: { count: references.length, references: [...references] },\n };\n}\n\nexport async function executeMemoryCommand(\n context: ICommandHostMemory & ICommandHostWorkspace,\n rawArgs: string,\n): Promise<ICommandResult> {\n const args = rawArgs.trim().split(/\\s+/).filter(Boolean);\n const subcommand = args[SUBCOMMAND_INDEX] ?? 'list';\n // SELFHOST-008 P1R: the single injected durable-memory port (or fs default) — authoritative for all\n // `/memory` operations, so a surface that swaps the store is honored here too (no split-brain).\n const store = createCommandMemoryStores(context);\n\n if (subcommand === 'list') return formatList(store);\n if (subcommand === 'show') return formatShow(store, args[TYPE_INDEX]);\n if (subcommand === 'pending') return formatPending(store);\n if (subcommand === 'approve') return approvePending(context, store, args[TYPE_INDEX]);\n if (subcommand === 'reject') return rejectPending(context, store, args[TYPE_INDEX]);\n if (subcommand === 'used') return formatUsed(context);\n if (subcommand === 'add') {\n const input = parseAdd(args);\n if (!input) return usage();\n if (hasSensitiveCommandMemoryContent(input.text)) {\n return {\n message: 'Refusing to save sensitive memory content.',\n success: false,\n };\n }\n const result = await store.append(input);\n return {\n message: result.deduplicated\n ? `${input.type} memory already exists in ${result.topicPath}`\n : `Saved ${input.type} memory to ${result.topicPath}`,\n success: true,\n data: {\n indexPath: result.indexPath,\n topicPath: result.topicPath,\n topic: result.topic,\n deduplicated: result.deduplicated,\n },\n };\n }\n\n return usage();\n}\n","import {\n MEMORY_COMMAND_ARGUMENT_HINT,\n MEMORY_COMMAND_DESCRIPTION,\n buildMemoryCommandSubcommands,\n} from '@robota-sdk/agent-framework';\n\nimport { executeMemoryCommand } from './memory-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\n/**\n * Model-invocable: remembering and recalling project conventions is the model's own work. The\n * subcommand flags (in `buildMemoryCommandSubcommands`) keep `approve`/`reject` user-only, because\n * pending candidates exist so the user reviews what the model proposed to remember.\n */\nconst MEMORY_COMMAND_MODEL_DESCRIPTION =\n 'Read and write this project’s durable memory. Use `list` or `show [topic]` to look up stored ' +\n 'conventions, preferences or references before asking the user again; `add <type> <topic> <text>` ' +\n 'to save a durable preference, project convention, feedback item or reference worth reusing ' +\n 'across sessions (never secrets, credentials or transient facts); `pending` to see candidates ' +\n 'awaiting the user’s review; `used` to report which memory items informed this turn. Bare lists ' +\n 'topics. Returns the requested topics or entries, or a confirmation of what was saved. Approving ' +\n 'or rejecting a pending candidate is the user’s review: suggest `/memory approve <id>` or ' +\n '`/memory reject <id>`.';\n\nexport function createMemoryCommandEntry(): ICommand {\n return {\n name: 'memory',\n displayName: 'Memory',\n description: MEMORY_COMMAND_DESCRIPTION,\n modelDescription: MEMORY_COMMAND_MODEL_DESCRIPTION,\n source: 'memory',\n argumentHint: MEMORY_COMMAND_ARGUMENT_HINT,\n modelInvocable: true,\n safety: 'write',\n subcommands: buildMemoryCommandSubcommands(),\n };\n}\n\nfunction createMemorySystemCommand(): ISystemCommand {\n const entry = createMemoryCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n subcommands: entry.subcommands,\n execute: executeMemoryCommand,\n };\n}\n\nexport class MemoryCommandSource implements ICommandSource {\n readonly name = 'memory';\n\n getCommands(): ICommand[] {\n return [createMemoryCommandEntry()];\n }\n}\n\nexport function createMemoryCommandModule(): ICommandModule {\n return {\n name: 'agent-command-memory',\n commandSources: [new MemoryCommandSource()],\n systemCommands: [createMemorySystemCommand()],\n };\n}\n","import {\n formatCommandPermissionsMessage,\n formatInvalidPermissionModeMessage,\n isPermissionMode,\n parsePermissionModeArgument,\n readCommandPermissionsState,\n retryCommandPermissionDenial,\n writeCommandPermissionMode,\n} from '@robota-sdk/agent-framework';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostSessionAccess,\n} from '@robota-sdk/agent-framework';\nimport type { TPermissionMode } from '@robota-sdk/agent-core';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\n/** Switch the mode, or the refusal to show when the session will not enter it. */\nexport function tryWritePermissionMode(\n context: ICommandHostAdapterAccess & ICommandHostSessionAccess,\n mode: TPermissionMode,\n): ICommandResult | undefined {\n try {\n writeCommandPermissionMode(context, mode);\n return undefined;\n } catch (error) {\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n}\n\nfunction executeRetry(\n context: ICommandHostAdapterAccess & ICommandHostSessionAccess,\n args: string,\n): ICommandResult {\n const position = Number(args.trim().split(/\\s+/)[1]);\n const denial = retryCommandPermissionDenial(context, position);\n if (denial === undefined) {\n return {\n message:\n 'Usage: /permissions retry <n>, where <n> numbers a call blocked by the auto-mode ' +\n 'classifier in /permissions.',\n success: false,\n };\n }\n const call =\n denial.argument !== undefined ? `${denial.toolName}(${denial.argument})` : denial.toolName;\n return {\n message: `${call} will run once, without the classifier, when the model tries it again.`,\n success: true,\n };\n}\n\nexport function executePermissionsCommand(\n context: ICommandHostAdapterAccess & ICommandHostSessionAccess,\n args: string,\n): ICommandResult {\n const arg = parsePermissionModeArgument(args);\n if (arg === 'retry') return executeRetry(context, args);\n if (arg !== undefined) {\n if (!isPermissionMode(arg)) {\n return {\n message: formatInvalidPermissionModeMessage(),\n success: false,\n };\n }\n\n const refused = tryWritePermissionMode(context, arg);\n if (refused !== undefined) return refused;\n const state = readCommandPermissionsState(context);\n return {\n message: `Permission mode set to: ${arg}\\n${formatCommandPermissionsMessage(state)}`,\n success: true,\n data: {\n mode: state.mode,\n sessionAllowed: state.sessionAllowed,\n },\n };\n }\n\n const state = readCommandPermissionsState(context);\n return {\n message: formatCommandPermissionsMessage(state),\n success: true,\n data: {\n mode: state.mode,\n sessionAllowed: state.sessionAllowed,\n },\n };\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport {\n buildPermissionModeSubcommands,\n formatInvalidPermissionModeMessage,\n isPermissionMode,\n parsePermissionModeArgument,\n readCommandPermissionMode,\n} from '@robota-sdk/agent-framework';\n\nimport { tryWritePermissionMode } from '../permissions/permissions-command.js';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostSessionAccess,\n ICommandHostUserInteraction,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\n/**\n * Ask the user to pick a permission mode (CMD-004 inline ask). Returns the chosen mode name, or\n * `undefined` when no interactive renderer is attached or the user cancelled — the caller then reports\n * the current mode instead of changing it (never a silent guess).\n */\nasync function resolveModeViaAsk(\n context: ICommandHostUserInteraction,\n): Promise<string | undefined> {\n const ui = context.getUserInteraction();\n if (!ui) return undefined;\n const options = buildPermissionModeSubcommands().map((sub) => ({\n value: sub.name,\n label: sub.name,\n description: sub.description,\n }));\n const response = await ui.ask(selectAction('mode', 'Select interaction mode', options));\n return response.type === 'answer' ? response.values[0] : undefined;\n}\n\nexport async function executeModeCommand(\n context: ICommandHostAdapterAccess & ICommandHostSessionAccess & ICommandHostUserInteraction,\n args: string,\n): Promise<ICommandResult> {\n let arg: string | undefined = parsePermissionModeArgument(args);\n\n if (arg === undefined) {\n arg = await resolveModeViaAsk(context);\n if (arg === undefined) {\n // No interactive answer — report the current mode without changing it.\n const mode = readCommandPermissionMode(context);\n return { message: `Current mode: ${mode}`, success: true, data: { mode } };\n }\n }\n\n if (!isPermissionMode(arg)) {\n return {\n message: formatInvalidPermissionModeMessage(),\n success: false,\n };\n }\n\n const refused = tryWritePermissionMode(context, arg);\n if (refused !== undefined) return refused;\n return {\n message: `Permission mode set to: ${arg}`,\n success: true,\n data: { mode: arg },\n };\n}\n","import {\n buildPermissionModeSubcommands,\n PERMISSION_MODE_ARGUMENT_HINT,\n PERMISSION_MODE_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executeModeCommand } from './mode-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createModeCommandEntry(): ICommand {\n return {\n name: 'mode',\n displayName: 'Interaction Mode',\n description: PERMISSION_MODE_COMMAND_DESCRIPTION,\n source: 'mode',\n argumentHint: PERMISSION_MODE_ARGUMENT_HINT,\n subcommands: buildPermissionModeSubcommands('mode'),\n // User-only: changes the permission mode; permission widening is the user's.\n modelInvocable: false,\n };\n}\n\nfunction createModeSystemCommand(): ISystemCommand {\n const entry = createModeCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executeModeCommand,\n };\n}\n\nexport class ModeCommandSource implements ICommandSource {\n readonly name = 'mode';\n\n getCommands(): ICommand[] {\n return [createModeCommandEntry()];\n }\n}\n\nexport function createModeCommandModule(): ICommandModule {\n return {\n name: 'agent-command-mode',\n commandSources: [new ModeCommandSource()],\n systemCommands: [createModeSystemCommand()],\n };\n}\n","/**\n * `/sandbox`: see how shell commands are confined and change it (issue #3082).\n *\n * The OS sandbox is live — the choice applies to the next command — and is saved in the user\n * settings so the next session starts the same way.\n */\nimport { selectAction } from '@robota-sdk/agent-core';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostUserInteraction,\n ICommandSandboxStatus,\n TSandboxCommandMode,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport const SANDBOX_MODES: readonly {\n readonly mode: TSandboxCommandMode;\n readonly description: string;\n}[] = [\n { mode: 'auto-allow', description: 'Confine shell commands; confined ones run without a prompt' },\n { mode: 'regular', description: 'Confine shell commands; prompts work as usual' },\n { mode: 'off', description: 'Run shell commands on this machine, unconfined' },\n];\n\nfunction isSandboxMode(value: string): value is TSandboxCommandMode {\n return SANDBOX_MODES.some((entry) => entry.mode === value);\n}\n\nexport function formatSandboxStatus(status: ICommandSandboxStatus): string {\n const lines = [\n `Sandbox: ${status.mode}${status.backend !== undefined ? ` (${status.backend})` : ''}`,\n ];\n if (status.unavailable !== undefined) {\n lines.push(\n status.mode === 'off'\n ? `Not available here: ${status.unavailable}.`\n : `Cannot run here: ${status.unavailable}. Commands run unconfined.`,\n );\n }\n if (status.mode !== 'off' && status.unavailable === undefined) {\n lines.push(\n 'Writes are limited to the workspace and temp directories; settings and git hooks stay read-only.',\n `Network: ${status.network ? 'allowed' : 'blocked'}.`,\n );\n if (status.excludedCommands.length > 0) {\n lines.push(`Run unconfined: ${status.excludedCommands.join(', ')}.`);\n }\n }\n return lines.join('\\n');\n}\n\nasync function askForMode(\n context: ICommandHostUserInteraction,\n current: TSandboxCommandMode,\n): Promise<string | undefined> {\n const ui = context.getUserInteraction();\n if (!ui) return undefined;\n const options = SANDBOX_MODES.map(({ mode, description }) => ({\n value: mode,\n label: mode === current ? `${mode} (current)` : mode,\n description,\n }));\n const response = await ui.ask(selectAction('sandbox', 'Sandbox mode', options));\n return response.type === 'answer' ? response.values[0] : undefined;\n}\n\nexport async function executeSandboxCommand(\n context: ICommandHostAdapterAccess & ICommandHostUserInteraction,\n args: string,\n): Promise<ICommandResult> {\n const adapter = context.getCommandHostAdapters?.().sandbox;\n if (adapter === undefined) {\n return { message: 'This host has no OS sandbox.', success: false };\n }\n const before = adapter.status();\n const requested = args.trim().split(/\\s+/)[0] || (await askForMode(context, before.mode));\n if (requested === undefined || requested === '') {\n return { message: formatSandboxStatus(before), success: true, data: { ...before } };\n }\n if (!isSandboxMode(requested)) {\n return {\n message: `Unknown sandbox mode \"${requested}\". Valid: ${SANDBOX_MODES.map((entry) => entry.mode).join(' | ')}`,\n success: false,\n };\n }\n adapter.setMode(requested);\n const after = adapter.status();\n return {\n message: `Sandbox mode set to: ${requested}\\n${formatSandboxStatus(after)}`,\n success: true,\n data: { ...after },\n };\n}\n","import { executeSandboxCommand, SANDBOX_MODES } from './sandbox-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nconst DESCRIPTION = 'Show or change how shell commands are confined';\nconst ARGUMENT_HINT = SANDBOX_MODES.map((entry) => entry.mode).join(' | ');\n\nexport function createSandboxCommandEntry(): ICommand {\n return {\n name: 'sandbox',\n displayName: 'Sandbox',\n description: DESCRIPTION,\n source: 'sandbox',\n argumentHint: ARGUMENT_HINT,\n subcommands: SANDBOX_MODES.map(({ mode, description }) => ({\n name: mode,\n description,\n source: 'sandbox',\n })),\n // User-only: changes the sandbox boundary; permission widening is the user's.\n modelInvocable: false,\n };\n}\n\nfunction createSandboxSystemCommand(): ISystemCommand {\n const entry = createSandboxCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executeSandboxCommand,\n };\n}\n\nexport class SandboxCommandSource implements ICommandSource {\n readonly name = 'sandbox';\n\n getCommands(): ICommand[] {\n return [createSandboxCommandEntry()];\n }\n}\n\nexport function createSandboxCommandModule(): ICommandModule {\n return {\n name: 'agent-command-sandbox',\n commandSources: [new SandboxCommandSource()],\n systemCommands: [createSandboxSystemCommand()],\n };\n}\n","import { selectAction } from '@robota-sdk/agent-core';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostSessionAccess,\n ICommandHostUserInteraction,\n ICommandModule,\n ISystemCommand,\n ICommandOutputStyleRegistryAdapter,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandResult, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nconst OUTPUT_STYLE_DESCRIPTION = 'List or switch the active provider-neutral response style';\nconst OUTPUT_STYLE_ARGUMENT_HINT = 'list | <style-id>';\n\nfunction getRegistry(\n context: ICommandHostAdapterAccess,\n): ICommandOutputStyleRegistryAdapter | undefined {\n return context.getCommandHostAdapters?.().outputStyleRegistry;\n}\n\nfunction formatStyleList(active: string, registry: ICommandOutputStyleRegistryAdapter): string {\n const lines = registry.listOutputStyles().map((style) => {\n const marker = style.id === active ? '* ' : ' ';\n const cost = style.tokenCost ? ` [input cost: ${style.tokenCost}]` : '';\n return `${marker}${style.id} — ${style.name}: ${style.description}${cost}`;\n });\n return ['Available output styles:', ...lines].join('\\n');\n}\n\nfunction listResult(\n context: ICommandHostSessionAccess,\n registry: ICommandOutputStyleRegistryAdapter,\n): ICommandResult {\n const active = context.getActiveOutputStyleId();\n const outputStyles = registry.listOutputStyles();\n return {\n success: true,\n message: formatStyleList(active, registry),\n data: { outputStyles, active },\n };\n}\n\nasync function chooseStyle(\n context: ICommandHostUserInteraction,\n registry: ICommandOutputStyleRegistryAdapter,\n): Promise<string | undefined> {\n const interaction = context.getUserInteraction();\n if (!interaction) return undefined;\n const options = registry.listOutputStyles().map((style) => ({\n value: style.id,\n label: style.id,\n description: style.description,\n }));\n const response = await interaction.ask(\n selectAction('output-style', 'Select an output style', options),\n );\n return response.type === 'answer' ? response.values[0] : undefined;\n}\n\nexport async function executeOutputStyleCommand(\n context: ICommandHostAdapterAccess & ICommandHostSessionAccess & ICommandHostUserInteraction,\n args: string,\n): Promise<ICommandResult> {\n const registry = getRegistry(context);\n if (!registry) {\n return {\n success: false,\n message: 'Output styles are not available in this environment.',\n };\n }\n\n let styleId = args.trim();\n if (styleId === 'list') return listResult(context, registry);\n if (!styleId) {\n styleId = (await chooseStyle(context, registry)) ?? '';\n if (!styleId) return listResult(context, registry);\n }\n\n const style = registry.getOutputStyle(styleId);\n if (!style) {\n return {\n success: false,\n message: `Unknown output style \"${styleId}\". Available: ${\n registry\n .listOutputStyles()\n .map((entry) => entry.id)\n .join(', ') || '(none)'\n }`,\n };\n }\n\n return {\n success: true,\n message: `Switching output style to ${style.name}...`,\n data: { outputStyle: style.id },\n hostActions: [{ type: 'output-style-change', styleId: style.id }],\n };\n}\n\nexport function createOutputStyleCommandEntry(): ICommand {\n return {\n name: 'output-style',\n displayName: 'Output Style',\n description: OUTPUT_STYLE_DESCRIPTION,\n argumentHint: OUTPUT_STYLE_ARGUMENT_HINT,\n source: 'output-style',\n userInvocable: true,\n // User-only: the user's presentation preference.\n modelInvocable: false,\n };\n}\n\nfunction createOutputStyleSystemCommand(): ISystemCommand {\n const entry = createOutputStyleCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n argumentHint: entry.argumentHint,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeOutputStyleCommand,\n };\n}\n\nexport class OutputStyleCommandSource implements ICommandSource {\n readonly name = 'output-style';\n\n getCommands(): ICommand[] {\n return [createOutputStyleCommandEntry()];\n }\n}\n\nexport function createOutputStyleCommandModule(): ICommandModule {\n return {\n name: 'agent-command-output-style',\n commandSources: [new OutputStyleCommandSource()],\n systemCommands: [createOutputStyleSystemCommand()],\n };\n}\n","import type { ICommandHostAdapterAccess, ICommandHostAdapters } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\n/** One row as the port hands it over. Derived, so it cannot drift from the adapter it reads. */\ntype TPeerSummary = ReturnType<NonNullable<ICommandHostAdapters['localPeers']>['list']>[number];\n\n/**\n * `/peers` (PEER-004, #1863) — which other live sessions this one can address.\n *\n * Discovery landed as a leaf (a guarded rendezvous directory, an entry per live session, liveness\n * settled by pid AND process start time) and nothing called it: measured on this tree, no file\n * outside the module and its tests referenced `announcePeer` or `openLocalPeerRendezvous`. This\n * command is the surface that makes it observable, which is also what makes it falsifiable — a\n * discovery layer nobody can look at is one nobody can catch being wrong.\n *\n * The command reads an injected adapter and touches no filesystem, for the same reason it never\n * constructs a transport: the guarded directory, its permissions and the liveness rule are\n * composition-root concerns and must have one owner.\n */\n\n/** `dead` is not shown. An entry whose process is gone is debris, not a peer. */\nfunction addressable(peer: TPeerSummary): boolean {\n return peer.liveness !== 'dead';\n}\n\nfunction describe(peer: TPeerSummary, ownSessionId: string): string {\n const self = peer.sessionId === ownSessionId ? ' (this session)' : '';\n // `unknown` is printed, never rounded to `alive`. A host that cannot read process start times\n // answers `unknown` for every peer, and a reader who is not told that would take a stale entry for\n // a live session.\n const liveness = peer.liveness === 'unknown' ? ' liveness unknown' : '';\n const status = peer.status === 'needs-input' ? 'needs input' : (peer.status ?? 'unknown');\n return ` ${peer.sessionId}${peer.name ? ` ${peer.name}` : ''} status ${status}${self ? '' : workspace(peer)}${liveness}${self}`;\n}\n\n/** The relation this session verified. A claim it could not confirm is named as such, not shown. */\nfunction workspace(peer: TPeerSummary): string {\n if (peer.workspaceClaim === 'mismatched') return ' workspace claim mismatched, not believed';\n switch (peer.workspaceRelation) {\n case undefined:\n return '';\n case 'unknown':\n return ' workspace unknown';\n default:\n return ` ${peer.workspaceRelation.replace('-', ' ')}`;\n }\n}\n\n/**\n * PEER-006 — `/peers send <session-id> <text>`.\n *\n * Split on the FIRST run of whitespace only: everything after the session id is the message, spaces\n * and all. Splitting on every space would silently truncate any message with more than one word,\n * which is nearly all of them.\n */\nfunction parseSend(args: string): { target: string; text: string } | undefined {\n const trimmed = args.trim();\n const at = trimmed.search(/\\s/);\n if (at === -1) return undefined;\n const text = trimmed.slice(at).trim();\n if (text === '') return undefined;\n return { target: trimmed.slice(0, at), text };\n}\n\n/** A state the sender can act on, rendered as a sentence rather than a status word. */\nfunction describeSend(result: { state: string; reason?: string }, target: string): ICommandResult {\n const reason = result.reason !== undefined ? ` ${result.reason}` : '';\n switch (result.state) {\n case 'acknowledged':\n case 'delivered':\n return { message: `Delivered to ${target}.`, success: true };\n case 'pending':\n // NOT reported as delivered. The peer has it and has not run it — usually because a turn is\n // already running there — and telling the operator it landed would hide a wait they can see.\n return {\n message: `${target} has the message; it is waiting behind work already running there.`,\n success: true,\n };\n case 'duplicate':\n return { message: `${target} had already seen that message.`, success: true };\n default:\n return { message: `Not delivered to ${target}.${reason}`, success: false };\n }\n}\n\nasync function executeSend(\n adapter: NonNullable<ICommandHostAdapters['localPeers']>,\n args: string,\n): Promise<ICommandResult> {\n if (adapter.send === undefined) {\n return {\n message: 'This environment can discover other sessions but cannot address them.',\n success: false,\n };\n }\n const parsed = parseSend(args);\n if (parsed === undefined) {\n return {\n message: 'Usage: /peers send <session-id> <message>. Run /peers for the session ids.',\n success: false,\n };\n }\n return describeSend(await adapter.send(parsed.target, parsed.text), parsed.target);\n}\n\nexport async function executePeersCommand(\n context: ICommandHostAdapterAccess,\n args = '',\n): Promise<ICommandResult> {\n const adapter = context.getCommandHostAdapters?.().localPeers;\n if (!adapter) {\n return { message: 'Local peer discovery is not available in this environment.', success: true };\n }\n\n // `send` must be a WHOLE word: `startsWith('send')` would also claim a session id beginning with\n // those four letters, and a uuid that happens to start `send…` is not a subcommand.\n const trimmed = args.trim();\n const sendVerb = /^send(?=\\s|$)/.exec(trimmed);\n if (sendVerb !== null) return executeSend(adapter, trimmed.slice(sendVerb[0].length));\n\n const own = adapter.ownSessionId();\n // The workspace-judged listing when the host has one; it reads git, so only this view asks for it.\n const peers = (\n adapter.listWithWorkspace !== undefined ? await adapter.listWithWorkspace() : adapter.list()\n ).filter(addressable);\n const others = peers.filter((peer) => peer.sessionId !== own);\n\n if (others.length === 0) {\n return {\n message:\n 'No other live session is announced. Start a second session on this host, as this user, ' +\n 'and it appears here.',\n success: true,\n };\n }\n\n const lines = peers.map((peer) => describe(peer, own));\n return {\n message: `Live sessions:\\n${lines.join('\\n')}\\n\\nSend to one: /peers send <session-id> <message>`,\n success: true,\n };\n}\n","import { executePeersCommand } from './peers-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createPeersCommandEntry(): ICommand {\n return {\n name: 'peers',\n displayName: 'Peers',\n description: 'List the other live sessions on this host, or send one a message',\n source: 'peers',\n // The model does not enumerate the operator's other sessions. Discovery is an operator-facing\n // view of who is at the machine, which is a fact about the person and not about the task.\n // User-only: sends messages into other sessions; crossing a session boundary is the user's call.\n modelInvocable: false,\n };\n}\n\nfunction createPeersSystemCommand(): ISystemCommand {\n const entry = createPeersCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: (context, args) => executePeersCommand(context, args),\n };\n}\n\nexport class PeersCommandSource implements ICommandSource {\n readonly name = 'peers';\n\n getCommands(): ICommand[] {\n return [createPeersCommandEntry()];\n }\n}\n\nexport function createPeersCommandModule(): ICommandModule {\n return {\n name: 'agent-command-peers',\n commandSources: [new PeersCommandSource()],\n systemCommands: [createPeersSystemCommand()],\n };\n}\n","import {\n buildPermissionModeSubcommands,\n PERMISSION_MODE_ARGUMENT_HINT,\n PERMISSIONS_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executePermissionsCommand } from './permissions-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createPermissionsCommandEntry(): ICommand {\n return {\n name: 'permissions',\n displayName: 'Permissions',\n description: PERMISSIONS_COMMAND_DESCRIPTION,\n source: 'permissions',\n argumentHint: PERMISSION_MODE_ARGUMENT_HINT,\n subcommands: buildPermissionModeSubcommands('permissions'),\n // User-only: edits permission rules; permission widening is the user's.\n modelInvocable: false,\n };\n}\n\nfunction createPermissionsSystemCommand(): ISystemCommand {\n const entry = createPermissionsCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executePermissionsCommand,\n };\n}\n\nexport class PermissionsCommandSource implements ICommandSource {\n readonly name = 'permissions';\n\n getCommands(): ICommand[] {\n return [createPermissionsCommandEntry()];\n }\n}\n\nexport function createPermissionsCommandModule(): ICommandModule {\n return {\n name: 'agent-command-permissions',\n commandSources: [new PermissionsCommandSource()],\n systemCommands: [createPermissionsSystemCommand()],\n };\n}\n","/**\n * SELFHOST-002: the `/plan` slash command — explicit plan-mode (plan → review → approve → act).\n * Delegates to the framework-owned plan controller via the command host context; the phase machine\n * and the `setPermissionMode` application both live in agent-framework. The mutation block stays the\n * existing `plan` permission mode; approving flips to `acceptEdits` (edits auto-apply, shell stays\n * per-call confirmed).\n */\n\nimport type { ICommandHostPlan } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IPlanArtifact } from '@robota-sdk/agent-interface-session';\n\nexport const PLAN_COMMAND_DESCRIPTION =\n 'Draft a reviewable plan, then approve it to unblock edits (plan → review → approve → act).';\n\nconst PLAN_COMMAND_USAGE =\n 'Usage:\\n /plan <objective> draft a plan for review (stays read-only until approved)\\n' +\n ' /plan status show the current plan and phase\\n' +\n ' /plan approve approve the plan (edits auto-apply; shell stays confirmed)\\n' +\n ' /plan revert return to drafting (re-blocks edits)';\n\nfunction formatPlan(plan: IPlanArtifact): string {\n const lines = [\n `Plan: ${plan.objective}`,\n `Phase: ${plan.phase}${plan.approvedAt ? ` (approved ${plan.approvedAt})` : ''}`,\n ];\n plan.steps.forEach((step, index) => {\n lines.push(` ${index + 1}. [${step.status}] ${step.description}`);\n });\n return lines.join('\\n');\n}\n\nexport async function executePlanCommand(\n context: ICommandHostPlan,\n args: string,\n): Promise<ICommandResult> {\n const trimmed = args.trim();\n const verb = trimmed.split(/\\s+/)[0]?.toLowerCase() ?? '';\n\n if (trimmed.length === 0 || verb === 'help') {\n return { message: PLAN_COMMAND_USAGE, success: true };\n }\n\n if (verb === 'status') {\n const plan = context.getPlanState();\n return plan\n ? { message: formatPlan(plan), success: true, data: { phase: plan.phase } }\n : { message: 'No plan is active.', success: true };\n }\n\n if (verb === 'approve') {\n if (!context.getPlanState()) {\n return { message: 'No plan to approve. Start one with /plan <objective>.', success: false };\n }\n try {\n const plan = context.approvePlan();\n return {\n message: `Plan approved — edits will auto-apply; shell steps stay confirmed.\\nPhase: ${plan.phase}`,\n success: true,\n data: { phase: plan.phase },\n };\n } catch (error) {\n // allow-fallback: an out-of-phase approval surfaces as a failed command, not a crash\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n }\n\n if (verb === 'revert') {\n if (!context.getPlanState()) {\n return { message: 'No plan to revert.', success: false };\n }\n const plan = context.revertPlan();\n return {\n message: `Reverted to drafting — edits are blocked again (plan mode).\\nPhase: ${plan.phase}`,\n success: true,\n data: { phase: plan.phase },\n };\n }\n\n let plan: IPlanArtifact;\n try {\n plan = await context.setPlan(trimmed);\n } catch (error) {\n // allow-fallback: surface an invalid-objective error as a failed command result, not a crash\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n return {\n message: `Plan drafted (read-only until approved). Review it, then run /plan approve:\\n${plan.objective}`,\n success: true,\n data: { planId: plan.id },\n };\n}\n","/**\n * SELFHOST-002: `/plan` command module registration.\n */\n\nimport { executePlanCommand, PLAN_COMMAND_DESCRIPTION } from './plan-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createPlanCommandEntry(): ICommand {\n return {\n name: 'plan',\n displayName: 'Plan Mode',\n description: PLAN_COMMAND_DESCRIPTION,\n source: 'plan',\n // User-only: approving a plan unblocks edits; that permission change is the user's.\n modelInvocable: false,\n };\n}\n\nfunction createPlanSystemCommand(): ISystemCommand {\n const entry = createPlanCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executePlanCommand,\n };\n}\n\nexport class PlanCommandSource implements ICommandSource {\n readonly name = 'plan';\n\n getCommands(): ICommand[] {\n return [createPlanCommandEntry()];\n }\n}\n\nexport function createPlanCommandModule(): ICommandModule {\n return {\n name: 'agent-command-plan',\n commandSources: [new PlanCommandSource()],\n systemCommands: [createPlanSystemCommand()],\n };\n}\n","import {\n createShowPluginManagerIntent,\n resolvePluginCommandAdapter,\n} from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostAdapterAccess } from '@robota-sdk/agent-framework';\nimport type { ICommandPluginAdapter, ICommandResult } from '@robota-sdk/agent-interface-command';\n\nfunction getSubcommandParts(args: string): { subcommand: string; subArgs: string } {\n const parts = args\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n return {\n subcommand: parts[0] ?? '',\n subArgs: parts.slice(1).join(' ').trim(),\n };\n}\n\nfunction usage(message: string): ICommandResult {\n return {\n success: false,\n message,\n };\n}\n\nfunction getPluginAdapter(context: ICommandHostAdapterAccess): ICommandPluginAdapter | undefined {\n return resolvePluginCommandAdapter(context);\n}\n\nasync function executePluginOperation(\n context: ICommandHostAdapterAccess,\n operation: (adapter: ICommandPluginAdapter) => Promise<string>,\n): Promise<ICommandResult> {\n const adapter = getPluginAdapter(context);\n if (adapter === undefined) {\n return {\n success: false,\n message: 'Plugin management is not available.',\n };\n }\n\n try {\n return {\n success: true,\n message: await operation(adapter),\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Plugin error: ${message}`,\n };\n }\n}\n\nasync function executeMarketplaceCommand(\n context: ICommandHostAdapterAccess,\n subArgs: string,\n): Promise<ICommandResult> {\n const { subcommand, subArgs: marketplaceArgs } = getSubcommandParts(subArgs);\n\n if (subcommand === 'add' && marketplaceArgs.length > 0) {\n return executePluginOperation(context, async (adapter) => {\n const registeredName = await adapter.marketplaceAdd(marketplaceArgs);\n return `Added marketplace: \"${registeredName}\" (from ${marketplaceArgs})\\nInstall plugins with: /plugin install <name>@${registeredName}`;\n });\n }\n\n if (subcommand === 'remove' && marketplaceArgs.length > 0) {\n return executePluginOperation(context, async (adapter) => {\n await adapter.marketplaceRemove(marketplaceArgs);\n return `Removed marketplace \"${marketplaceArgs}\" and uninstalled its plugins.`;\n });\n }\n\n if (subcommand === 'update' && marketplaceArgs.length > 0) {\n return executePluginOperation(context, async (adapter) => {\n await adapter.marketplaceUpdate(marketplaceArgs);\n return `Updated marketplace \"${marketplaceArgs}\".`;\n });\n }\n\n if (subcommand === 'list') {\n return executePluginOperation(context, async (adapter) => {\n const sources = await adapter.marketplaceList();\n if (sources.length === 0) {\n return 'No marketplace sources configured.';\n }\n const lines = sources.map((source) => ` ${source.name} (${source.type})`);\n return `Marketplace sources:\\n${lines.join('\\n')}`;\n });\n }\n\n return usage('Usage: /plugin marketplace add <source> | remove <name> | update <name> | list');\n}\n\ntype TPluginIdOperation = (\n adapter: ICommandPluginAdapter,\n pluginId: string,\n) => Promise<string> | string;\n\nfunction executePluginIdOperation(\n context: ICommandHostAdapterAccess,\n pluginId: string,\n usageMessage: string,\n operation: TPluginIdOperation,\n): Promise<ICommandResult> {\n if (pluginId.length === 0) {\n return Promise.resolve(usage(usageMessage));\n }\n return executePluginOperation(context, (adapter) =>\n Promise.resolve(operation(adapter, pluginId)),\n );\n}\n\nfunction executePluginManager(): ICommandResult {\n return {\n success: true,\n message: 'Opening plugin manager...',\n uiIntents: [createShowPluginManagerIntent()],\n };\n}\n\nfunction executeInstallCommand(\n context: ICommandHostAdapterAccess,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin install <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.install(targetPluginId);\n return `Installed plugin: ${targetPluginId}`;\n },\n );\n}\n\nfunction executeUninstallCommand(\n context: ICommandHostAdapterAccess,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin uninstall <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.uninstall(targetPluginId);\n return `Uninstalled plugin: ${targetPluginId}`;\n },\n );\n}\n\nfunction executeEnableCommand(\n context: ICommandHostAdapterAccess,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin enable <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.enable(targetPluginId);\n return `Enabled plugin: ${targetPluginId}`;\n },\n );\n}\n\nfunction executeDisableCommand(\n context: ICommandHostAdapterAccess,\n pluginId: string,\n): Promise<ICommandResult> {\n return executePluginIdOperation(\n context,\n pluginId,\n 'Usage: /plugin disable <name>@<marketplace>',\n async (adapter, targetPluginId) => {\n await adapter.disable(targetPluginId);\n return `Disabled plugin: ${targetPluginId}`;\n },\n );\n}\n\nexport async function executePluginCommand(\n context: ICommandHostAdapterAccess,\n args: string,\n): Promise<ICommandResult> {\n const { subcommand, subArgs } = getSubcommandParts(args);\n switch (subcommand) {\n case '':\n case 'manage':\n return executePluginManager();\n case 'install':\n return executeInstallCommand(context, subArgs);\n case 'uninstall':\n return executeUninstallCommand(context, subArgs);\n case 'enable':\n return executeEnableCommand(context, subArgs);\n case 'disable':\n return executeDisableCommand(context, subArgs);\n case 'marketplace':\n return executeMarketplaceCommand(context, subArgs);\n default:\n return usage(`Unknown plugin subcommand: ${subcommand}`);\n }\n}\n\nexport async function executeReloadPluginsCommand(\n context: ICommandHostAdapterAccess,\n _args: string,\n): Promise<ICommandResult> {\n return executePluginOperation(context, async (adapter) => {\n const result = await adapter.reloadPlugins();\n const suffix =\n result.loadedPluginCount === 1\n ? '1 plugin resource'\n : `${result.loadedPluginCount} plugin resources`;\n return `Reloaded ${suffix}.`;\n }).then((result) => {\n if (!result.success) return result;\n // CMD-004 Stage E: the semantic reload already ran HOST-side above (`adapter.reloadPlugins()`);\n // the requester-local registry/autocomplete refresh rides the result as a data hint.\n return {\n ...result,\n data: { ...result.data, pluginRegistryReloaded: true },\n };\n });\n}\n","import {\n buildPluginCommandSubcommands,\n PLUGIN_COMMAND_ARGUMENT_HINT,\n PLUGIN_COMMAND_DESCRIPTION,\n RELOAD_PLUGINS_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executePluginCommand, executeReloadPluginsCommand } from './plugin-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createPluginCommandEntry(): ICommand {\n return {\n name: 'plugin',\n displayName: 'Plugins',\n description: PLUGIN_COMMAND_DESCRIPTION,\n source: 'plugin-manager',\n // User-only: installs and enables code; a trust decision.\n modelInvocable: false,\n argumentHint: PLUGIN_COMMAND_ARGUMENT_HINT,\n subcommands: buildPluginCommandSubcommands(),\n };\n}\n\nexport function createReloadPluginsCommandEntry(): ICommand {\n return {\n name: 'reload-plugins',\n displayName: 'Reload Plugins',\n description: RELOAD_PLUGINS_COMMAND_DESCRIPTION,\n source: 'plugin-manager',\n // User-only: reloading activates whatever plugin code is installed now; a trust decision.\n modelInvocable: false,\n };\n}\n\nfunction createPluginSystemCommand(): ISystemCommand {\n const entry = createPluginCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n subcommands: entry.subcommands,\n execute: executePluginCommand,\n };\n}\n\nfunction createReloadPluginsSystemCommand(): ISystemCommand {\n const entry = createReloadPluginsCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeReloadPluginsCommand,\n };\n}\n\nexport class PluginManagerCommandSource implements ICommandSource {\n readonly name = 'plugin-manager';\n\n getCommands(): ICommand[] {\n return [createPluginCommandEntry(), createReloadPluginsCommandEntry()];\n }\n}\n\nexport function createPluginCommandModule(): ICommandModule {\n return {\n name: 'agent-command-plugin',\n commandSources: [new PluginManagerCommandSource()],\n systemCommands: [createPluginSystemCommand(), createReloadPluginsSystemCommand()],\n };\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport { applyPresetToSession } from '@robota-sdk/agent-framework';\nimport { createPresetRegistry } from '@robota-sdk/agent-preset';\n\nimport type {\n ICommandHostAdapterAccess,\n ICommandHostPresetApplication,\n IPresetApplicationOptions,\n ICommandHostSessionAccess,\n ICommandHostUserInteraction,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IPresetSummary } from '@robota-sdk/agent-preset';\n\n/**\n * ARCH-009 — the registry `/preset` discovers through.\n *\n * The host supplies the instance it resolved with through the ADAPTER bag — the same path\n * `/permission-mode` and `/plugin` already take to their host capabilities. A host that supplies none\n * gets a fresh built-ins registry. That order is the point: while discovery read a module-global\n * registry directly, two products in one process shared one mutable list, so ARCH-008's per-instance\n * resolution was only half-true for an embedded host. A command runs with an `ICommandHostContext`\n * and nothing else, so the context is the only path from here to the instance the shell built.\n *\n * The fallback is deliberate rather than transitional, and it is no longer process state: a host that\n * never loads external presets has nothing to hand over, and `/preset` should still list the\n * built-ins. `createPresetRegistry()` with no argument is exactly that, constructed per call.\n */\n/**\n * What `/preset` actually needs from a registry — three members, no assertion.\n *\n * Narrower than `agent-preset`'s `IPresetRegistry` on purpose. Review of ARCH-009 reported the first\n * version reaching that contract with three casts, one of which (`listPresets()`) widened optional\n * `title`/`description` into required ones and would have printed `id — undefined: undefined` for a\n * host that typechecked. The fix is not a better cast: it is asking for the shape the command uses,\n * so both the built-in registry and a host adapter satisfy it STRUCTURALLY and nothing is asserted.\n *\n * `getPreset` returns `unknown` because presence is the whole question here.\n */\ninterface IPresetDiscovery {\n listPresets(): readonly IPresetSummary[];\n getPreset(id: string): unknown;\n resolvePreset(id: string, context?: unknown): IPresetApplicationOptions;\n}\n\nfunction presetRegistry(context: ICommandHostAdapterAccess): IPresetDiscovery {\n return context.getCommandHostAdapters?.().presetRegistry ?? createPresetRegistry();\n}\n\n/** Read the active preset id from the session, defaulting when the optional seam is absent. */\nfunction readActivePresetId(context: ICommandHostSessionAccess): string {\n return context.getSession().getActivePresetId();\n}\n\n/** Build the `/preset` listing: one line per preset, marking the active one with a `*` prefix. */\nfunction formatPresetList(active: string, registry: IPresetDiscovery): string {\n const lines = registry.listPresets().map((preset) => {\n const marker = preset.id === active ? '* ' : ' ';\n return `${marker}${preset.id} — ${preset.title}: ${preset.description}`;\n });\n return ['Available presets:', ...lines].join('\\n');\n}\n\n/** Build the rejection message for an unknown preset id, listing the valid ids. */\nfunction formatUnknownPresetMessage(id: string, registry: IPresetDiscovery): string {\n const ids = registry\n .listPresets()\n .map((preset) => preset.id)\n .join(', ');\n return `Unknown preset: ${id}. Available: ${ids}`;\n}\n\n/** The `/preset` (or `/preset list`) listing result. */\nfunction presetListResult(\n context: ICommandHostSessionAccess,\n registry: IPresetDiscovery,\n): ICommandResult {\n const active = readActivePresetId(context);\n return {\n message: formatPresetList(active, registry),\n success: true,\n data: { presets: registry.listPresets(), active },\n };\n}\n\n/**\n * Ask the user to pick a preset (CMD-004 inline ask). Returns the chosen id, or `undefined` when no\n * interactive renderer is attached or the user cancelled — the caller then shows the preset list.\n */\nasync function resolvePresetViaAsk(\n context: ICommandHostUserInteraction,\n registry: IPresetDiscovery,\n): Promise<string | undefined> {\n const ui = context.getUserInteraction();\n if (!ui) return undefined;\n const options = registry.listPresets().map((preset) => ({\n value: preset.id,\n label: preset.id,\n description: preset.description,\n }));\n const response = await ui.ask(selectAction('preset', 'Select a preset', options));\n return response.type === 'answer' ? response.values[0] : undefined;\n}\n\nexport async function executePresetCommand(\n context: ICommandHostPresetApplication &\n ICommandHostSessionAccess &\n ICommandHostUserInteraction &\n ICommandHostAdapterAccess,\n args: string,\n): Promise<ICommandResult> {\n // ARCH-009: resolved ONCE per invocation, so listing, lookup and resolution cannot disagree — a\n // host that swapped registries mid-command would otherwise report one set and apply another.\n const registry = presetRegistry(context);\n let id: string | undefined = args.trim().split(/\\s+/)[0];\n\n if (id === 'list') {\n return presetListResult(context, registry);\n }\n\n if (id === undefined || id.length === 0) {\n id = await resolvePresetViaAsk(context, registry);\n if (id === undefined) {\n return presetListResult(context, registry);\n }\n }\n\n if (registry.getPreset(id) === undefined) {\n return {\n message: formatUnknownPresetMessage(id, registry),\n success: false,\n };\n }\n\n const resolved = registry.resolvePreset(id);\n const result = await applyPresetToSession(context, id, resolved);\n // INFRA-032: surface any preset command-module name that matched no live module as a non-fatal\n // notice — an in-session `/preset` switch is no longer silent about a short form / typo.\n const noticeLines = result.unknownCommandModules.map(\n ({ name, kind }) =>\n `Preset command-module \"${name}\" (${kind}) matched no module — expected the agent-command-* form; ignored.`,\n );\n return {\n message: [`Switched to preset: ${id}`, ...noticeLines].join('\\n'),\n success: true,\n data: { preset: id, unknownCommandModules: result.unknownCommandModules },\n };\n}\n","import { createPresetRegistry } from '@robota-sdk/agent-preset';\n\nimport { executePresetCommand } from './preset-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nconst PRESET_COMMAND_DESCRIPTION = 'List presets or switch the active preset';\nconst PRESET_ARGUMENT_HINT = 'list | <preset-id>';\n\n/**\n * Build one subcommand per registered preset id (mirrors the permission-mode subcommands).\n *\n * ARCH-009 LIMIT, stated rather than left implicit: this lists the BUILT-INS, because it builds a\n * STATIC catalog entry at module-construction time and has no `ICommandHostContext` to reach a\n * host-supplied registry. `/preset`'s own execution — listing, lookup, resolution — goes through the\n * host's registry, so an embedded host with its own presets resolves and applies correctly; only the\n * pre-computed subcommand hints for tab-completion omit that host's external presets.\n *\n * What ARCH-009 changed here is what the limit COSTS. This used to read a process-wide mutable\n * registry, so the hints a host saw depended on which other host had loaded presets first. They are\n * now the built-ins and nothing else — wrong the same way for everyone, and never someone else's.\n *\n * Closing it needs the catalog to be built per host rather than per module, which is a change to how\n * command modules are constructed and not to this file. Filed separately.\n */\nfunction buildPresetSubcommands(source = 'preset'): ICommand[] {\n return createPresetRegistry()\n .listPresets()\n .map((preset) => ({\n name: preset.id,\n description: preset.description,\n source,\n }));\n}\n\nexport function createPresetCommandEntry(): ICommand {\n return {\n name: 'preset',\n displayName: 'Agent Preset',\n description: PRESET_COMMAND_DESCRIPTION,\n source: 'preset',\n argumentHint: PRESET_ARGUMENT_HINT,\n subcommands: buildPresetSubcommands('preset'),\n // User-only: a preset swaps tools, commands and permission posture; the user chooses it.\n modelInvocable: false,\n };\n}\n\nfunction createPresetSystemCommand(): ISystemCommand {\n const entry = createPresetCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executePresetCommand,\n };\n}\n\nexport class PresetCommandSource implements ICommandSource {\n readonly name = 'preset';\n\n getCommands(): ICommand[] {\n return [createPresetCommandEntry()];\n }\n}\n\nexport function createPresetCommandModule(): ICommandModule {\n return {\n name: 'agent-command-preset',\n commandSources: [new PresetCommandSource()],\n systemCommands: [createPresetSystemCommand()],\n };\n}\n","import { findProviderDefinition, formatSupportedProviderTypes } from '@robota-sdk/agent-core';\nimport { suggestProviderProfileName } from '@robota-sdk/agent-framework';\n\nimport type {\n IProviderDefinition,\n IProviderSetupHelpLink,\n IProviderSetupStepDefinition,\n TProviderSetupField,\n} from '@robota-sdk/agent-core';\nimport type { IProviderSetupInput } from '@robota-sdk/agent-framework';\n\nexport type TProviderSetupType = string;\nexport type TPromptInput = (label: string, masked?: boolean) => Promise<string>;\n\nexport interface IProviderSetupPromptStep extends IProviderSetupStepDefinition {\n key: TProviderSetupField;\n}\n\nexport interface IProviderSetupFlowState {\n type: TProviderSetupType;\n steps: readonly IProviderSetupPromptStep[];\n setupHelpLinks: readonly IProviderSetupHelpLink[];\n stepIndex: number;\n values: Partial<Record<TProviderSetupField, string>>;\n existingProfileNames: readonly string[];\n profileName?: string;\n setCurrent?: boolean;\n}\n\nexport interface IProviderSetupFlowOptions {\n existingProfileNames?: readonly string[];\n initialValues?: Partial<Record<TProviderSetupField, string>>;\n profileName?: string;\n setCurrent?: boolean;\n}\n\nexport type TProviderSetupFlowSubmitResult =\n | {\n status: 'next';\n state: IProviderSetupFlowState;\n }\n | {\n status: 'complete';\n input: IProviderSetupInput;\n }\n | {\n status: 'error';\n state: IProviderSetupFlowState;\n message: string;\n };\n\nexport function createProviderSetupFlow(\n type: TProviderSetupType,\n providerDefinitions: readonly IProviderDefinition[],\n options: IProviderSetupFlowOptions = {},\n): IProviderSetupFlowState {\n const definition = getProviderSetupDefinition(type, providerDefinitions);\n return {\n type,\n steps: applyProviderSetupInitialValues(\n getProviderSetupSteps(definition),\n options.initialValues,\n ),\n setupHelpLinks: definition.setupHelpLinks ?? [],\n stepIndex: 0,\n values: {},\n existingProfileNames: options.existingProfileNames ?? [],\n ...(options.profileName !== undefined ? { profileName: options.profileName } : {}),\n ...(options.setCurrent !== undefined ? { setCurrent: options.setCurrent } : {}),\n };\n}\n\nexport function formatProviderSetupSelectionPrompt(\n providerDefinitions: readonly IProviderDefinition[],\n): string {\n if (providerDefinitions.length === 0) {\n return ' No providers are available.';\n }\n const lines = [\n ' Select provider:',\n ...providerDefinitions.map(\n (definition, index) => ` ${index + 1}. ${formatProviderSetupChoiceLabel(definition)}`,\n ),\n ` Provider [1-${providerDefinitions.length}] (default: 1): `,\n ];\n return lines.join('\\n');\n}\n\nexport function resolveProviderSetupSelection(\n rawValue: string,\n providerDefinitions: readonly IProviderDefinition[],\n): TProviderSetupType {\n const value = rawValue.trim();\n const selectedValue = value.length > 0 ? value : '1';\n const index = parseProviderSelectionIndex(selectedValue);\n if (index !== undefined) {\n const definition = providerDefinitions[index];\n if (definition !== undefined) {\n return definition.type;\n }\n throw new Error(\n `Provider selection ${selectedValue} is out of range. Currently supported: ${formatSupportedProviderTypes(providerDefinitions)}`,\n );\n }\n const definition = findProviderDefinition(providerDefinitions, selectedValue);\n if (definition === undefined) {\n throw new Error(\n `Unknown provider: ${selectedValue}. Currently supported: ${formatSupportedProviderTypes(providerDefinitions)}`,\n );\n }\n return definition.type;\n}\n\nexport function getProviderSetupStep(state: IProviderSetupFlowState): IProviderSetupPromptStep {\n const step = state.steps[state.stepIndex];\n if (step === undefined) {\n throw new Error(`Provider setup step ${state.stepIndex} is out of range`);\n }\n return step;\n}\n\nexport function submitProviderSetupValue(\n state: IProviderSetupFlowState,\n rawValue: string,\n): TProviderSetupFlowSubmitResult {\n const step = getProviderSetupStep(state);\n const value = rawValue.trim() || step.defaultValue || '';\n const validationMessage = validateProviderSetupValue(step, value);\n if (validationMessage !== undefined) {\n return { status: 'error', state, message: validationMessage };\n }\n\n const nextState = {\n ...state,\n stepIndex: state.stepIndex + 1,\n values: { ...state.values, [step.key]: value },\n };\n if (nextState.stepIndex < state.steps.length) {\n return { status: 'next', state: nextState };\n }\n return { status: 'complete', input: buildProviderSetupInput(nextState) };\n}\n\nexport async function runProviderSetupPromptFlow(\n type: TProviderSetupType,\n promptInput: TPromptInput,\n providerDefinitions: readonly IProviderDefinition[],\n options: IProviderSetupFlowOptions = {},\n): Promise<IProviderSetupInput> {\n let state = createProviderSetupFlow(type, providerDefinitions, options);\n const stepCount = state.steps.length;\n while (state.stepIndex < stepCount) {\n const step = getProviderSetupStep(state);\n const value = await promptInput(\n formatProviderSetupPromptLabel(step, state.setupHelpLinks),\n step.masked === true,\n );\n const result = submitProviderSetupValue(state, value);\n if (result.status === 'complete') {\n return result.input;\n }\n if (result.status === 'error') {\n throw new Error(result.message);\n }\n state = result.state;\n }\n throw new Error('Provider setup flow ended without completion');\n}\n\nexport function formatProviderSetupPromptLabel(\n step: IProviderSetupPromptStep,\n setupHelpLinks: readonly IProviderSetupHelpLink[] = [],\n): string {\n const suffix = step.defaultValue !== undefined ? ` (default: ${step.defaultValue})` : '';\n const setupHelp = formatProviderSetupHelpLinks(setupHelpLinks);\n const prefix = setupHelp.length > 0 ? `${setupHelp}\\n` : '';\n return `${prefix} ${step.title}${suffix}: `;\n}\n\nconst CATEGORY_BADGES: Record<string, string> = {\n 'cloud-paid': '[Cloud/Paid]',\n 'cloud-free': '[Cloud/Free]',\n 'local-free': '[Local/Free]',\n};\n\nexport function formatProviderSetupChoiceLabel(definition: IProviderDefinition): string {\n const badge =\n definition.category !== undefined ? `${CATEGORY_BADGES[definition.category] ?? ''} ` : '';\n const name =\n definition.displayName !== undefined\n ? `${definition.displayName} (${definition.type})`\n : definition.type;\n const label = `${badge}${name}`;\n return definition.description !== undefined ? `${label} — ${definition.description}` : label;\n}\n\nexport function formatProviderSetupHelpLinks(\n setupHelpLinks: readonly IProviderSetupHelpLink[] = [],\n): string {\n if (setupHelpLinks.length === 0) {\n return '';\n }\n return setupHelpLinks\n .map(\n (link) =>\n ` Setup help: ${formatProviderSetupHelpLinkKind(link.kind)}: ${link.label} - ${link.url}`,\n )\n .join('\\n');\n}\n\nfunction parseProviderSelectionIndex(value: string): number | undefined {\n if (!/^\\d+$/.test(value)) {\n return undefined;\n }\n return Number(value) - 1;\n}\n\nexport function validateProviderSetupValue(\n step: IProviderSetupPromptStep,\n value: string,\n): string | undefined {\n if (step.required === true && value.length === 0) {\n return 'Required';\n }\n return undefined;\n}\n\nfunction getProviderSetupDefinition(\n type: TProviderSetupType,\n providerDefinitions: readonly IProviderDefinition[],\n): IProviderDefinition {\n const definition = findProviderDefinition(providerDefinitions, type);\n if (definition === undefined) {\n throw new Error(\n `Unknown provider: ${type}. Currently supported: ${formatSupportedProviderTypes(providerDefinitions)}`,\n );\n }\n return definition;\n}\n\nfunction getProviderSetupSteps(definition: IProviderDefinition): IProviderSetupPromptStep[] {\n if (definition.setupSteps !== undefined) {\n return [...definition.setupSteps];\n }\n\n const steps: IProviderSetupPromptStep[] = [\n {\n key: 'model',\n title: `${definition.type} model`,\n defaultValue: definition.defaults?.model,\n required: definition.defaults?.model === undefined,\n },\n ];\n if (definition.defaults?.baseURL !== undefined) {\n steps.unshift({\n key: 'baseURL',\n title: `${definition.type} base URL`,\n defaultValue: definition.defaults.baseURL,\n });\n }\n if (definition.requiresApiKey === true) {\n steps.push({\n key: 'apiKey',\n title: `${definition.type} API key`,\n defaultValue: definition.defaults?.apiKey,\n required: definition.defaults?.apiKey === undefined,\n masked: true,\n });\n }\n return steps;\n}\n\nfunction formatProviderSetupHelpLinkKind(kind: IProviderSetupHelpLink['kind']): string {\n if (kind === 'api-key') {\n return 'API key';\n }\n if (kind === 'console') {\n return 'Console';\n }\n return 'Official';\n}\n\nfunction applyProviderSetupInitialValues(\n steps: readonly IProviderSetupPromptStep[],\n initialValues: Partial<Record<TProviderSetupField, string>> | undefined,\n): IProviderSetupPromptStep[] {\n if (initialValues === undefined) {\n return [...steps];\n }\n return steps.map((step) => {\n const initialValue = initialValues[step.key];\n if (initialValue === undefined) {\n return step;\n }\n return {\n ...step,\n defaultValue: initialValue,\n required: false,\n };\n });\n}\n\nfunction buildProviderSetupInput(state: IProviderSetupFlowState): IProviderSetupInput {\n const profile =\n state.profileName ??\n suggestProviderProfileName(\n { type: state.type },\n { existingProfileNames: state.existingProfileNames },\n );\n const apiKey = state.values.apiKey;\n return {\n profile,\n type: state.type,\n model: state.values.model,\n ...(apiKey !== undefined && apiKey.length > 0 && { apiKey }),\n ...(state.values.baseURL !== undefined && { baseURL: state.values.baseURL }),\n setCurrent: state.setCurrent ?? true,\n };\n}\n","import { textAction } from '@robota-sdk/agent-core';\nimport { buildProviderSetupPatch, mergeProviderPatch } from '@robota-sdk/agent-framework';\n\nimport {\n createProviderSetupFlow,\n formatProviderSetupHelpLinks,\n getProviderSetupStep,\n submitProviderSetupValue,\n} from './provider-setup-flow.js';\n\nimport type { IProviderSetupFlowState } from './provider-setup-flow.js';\nimport type { IActionRequest, IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n IProviderCommandModuleOptions,\n IProviderSetupInput,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nconst PROVIDER_RESTART_ACTION = {\n type: 'session-restart',\n reason: 'other',\n} as const;\n\nexport function createSetupFlow(\n type: string,\n options: IProviderCommandModuleOptions,\n): IProviderSetupFlowState {\n return createProviderSetupFlow(type, options.providerDefinitions, {\n existingProfileNames: Object.keys(options.settings.readMergedSettings().providers ?? {}),\n });\n}\n\n/** Build the per-step `IActionRequest` for the current setup step (CMD-004 inline ask). */\nfunction toProviderSetupStepRequest(\n flow: IProviderSetupFlowState,\n errorMessage?: string,\n): IActionRequest {\n const step = getProviderSetupStep(flow);\n const placeholder =\n step.masked === true && step.defaultValue !== undefined ? '(unchanged)' : step.defaultValue;\n const helpLinks = formatProviderSetupHelpLinks(flow.setupHelpLinks);\n const description =\n [errorMessage, helpLinks.length > 0 ? helpLinks : undefined]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join('\\n') || undefined;\n return textAction(`provider-setup-${step.key}`, step.title, {\n description,\n placeholder,\n allowEmpty: step.defaultValue !== undefined,\n masked: step.masked,\n });\n}\n\n/**\n * Drive the setup-step engine through inline `ui.ask` calls (CMD-004), re-asking the same step when a\n * step fails validation (the error is surfaced in the request description). The `complete` sink differs\n * between the add and edit paths.\n */\nexport async function runProviderSetupAsk(\n ui: IUserInteraction,\n flow: IProviderSetupFlowState,\n complete: (input: IProviderSetupInput) => ICommandResult,\n cancelMessage: string,\n): Promise<ICommandResult> {\n let state = flow;\n let errorMessage: string | undefined;\n for (;;) {\n const response = await ui.ask(toProviderSetupStepRequest(state, errorMessage));\n if (response.type === 'cancelled') {\n return { message: cancelMessage, success: true };\n }\n const result = submitProviderSetupValue(state, response.text ?? '');\n if (result.status === 'error') {\n errorMessage = result.message;\n continue;\n }\n if (result.status === 'complete') {\n return complete(result.input);\n }\n state = result.state;\n errorMessage = undefined;\n }\n}\n\n/** Run the `/provider add` setup wizard inline. */\nexport function runProviderAddSetup(\n ui: IUserInteraction,\n flow: IProviderSetupFlowState,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n return runProviderSetupAsk(\n ui,\n flow,\n (input) => completeProviderSetup(input, options),\n 'Provider setup cancelled.',\n );\n}\n\nfunction completeProviderSetup(\n input: IProviderSetupInput,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const target = options.settings.readTargetSettings();\n const patch = buildProviderSetupPatch(input, {\n providerDefinitions: options.providerDefinitions,\n });\n options.settings.writeTargetSettings(mergeProviderPatch(target, patch));\n return {\n message: `Provider ${input.profile} configured. Restarting...`,\n success: true,\n hostActions: [{ ...PROVIDER_RESTART_ACTION, message: 'Provider setup restart' }],\n };\n}\n","import {\n buildProviderSetupPatch,\n formatOrgPolicyViolationMessage,\n isApiKeyPlaintext,\n setCurrentProvider,\n upsertProviderProfile,\n} from '@robota-sdk/agent-framework';\n\nimport { runProviderSetupAsk } from './provider-command-setup.js';\nimport { createProviderSetupFlow } from './provider-setup-flow.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n IProviderSetupInput,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport function formatProviderChoiceLabel(\n name: string,\n profile: IProviderProfileSettings,\n currentProvider: string | undefined,\n): string {\n const marker = name === currentProvider ? '* ' : '';\n return `${marker}${name}: ${profile.type ?? 'unknown'} ${profile.model ?? '(no model)'}`;\n}\n\nexport function buildProviderSwitch(\n providers: Record<string, IProviderProfileSettings> | undefined,\n profileName: string | undefined,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n if (!profileName) {\n return { message: 'Usage: /provider switch <profile>', success: false };\n }\n if (!providers?.[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const { orgPolicy } = options;\n if (orgPolicy?.allowedProviders && !orgPolicy.allowedProviders.includes(profileName)) {\n return {\n message: formatOrgPolicyViolationMessage(\n `Provider \"${profileName}\" is not allowed by your organization policy. Allowed: ${orgPolicy.allowedProviders.join(', ')}.`,\n orgPolicy.adminContact,\n ),\n success: false,\n };\n }\n if (options.settings.readMergedSettings().currentProvider === profileName) {\n return { message: `Already using provider \"${profileName}\".`, success: true };\n }\n const profile = providers[profileName];\n const target = options.settings.readTargetSettings();\n const merged = options.settings.readMergedSettings();\n const next =\n target.providers?.[profileName] !== undefined || merged.providers?.[profileName] !== undefined\n ? { ...target, currentProvider: profileName }\n : setCurrentProvider(target, profileName);\n options.settings.writeTargetSettings(next);\n const modelLabel = profile.model ?? 'unknown model';\n return {\n message: `Switched to ${profileName} (${modelLabel}). History preserved.`,\n success: true,\n hostActions: [{ type: 'provider-hot-swap', profileName }],\n };\n}\n\nexport async function buildProviderEdit(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n const profile = settings.providers?.[profileName];\n if (!profile) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n if (!profile.type) {\n return { message: `Provider profile \"${profileName}\" is missing type.`, success: false };\n }\n let flow;\n try {\n flow = createProviderSetupFlow(profile.type, options.providerDefinitions, {\n profileName,\n setCurrent: false,\n initialValues: getProviderProfileSetupValues(profile),\n });\n } catch (error) {\n return { message: error instanceof Error ? error.message : String(error), success: false };\n }\n return runProviderSetupAsk(\n ui,\n flow,\n (input) => completeProviderEdit(input, profileName, options),\n 'Provider edit cancelled.',\n );\n}\n\nfunction getProviderProfileSetupValues(profile: IProviderProfileSettings): {\n model?: string;\n apiKey?: string;\n baseURL?: string;\n} {\n return {\n ...(typeof profile.model === 'string' ? { model: profile.model } : {}),\n ...(typeof profile.apiKey === 'string' ? { apiKey: profile.apiKey } : {}),\n ...(typeof profile.baseURL === 'string' ? { baseURL: profile.baseURL } : {}),\n };\n}\n\nfunction completeProviderEdit(\n input: IProviderSetupInput,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const merged = options.settings.readMergedSettings();\n const currentProfile = merged.providers?.[profileName];\n if (!currentProfile) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const { orgPolicy } = options;\n if (orgPolicy?.requireApiKeyFromEnv && isApiKeyPlaintext(input.apiKey)) {\n return {\n message: formatOrgPolicyViolationMessage(\n 'Your organization policy requires API keys to be stored as environment variable references ($ENV:VAR_NAME), not as plaintext.',\n orgPolicy.adminContact,\n ),\n success: false,\n };\n }\n const target = options.settings.readTargetSettings();\n const patch = buildProviderSetupPatch(input, {\n providerDefinitions: options.providerDefinitions,\n });\n const updatedProfile = patch.providers[profileName];\n if (!updatedProfile) {\n return { message: `Provider profile \"${profileName}\" was not updated.`, success: false };\n }\n options.settings.writeTargetSettings(\n upsertProviderProfile(target, profileName, { ...currentProfile, ...updatedProfile }),\n );\n const isCurrent = merged.currentProvider === profileName;\n return {\n message: isCurrent\n ? `Provider ${profileName} updated. Switching...`\n : `Provider ${profileName} updated.`,\n success: true,\n ...(isCurrent ? { hostActions: [{ type: 'provider-hot-swap' as const, profileName }] } : {}),\n };\n}\n","import { confirmAction, isConfirmed, selectAction, textAction } from '@robota-sdk/agent-core';\nimport {\n deleteProviderProfile,\n sanitizeProviderProfileName,\n upsertProviderProfile,\n} from '@robota-sdk/agent-framework';\n\nimport { formatProviderChoiceLabel } from './provider-command-profile-operations.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type { IProviderCommandModuleOptions } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nconst MAX_DUPLICATE_PROFILE_SUFFIX = 1000;\nconst PROVIDER_RESTART_ACTION = {\n type: 'session-restart',\n reason: 'other',\n} as const;\n\nexport async function buildProviderDuplicate(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n if (!settings.providers?.[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const defaultName = suggestDuplicateProfileName(profileName, Object.keys(settings.providers));\n let errorMessage: string | undefined;\n for (;;) {\n const response = await ui.ask(\n textAction('provider-duplicate', `Duplicate ${profileName} as`, {\n description: errorMessage,\n placeholder: defaultName,\n allowEmpty: true,\n }),\n );\n if (response.type === 'cancelled') {\n return { message: 'Provider duplicate cancelled.', success: true };\n }\n const value = response.text ?? '';\n // Re-ask on validation failure, surfacing the reason (CMD-004 re-ask loop replaces the closure).\n const validationMessage = validateDuplicateProfileName(value, defaultName, options);\n if (validationMessage !== undefined) {\n errorMessage = validationMessage;\n continue;\n }\n return completeProviderDuplicate(profileName, value, defaultName, options);\n }\n}\n\nfunction validateDuplicateProfileName(\n value: string,\n defaultName: string,\n options: IProviderCommandModuleOptions,\n): string | undefined {\n const name = normalizeProfileName(value, defaultName);\n if (name.length === 0) {\n return 'Required';\n }\n if (options.settings.readMergedSettings().providers?.[name] !== undefined) {\n return `Provider profile \"${name}\" already exists`;\n }\n return undefined;\n}\n\nfunction completeProviderDuplicate(\n profileName: string,\n value: string,\n defaultName: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const settings = options.settings.readMergedSettings();\n const sourceProfile = settings.providers?.[profileName];\n if (!sourceProfile) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const targetName = normalizeProfileName(value, defaultName);\n const validationMessage = validateDuplicateProfileName(targetName, defaultName, options);\n if (validationMessage !== undefined) {\n return { message: validationMessage, success: false };\n }\n options.settings.writeTargetSettings(\n upsertProviderProfile(options.settings.readTargetSettings(), targetName, { ...sourceProfile }),\n );\n return {\n message: `Provider profile duplicated: ${profileName} -> ${targetName}.`,\n success: true,\n };\n}\n\nexport async function buildProviderDelete(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n const providers = settings.providers ?? {};\n if (!providers[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n if (Object.keys(providers).length <= 1) {\n return { message: 'Cannot delete the only provider profile.', success: false };\n }\n if (options.settings.readTargetSettings().providers?.[profileName] === undefined) {\n return {\n message: `Provider profile \"${profileName}\" is not stored in the active write target; edit its source settings file or override it before deleting.`,\n success: false,\n };\n }\n const response = await ui.ask(\n confirmAction('provider-delete', `Delete provider profile ${profileName}?`),\n );\n if (!isConfirmed(response)) {\n return { message: 'Provider delete cancelled.', success: true };\n }\n return confirmProviderDelete(ui, profileName, options);\n}\n\nasync function confirmProviderDelete(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n if (settings.currentProvider !== profileName) {\n options.settings.writeTargetSettings(\n deleteProviderProfile(options.settings.readTargetSettings(), profileName),\n );\n return { message: `Provider profile deleted: ${profileName}.`, success: true };\n }\n const replacementOptions = Object.entries(settings.providers ?? {})\n .filter(([name]) => name !== profileName)\n .map(([name, profile]) => ({\n value: name,\n label: formatProviderChoiceLabel(name, profile, settings.currentProvider),\n }));\n const response = await ui.ask(\n selectAction(\n 'provider-delete-replacement',\n `Replacement provider for ${profileName}`,\n replacementOptions,\n {\n maxVisible: 8,\n },\n ),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider delete cancelled.', success: true };\n }\n return completeActiveProviderDelete(profileName, response.values[0], options);\n}\n\nfunction completeActiveProviderDelete(\n profileName: string,\n replacementName: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const settings = options.settings.readMergedSettings();\n if (settings.providers?.[replacementName] === undefined || replacementName === profileName) {\n return { message: `Provider profile \"${replacementName}\" was not found.`, success: false };\n }\n const target = deleteProviderProfile(options.settings.readTargetSettings(), profileName);\n options.settings.writeTargetSettings({ ...target, currentProvider: replacementName });\n return {\n message: `Provider profile deleted: ${profileName}. Restarting with ${replacementName}...`,\n success: true,\n hostActions: [{ ...PROVIDER_RESTART_ACTION, message: 'Provider delete restart' }],\n };\n}\n\nfunction suggestDuplicateProfileName(\n profileName: string,\n existingProfileNames: readonly string[],\n): string {\n const base = sanitizeProviderProfileName(`${profileName}-copy`) ?? 'provider-copy';\n if (!existingProfileNames.includes(base)) {\n return base;\n }\n for (let index = 2; index < MAX_DUPLICATE_PROFILE_SUFFIX; index += 1) {\n const candidate = `${base}-${index}`;\n if (!existingProfileNames.includes(candidate)) {\n return candidate;\n }\n }\n return `${base}-${Date.now()}`;\n}\n\nfunction normalizeProfileName(value: string, defaultName: string): string {\n const raw = value.trim() || defaultName;\n return sanitizeProviderProfileName(raw) ?? '';\n}\n","import { selectAction } from '@robota-sdk/agent-core';\nimport { testProviderProfileCommand } from '@robota-sdk/agent-framework';\n\nimport {\n buildProviderDelete,\n buildProviderDuplicate,\n} from './provider-command-profile-lifecycle.js';\nimport {\n buildProviderEdit,\n buildProviderSwitch,\n formatProviderChoiceLabel,\n} from './provider-command-profile-operations.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nconst ACTION_SWITCH = 'switch';\nconst ACTION_EDIT = 'edit';\nconst ACTION_TEST = 'test';\nconst ACTION_DUPLICATE = 'duplicate';\nconst ACTION_DELETE = 'delete';\nconst ACTION_CANCEL = 'cancel';\n\n/**\n * Ask the user to pick a provider profile, then drive its action menu (CMD-004 inline ask). Replaces\n * the former returned choice→submit continuation chain — the picker's own option list is the rendered\n * profile list, so the caller no longer prepends a separate list message.\n */\nexport async function askProviderProfileSelection(\n ui: IUserInteraction,\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const profileOptions = Object.entries(providers ?? {}).map(([name, profile]) => ({\n value: name,\n label: formatProviderChoiceLabel(name, profile, currentProvider),\n }));\n const response = await ui.ask(\n selectAction('provider-profile', 'Select provider profile', profileOptions, { maxVisible: 8 }),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider profile selection cancelled.', success: true };\n }\n return askProviderProfileAction(ui, response.values[0], options);\n}\n\nasync function askProviderProfileAction(\n ui: IUserInteraction,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n if (!settings.providers?.[profileName]) {\n return { message: `Provider profile \"${profileName}\" was not found.`, success: false };\n }\n const response = await ui.ask(\n selectAction('provider-profile-action', `Provider profile: ${profileName}`, [\n { value: ACTION_SWITCH, label: 'Switch' },\n { value: ACTION_EDIT, label: 'Edit' },\n { value: ACTION_TEST, label: 'Test' },\n { value: ACTION_DUPLICATE, label: 'Duplicate' },\n { value: ACTION_DELETE, label: 'Delete' },\n { value: ACTION_CANCEL, label: 'Cancel' },\n ]),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider profile action cancelled.', success: true };\n }\n return executeProviderProfileAction(ui, profileName, response.values[0], options);\n}\n\nasync function executeProviderProfileAction(\n ui: IUserInteraction,\n profileName: string,\n action: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n switch (action) {\n case ACTION_SWITCH:\n return buildProviderSwitch(settings.providers, profileName, options);\n case ACTION_EDIT:\n return buildProviderEdit(ui, profileName, options);\n case ACTION_TEST:\n return testProviderProfileCommand(\n settings.currentProvider,\n settings.providers,\n profileName,\n options,\n );\n case ACTION_DUPLICATE:\n return buildProviderDuplicate(ui, profileName, options);\n case ACTION_DELETE:\n return buildProviderDelete(ui, profileName, options);\n case ACTION_CANCEL:\n return { message: 'Provider profile action cancelled.', success: true };\n default:\n return { message: `Unknown provider profile action \"${action}\".`, success: false };\n }\n}\n","import {\n findProviderDefinition,\n formatSupportedProviderTypes,\n selectAction,\n} from '@robota-sdk/agent-core';\nimport { testProviderProfileCommand } from '@robota-sdk/agent-framework';\n\nimport { buildProviderSwitch } from './provider-command-profile-operations.js';\nimport { askProviderProfileSelection } from './provider-command-profile.js';\nimport { createSetupFlow, runProviderAddSetup } from './provider-command-setup.js';\nimport { formatProviderSetupChoiceLabel } from './provider-setup-flow.js';\n\nimport type { IUserInteraction } from '@robota-sdk/agent-core';\nimport type {\n ICommandHostUserInteraction,\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport async function executeProviderCommand(\n context: ICommandHostUserInteraction,\n args: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const ui = context.getUserInteraction();\n const settings = options.settings.readMergedSettings();\n const trimmedArgs = args.trim();\n if (trimmedArgs.length === 0) {\n return buildProviderProfilePicker(ui, settings.currentProvider, settings.providers, options);\n }\n const [subcommand = 'current', profileArg] = trimmedArgs.split(/\\s+/);\n\n if (subcommand === 'list') {\n return buildProviderProfilePicker(ui, settings.currentProvider, settings.providers, options);\n }\n if (subcommand === 'current' || subcommand === '') {\n return {\n message: formatCurrentProvider(settings.currentProvider, settings.providers),\n success: true,\n };\n }\n if (subcommand === 'switch') {\n return buildProviderSwitch(settings.providers, profileArg, options);\n }\n if (subcommand === 'test') {\n return testProviderProfileCommand(\n settings.currentProvider,\n settings.providers,\n profileArg,\n options,\n );\n }\n if (subcommand === 'add') {\n return buildProviderSetup(ui, profileArg, options);\n }\n\n return {\n message: 'Usage: provider [current|list|switch <profile>|add <type>|test [profile]]',\n success: false,\n };\n}\n\n/**\n * List the provider profiles. With an interactive renderer attached, drive the inline profile picker\n * (CMD-004); without one (headless/automation) or with no profiles, return the formatted list as text.\n */\nfunction buildProviderProfilePicker(\n ui: IUserInteraction | undefined,\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> | ICommandResult {\n if (!ui || Object.keys(providers ?? {}).length === 0) {\n return { message: formatProviderList(currentProvider, providers), success: true };\n }\n return askProviderProfileSelection(ui, currentProvider, providers, options);\n}\n\nfunction formatProviderList(\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n): string {\n const entries = Object.entries(providers ?? {});\n if (entries.length === 0) {\n return 'No provider profiles configured.';\n }\n return entries\n .map(([name, profile]) => {\n const marker = name === currentProvider ? '*' : '-';\n return `${marker} ${name}: ${profile.type ?? 'unknown'} ${profile.model ?? '(no model)'}`;\n })\n .join('\\n');\n}\n\nfunction formatCurrentProvider(\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n): string {\n if (!currentProvider) {\n return 'No current provider configured.';\n }\n const profile = providers?.[currentProvider];\n if (!profile) {\n return `Current provider \"${currentProvider}\" was not found in providers.`;\n }\n return [\n `Current provider: ${currentProvider}`,\n `Type: ${profile.type ?? 'unknown'}`,\n `Model: ${profile.model ?? '(no model)'}`,\n ...(profile.baseURL ? [`Base URL: ${profile.baseURL}`] : []),\n ].join('\\n');\n}\n\n/**\n * Configure a provider profile. With an explicit `type`, run the setup wizard directly; without one,\n * ask the user to pick a provider type first (CMD-004). Without an interactive renderer, setup cannot\n * proceed — return usage text instead of a silent guess.\n */\nfunction buildProviderSetup(\n ui: IUserInteraction | undefined,\n type: string | undefined,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> | ICommandResult {\n if (type === undefined || type.length === 0) {\n if (!ui) {\n return {\n message: `Usage: provider add <type>. Supported: ${formatSupportedProviderTypes(options.providerDefinitions)}`,\n success: false,\n };\n }\n return askProviderSetupType(ui, options);\n }\n if (findProviderDefinition(options.providerDefinitions, type) === undefined) {\n return {\n message: `Usage: provider add <type>. Supported: ${formatSupportedProviderTypes(options.providerDefinitions)}`,\n success: false,\n };\n }\n if (!ui) {\n return {\n message: `Provider setup for \"${type}\" requires an interactive session.`,\n success: false,\n };\n }\n return runProviderAddSetup(ui, createSetupFlow(type, options), options);\n}\n\nasync function askProviderSetupType(\n ui: IUserInteraction,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const typeOptions = options.providerDefinitions.map((definition) => ({\n value: definition.type,\n label: formatProviderSetupChoiceLabel(definition),\n }));\n const response = await ui.ask(\n selectAction('provider-type', 'Select provider', typeOptions, { maxVisible: 6 }),\n );\n if (response.type !== 'answer' || response.values[0] === undefined) {\n return { message: 'Provider setup cancelled.', success: true };\n }\n const type = response.values[0];\n if (findProviderDefinition(options.providerDefinitions, type) === undefined) {\n return {\n message: `Usage: provider add <type>. Supported: ${formatSupportedProviderTypes(options.providerDefinitions)}`,\n success: false,\n };\n }\n return runProviderAddSetup(ui, createSetupFlow(type, options), options);\n}\n","import { executeProviderCommand } from './provider-command-execution.js';\n\nimport type {\n ICommandModule as TCommandModule,\n IProviderCommandModuleOptions,\n IProviderCommandSettingsAdapter,\n ISystemCommand as TSystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\nexport type { IProviderCommandModuleOptions, IProviderCommandSettingsAdapter };\n\nfunction buildProviderSubcommands(): ICommand[] {\n return [\n { name: 'current', description: 'Show current provider', source: 'provider' },\n { name: 'list', description: 'List provider profiles', source: 'provider' },\n { name: 'switch', description: 'Hot-swap to another provider profile', source: 'provider' },\n { name: 'add', description: 'Configure a provider profile', source: 'provider' },\n { name: 'test', description: 'Test provider profile', source: 'provider' },\n ];\n}\n\nexport function createProviderCommandEntry(): ICommand {\n return {\n name: 'provider',\n displayName: 'Provider Setup',\n description: 'Manage provider profiles',\n source: 'provider',\n // User-only: provider profiles hold account credentials; a credential action.\n modelInvocable: false,\n argumentHint: 'current | list | switch <profile> | add [type] | test [profile]',\n subcommands: buildProviderSubcommands(),\n example: '/provider switch production',\n };\n}\n\nexport class ProviderCommandSource implements ICommandSource {\n readonly name = 'provider';\n\n getCommands(): ICommand[] {\n return [createProviderCommandEntry()];\n }\n}\n\nfunction createProviderSystemCommand(options: IProviderCommandModuleOptions): TSystemCommand {\n const entry = createProviderCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n example: entry.example,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: (context, args) => executeProviderCommand(context, args, options),\n };\n}\n\nexport function createProviderCommandModule(\n options: IProviderCommandModuleOptions,\n): TCommandModule {\n return {\n name: 'agent-command-provider',\n commandSources: [new ProviderCommandSource()],\n systemCommands: [createProviderSystemCommand(options)],\n };\n}\n","import type { TPromptInput } from './provider-setup-flow.js';\nimport type { ITerminalOutput } from '@robota-sdk/agent-core';\n\nexport type TOnboardingPath = 'has-key' | 'free-key' | 'local';\n\nexport interface IOnboardingResult {\n path: TOnboardingPath;\n preselectedType?: string;\n}\n\nconst ONBOARDING_PROMPT = `\n Do you have an API key for an AI provider?\n\n 1. Yes, I have an API key\n 2. No — get a free key (Google Gemini, takes ~2 min)\n 3. No — use a local model (LM Studio, no API key needed)\n\n Choose [1-3] (default: 1): `;\n\nconst GEMINI_GUIDE = `\n ── Get a free Gemini API key ────────────────────────────────────────────────\n\n 1. Open https://aistudio.google.com/apikey in your browser\n 2. Sign in with your Google account\n 3. Click \"Create API key\" (takes ~30 seconds)\n 4. Copy the key starting with \"AIza...\"\n\n ─────────────────────────────────────────────────────────────────────────────\n`;\n\nconst LOCAL_MODEL_GUIDE = `\n ── Set up a local model with LM Studio ──────────────────────────────────────\n\n 1. Download LM Studio from https://lmstudio.ai\n 2. Open LM Studio → search for a model (e.g. \"llama\" or \"phi\") → Download\n 3. Go to Developer tab → click Start Server\n (default address: http://localhost:1234)\n\n When the server is running, come back here and press Enter to continue.\n\n ─────────────────────────────────────────────────────────────────────────────\n`;\n\nexport async function runOnboardingBranch(\n promptInput: TPromptInput,\n terminal: ITerminalOutput,\n): Promise<IOnboardingResult> {\n const raw = await promptInput(ONBOARDING_PROMPT);\n const choice = raw.trim() || '1';\n\n if (choice === '2') {\n terminal.writeLine(GEMINI_GUIDE);\n await promptInput(' Press Enter when you have your API key: ');\n return { path: 'free-key', preselectedType: 'gemini' };\n }\n\n if (choice === '3') {\n terminal.writeLine(LOCAL_MODEL_GUIDE);\n await promptInput(' Press Enter when LM Studio server is running: ');\n return { path: 'local', preselectedType: 'gemma' };\n }\n\n return { path: 'has-key' };\n}\n","import {\n checkSettingsDocument,\n ProviderConfigError,\n readMergedProviderSettings,\n resolveEnvDefaultProvider,\n applyProviderConfiguration,\n resolveProviderSettingsWriteTarget,\n WorkspaceAuthorityRequiredError,\n} from '@robota-sdk/agent-framework';\n\nimport { runOnboardingBranch } from './provider-onboarding.js';\nimport {\n formatProviderSetupSelectionPrompt,\n resolveProviderSetupSelection,\n runProviderSetupPromptFlow,\n type TPromptInput,\n} from './provider-setup-flow.js';\n\nimport type { IProviderDefinition } from '@robota-sdk/agent-core';\nimport type { ITerminalOutput } from '@robota-sdk/agent-core';\nimport type {\n ISettingsDocumentStore,\n TSettingsScope,\n TSettingsSource,\n} from '@robota-sdk/agent-framework';\n\nexport interface IProviderStartupContext {\n provider?: string;\n settingsScope?: TSettingsScope;\n settingsSources: readonly TSettingsSource[];\n settingsStores: readonly ISettingsDocumentStore[];\n}\n\nexport interface IEnsureProviderConfigOptions {\n formatError: (defs: readonly IProviderDefinition[]) => string;\n isInteractive?: () => boolean;\n /** Environment map for env-default synthesis (test seam, default: process.env). */\n env?: Record<string, string | undefined>;\n}\n\nexport async function runProviderStartupSetup(\n cwd: string,\n ctx: IProviderStartupContext,\n promptInput: TPromptInput,\n terminal: ITerminalOutput,\n providerDefinitions: readonly IProviderDefinition[],\n): Promise<void> {\n const onboarding = await runOnboardingBranch(promptInput, terminal);\n const access = resolveSettingsAccess(ctx);\n const existingProfileNames = Object.keys(\n readMergedProviderSettings(access.sources).providers ?? {},\n );\n const settingsStore = selectSettingsStore(access.stores, ctx.settingsScope);\n\n let type: string;\n if (onboarding.preselectedType !== undefined) {\n type = onboarding.preselectedType;\n } else {\n const providerChoice = await promptInput(\n formatProviderSetupSelectionPrompt(providerDefinitions),\n );\n type = resolveProviderSetupSelection(providerChoice, providerDefinitions);\n }\n\n const input = await runProviderSetupPromptFlow(type, promptInput, providerDefinitions, {\n existingProfileNames,\n });\n applyProviderConfiguration(settingsStore, input, { providerDefinitions });\n const language = await promptInput(' Response language (ko/en/ja/zh, default: en): ');\n if (language) {\n const settings = settingsStore.read();\n settings.language = language;\n settingsStore.write(settings);\n }\n terminal.writeLine(`\\n Config saved to ${settingsStore.displayName}\\n`);\n}\n\nexport async function ensureProviderConfig(\n cwd: string,\n ctx: IProviderStartupContext,\n promptInput: TPromptInput,\n terminal: ITerminalOutput,\n providerDefinitions: readonly IProviderDefinition[],\n options: IEnsureProviderConfigOptions,\n): Promise<void> {\n const access = resolveSettingsAccess(ctx);\n const merged = readMergedProviderSettings(access.sources);\n const selectedSettings =\n ctx.provider !== undefined ? { ...merged, currentProvider: ctx.provider } : merged;\n if (checkSettingsDocument(selectedSettings, providerDefinitions) === 'valid') {\n return;\n }\n // Zero-config startup: a recognized provider env key with complete definition defaults\n // makes setup unnecessary — resolution will synthesize an env-default config.\n if (\n ctx.provider === undefined &&\n resolveEnvDefaultProvider(providerDefinitions, options.env) !== undefined\n ) {\n return;\n }\n const checkInteractive = options.isInteractive ?? (() => false);\n if (!checkInteractive()) {\n throw new ProviderConfigError(options.formatError(providerDefinitions));\n }\n await runProviderStartupSetup(\n cwd,\n selectStartupContext(ctx, access.stores),\n promptInput,\n terminal,\n providerDefinitions,\n );\n const updated = readMergedProviderSettings(access.sources);\n const updatedSettings =\n ctx.provider !== undefined ? { ...updated, currentProvider: ctx.provider } : updated;\n if (checkSettingsDocument(updatedSettings, providerDefinitions) !== 'valid') {\n throw new ProviderConfigError(options.formatError(providerDefinitions));\n }\n}\n\nfunction resolveSettingsAccess(ctx: IProviderStartupContext): {\n sources: readonly TSettingsSource[];\n stores: readonly ISettingsDocumentStore[];\n} {\n if (ctx.settingsSources === undefined || ctx.settingsStores === undefined) {\n throw new Error('Provider startup requires host settings sources and stores.');\n }\n return {\n sources: ctx.settingsSources,\n stores: ctx.settingsStores,\n };\n}\n\nfunction selectSettingsStore(\n stores: readonly ISettingsDocumentStore[],\n scope: TSettingsScope | undefined,\n): ISettingsDocumentStore {\n if (scope === undefined) return resolveProviderSettingsWriteTarget(stores);\n const targetScope = scope === 'user' ? 'user' : 'project-local';\n const store = stores.findLast((candidate) => candidate.scope === targetScope);\n if (store !== undefined) return store;\n throw new WorkspaceAuthorityRequiredError(\n `No authorized ${targetScope} settings store is available.`,\n );\n}\n\nfunction selectStartupContext(\n ctx: IProviderStartupContext,\n stores: readonly ISettingsDocumentStore[],\n): IProviderStartupContext {\n if (ctx.settingsScope !== undefined || ctx.provider !== undefined) return ctx;\n const currentProviderStore = findHighestPriorityCurrentProviderStore(stores);\n if (currentProviderStore?.kind === 'project') return { ...ctx, settingsScope: 'project-local' };\n return ctx;\n}\n\nfunction findHighestPriorityCurrentProviderStore(\n stores: readonly ISettingsDocumentStore[],\n): ISettingsDocumentStore | undefined {\n for (let index = stores.length - 1; index >= 0; index -= 1) {\n const store = stores[index];\n if (store === undefined) continue;\n const settings = store.read();\n if (typeof settings.currentProvider === 'string') {\n return store;\n }\n }\n return undefined;\n}\n","import type {\n ICommandHostAdapterAccess,\n ICommandHostWorkspace,\n TRemoteControlStatus,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\n/**\n * `/remote-control` (REMOTE-008) — enable/stop P2P remote control and report status.\n *\n * The command is a declarative trigger: `enable` and `stop` return typed HOST ACTIONS\n * (`remote-control-enable` / `remote-control-stop`) executed by the session via the composition-root\n * adapter (commands never construct transports). `status` reads the injected\n * `ICommandHostAdapters.remoteControl.getStatus()` view — absent ⇒ the feature is unavailable in this host.\n *\n * Pairing and trust belong to the operator at this terminal. A surface that is already connected\n * may stop remote control and read its state, but it cannot mint a pairing link, read the one on\n * offer, or revoke a trusted device: otherwise one connected surface could admit the next.\n */\n\nconst OPERATOR_ONLY =\n 'only the operator at this terminal can do this; a connected surface cannot pair, enroll or revoke devices. ' +\n 'Run `/remote-control` on the host terminal.';\n\nfunction formatStatus(\n status: TRemoteControlStatus | undefined,\n showPairingLink: boolean,\n): ICommandResult {\n if (!status) {\n return { message: 'Remote control is not available in this environment.', success: true };\n }\n switch (status.state) {\n case 'off':\n return {\n message: 'Remote control is off. Use `/remote-control` to enable it.',\n success: true,\n };\n case 'no-relay':\n return {\n message:\n 'Remote control is unavailable: no signaling relay is configured ' +\n '(set `transports.webrtc.options.relayUrl`).',\n success: true,\n };\n case 'awaiting-pairing':\n return {\n message: showPairingLink\n ? `Remote control is waiting for a device to pair.\\nOpen: ${status.pairingUrl}`\n : 'Remote control is waiting for a device to pair. The pairing link is shown only on the host terminal.',\n success: true,\n };\n case 'paired':\n return { message: 'Remote control is active — a device is paired.', success: true };\n default:\n return { message: 'Remote control status is unknown.', success: true };\n }\n}\n\nexport function executeRemoteControlCommand(\n context: ICommandHostAdapterAccess & Pick<ICommandHostWorkspace, 'getCommandInvocationSource'>,\n args: string,\n): ICommandResult {\n const operator = context.getCommandInvocationSource() === 'user';\n const trimmed = args.trim();\n // Split into a lowercased verb + the original-case remainder (a deviceId is case-sensitive base64url).\n const spaceAt = trimmed.indexOf(' ');\n const verb = (spaceAt === -1 ? trimmed : trimmed.slice(0, spaceAt)).toLowerCase();\n const rest = spaceAt === -1 ? '' : trimmed.slice(spaceAt + 1).trim();\n\n if (verb === 'status') {\n const adapter = context.getCommandHostAdapters?.().remoteControl;\n const result = formatStatus(adapter?.getStatus(), operator);\n if (!adapter?.describeKeyStorage) return result;\n const storage = adapter.describeKeyStorage() ?? 'chosen when remote control is first enabled';\n return { ...result, message: `${result.message}\\nHost key storage: ${storage}` };\n }\n\n if (verb === 'devices') {\n const adapter = context.getCommandHostAdapters?.().remoteControl;\n const devices = adapter?.listDevices?.();\n if (!devices) {\n return {\n message: 'Trusted-device reconnect is not available in this environment.',\n success: true,\n };\n }\n if (devices.length === 0) {\n return { message: 'No trusted devices are enrolled yet.', success: true };\n }\n const lines = devices.map((d) => ` ${d.deviceId} ${d.label} (last seen ${d.lastSeenAt})`);\n return { message: `Trusted devices:\\n${lines.join('\\n')}`, success: true };\n }\n\n if (verb === 'revoke') {\n if (!operator) {\n return { message: `\\`/remote-control revoke\\`: ${OPERATOR_ONLY}`, success: false };\n }\n if (!rest) {\n return { message: 'Usage: /remote-control revoke <deviceId>', success: false };\n }\n const adapter = context.getCommandHostAdapters?.().remoteControl;\n if (!adapter?.revokeDevice) {\n return {\n message: 'Trusted-device reconnect is not available in this environment.',\n success: true,\n };\n }\n const removed = adapter.revokeDevice(rest);\n return removed\n ? { message: `Revoked trusted device ${rest}. It must re-pair to reconnect.`, success: true }\n : { message: `No trusted device with id ${rest}.`, success: false };\n }\n\n if (verb === 'stop' || verb === 'off') {\n return {\n message: 'Stopping remote control...',\n success: true,\n hostActions: [{ type: 'remote-control-stop' as const }],\n };\n }\n\n // Default (empty / `enable` / `on`): request enable. The host reports the pairing QR/link.\n if (verb === '' || verb === 'enable' || verb === 'on') {\n if (!operator) {\n return { message: `\\`/remote-control enable\\`: ${OPERATOR_ONLY}`, success: false };\n }\n return {\n message: 'Enabling remote control...',\n success: true,\n hostActions: [{ type: 'remote-control-enable' as const }],\n };\n }\n\n return {\n message: `Unknown argument \"${verb}\". Usage: /remote-control [enable|stop|status|devices|revoke <id>]`,\n success: false,\n };\n}\n","import { executeRemoteControlCommand } from './remote-control-command.js';\nimport { createSystemCommandFromEntry } from '../command-module-utils.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createRemoteControlCommandEntry(): ICommand {\n return {\n name: 'remote-control',\n displayName: 'Remote control',\n description:\n 'Enable P2P remote control (pair a device to co-drive this session), or check status. Pairing and revoking run only for the operator at the host terminal; a connected surface can stop remote control and read its status, without the pairing link.',\n source: 'remote-control',\n // User-only: pairing and revoking devices are trust decisions. The command also refuses them when\n // they come from a connected surface rather than the operator at this terminal.\n modelInvocable: false,\n userInvocable: true,\n argumentHint: '[enable|stop|status|devices|revoke <device-id>]',\n subcommands: [\n { name: 'status', description: 'Show remote-control status', source: 'remote-control' },\n { name: 'devices', description: 'List trusted devices', source: 'remote-control' },\n {\n name: 'enable',\n description: 'Enable remote control and pair a device',\n source: 'remote-control',\n },\n { name: 'stop', description: 'Stop remote control', source: 'remote-control' },\n {\n name: 'revoke',\n description: 'Revoke a trusted device',\n source: 'remote-control',\n argumentHint: '<device-id>',\n },\n ],\n };\n}\n\nfunction createRemoteControlSystemCommand(): ISystemCommand {\n const entry = createRemoteControlCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: (context, args) => executeRemoteControlCommand(context, args),\n });\n}\n\nexport class RemoteControlCommandSource implements ICommandSource {\n readonly name = 'remote-control';\n\n getCommands(): ICommand[] {\n return [createRemoteControlCommandEntry()];\n }\n}\n\nexport function createRemoteControlCommandModule(): ICommandModule {\n return {\n name: 'agent-command-remote-control',\n commandSources: [new RemoteControlCommandSource()],\n systemCommands: [createRemoteControlSystemCommand()],\n };\n}\n","import type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport function executeResetCommand(): ICommandResult {\n return {\n success: true,\n message: 'Reset requested.',\n data: { resetRequested: true },\n hostActions: [{ type: 'settings-reset' }],\n };\n}\n","import { executeResetCommand } from './reset-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nconst RESET_COMMAND_DESCRIPTION = 'Delete settings';\n\nexport function createResetCommandEntry(): ICommand {\n return {\n name: 'reset',\n displayName: 'Reset Settings',\n description: RESET_COMMAND_DESCRIPTION,\n source: 'reset',\n // User-only: discards the user's settings.\n modelInvocable: false,\n };\n}\n\nfunction createResetSystemCommand(): ISystemCommand {\n const entry = createResetCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: executeResetCommand,\n };\n}\n\nexport class ResetCommandSource implements ICommandSource {\n readonly name = 'reset';\n\n getCommands(): ICommand[] {\n return [createResetCommandEntry()];\n }\n}\n\nexport function createResetCommandModule(): ICommandModule {\n return {\n name: 'agent-command-reset',\n commandSources: [new ResetCommandSource()],\n systemCommands: [createResetSystemCommand()],\n };\n}\n","import {\n inspectCommandEditCheckpoint,\n listCommandEditCheckpoints,\n restoreCommandEditCheckpoint,\n rollbackCommandEditCheckpoint,\n forkCommandEditCheckpoint,\n switchCommandEditCheckpointBranch,\n listCommandEditCheckpointBranches,\n} from '@robota-sdk/agent-framework';\n\nimport type {\n ICommandHostCheckpoints,\n IEditCheckpointInspection,\n IEditCheckpointRestoreResult,\n IEditCheckpointSummary,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nconst SUBCOMMAND_INDEX = 0;\nconst CHECKPOINT_ID_INDEX = 1;\nconst PROMPT_PREVIEW_LENGTH = 120;\nconst ELLIPSIS_LENGTH = 3;\n\nfunction usage(): ICommandResult {\n return {\n message:\n 'Usage: rewind [list] | rewind inspect <checkpoint-id> | rewind restore <checkpoint-id> | rewind code <checkpoint-id> | rewind rollback <checkpoint-id>',\n success: false,\n };\n}\n\nfunction formatPrompt(prompt: string): string {\n const compact = prompt.replace(/\\s+/g, ' ').trim();\n if (compact.length <= PROMPT_PREVIEW_LENGTH) return compact;\n return `${compact.slice(0, PROMPT_PREVIEW_LENGTH - ELLIPSIS_LENGTH)}...`;\n}\n\nfunction formatList(checkpoints: readonly IEditCheckpointSummary[]): ICommandResult {\n const lines =\n checkpoints.length > 0\n ? checkpoints.map(\n (checkpoint) =>\n `- ${checkpoint.id} files=${checkpoint.fileCount} ${checkpoint.createdAt} ${formatPrompt(\n checkpoint.prompt,\n )}`,\n )\n : ['(no edit checkpoints)'];\n\n return {\n message: ['Edit checkpoints:', ...lines].join('\\n'),\n success: true,\n data: { count: checkpoints.length, checkpoints: [...checkpoints] },\n };\n}\n\nfunction formatCheckpointIds(ids: readonly string[]): string {\n return ids.length > 0 ? ids.join(', ') : '(none)';\n}\n\nfunction formatInspection(inspection: IEditCheckpointInspection): ICommandResult {\n const fileLines =\n inspection.capturedFiles.length > 0\n ? inspection.capturedFiles.map((file) => {\n const size =\n file.snapshotSizeBytes === undefined ? '' : ` size=${file.snapshotSizeBytes}B`;\n return `- ${file.relativePath} action=${file.restoreAction} snapshot=${String(\n file.snapshotAvailable,\n )}${size}`;\n })\n : ['(no files captured)'];\n\n return {\n message: [\n `Checkpoint ${inspection.target.id}`,\n `Prompt: ${formatPrompt(inspection.target.prompt)}`,\n 'Captured files:',\n ...fileLines,\n `Restore later checkpoints: files=${inspection.restoreToCheckpoint.fileCount} checkpoints=${formatCheckpointIds(\n inspection.restoreToCheckpoint.checkpointIds,\n )}`,\n `Rollback through checkpoint: files=${inspection.rollbackThroughCheckpoint.fileCount} checkpoints=${formatCheckpointIds(\n inspection.rollbackThroughCheckpoint.checkpointIds,\n )}`,\n ].join('\\n'),\n success: true,\n data: { inspection },\n };\n}\n\nfunction formatRestoreResult(result: IEditCheckpointRestoreResult): ICommandResult {\n return {\n message: [\n `Restored code to ${result.target.id}.`,\n `Restored files: ${result.restoredFileCount}`,\n `Rolled back checkpoints: ${result.restoredCheckpointCount}`,\n ].join('\\n'),\n success: true,\n data: {\n target: result.target,\n restoredCheckpointCount: result.restoredCheckpointCount,\n restoredFileCount: result.restoredFileCount,\n removedCheckpointCount: result.removedCheckpointCount,\n },\n };\n}\n\nfunction formatRollbackResult(result: IEditCheckpointRestoreResult): ICommandResult {\n return {\n message: [\n `Rolled back code through ${result.target.id}.`,\n `Restored files: ${result.restoredFileCount}`,\n `Removed checkpoints: ${result.removedCheckpointCount}`,\n ].join('\\n'),\n success: true,\n data: {\n target: result.target,\n restoredCheckpointCount: result.restoredCheckpointCount,\n restoredFileCount: result.restoredFileCount,\n removedCheckpointCount: result.removedCheckpointCount,\n },\n };\n}\n\nfunction formatError(error: Error | string): ICommandResult {\n return {\n message: error instanceof Error ? error.message : String(error),\n success: false,\n };\n}\n\nfunction inspect(\n context: ICommandHostCheckpoints,\n checkpointId: string | undefined,\n): ICommandResult {\n if (!checkpointId) return usage();\n try {\n return formatInspection(inspectCommandEditCheckpoint(context, checkpointId));\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nasync function restore(\n context: ICommandHostCheckpoints,\n checkpointId: string | undefined,\n): Promise<ICommandResult> {\n if (!checkpointId) return usage();\n try {\n return formatRestoreResult(await restoreCommandEditCheckpoint(context, checkpointId));\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nasync function rollback(\n context: ICommandHostCheckpoints,\n checkpointId: string | undefined,\n): Promise<ICommandResult> {\n if (!checkpointId) return usage();\n try {\n return formatRollbackResult(await rollbackCommandEditCheckpoint(context, checkpointId));\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\n// SELFHOST-007: branching time-travel handlers.\nasync function fork(\n context: ICommandHostCheckpoints,\n checkpointId: string | undefined,\n): Promise<ICommandResult> {\n if (!checkpointId) return usage();\n try {\n const result = await forkCommandEditCheckpoint(context, checkpointId);\n return {\n message: [\n `Forked a new branch from ${result.target.id} (the previous future is preserved).`,\n `Restored files: ${result.restoredFileCount}`,\n ].join('\\n'),\n success: true,\n data: { target: result.target, restoredFileCount: result.restoredFileCount },\n };\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nfunction switchBranch(\n context: ICommandHostCheckpoints,\n checkpointId: string | undefined,\n): ICommandResult {\n if (!checkpointId) return usage();\n try {\n switchCommandEditCheckpointBranch(context, checkpointId);\n return { message: `Switched to checkpoint branch ${checkpointId}.`, success: true };\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nfunction branches(context: ICommandHostCheckpoints): ICommandResult {\n try {\n const tips = listCommandEditCheckpointBranches(context);\n return {\n message:\n tips.length === 0\n ? 'No checkpoint branches yet.'\n : `Branch tips:\\n${tips.map((id) => `- ${id}`).join('\\n')}`,\n success: true,\n data: { branches: tips },\n };\n } catch (error) {\n return formatError(error instanceof Error ? error : String(error));\n }\n}\n\nexport async function executeRewindCommand(\n context: ICommandHostCheckpoints,\n rawArgs: string,\n): Promise<ICommandResult> {\n const args = rawArgs.trim().split(/\\s+/).filter(Boolean);\n const subcommand = args[SUBCOMMAND_INDEX] ?? 'list';\n\n if (subcommand === 'list') {\n return formatList(listCommandEditCheckpoints(context));\n }\n\n if (subcommand === 'inspect') {\n return inspect(context, args[CHECKPOINT_ID_INDEX]);\n }\n\n if (subcommand === 'restore' || subcommand === 'code') {\n return restore(context, args[CHECKPOINT_ID_INDEX]);\n }\n\n if (subcommand === 'rollback') {\n return rollback(context, args[CHECKPOINT_ID_INDEX]);\n }\n\n // SELFHOST-007: branching time-travel subcommands.\n if (subcommand === 'fork') {\n return fork(context, args[CHECKPOINT_ID_INDEX]);\n }\n if (subcommand === 'switch') {\n return switchBranch(context, args[CHECKPOINT_ID_INDEX]);\n }\n if (subcommand === 'branches') {\n return branches(context);\n }\n\n return usage();\n}\n","import {\n REWIND_COMMAND_ARGUMENT_HINT,\n REWIND_COMMAND_DESCRIPTION,\n buildRewindCommandSubcommands,\n} from '@robota-sdk/agent-framework';\n\nimport { executeRewindCommand } from './rewind-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createRewindCommandEntry(): ICommand {\n return {\n name: 'rewind',\n displayName: 'Rewind History',\n description: REWIND_COMMAND_DESCRIPTION,\n source: 'rewind',\n argumentHint: REWIND_COMMAND_ARGUMENT_HINT,\n // User-only: rewrites the user's history and files; the user decides what to undo.\n modelInvocable: false,\n safety: 'write',\n subcommands: buildRewindCommandSubcommands(),\n };\n}\n\nfunction createRewindSystemCommand(): ISystemCommand {\n const entry = createRewindCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n argumentHint: entry.argumentHint,\n userInvocable: true,\n modelInvocable: false,\n safety: 'write',\n subcommands: entry.subcommands,\n execute: executeRewindCommand,\n };\n}\n\nexport class RewindCommandSource implements ICommandSource {\n readonly name = 'rewind';\n\n getCommands(): ICommand[] {\n return [createRewindCommandEntry()];\n }\n}\n\nexport function createRewindCommandModule(): ICommandModule {\n return {\n name: 'agent-command-rewind',\n commandSources: [new RewindCommandSource()],\n systemCommands: [createRewindSystemCommand()],\n };\n}\n","import { createHash } from 'node:crypto';\n\n/** Fixed loops are spread across a stable wall-clock slot; self-paced delays are not jittered. */\nexport function jitterFixedLoop(\n loopId: string,\n cadence: { description: string; milliseconds: number; cronExpression: string },\n): { cronExpression: string; jitterSeconds: number } {\n const maxSeconds = Math.floor(Math.min(30 * 60, cadence.milliseconds / 2_000));\n const hash = createHash('sha256').update(loopId).digest().readUInt32BE(0);\n const jitterSeconds = hash % (maxSeconds + 1);\n if (jitterSeconds === 0) return { cronExpression: cadence.cronExpression, jitterSeconds };\n\n const match = /^(\\d+)(s|m|h)$/.exec(cadence.description);\n if (!match) throw new Error('Unsupported fixed-loop cadence for jitter.');\n const step = Number(match[1]);\n const unit = match[2];\n const second = jitterSeconds % 60;\n const minute = Math.floor(jitterSeconds / 60);\n if (unit === 's') {\n return {\n cronExpression: step === 60\n ? `${jitterSeconds} * * * * *`\n : `${jitterSeconds}-59/${step} * * * * *`,\n jitterSeconds,\n };\n }\n if (unit === 'm') {\n return {\n cronExpression: step === 60\n ? `${second} ${minute} * * * *`\n : `${second} ${minute}-59/${step} * * * *`,\n jitterSeconds,\n };\n }\n return {\n cronExpression: step === 24\n ? `${second} ${minute} 0 * * *`\n : `${second} ${minute} */${step} * * *`,\n jitterSeconds,\n };\n}\n","/** Fixed or self-paced session-local repetition. */\n\nimport { randomUUID } from 'node:crypto';\n\nimport { jitterFixedLoop } from './loop-jitter.js';\n\nimport type { IAgentJobHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IBackgroundTaskState } from '@robota-sdk/agent-interface-execution';\n\nconst LOOP_LABEL = 'Loop: ';\nconst SECONDS_PER_MINUTE = 60;\nconst HOURS_PER_DAY = 24;\nconst MAX_LABEL_LENGTH = 48;\nconst MAX_ACTIVE_LOOPS = 3;\nconst LOOP_LIFETIME_MS = 7 * 24 * 60 * 60_000;\nconst MAX_DEFAULT_PROMPT_LENGTH = 4_096;\nconst pendingCreates = new WeakMap<object, number>();\nconst TRAILING_UNITS = new Set([\n 'second', 'seconds', 'minute', 'minutes', 'hour', 'hours', 'day', 'days', 's', 'm', 'h', 'd',\n]);\nconst USAGE =\n 'Usage: /loop [<prompt>] | /loop <N><s|m|h|d> [<prompt>] | /loop <prompt> every <N> <unit> | /loop list | /loop stop <id>. Bare and interval-only forms require a host maintenance prompt.';\n\nexport interface ILoopCommandOptions {\n /** Product-host-owned maintenance text, used only when the operator omits a prompt. */\n defaultPrompt?: string;\n /** Re-read the project/user default for each new loop; an explicit prompt never calls this. */\n resolveDefaultPrompt?: () => string;\n /** Host kill switch; listing and stopping existing loops remain available. */\n disabled?: boolean;\n}\n\nconst UNIT_MS: Record<string, number> = {\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\ninterface ILoopCadence {\n cronExpression: string;\n milliseconds: number;\n description: string;\n}\n\nconst CADENCES: ILoopCadence[] = [\n ...divisors(SECONDS_PER_MINUTE).map((n) => ({\n cronExpression: n === SECONDS_PER_MINUTE ? '0 * * * * *' : `*/${n} * * * * *`,\n milliseconds: n * UNIT_MS.s!,\n description: `${n}s`,\n })),\n ...divisors(SECONDS_PER_MINUTE)\n .filter((n) => n > 1)\n .map((n) => ({\n cronExpression: n === SECONDS_PER_MINUTE ? '0 0 * * * *' : `0 */${n} * * * *`,\n milliseconds: n * UNIT_MS.m!,\n description: `${n}m`,\n })),\n ...divisors(HOURS_PER_DAY)\n .filter((n) => n > 1)\n .map((n) => ({\n cronExpression: n === HOURS_PER_DAY ? '0 0 0 * * *' : `0 0 */${n} * * *`,\n milliseconds: n * UNIT_MS.h!,\n description: `${n}h`,\n })),\n];\n\nfunction divisors(maximum: number): number[] {\n return Array.from({ length: maximum }, (_, index) => index + 1).filter(\n (value) => maximum % value === 0,\n );\n}\n\nfunction parseDuration(amountText: string, unit: string): number | undefined {\n const amount = Number(amountText);\n const multiplier = UNIT_MS[unit];\n if (!Number.isSafeInteger(amount) || amount <= 0 || multiplier === undefined) return undefined;\n const milliseconds = amount * multiplier;\n return Number.isSafeInteger(milliseconds) && milliseconds <= UNIT_MS.d ? milliseconds : undefined;\n}\n\nfunction parseTrailingInterval(args: string): { instruction: string; amount: string; unit: string } | undefined {\n let cursor = args.length;\n while (cursor > 0 && /[a-z]/i.test(args[cursor - 1]!)) cursor -= 1;\n const unit = args.slice(cursor).toLowerCase();\n if (!TRAILING_UNITS.has(unit)) return undefined;\n while (cursor > 0 && /\\s/u.test(args[cursor - 1]!)) cursor -= 1;\n const amountEnd = cursor;\n while (cursor > 0 && args.charCodeAt(cursor - 1) >= 48 && args.charCodeAt(cursor - 1) <= 57) cursor -= 1;\n if (cursor === amountEnd) return undefined;\n const amount = args.slice(cursor, amountEnd);\n const spaceAfterEvery = cursor;\n while (cursor > 0 && /\\s/u.test(args[cursor - 1]!)) cursor -= 1;\n if (cursor === spaceAfterEvery || args.slice(cursor - 5, cursor).toLowerCase() !== 'every') return undefined;\n cursor -= 5;\n const spaceBeforeEvery = cursor;\n while (cursor > 0 && /\\s/u.test(args[cursor - 1]!)) cursor -= 1;\n if (cursor === spaceBeforeEvery) return undefined;\n const instruction = args.slice(0, cursor).trim();\n return instruction ? { instruction, amount, unit } : undefined;\n}\n\nfunction parseCreate(\n args: string,\n defaultPrompt: string | undefined,\n): { instruction: string; requestedMs: number } | undefined {\n const boundedDefault =\n defaultPrompt && defaultPrompt.length <= MAX_DEFAULT_PROMPT_LENGTH\n ? defaultPrompt.trim()\n : undefined;\n if (args === '') return undefined;\n const intervalOnly = /^(\\d+)(s|m|h|d)$/i.exec(args);\n if (intervalOnly && boundedDefault) {\n const requestedMs = parseDuration(intervalOnly[1]!, intervalOnly[2]!.toLowerCase());\n return requestedMs === undefined ? undefined : { instruction: boundedDefault, requestedMs };\n }\n const leading = /^(\\d+)(s|m|h|d)\\s+([\\s\\S]+)$/i.exec(args);\n if (leading) {\n const instruction = leading[3]!.trim();\n const requestedMs = parseDuration(leading[1]!, leading[2]!.toLowerCase());\n if (instruction && requestedMs !== undefined && !parseTrailingInterval(instruction)) {\n return { instruction, requestedMs };\n }\n return undefined;\n }\n\n const trailing = parseTrailingInterval(args);\n if (!trailing) return undefined;\n const requestedMs = parseDuration(trailing.amount, trailing.unit[0]!);\n return requestedMs !== undefined ? { instruction: trailing.instruction, requestedMs } : undefined;\n}\n\nfunction chooseCadence(requestedMs: number): ILoopCadence {\n // Calendar-aligned cron steps cannot express every duration. Choose the first step that is\n // never more frequent than requested, and report the normalization to the caller.\n return CADENCES.find((cadence) => cadence.milliseconds >= requestedMs)!;\n}\n\nfunction activeLoops(host: Pick<IAgentJobHostContext, 'listSchedules'>): IBackgroundTaskState[] {\n return host\n .listSchedules()\n .filter(\n (task) =>\n task.metadata?.['sessionLoop'] === true &&\n task.metadata?.['sessionLoopSelfPaced'] !== true &&\n task.status !== 'cancelled' &&\n task.status !== 'completed' &&\n task.status !== 'failed',\n );\n}\n\nfunction activeSelfPacedLoops(host: Pick<IAgentJobHostContext, 'listSelfPacedLoops'>) {\n return (host.listSelfPacedLoops?.() ?? []).filter(\n (loop) => loop.phase !== 'stopped' && loop.phase !== 'expired',\n );\n}\n\nfunction loopIdOf(task: IBackgroundTaskState): string {\n const id = task.metadata?.['sessionLoopId'];\n // Loops created before stable ids were introduced keep their runtime id as the stop handle.\n return typeof id === 'string' && id.length > 0 ? id : task.id;\n}\n\nexport async function executeLoopCommand(\n host: Pick<IAgentJobHostContext, 'spawnScheduledWake' | 'listSchedules' | 'createSelfPacedLoop' | 'listSelfPacedLoops' | 'stopSelfPacedLoop'>,\n cancelBackgroundTask: (taskId: string, reason: string) => Promise<void>,\n args: string,\n options: ILoopCommandOptions = {},\n): Promise<ICommandResult> {\n const trimmed = args.trim();\n if (trimmed === 'list') return listLoops(host, options);\n if (/^stop(?:\\s|$)/.test(trimmed)) return stopLoop(host, cancelBackgroundTask, trimmed);\n\n if (options.disabled) {\n return { success: false, message: 'Session loops are disabled by the host.' };\n }\n return createLoop(host, trimmed, options);\n}\n\nfunction listLoops(\n host: Pick<IAgentJobHostContext, 'listSchedules' | 'listSelfPacedLoops'>,\n options: ILoopCommandOptions,\n): ICommandResult {\n const loops = activeLoops(host);\n const selfPaced = activeSelfPacedLoops(host);\n const header = options.disabled ? 'Session loops are disabled by the host.\\n' : '';\n return {\n success: true,\n message:\n header +\n (loops.length + selfPaced.length === 0\n ? 'No active loops.'\n : [\n ...loops.map((task) => `- ${loopIdOf(task)} [${task.status}] ${task.label}`),\n ...selfPaced.map((loop) =>\n `- ${loop.loopId} [${loop.phase}] Loop: ${loop.instruction}` +\n (loop.phase === 'waiting' && loop.delaySeconds !== undefined && loop.reason\n ? ` — next ${loop.delaySeconds}s: ${loop.reason}`\n : ''),\n ),\n ].join('\\n')),\n data: { count: loops.length + selfPaced.length },\n };\n}\n\nasync function stopLoop(\n host: Pick<IAgentJobHostContext, 'listSchedules' | 'listSelfPacedLoops' | 'stopSelfPacedLoop'>,\n cancelBackgroundTask: (taskId: string, reason: string) => Promise<void>,\n args: string,\n): Promise<ICommandResult> {\n const match = /^stop\\s+(\\S+)$/.exec(args);\n if (!match) return { success: false, message: USAGE };\n const selfPaced = activeSelfPacedLoops(host).find((loop) => loop.loopId === match[1]);\n if (selfPaced) {\n if (!host.stopSelfPacedLoop) return { success: false, message: 'This host cannot stop self-paced loops.' };\n await host.stopSelfPacedLoop(selfPaced.loopId, 'Loop stopped by user');\n return {\n success: true,\n message: `Loop stopped: ${selfPaced.loopId}. An already-running turn may finish.`,\n data: { loopId: selfPaced.loopId },\n };\n }\n const task = activeLoops(host).find((candidate) => loopIdOf(candidate) === match[1]);\n if (!task) return { success: false, message: `Active loop not found: ${match[1]}` };\n await cancelBackgroundTask(task.id, 'Loop stopped by user');\n return {\n success: true,\n message: `Loop stopped: ${loopIdOf(task)}. An already-running turn may finish.`,\n data: { loopId: loopIdOf(task), taskId: task.id },\n };\n}\n\nasync function createLoop(\n host: Pick<IAgentJobHostContext, 'spawnScheduledWake' | 'listSchedules' | 'createSelfPacedLoop' | 'listSelfPacedLoops'>,\n args: string,\n options: ILoopCommandOptions,\n): Promise<ICommandResult> {\n const useDefaultPrompt = args === '' || /^\\d+(s|m|h|d)$/i.test(args);\n let defaultPrompt = options.defaultPrompt;\n if (useDefaultPrompt && options.resolveDefaultPrompt) {\n try {\n defaultPrompt = options.resolveDefaultPrompt();\n } catch (error) {\n return { success: false, message: `Default loop prompt could not be loaded: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n const parsed = parseCreate(args, defaultPrompt);\n if (!parsed) {\n if (/^\\d+[a-z](?:\\s|$)/i.test(args) || parseTrailingInterval(args)) {\n return { success: false, message: USAGE };\n }\n const instruction = (args || defaultPrompt || '').trim();\n if (!instruction || (args === '' && instruction.length > MAX_DEFAULT_PROMPT_LENGTH)) {\n return { success: false, message: USAGE };\n }\n if (!host.createSelfPacedLoop) {\n return { success: false, message: 'Self-paced loops require a persistent interactive session.' };\n }\n const pending = pendingCreates.get(host) ?? 0;\n if (activeLoops(host).length + activeSelfPacedLoops(host).length + pending >= MAX_ACTIVE_LOOPS) {\n return { success: false, message: `At most ${MAX_ACTIVE_LOOPS} active loops are allowed. Stop one before creating another.` };\n }\n pendingCreates.set(host, pending + 1);\n try {\n const loop = useDefaultPrompt\n ? await host.createSelfPacedLoop(instruction, { useDefaultPrompt: true })\n : await host.createSelfPacedLoop(instruction);\n return {\n success: true,\n message: `Self-paced loop ${loop.loopId} started. It will choose a 1–60 minute delay after each iteration and expires ${loop.expiresAt}. Stop with /loop stop ${loop.loopId}.`,\n data: { loopId: loop.loopId, expiresAt: loop.expiresAt },\n };\n } finally {\n const remaining = (pendingCreates.get(host) ?? 1) - 1;\n if (remaining === 0) pendingCreates.delete(host);\n else pendingCreates.set(host, remaining);\n }\n }\n const pending = pendingCreates.get(host) ?? 0;\n if (activeLoops(host).length + activeSelfPacedLoops(host).length + pending >= MAX_ACTIVE_LOOPS) {\n return {\n success: false,\n message: `At most ${MAX_ACTIVE_LOOPS} active loops are allowed. Stop one before creating another.`,\n };\n }\n const cadence = chooseCadence(parsed.requestedMs);\n const label = `${LOOP_LABEL}${parsed.instruction.slice(0, MAX_LABEL_LENGTH)}`;\n const loopId = `loop_${randomUUID()}`;\n const jitter = jitterFixedLoop(loopId, cadence);\n const nowMs = Date.now();\n const firstAllowedAt = new Date(nowMs + parsed.requestedMs).toISOString();\n const expiresAt = new Date(nowMs + LOOP_LIFETIME_MS).toISOString();\n pendingCreates.set(host, pending + 1);\n let task: IBackgroundTaskState;\n try {\n task = await host.spawnScheduledWake({\n label,\n cronExpression: jitter.cronExpression,\n agentInstruction: parsed.instruction,\n sessionLoop: true,\n sessionLoopId: loopId,\n ...(useDefaultPrompt ? { sessionLoopDefaultPrompt: true } : {}),\n sessionLoopFirstAllowedAt: firstAllowedAt,\n sessionLoopExpiresAt: expiresAt,\n });\n } finally {\n const remaining = (pendingCreates.get(host) ?? 1) - 1;\n if (remaining === 0) pendingCreates.delete(host);\n else pendingCreates.set(host, remaining);\n }\n const rounded = cadence.milliseconds !== parsed.requestedMs ? ' (rounded up)' : '';\n // `spawnScheduledWake` always spawns a scheduled-kind task; the kind check lets TypeScript\n // narrow to the member that carries `nextFireAt` (#2079).\n const nextFire =\n task.kind === 'scheduled' && task.nextFireAt && task.nextFireAt >= firstAllowedAt\n ? ` Next fire: ${task.nextFireAt}.`\n : '';\n return {\n success: true,\n message: `Loop ${loopId} uses a ${cadence.description}${rounded} local-clock step with stable offset +${jitter.jitterSeconds}s; elapsed gaps can change with daylight saving. First eligible at or after ${firstAllowedAt}.${nextFire} Expires: ${expiresAt}. Stop with /loop stop ${loopId}.`,\n data: {\n loopId,\n taskId: task.id,\n requestedMs: parsed.requestedMs,\n cadenceLabel: cadence.description,\n cronExpression: jitter.cronExpression,\n jitterSeconds: jitter.jitterSeconds,\n firstAllowedAt,\n expiresAt,\n },\n };\n}\n","/**\n * FLOW-005: parse the `<when>` portion of `/schedule` into a cron expression croner accepts.\n *\n * Two forms:\n * in <N><unit> <instruction> — one-shot, fires once at now + duration (s|m|h|d)\n * cron \"<expr>\" <instruction> — recurring, a standard cron expression\n */\n\nexport interface IScheduleSpec {\n cronExpression: string;\n instruction: string;\n recurring: boolean;\n}\n\nexport type TScheduleParseResult = { ok: true; spec: IScheduleSpec } | { ok: false; error: string };\n\nconst DURATION_MS: Record<string, number> = {\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\nconst USAGE =\n 'Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron \"<expr>\" <instruction>';\n\nexport function parseScheduleSpec(args: string, now: number): TScheduleParseResult {\n const trimmed = args.trim();\n if (trimmed.length === 0) return { ok: false, error: USAGE };\n\n if (trimmed.startsWith('in ')) {\n const rest = trimmed.slice(3).trim();\n const spaceIdx = rest.indexOf(' ');\n if (spaceIdx === -1) return { ok: false, error: `Missing instruction. ${USAGE}` };\n const durationToken = rest.slice(0, spaceIdx);\n const instruction = rest.slice(spaceIdx + 1).trim();\n const match = /^(\\d+)(s|m|h|d)$/.exec(durationToken);\n if (!match) return { ok: false, error: `Invalid duration \"${durationToken}\". ${USAGE}` };\n if (instruction.length === 0) return { ok: false, error: `Missing instruction. ${USAGE}` };\n const ms = parseInt(match[1]!, 10) * DURATION_MS[match[2]!]!;\n return {\n ok: true,\n spec: {\n cronExpression: new Date(now + ms).toISOString(),\n instruction,\n recurring: false,\n },\n };\n }\n\n if (trimmed.startsWith('cron ')) {\n const rest = trimmed.slice(5).trim();\n // `(\\S.*)` — not `(.+)`: `\\s+(.+)` is ambiguous (`.` also matches spaces), so a failing\n // input runs in O(n^2). Requiring the instruction to start with a non-space pins the split\n // point after the greedy `\\s+`, making the match linear. Behaviour is unchanged because the\n // greedy `\\s+` already consumed every leading space and the capture is trimmed below.\n const quoted = /^[\"']([^\"']+)[\"']\\s+(\\S.*)$/.exec(rest);\n if (!quoted) {\n return { ok: false, error: `cron form needs a quoted expression. ${USAGE}` };\n }\n const instruction = quoted[2]!.trim();\n if (instruction.length === 0) return { ok: false, error: `Missing instruction. ${USAGE}` };\n return {\n ok: true,\n spec: { cronExpression: quoted[1]!.trim(), instruction, recurring: true },\n };\n }\n\n return { ok: false, error: USAGE };\n}\n","/**\n * FLOW-005: `/schedule` and `/monitor` command executors — create agent-wake background tasks.\n */\n\nimport { MonitorCommandRefusedError } from '@robota-sdk/agent-framework';\nimport { parseScheduleSpec } from './schedule-spec-parser.js';\n\nimport type { IAgentJobHostContext } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nimport type { IBackgroundTaskState } from '@robota-sdk/agent-interface-execution';\n\nconst MAX_LABEL_LENGTH = 48;\n\nfunction labelFor(prefix: string, instruction: string): string {\n const snippet = instruction.slice(0, MAX_LABEL_LENGTH);\n return `${prefix}: ${snippet}${instruction.length > MAX_LABEL_LENGTH ? '…' : ''}`;\n}\n\n// SELFHOST-012: management subcommands over the existing scheduler. Create (FLOW-005) stays the default form —\n// a create spec always begins with `in`/`cron`, so these keywords never collide with it.\nconst MANAGE_USAGE =\n 'Usage: /schedule list | pause <id> | resume <id> | edit <id> <spec> (or a create spec: in <N><s|m|h|d> … | cron \"<expr>\" …)';\n\n/** One-line list view: id, status, cadence, label, and next-fire time. The `[status]` already conveys paused. */\nfunction formatScheduleList(schedules: IBackgroundTaskState[]): string {\n if (schedules.length === 0) return 'No schedules.';\n return schedules\n .map((s) => {\n // `listSchedules()` only ever returns scheduled-kind tasks; the kind check is what lets\n // TypeScript narrow to the member that carries `schedule`/`nextFireAt` (#2079).\n const cadence =\n s.kind === 'scheduled' ? (s.schedule?.cronExpression ?? '(unknown)') : '(unknown)';\n const when = s.kind === 'scheduled' && s.nextFireAt ? `next ${s.nextFireAt}` : '—';\n return `- ${s.id} [${s.status}] ${cadence} — ${s.label} (${when})`;\n })\n .join('\\n');\n}\n\nasync function executeScheduleManagement(\n host: IAgentJobHostContext,\n action: string,\n rest: string,\n now: number,\n): Promise<ICommandResult | undefined> {\n if (action === 'list') {\n const schedules = host.listSchedules();\n return {\n message: formatScheduleList(schedules),\n success: true,\n data: { count: schedules.length },\n };\n }\n if (action === 'pause' || action === 'resume') {\n const id = rest.split(/\\s+/)[0];\n if (!id) return { message: MANAGE_USAGE, success: false };\n if (action === 'pause') {\n await host.pauseSchedule(id);\n return { message: `Schedule paused: ${id}`, success: true, data: { taskId: id } };\n }\n await host.resumeSchedule(id);\n return { message: `Schedule resumed: ${id}`, success: true, data: { taskId: id } };\n }\n if (action === 'edit') {\n const idSpaceIdx = rest.indexOf(' ');\n const id = idSpaceIdx === -1 ? rest : rest.slice(0, idSpaceIdx);\n const spec = idSpaceIdx === -1 ? '' : rest.slice(idSpaceIdx + 1).trim();\n if (!id || !spec) return { message: MANAGE_USAGE, success: false };\n const parsed = parseScheduleSpec(spec, now);\n if (!parsed.ok) return { message: parsed.error, success: false };\n await host.editSchedule(id, {\n cronExpression: parsed.spec.cronExpression,\n agentInstruction: parsed.spec.instruction,\n // CMD-009: `list` renders the label, so it must follow the instruction it summarizes.\n label: labelFor('Scheduled', parsed.spec.instruction),\n });\n return {\n message: `Schedule updated: ${id} (cron \\`${parsed.spec.cronExpression}\\`).`,\n success: true,\n data: { taskId: id, cronExpression: parsed.spec.cronExpression },\n };\n }\n return undefined; // not a management subcommand — fall through to create\n}\n\nexport async function executeScheduleCommand(\n host: IAgentJobHostContext,\n args: string,\n now: number = Date.now(),\n): Promise<ICommandResult> {\n const trimmed = args.trim();\n const spaceIdx = trimmed.indexOf(' ');\n const action = (spaceIdx === -1 ? trimmed : trimmed.slice(0, spaceIdx)).toLowerCase();\n const rest = spaceIdx === -1 ? '' : trimmed.slice(spaceIdx + 1).trim();\n\n const managed = await executeScheduleManagement(host, action, rest, now);\n if (managed) return managed;\n\n // Default: create (FLOW-005 form). On a parse failure also surface the management usage — a mistyped\n // subcommand (e.g. `pasue <id>`) falls through here, and the create-only error hides list/pause/resume/edit.\n const parsed = parseScheduleSpec(args, now);\n if (!parsed.ok) return { message: `${parsed.error}\\n${MANAGE_USAGE}`, success: false };\n\n const { cronExpression, instruction, recurring } = parsed.spec;\n const task = await host.spawnScheduledWake({\n label: labelFor('Scheduled', instruction),\n cronExpression,\n agentInstruction: instruction,\n });\n\n const when = recurring ? `cron \\`${cronExpression}\\`` : `once at ${cronExpression}`;\n return {\n message: `Scheduled wake (${when}): \"${instruction}\" — task ${task.id}.`,\n success: true,\n data: { taskId: task.id, cronExpression, recurring },\n };\n}\n\nconst MONITOR_USAGE = 'Usage: /monitor \"<command>\" \"<pattern>\" <instruction>';\n\n/** Parse `\"<command>\" \"<pattern>\" <instruction>` (quotes may be single or double). */\nfunction parseMonitorArgs(\n args: string,\n): { command: string; matchPattern: string; instruction: string } | null {\n // `(\\S.*)` — not `(.+)`: `\\s+(.+)` is ambiguous (`.` also matches spaces), so a failing input\n // runs in O(n^2). Requiring a non-space first character pins the split point after the greedy\n // `\\s+` and makes the match linear, without changing which inputs are accepted.\n const match = /^[\"']([^\"']+)[\"']\\s+[\"']([^\"']+)[\"']\\s+(\\S.*)$/.exec(args.trim());\n if (!match) return null;\n const instruction = match[3]!.trim();\n if (instruction.length === 0) return null;\n return { command: match[1]!, matchPattern: match[2]!, instruction };\n}\n\nexport async function executeMonitorCommand(\n host: IAgentJobHostContext,\n args: string,\n): Promise<ICommandResult> {\n const parsed = parseMonitorArgs(args);\n if (!parsed) return { message: MONITOR_USAGE, success: false };\n\n let task: IBackgroundTaskState;\n try {\n task = await host.spawnMonitorWake({\n label: labelFor('Monitor', parsed.instruction),\n command: parsed.command,\n matchPattern: parsed.matchPattern,\n agentInstruction: parsed.instruction,\n });\n } catch (error) {\n if (error instanceof MonitorCommandRefusedError) {\n return { message: error.message, success: false };\n }\n throw error;\n }\n\n return {\n message: `Monitoring \\`${parsed.command}\\` for /${parsed.matchPattern}/ — task ${task.id}.`,\n success: true,\n data: { taskId: task.id, matchPattern: parsed.matchPattern },\n };\n}\n","/**\n * FLOW-005: the `/schedule` + `/monitor` command module — surfaces agent-wake scheduling\n * and process monitoring to users (and the model as tools).\n */\n\nimport { executeLoopCommand } from './loop-command.js';\nimport { executeMonitorCommand, executeScheduleCommand } from './schedule-command.js';\n\nimport type { ILoopCommandOptions } from './loop-command.js';\nimport type {\n IAgentJobHostContext,\n ICommandHostAgentJobs,\n ICommandModule,\n ISystemCommand,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandResult, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nfunction getAgentHostContext(context: ICommandHostAgentJobs): IAgentJobHostContext {\n const cap = context.getAgentJobCapability();\n if (!cap) throw new Error('Scheduling requires an active agent runtime.');\n return cap;\n}\n\nconst SCHEDULE_DESCRIPTION =\n 'Schedule the agent to wake on a timer, and manage schedules (list / pause / resume / edit).';\nconst SCHEDULE_ARGUMENT_HINT =\n 'in <N><s|m|h|d> <instruction> | cron \"<expr>\" <instruction> | list | pause <id> | resume <id> | edit <id> <spec>';\nconst MONITOR_DESCRIPTION =\n 'Watch a process’s output and wake the agent when a line matches a pattern.';\nconst MONITOR_ARGUMENT_HINT = '\"<command>\" \"<pattern>\" <instruction>';\n\n// Model-invocable, all three: waking itself later, watching a process and repeating a prompt are the\n// model's own pacing. `/monitor` starts a process, so the model's command is decided by the shell\n// tool's own gate (see the system command below) — never a way around a Bash/Shell rule.\nconst SCHEDULE_MODEL_DESCRIPTION =\n 'Wake yourself later with an instruction. Use it when work must wait (a deploy, a long build, a ' +\n 'reply) instead of polling: `in <N><s|m|h|d> <instruction>` or `cron \"<expr>\" <instruction>`; ' +\n '`list`, `pause`, `resume` and `edit` manage existing schedules. Returns the schedule id, or the ' +\n 'schedule list.';\nconst MONITOR_MODEL_DESCRIPTION =\n 'Run a command in the background and wake yourself when a line of its output matches a pattern. ' +\n 'Use it to wait for a server to start, a test to fail or a log line to appear instead of polling. ' +\n 'The command is allowed, refused or asked about by the same permission rules as a shell tool ' +\n 'call. Returns the monitor task id, or a refusal naming what the user must allow.';\nconst LOOP_MODEL_DESCRIPTION =\n 'Repeat a prompt on a fixed cadence (`<N><s|m|h|d> [prompt]`) or self-paced (bare or prompt ' +\n 'only: each iteration chooses its next delay or stops). Use it when the user asks for recurring ' +\n 'work in this session. `list` shows active loops; `stop <id>` ends one. Returns the loop id and ' +\n 'its next fire time, or the loop list.';\n\nexport function createScheduleCommandEntry(): ICommand {\n return {\n name: 'schedule',\n displayName: 'Schedule Wake',\n description: SCHEDULE_DESCRIPTION,\n modelDescription: SCHEDULE_MODEL_DESCRIPTION,\n source: 'schedule',\n argumentHint: SCHEDULE_ARGUMENT_HINT,\n modelInvocable: true,\n };\n}\n\nexport function createMonitorCommandEntry(): ICommand {\n return {\n name: 'monitor',\n displayName: 'Monitor Process',\n description: MONITOR_DESCRIPTION,\n modelDescription: MONITOR_MODEL_DESCRIPTION,\n source: 'schedule',\n argumentHint: MONITOR_ARGUMENT_HINT,\n modelInvocable: true,\n };\n}\n\nexport function createLoopCommandEntry(): ICommand {\n return {\n name: 'loop',\n displayName: 'Repeat Prompt',\n description:\n 'Repeat a prompt on a fixed cadence or let each iteration choose its next delay; list or stop active loops.',\n modelDescription: LOOP_MODEL_DESCRIPTION,\n source: 'schedule',\n argumentHint: '[prompt] | <N><s|m|h|d> [prompt] | <prompt> every <N> <unit> | list | stop <id>',\n modelInvocable: true,\n subcommands: [\n { name: 'list', description: 'List active loops', source: 'schedule' },\n {\n name: 'stop',\n description: 'Stop an active loop',\n source: 'schedule',\n argumentHint: '<id>',\n },\n ],\n };\n}\n\nfunction createScheduleSystemCommand(): ISystemCommand {\n const entry = createScheduleCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n execute: (context, args): Promise<ICommandResult> =>\n executeScheduleCommand(getAgentHostContext(context), args),\n };\n}\n\nfunction createMonitorSystemCommand(): ISystemCommand {\n const entry = createMonitorCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n // It starts a process, so it is never treated as read-only (a remote read-only policy refuses\n // it). The MODEL's call is not asked about by the command's name: the host decides the\n // monitored command as a shell tool call (hooks, Bash/Shell rules, the mode and the prompt, never\n // the sandbox's auto-approval), so one \"always allow\" of `/monitor` never approves another command.\n requiresPermission: true,\n modelRequiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n lifecycle: 'inline',\n execute: (context, args): Promise<ICommandResult> =>\n executeMonitorCommand(getAgentHostContext(context), args),\n };\n}\n\nfunction createLoopSystemCommand(options: ILoopCommandOptions): ISystemCommand {\n const entry = createLoopCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n // A static conservative classification keeps remote read-only policies from admitting\n // create/stop through this mixed read/write command; list is gated too.\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: (context, args): Promise<ICommandResult> =>\n executeLoopCommand(\n getAgentHostContext(context),\n (taskId, reason) => context.cancelBackgroundTask(taskId, reason),\n args,\n options,\n ),\n };\n}\n\nexport class ScheduleCommandSource implements ICommandSource {\n readonly name = 'schedule';\n\n getCommands(): ICommand[] {\n return [createScheduleCommandEntry(), createMonitorCommandEntry(), createLoopCommandEntry()];\n }\n}\n\nexport function createScheduleCommandModule(options: ILoopCommandOptions = {}): ICommandModule {\n return {\n name: 'agent-command-schedule',\n commandSources: [new ScheduleCommandSource()],\n systemCommands: [\n createScheduleSystemCommand(),\n createMonitorSystemCommand(),\n createLoopSystemCommand(options),\n ],\n sessionRequirements: ['agent-runtime'],\n };\n}\n","import { calculateModelCost } from '@robota-sdk/agent-core';\n\n/**\n * Returns USD cost, or undefined if the model is not in the pricing table.\n * Delegates to the agent-core pricing SSOT (`calculateModelCost`); this package owns only the\n * command-facing display helpers below.\n */\nexport function calculateCost(\n modelId: string,\n inputTokens: number,\n outputTokens: number,\n): number | undefined {\n return calculateModelCost(modelId, inputTokens, outputTokens);\n}\n\n/** Format a USD amount for display (e.g. \"$0.0043\"). */\nexport function formatUsd(amount: number): string {\n if (amount < 0.01) return `$${amount.toFixed(4)}`;\n if (amount < 1) return `$${amount.toFixed(3)}`;\n return `$${amount.toFixed(2)}`;\n}\n\n/** Format a token count with comma separators (e.g. \"45,000\"). */\nexport function formatTokens(count: number): string {\n return count.toLocaleString('en-US');\n}\n","import { confirmAction, isConfirmed } from '@robota-sdk/agent-core';\nimport {\n RENAME_COMMAND_USAGE,\n clearConversationHistory,\n createShowSessionPickerIntent,\n createSessionRenameHostAction,\n formatCommandSessionReplayValidationReport,\n parseSessionNameArgument,\n readCommandSessionInfo,\n validateCommandSessionReplayLog,\n} from '@robota-sdk/agent-framework';\n\nimport { calculateCost, formatTokens, formatUsd } from './model-pricing.js';\n\nimport type {\n ICommandCostBudgetAdapter,\n ICommandHostAdapterAccess,\n ICommandHostNoCapability,\n ICommandHostSessionAccess,\n ICommandHostUserInteraction,\n ICommandHostWorkspace,\n ISessionUsageRecord,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport const CLEAR_COMMAND_MESSAGE = 'Conversation cleared.';\n\nexport const CD_COMMAND_DESCRIPTION = 'Move this session to another working directory';\nexport const CD_COMMAND_USAGE = 'Usage: /cd <directory>';\n\n/**\n * `/cd <directory>` (issue #3081) requests the host-executed move. The checks — no turn running, no\n * live background task, the target exists, no `Cd(...)` deny rule — run where the session state is,\n * when the host applies the action.\n */\nexport function executeCdCommand(_context: ICommandHostNoCapability, args: string): ICommandResult {\n const path = args.trim();\n if (path === '') return { success: false, message: CD_COMMAND_USAGE };\n return { success: true, message: '', hostActions: [{ type: 'workspace-move', path }] };\n}\n\nexport async function executeClearCommand(\n context: ICommandHostSessionAccess & ICommandHostUserInteraction,\n _args: string,\n): Promise<ICommandResult> {\n // Confirm only when an interactive renderer is attached; with no human the explicit /clear proceeds.\n const ui = context.getUserInteraction();\n if (ui) {\n const response = await ui.ask(confirmAction('clear', 'Clear conversation history?'));\n if (!isConfirmed(response)) {\n return { success: true, message: 'Clear cancelled.' };\n }\n }\n\n // CMD-004 Stage E: the clear mutation runs host-side and the session broadcasts `history_cleared`\n // to every attached surface — the result carries no separate notification.\n clearConversationHistory(context);\n return { success: true, message: CLEAR_COMMAND_MESSAGE };\n}\n\nexport function executeRenameCommand(\n _context: ICommandHostNoCapability,\n args: string,\n): ICommandResult {\n const name = parseSessionNameArgument(args);\n if (name === undefined) {\n return { success: false, message: RENAME_COMMAND_USAGE };\n }\n\n return {\n success: true,\n message: `Session renamed to \"${name}\".`,\n data: { name },\n hostActions: [createSessionRenameHostAction(name)],\n };\n}\n\nexport function executeResumeCommand(): ICommandResult {\n return {\n success: true,\n message: 'Opening session picker...',\n data: { triggerResumePicker: true },\n uiIntents: [createShowSessionPickerIntent()],\n };\n}\n\ntype TCostCommandContext = ICommandHostSessionAccess &\n ICommandHostWorkspace &\n ICommandHostAdapterAccess;\n\n/**\n * CMD-007 (issue #2058): the budget lives behind `ICommandCostBudgetAdapter`, composed by the shell.\n * This package owns no path literal and no filesystem call for it any more — atomic/symlink-safe\n * writing is the adapter's policy (agent-cli's file adapter keeps the O_NOFOLLOW guard).\n */\nfunction costBudgetAdapter(context: TCostCommandContext): ICommandCostBudgetAdapter | undefined {\n return context.getCommandHostAdapters?.().costBudget;\n}\n\nconst BUDGET_UNAVAILABLE_MESSAGE =\n 'Budget persistence is not available on this host (no cost-budget adapter was composed).';\n\n/** What to tell the operator when the adapter refused the write; the adapter names the cause. */\nfunction describeBudgetWriteFailure(error: unknown): string {\n return `Could not write the budget: ${error instanceof Error ? error.message : String(error)}`;\n}\n\ninterface ICostTotals {\n inputTokens: number;\n outputTokens: number;\n /** Absent when nothing could be priced. */\n costUsd?: number;\n /** Some usage could not be priced, so the cost is a lower bound. */\n partial: boolean;\n /** The models the cost was priced on. */\n models: string[];\n}\n\n/**\n * Total the session's usage records. A record priced on its own model (the advisor's) keeps that\n * price; a main-thread record without one is priced on the session's model. A consulted model whose\n * price is unknown is left unpriced rather than priced as the main model.\n */\nfunction totalSessionUsage(\n records: readonly ISessionUsageRecord[],\n modelId: string | undefined,\n): ICostTotals | undefined {\n if (records.length === 0) return undefined;\n const totals: ICostTotals = { inputTokens: 0, outputTokens: 0, partial: false, models: [] };\n const models = new Set<string>();\n let cost = 0;\n let priced = false;\n for (const record of records) {\n totals.inputTokens += record.promptTokens;\n totals.outputTokens += record.completionTokens;\n const consulted = record.source?.scope === 'tool';\n const recordCost =\n record.costUsd ??\n (!consulted && modelId\n ? calculateCost(modelId, record.promptTokens, record.completionTokens)\n : undefined);\n if (recordCost === undefined) {\n totals.partial = true;\n continue;\n }\n cost += recordCost;\n priced = true;\n models.add(consulted ? (record.source?.label ?? 'another model') : (modelId ?? 'main model'));\n }\n if (priced) totals.costUsd = cost;\n totals.models = [...models];\n return totals;\n}\n\nfunction buildCostOutput(context: TCostCommandContext): {\n lines: string[];\n data: Record<string, unknown>;\n} {\n const session = context.getSession();\n const sessionInfo = readCommandSessionInfo(context);\n const modelId = session.getModelId();\n const totals = totalSessionUsage(context.getSessionUsage(), modelId);\n const lines: string[] = [\n `Session: ${sessionInfo.sessionId}`,\n `Messages: ${sessionInfo.messageCount}`,\n ];\n const data: Record<string, unknown> = {\n sessionId: sessionInfo.sessionId,\n messageCount: sessionInfo.messageCount,\n };\n\n if (totals) {\n lines.push(\n `Tokens: ${formatTokens(totals.inputTokens)} input / ${formatTokens(totals.outputTokens)} output`,\n );\n data.inputTokens = totals.inputTokens;\n data.outputTokens = totals.outputTokens;\n\n const cost = totals.costUsd;\n if (cost !== undefined) {\n const priced =\n totals.models.length > 1 ? `mixed: ${totals.models.join(', ')}` : (totals.models[0] ?? '');\n const note = totals.partial ? '; some usage could not be priced' : '';\n lines.push(`Cost: ${formatUsd(cost)} (${priced}${note})`);\n data.estimatedCostUsd = cost;\n data.costModels = totals.models;\n if (totals.partial) data.costPartial = true;\n\n const budget = costBudgetAdapter(context)?.read();\n if (budget?.monthly) {\n const remaining = budget.monthly - cost;\n const pct = Math.min(100, Math.round((cost / budget.monthly) * 100));\n lines.push(\n `Budget: ${formatUsd(remaining)} remaining of ${formatUsd(budget.monthly)}/mo (${pct}% used)`,\n );\n data.budgetMonthly = budget.monthly;\n data.budgetRemainingUsd = remaining;\n }\n }\n } else {\n lines.push('Tokens: not yet available (no turns completed)');\n }\n\n return { lines, data };\n}\n\nexport function executeCostCommand(context: TCostCommandContext, args: string): ICommandResult {\n const trimmed = args.trim();\n\n if (trimmed.startsWith('budget')) {\n const budgetArg = trimmed.slice('budget'.length).trim();\n // Argument shape is judged before the host is asked for persistence: a malformed amount is a\n // usage error on every host, not a symptom of the adapter that would have stored it.\n const amount = budgetArg === 'clear' || budgetArg === '' ? undefined : parseFloat(budgetArg);\n if (amount !== undefined && (!Number.isFinite(amount) || amount <= 0)) {\n return {\n success: false,\n message: 'Usage: /cost budget <amount> (e.g. /cost budget 5.00)',\n };\n }\n const adapter = costBudgetAdapter(context);\n if (adapter === undefined) return { success: false, message: BUDGET_UNAVAILABLE_MESSAGE };\n\n if (budgetArg === 'clear') {\n try {\n adapter.clear();\n } catch (error) {\n return { success: false, message: describeBudgetWriteFailure(error) };\n }\n return { success: true, message: 'Monthly budget cleared.' };\n }\n\n if (budgetArg === '') {\n const current = adapter.read();\n if (!current?.monthly) {\n return {\n success: true,\n message: 'No budget set. Use: /cost budget <amount>',\n };\n }\n return { success: true, message: `Monthly budget: ${formatUsd(current.monthly)}` };\n }\n\n if (amount === undefined) return { success: false, message: BUDGET_UNAVAILABLE_MESSAGE };\n try {\n adapter.write({ monthly: amount });\n } catch (error) {\n return { success: false, message: describeBudgetWriteFailure(error) };\n }\n return { success: true, message: `Monthly budget set to ${formatUsd(amount)}.` };\n }\n\n const { lines, data } = buildCostOutput(context);\n return { success: true, message: lines.join('\\n'), data };\n}\n\nexport function executeValidateSessionCommand(\n context: ICommandHostSessionAccess & ICommandHostWorkspace,\n _args: string,\n): ICommandResult {\n const report = validateCommandSessionReplayLog(context);\n return {\n success: report.validation.ok,\n message: formatCommandSessionReplayValidationReport(report),\n data: {\n logFile: report.logFile,\n entryCount: report.entryCount,\n issueCount: report.validation.issues.length,\n ok: report.validation.ok,\n },\n };\n}\n","import {\n CLEAR_COMMAND_DESCRIPTION,\n COST_COMMAND_DESCRIPTION,\n RENAME_COMMAND_DESCRIPTION,\n RESUME_COMMAND_DESCRIPTION,\n VALIDATE_SESSION_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport {\n CD_COMMAND_DESCRIPTION,\n executeCdCommand,\n executeClearCommand,\n executeCostCommand,\n executeRenameCommand,\n executeResumeCommand,\n executeValidateSessionCommand,\n} from './session-command.js';\nimport { createSystemCommandFromEntry } from '../command-module-utils.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createClearCommandEntry(): ICommand {\n return {\n name: 'clear',\n displayName: 'Clear History',\n description: CLEAR_COMMAND_DESCRIPTION,\n source: 'session',\n // User-only: wiping the conversation is the user's decision.\n modelInvocable: false,\n userInvocable: true,\n };\n}\n\nexport function createRenameCommandEntry(): ICommand {\n return {\n name: 'rename',\n displayName: 'Rename Session',\n description: RENAME_COMMAND_DESCRIPTION,\n argumentHint: '<name>',\n source: 'session',\n // User-only: the session's name is the user's label; UI-only.\n modelInvocable: false,\n userInvocable: true,\n };\n}\n\nexport function createCdCommandEntry(): ICommand {\n return {\n name: 'cd',\n displayName: 'Change Directory',\n description: CD_COMMAND_DESCRIPTION,\n argumentHint: '<directory>',\n source: 'session',\n // A move re-roots what every later tool call may touch; only the user decides it.\n modelInvocable: false,\n userInvocable: true,\n };\n}\n\nexport function createResumeCommandEntry(): ICommand {\n return {\n name: 'resume',\n displayName: 'Resume Session',\n description: RESUME_COMMAND_DESCRIPTION,\n source: 'session',\n // User-only: switching to another session is the user's decision.\n modelInvocable: false,\n userInvocable: true,\n };\n}\n\nexport function createCostCommandEntry(): ICommand {\n return {\n name: 'cost',\n displayName: 'Session Cost',\n description: COST_COMMAND_DESCRIPTION,\n // Model-invocable for the read-only report only: the model can weigh cost before an expensive\n // step. The monthly budget is the user's spending decision, so `budget` stays user-only.\n modelDescription:\n 'Report this session’s token usage and estimated cost. Use it before an expensive step (a ' +\n 'large refactor, many subagents) or when the user asks what the session has cost. Returns ' +\n 'the message count, input/output token totals and the estimated USD cost, with the remaining ' +\n 'monthly budget when one is set. Setting or clearing the budget is the user’s decision: suggest `/cost budget <amount>`.',\n argumentHint: '[budget [<amount>|clear]]',\n // The bare `/cost` is the report, so choosing it from a menu runs it.\n runsBare: true,\n source: 'session',\n modelInvocable: true,\n userInvocable: true,\n subcommands: [\n {\n name: 'budget',\n description: 'Show, set, or clear the monthly budget',\n argumentHint: '[<amount>|clear]',\n source: 'session',\n modelInvocable: false,\n },\n ],\n };\n}\n\nexport function createValidateSessionCommandEntry(): ICommand {\n return {\n name: 'validate-session',\n displayName: 'Validate Session',\n description: VALIDATE_SESSION_COMMAND_DESCRIPTION,\n source: 'session',\n // User-only: a diagnostic of the replay log for the user; nothing the model acts on.\n modelInvocable: false,\n userInvocable: true,\n };\n}\n\nfunction createClearSystemCommand(): ISystemCommand {\n const entry = createClearCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: executeClearCommand,\n });\n}\n\nfunction createRenameSystemCommand(): ISystemCommand {\n const entry = createRenameCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: executeRenameCommand,\n });\n}\n\nfunction createCdSystemCommand(): ISystemCommand {\n const entry = createCdCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: executeCdCommand,\n });\n}\n\nfunction createResumeSystemCommand(): ISystemCommand {\n const entry = createResumeCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: executeResumeCommand,\n });\n}\n\nfunction createCostSystemCommand(): ISystemCommand {\n const entry = createCostCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: executeCostCommand,\n });\n}\n\nfunction createValidateSessionSystemCommand(): ISystemCommand {\n const entry = createValidateSessionCommandEntry();\n return createSystemCommandFromEntry(entry, {\n requiresPermission: false,\n lifecycle: 'inline',\n execute: executeValidateSessionCommand,\n });\n}\n\nexport class SessionCommandSource implements ICommandSource {\n readonly name = 'session';\n\n getCommands(): ICommand[] {\n return [\n createClearCommandEntry(),\n createRenameCommandEntry(),\n createCdCommandEntry(),\n createResumeCommandEntry(),\n createCostCommandEntry(),\n createValidateSessionCommandEntry(),\n ];\n }\n}\n\nexport function createSessionCommandModule(): ICommandModule {\n return {\n name: 'agent-command-session',\n commandSources: [new SessionCommandSource()],\n systemCommands: [\n createClearSystemCommand(),\n createRenameSystemCommand(),\n createCdSystemCommand(),\n createResumeSystemCommand(),\n createCostSystemCommand(),\n createValidateSessionSystemCommand(),\n ],\n };\n}\n","import type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createSettingsCommandEntry(): ICommand {\n return {\n name: 'settings',\n displayName: 'Settings',\n description: 'Open transport settings — enable/disable transports and configure options',\n source: 'settings',\n // User-only: transport settings screen; UI-only.\n modelInvocable: false,\n };\n}\n\nfunction createSettingsSystemCommand(): ISystemCommand {\n const entry = createSettingsCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: async () => ({\n success: true,\n message: 'Opening settings...',\n uiIntents: [{ type: 'show-settings' as const }],\n }),\n };\n}\n\nexport class SettingsCommandSource implements ICommandSource {\n readonly name = 'settings';\n\n getCommands(): ICommand[] {\n return [createSettingsCommandEntry()];\n }\n}\n\nexport function createSettingsCommandModule(): ICommandModule {\n return {\n name: 'agent-command-settings',\n commandSources: [new SettingsCommandSource()],\n systemCommands: [createSettingsSystemCommand()],\n };\n}\n","/**\n * TERM-003 shell-selection seam, now backed by the cross-platform SSOT resolver in agent-core\n * (TERM-008). Keep all shell choice behind this function so the call sites never change; the\n * per-platform logic (POSIX `$SHELL`/`sh`, Windows PowerShell) lives once in `resolvePlatformShell`.\n */\nimport { resolvePlatformShell } from '@robota-sdk/agent-core';\n\nexport interface IResolvedShell {\n /** Executable to spawn. */\n command: string;\n /** Args for an interactive shell session (drop-to-shell). */\n interactiveArgs: readonly string[];\n /** Args to run a single command string non-interactively. */\n commandArgs(command: string): readonly string[];\n}\n\n/** Resolve the interactive shell for the current platform via the agent-core SSOT resolver. */\nexport function resolveShell(executable?: string): IResolvedShell {\n const shell = resolvePlatformShell({ executable });\n return {\n command: shell.command,\n interactiveArgs: shell.interactiveArgs,\n commandArgs: (cmd: string) => shell.commandArgs(cmd),\n };\n}\n","/**\n * TERM-003: `/shell` — hand the real terminal to an interactive subshell (or run a single command\n * interactively), then return to the agent session. Uses the framework terminal-handoff capability;\n * the shell choice goes through the `resolveShell()` seam (macOS/Linux first).\n */\nimport { resolveShell } from './resolve-shell.js';\nimport { spawnInherited } from './spawn-inherited.js';\n\nimport type {\n ICommandHostTerminalHandoff,\n ICommandHostWorkspace,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport const SHELL_COMMAND_DESCRIPTION =\n 'Drop to an interactive shell (or run `/shell <command>` interactively), then return to the agent.';\n\nexport async function executeShellCommand(\n context: ICommandHostTerminalHandoff & ICommandHostWorkspace,\n args: string,\n executable?: string,\n): Promise<ICommandResult> {\n if (!context.canHandoffTerminal()) {\n return {\n message: 'An interactive shell is unavailable here (no interactive terminal).',\n success: false,\n };\n }\n\n const shell = resolveShell(executable);\n const cwd = context.getCwd();\n const command = args.trim();\n\n const exitCode = await context.runWithTerminal(async () =>\n command.length > 0\n ? spawnInherited(shell.command, shell.commandArgs(command), cwd)\n : spawnInherited(shell.command, shell.interactiveArgs, cwd),\n );\n\n return {\n message:\n command.length > 0\n ? `Command exited (code ${exitCode}).`\n : `Shell session ended (code ${exitCode}).`,\n success: exitCode === 0,\n data: { exitCode },\n };\n}\n","/**\n * TERM-003: `/shell` command module — a framework-level consumer of the terminal-handoff capability.\n */\nimport { executeShellCommand, SHELL_COMMAND_DESCRIPTION } from './shell-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createShellCommandEntry(): ICommand {\n return {\n name: 'shell',\n displayName: 'Shell',\n description: SHELL_COMMAND_DESCRIPTION,\n source: 'shell',\n // User-only: the user's own shell passthrough; the model has its permission-gated shell tool.\n modelInvocable: false,\n };\n}\n\nfunction createShellSystemCommand(executable?: string): ISystemCommand {\n const entry = createShellCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: true,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: (context, args) => executeShellCommand(context, args, executable),\n };\n}\n\nexport class ShellCommandSource implements ICommandSource {\n readonly name = 'shell';\n\n getCommands(): ICommand[] {\n return [createShellCommandEntry()];\n }\n}\n\nexport function createShellCommandModule(executable?: string): ICommandModule {\n return {\n name: 'agent-command-shell',\n commandSources: [new ShellCommandSource()],\n systemCommands: [createShellSystemCommand(executable)],\n };\n}\n","import type {\n ICommandHostCatalog,\n ICommandHostWorkspace,\n ICommandSkillListEntry,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport const SKILLS_COMMAND_DESCRIPTION = 'List registered skills, or activate one by name';\n\n/** What the model is told about `skills`; `SKILLS_COMMAND_DESCRIPTION` is the `/help` line. */\nexport const SKILLS_COMMAND_MODEL_DESCRIPTION =\n 'Skill command. Before following a matching registered skill from the system prompt Skills section, invoke the projected skills command tool with args \"<skill-name> [args]\". Without arguments, list registered skills. With a skill name, activate that skill; a skill that declares it is not model-invocable is refused. Returns the skill list with each skill\\'s description, or the activated skill\\'s instructions to follow. Slash syntax is a UI input/display concern; the SDK command identity is \"skills\".';\n\ninterface IParsedSkillsArgs {\n readonly action: 'list' | 'activate';\n readonly skillName?: string;\n readonly skillArgs: string;\n}\n\nfunction formatSkillFlags(skill: ICommandSkillListEntry): string {\n const flags: string[] = [];\n if (!skill.modelInvocable) flags.push('model-disabled');\n if (!skill.userInvocable) flags.push('model-only');\n if (skill.context) flags.push(`context:${skill.context}`);\n if (skill.agent) flags.push(`agent:${skill.agent}`);\n return flags.length > 0 ? ` [${flags.join(', ')}]` : '';\n}\n\nfunction formatSkillLine(skill: ICommandSkillListEntry): string {\n const hint = skill.argumentHint ? ` ${skill.argumentHint}` : '';\n return `- ${skill.name}${hint}: ${skill.description}${formatSkillFlags(skill)}`;\n}\n\nfunction formatSkillsMessage(skills: readonly ICommandSkillListEntry[]): string {\n if (skills.length === 0) {\n return [\n 'No skills are registered for this session.',\n '',\n 'Skills are metadata until activated. Do not invent or imitate a skill workflow when no matching registered skill exists.',\n ].join('\\n');\n }\n\n return [\n 'Registered skills:',\n ...skills.map(formatSkillLine),\n '',\n 'Activation contract:',\n '- Use /skills <skill-name> [args] to activate a matching skill.',\n '- Treat /<skill-name> as a virtual alias for /skills <skill-name>.',\n '- The system prompt Skills section is skill selection metadata.',\n '- Treat descriptions as selection metadata only, not as loaded SKILL.md content.',\n '- Do not answer by merely naming, recommending, or imitating a matching skill.',\n '- If no listed skill matches the task, continue without claiming a skill was activated.',\n ].join('\\n');\n}\n\nfunction parseSkillsArgs(args: string): IParsedSkillsArgs {\n const trimmed = args.trim();\n if (trimmed.length === 0 || trimmed === 'list') {\n return { action: 'list', skillArgs: '' };\n }\n\n const [skillName = '', ...rest] = trimmed.split(/\\s+/);\n if (skillName.length === 0) {\n return { action: 'list', skillArgs: '' };\n }\n\n return {\n action: 'activate',\n skillName,\n skillArgs: rest.join(' '),\n };\n}\n\nexport async function executeSkillsCommand(\n context: ICommandHostCatalog & ICommandHostWorkspace,\n args = '',\n): Promise<ICommandResult> {\n const parsed = parseSkillsArgs(args);\n if (parsed.action === 'activate' && parsed.skillName !== undefined) {\n const displayInput = `/${parsed.skillName}${parsed.skillArgs ? ` ${parsed.skillArgs}` : ''}`;\n const result = await context.executeSkillCommandByName(parsed.skillName, parsed.skillArgs, {\n invocationSource: context.getCommandInvocationSource(),\n displayInput,\n rawInput: displayInput,\n });\n return (\n result ?? {\n success: false,\n message: `Unknown skill: ${parsed.skillName}`,\n }\n );\n }\n\n const skills = context.listSkills();\n return {\n success: true,\n message: formatSkillsMessage(skills),\n data: {\n skills,\n activationContract: {\n activateWith: '/skills <skill-name> [args]',\n activationRequiredBeforeWorkflow: true,\n metadataIsNotSkillContent: true,\n },\n },\n };\n}\n","import { SkillCommandSource } from '@robota-sdk/agent-framework';\n\nimport {\n executeSkillsCommand,\n SKILLS_COMMAND_DESCRIPTION,\n SKILLS_COMMAND_MODEL_DESCRIPTION,\n} from './skills-command.js';\n\nimport type {\n ICommandModule,\n IContributionSource,\n ISystemCommand,\n ISkillRootDescriptor,\n} from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport interface ISkillsCommandModuleOptions {\n readonly contributionSources: readonly IContributionSource[];\n readonly skillRoots?: readonly ISkillRootDescriptor[];\n}\n\nexport function createSkillsCommandEntry(): ICommand {\n return {\n name: 'skills',\n displayName: 'Skills',\n description: SKILLS_COMMAND_DESCRIPTION,\n // Model-invocable: activating a skill is how the model follows one; a skill's own\n // `disable-model-invocation` frontmatter still refuses it per skill.\n modelDescription: SKILLS_COMMAND_MODEL_DESCRIPTION,\n source: 'skills',\n modelInvocable: true,\n userInvocable: true,\n argumentHint: '[list | <skill-name> [args]]',\n safety: 'read-only',\n };\n}\n\nfunction createSkillsSystemCommand(): ISystemCommand {\n const entry = createSkillsCommandEntry();\n return {\n name: entry.name,\n semanticRole: 'skillActivation',\n ...(entry.modelDescription !== undefined ? { modelDescription: entry.modelDescription } : {}),\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: true,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n lifecycle: 'inline',\n execute: executeSkillsCommand,\n };\n}\n\nexport class SkillsCommandSource implements ICommandSource {\n readonly name = 'skills';\n\n getCommands(): ICommand[] {\n return [createSkillsCommandEntry()];\n }\n}\n\nexport function createSkillsCommandModule(options: ISkillsCommandModuleOptions): ICommandModule {\n const commandSources: ICommandSource[] = [new SkillsCommandSource()];\n commandSources.push(\n new SkillCommandSource(options.contributionSources, options.skillRoots ?? []),\n );\n\n return {\n name: 'agent-command-skills',\n commandSources,\n systemCommands: [createSkillsSystemCommand()],\n };\n}\n","import { DEFAULT_STATUS_LINE_COMMAND_SETTINGS } from '@robota-sdk/agent-framework';\n\nimport type { ICommandHostNoCapability } from '@robota-sdk/agent-framework';\nimport type {\n ICommandResult,\n TStatusLineCommandSettingsPatch,\n} from '@robota-sdk/agent-interface-command';\n\ninterface IStatusLineCommandSuccessAction {\n success: true;\n message: string;\n patch: TStatusLineCommandSettingsPatch;\n}\n\ninterface IStatusLineCommandFailureAction {\n success: false;\n message: string;\n}\n\ntype TStatusLineCommandAction = IStatusLineCommandSuccessAction | IStatusLineCommandFailureAction;\n\nexport const STATUSLINE_USAGE = [\n 'Usage: /statusline on | off | reset | git on | git off',\n 'Fields: model, context, permission mode, message count, session name, thinking state, git branch.',\n].join('\\n');\n\nfunction parseStatusLineArgs(args: string): TStatusLineCommandAction {\n const parts = args\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n const [first, second] = parts;\n\n if (first === 'on' && second === undefined) {\n return { success: true, message: 'Status line enabled.', patch: { enabled: true } };\n }\n if (first === 'off' && second === undefined) {\n return { success: true, message: 'Status line disabled.', patch: { enabled: false } };\n }\n if (first === 'reset' && second === undefined) {\n return {\n success: true,\n message: 'Status line settings reset.',\n patch: { ...DEFAULT_STATUS_LINE_COMMAND_SETTINGS },\n };\n }\n if (first === 'git' && second === 'on' && parts.length === 2) {\n return {\n success: true,\n message: 'Status line git branch shown.',\n patch: { gitBranch: true },\n };\n }\n if (first === 'git' && second === 'off' && parts.length === 2) {\n return {\n success: true,\n message: 'Status line git branch hidden.',\n patch: { gitBranch: false },\n };\n }\n\n return { success: false, message: STATUSLINE_USAGE };\n}\n\nexport function executeStatusLineCommand(\n _context: ICommandHostNoCapability,\n args: string,\n): ICommandResult {\n const action = parseStatusLineArgs(args);\n if (!action.success) {\n return { success: false, message: action.message };\n }\n\n return {\n success: true,\n message: action.message,\n hostActions: [{ type: 'statusline-settings-patch', patch: action.patch }],\n };\n}\n","import {\n buildStatusLineCommandSubcommands,\n STATUSLINE_COMMAND_ARGUMENT_HINT,\n STATUSLINE_COMMAND_DESCRIPTION,\n} from '@robota-sdk/agent-framework';\n\nimport { executeStatusLineCommand } from './statusline-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createStatusLineCommandEntry(): ICommand {\n return {\n name: 'statusline',\n displayName: 'Status Line',\n description: STATUSLINE_COMMAND_DESCRIPTION,\n source: 'statusline',\n argumentHint: STATUSLINE_COMMAND_ARGUMENT_HINT,\n subcommands: buildStatusLineCommandSubcommands('statusline'),\n // User-only: UI preference.\n modelInvocable: false,\n };\n}\n\nfunction createStatusLineSystemCommand(): ISystemCommand {\n const entry = createStatusLineCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n subcommands: entry.subcommands,\n lifecycle: 'inline',\n execute: executeStatusLineCommand,\n };\n}\n\nexport class StatusLineCommandSource implements ICommandSource {\n readonly name = 'statusline';\n\n getCommands(): ICommand[] {\n return [createStatusLineCommandEntry()];\n }\n}\n\nexport function createStatusLineCommandModule(): ICommandModule {\n return {\n name: 'agent-command-statusline',\n commandSources: [new StatusLineCommandSource()],\n systemCommands: [createStatusLineSystemCommand()],\n };\n}\n","import type {\n ICommandModule,\n ISystemCommand,\n TAppearanceSettingsPatch,\n} from '@robota-sdk/agent-framework';\nimport type {\n ICommand,\n ICommandResult,\n ICommandSource,\n IThemeAppearanceState,\n IThemeCatalogueEntry,\n IThemeCataloguePort,\n} from '@robota-sdk/agent-interface-command';\n\nconst THEME_DESCRIPTION =\n 'List, preview or switch the terminal colour theme, and toggle syntax highlighting and motion';\nconst THEME_ARGUMENT_HINT = 'list | <theme-id> | syntax on|off | motion on|off';\n\nconst THEME_UNAVAILABLE = 'Themes are not available in this environment.';\n\nfunction formatToggle(value: boolean): string {\n return value ? 'on' : 'off';\n}\n\nfunction formatCatalogue(catalogue: IThemeCataloguePort): string {\n const { settings, reducedMotionPin } = catalogue.getAppearance();\n const rows = catalogue.listThemes().map((theme) => {\n const marker = theme.id === settings.theme ? '* ' : ' ';\n return `${marker}${theme.id} — ${theme.name} (${theme.appearance}, ${theme.source})`;\n });\n // Two facts, never one: what this run does, and what is saved. Reporting the SAVED value beside\n // the tier reads as a contradiction on a `--no-reduced-motion` run over a `true` setting, and as\n // an outright wrong answer to \"is motion reduced right now\".\n const motion = reducedMotionPin\n ? `${formatToggle(reducedMotionPin.reducedMotion)} for this run (pinned by ${reducedMotionPin.tier}; saved ${formatToggle(settings.reducedMotion)})`\n : formatToggle(settings.reducedMotion);\n return [\n 'Available themes:',\n ...rows,\n '',\n `syntax highlighting: ${formatToggle(settings.syntaxHighlighting)}`,\n `reduced motion: ${motion}`,\n ].join('\\n');\n}\n\nfunction listResult(catalogue: IThemeCataloguePort): ICommandResult {\n return {\n success: true,\n message: formatCatalogue(catalogue),\n data: {\n themes: catalogue.listThemes().map((theme) => ({ ...theme })),\n appearance: { ...catalogue.getAppearance().settings },\n },\n };\n}\n\nfunction unknownThemeResult(id: string, catalogue: IThemeCataloguePort): ICommandResult {\n const known = catalogue\n .listThemes()\n .map((theme) => theme.id)\n .join(', ');\n return {\n success: false,\n message: `Unknown theme \"${id}\". Available: ${known || '(none)'}`,\n };\n}\n\n/** `on` / `off`, and nothing else — a typo must not read as its opposite. */\nfunction parseToggle(word: string | undefined): boolean | undefined {\n if (word === 'on') return true;\n if (word === 'off') return false;\n return undefined;\n}\n\ninterface IParsedThemeArgs {\n readonly patch?: TAppearanceSettingsPatch;\n readonly themeId?: string;\n readonly error?: string;\n}\n\n/**\n * `/theme <id> [syntax on|off] [motion on|off]`, or a bare `syntax`/`motion` toggle. The theme id is\n * NOT resolved here — parsing answers what was asked for, and the caller decides whether the\n * catalogue holds it, so an unknown id is reported with the catalogue rather than as a parse error.\n */\nfunction parseThemeArgs(tokens: readonly string[]): IParsedThemeArgs {\n const patch: TAppearanceSettingsPatch = {};\n let index = 0;\n let themeId: string | undefined;\n if (tokens[0] !== 'syntax' && tokens[0] !== 'motion') {\n themeId = tokens[0];\n index = 1;\n }\n while (index < tokens.length) {\n const key = tokens[index];\n const value = parseToggle(tokens[index + 1]);\n if ((key !== 'syntax' && key !== 'motion') || value === undefined) {\n return { error: `Usage: /theme ${THEME_ARGUMENT_HINT}` };\n }\n if (key === 'syntax') patch.syntaxHighlighting = value;\n else patch.reducedMotion = !value;\n index += 2;\n }\n return { patch, ...(themeId === undefined ? {} : { themeId }) };\n}\n\n/**\n * `motion on` means \"animate\", which is `reducedMotion: false`. The inversion lives in one place\n * precisely because reading it backwards is the easy mistake — a user asking for motion and getting\n * stillness would look like the command doing nothing.\n */\nfunction describeChange(\n patch: TAppearanceSettingsPatch,\n theme: IThemeCatalogueEntry | undefined,\n state: IThemeAppearanceState,\n): string {\n const parts: string[] = [];\n if (theme) parts.push(`theme ${theme.name}`);\n if (patch.syntaxHighlighting !== undefined) {\n parts.push(`syntax highlighting ${formatToggle(patch.syntaxHighlighting)}`);\n }\n if (patch.reducedMotion !== undefined) {\n parts.push(`motion ${formatToggle(!patch.reducedMotion)}`);\n }\n const applied = parts.length > 0 ? `Applied: ${parts.join(', ')}.` : 'Nothing to change.';\n // The pin is reported, never silently obeyed or silently overridden: the setting IS persisted and\n // takes effect next run, while this run keeps what pinned it.\n if (patch.reducedMotion !== undefined && state.reducedMotionPin) {\n return `${applied} Saved, but this run keeps reduced motion pinned by ${state.reducedMotionPin.tier}.`;\n }\n return applied;\n}\n\nexport function executeThemeCommand(\n catalogue: IThemeCataloguePort | undefined,\n args: string,\n): ICommandResult {\n if (!catalogue) return { success: false, message: THEME_UNAVAILABLE };\n\n const tokens = args.trim().split(/\\s+/u).filter(Boolean);\n if (tokens.length === 0) {\n return {\n success: true,\n message: 'Opening the theme picker...',\n uiIntents: [{ type: 'show-theme-picker' }],\n };\n }\n if (tokens.length === 1 && tokens[0] === 'list') return listResult(catalogue);\n\n const parsed = parseThemeArgs(tokens);\n if (parsed.error !== undefined || !parsed.patch) {\n return { success: false, message: parsed.error ?? `Usage: /theme ${THEME_ARGUMENT_HINT}` };\n }\n\n const patch = { ...parsed.patch };\n let theme: IThemeCatalogueEntry | undefined;\n if (parsed.themeId !== undefined) {\n theme = catalogue.getTheme(parsed.themeId);\n // An unknown id writes NOTHING — not the theme, and not the toggles submitted beside it.\n if (!theme) return unknownThemeResult(parsed.themeId, catalogue);\n patch.theme = theme.id;\n }\n\n return {\n success: true,\n message: describeChange(patch, theme, catalogue.getAppearance()),\n data: { appearance: { ...patch } },\n hostActions: [{ type: 'appearance-settings-patch', patch }],\n };\n}\n\nexport function createThemeCommandEntry(): ICommand {\n return {\n name: 'theme',\n displayName: 'Theme',\n description: THEME_DESCRIPTION,\n argumentHint: THEME_ARGUMENT_HINT,\n source: 'theme',\n userInvocable: true,\n // User-only: UI preference.\n modelInvocable: false,\n };\n}\n\nexport class ThemeCommandSource implements ICommandSource {\n readonly name = 'theme';\n\n getCommands(): ICommand[] {\n return [createThemeCommandEntry()];\n }\n}\n\nexport function createThemeCommandModule(catalogue: IThemeCataloguePort): ICommandModule {\n const entry = createThemeCommandEntry();\n const command: ISystemCommand = {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n argumentHint: entry.argumentHint,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n lifecycle: 'inline',\n execute: (_context, args) => executeThemeCommand(catalogue, args),\n };\n return {\n name: 'agent-command-theme',\n commandSources: [new ThemeCommandSource()],\n systemCommands: [command],\n };\n}\n","export const USER_LOCAL_COMMAND_DESCRIPTION = 'Inspect user-local storage and memory state.';\nexport const USER_LOCAL_COMMAND_ARGUMENT_HINT =\n 'storage list [--format json] | memory set/list/inspect/disable/delete';\nexport const USER_LOCAL_COMMAND_USAGE =\n '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>';\n","import {\n deleteUserLocalMemoryItem,\n disableUserLocalMemoryItem,\n inspectUserLocalMemoryItem,\n listUserLocalMemoryItems,\n setUserLocalMemoryItem,\n} from '@robota-sdk/agent-framework';\n\nimport { USER_LOCAL_COMMAND_USAGE } from './user-local-command-constants.js';\n\nimport type { TUserLocalMemoryCategory } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\n\nexport interface IUserLocalMemoryCommandArgs {\n readonly action?: string;\n readonly positional: readonly string[];\n readonly format: 'text' | 'json';\n readonly summary?: string;\n readonly source?: string;\n}\n\nfunction formatMemoryListText(\n items: readonly { category: string; key: string; enabled: boolean }[],\n): string {\n if (items.length === 0) {\n return 'No user-local memory items.';\n }\n return items\n .map((item) => `- ${item.category}/${item.key} (${item.enabled ? 'enabled' : 'disabled'})`)\n .join('\\n');\n}\n\nfunction parseMemoryCategory(value: string | undefined): TUserLocalMemoryCategory {\n if (value === undefined) {\n throw new Error('User-local memory category is required.');\n }\n return value as TUserLocalMemoryCategory;\n}\n\nasync function executeMemoryListCommand(\n activeRepositoryRoot: string,\n storageRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const list = await listUserLocalMemoryItems({ activeRepositoryRoot, storageRoot });\n return {\n message:\n parsed.format === 'json' ? JSON.stringify(list, null, 2) : formatMemoryListText(list.items),\n success: true,\n data: { list },\n };\n}\n\nasync function executeMemorySetCommand(\n activeRepositoryRoot: string,\n storageRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key, value] = parsed.positional;\n const item = await setUserLocalMemoryItem({\n activeRepositoryRoot,\n storageRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n value: value ?? '',\n summary: parsed.summary ?? '',\n source: parsed.source ?? '',\n });\n return {\n message: `Stored user-local memory item ${item.category}/${item.key} at ${item.storageLocation}`,\n success: true,\n data: { item },\n };\n}\n\nasync function executeMemoryInspectCommand(\n activeRepositoryRoot: string,\n storageRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key] = parsed.positional;\n const item = await inspectUserLocalMemoryItem({\n activeRepositoryRoot,\n storageRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n });\n return {\n message:\n parsed.format === 'json'\n ? JSON.stringify(item, null, 2)\n : `${item.category}/${item.key}: ${item.summary}`,\n success: true,\n data: { item },\n };\n}\n\nasync function executeMemoryDisableCommand(\n activeRepositoryRoot: string,\n storageRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key] = parsed.positional;\n const item = await disableUserLocalMemoryItem({\n activeRepositoryRoot,\n storageRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n });\n return {\n message: `Disabled user-local memory item ${item.category}/${item.key}`,\n success: true,\n data: { item },\n };\n}\n\nasync function executeMemoryDeleteCommand(\n activeRepositoryRoot: string,\n storageRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n const [category, key] = parsed.positional;\n const result = await deleteUserLocalMemoryItem({\n activeRepositoryRoot,\n storageRoot,\n category: parseMemoryCategory(category),\n key: key ?? '',\n });\n return {\n message: `Deleted user-local memory item ${result.category}/${result.key}`,\n success: true,\n data: { result },\n };\n}\n\nexport async function executeMemoryCommand(\n cwd: string,\n storageRoot: string,\n parsed: IUserLocalMemoryCommandArgs,\n): Promise<ICommandResult> {\n if ((parsed.action ?? 'list') === 'list') {\n return executeMemoryListCommand(cwd, storageRoot, parsed);\n }\n if (parsed.action === 'set') {\n return executeMemorySetCommand(cwd, storageRoot, parsed);\n }\n if (parsed.action === 'inspect') {\n return executeMemoryInspectCommand(cwd, storageRoot, parsed);\n }\n if (parsed.action === 'disable') {\n return executeMemoryDisableCommand(cwd, storageRoot, parsed);\n }\n if (parsed.action === 'delete') {\n return executeMemoryDeleteCommand(cwd, storageRoot, parsed);\n }\n return {\n message: USER_LOCAL_COMMAND_USAGE,\n success: false,\n };\n}\n","import { inspectUserLocalStorage } from '@robota-sdk/agent-framework';\n\nimport { USER_LOCAL_COMMAND_USAGE } from './user-local-command-constants.js';\nimport { executeMemoryCommand } from './user-local-memory-command.js';\n\nimport type { ICommandHostWorkspace } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } from '@robota-sdk/agent-interface-command';\nexport {\n USER_LOCAL_COMMAND_ARGUMENT_HINT,\n USER_LOCAL_COMMAND_DESCRIPTION,\n USER_LOCAL_COMMAND_USAGE,\n} from './user-local-command-constants.js';\n\ntype TUserLocalOutputFormat = 'text' | 'json';\n\nexport interface IUserLocalDirectCommandOptions {\n readonly cwd: string;\n readonly storageRoot: string;\n readonly argv: readonly string[];\n readonly format?: string;\n readonly summary?: string;\n readonly source?: string;\n}\n\ninterface IParsedUserLocalCommand {\n readonly target?: string;\n readonly action?: string;\n readonly positional: readonly string[];\n readonly format: TUserLocalOutputFormat;\n readonly summary?: string;\n readonly source?: string;\n}\n\ninterface IParsedUserLocalOption {\n readonly format?: string;\n readonly summary?: string;\n readonly source?: string;\n readonly nextIndex: number;\n}\n\nfunction parseOutputFormat(value: string | undefined): TUserLocalOutputFormat {\n if (value === undefined || value === 'text') {\n return 'text';\n }\n if (value === 'json') {\n return 'json';\n }\n throw new Error(`Unsupported user-local output format: ${value}`);\n}\n\nfunction parseUserLocalOption(\n arg: string,\n argv: readonly string[],\n index: number,\n): IParsedUserLocalOption | null {\n if (arg === '--format') {\n return { format: argv[index + 1], nextIndex: index + 1 };\n }\n if (arg.startsWith('--format=')) {\n return { format: arg.slice('--format='.length), nextIndex: index };\n }\n if (arg === '--summary') {\n return { summary: argv[index + 1], nextIndex: index + 1 };\n }\n if (arg.startsWith('--summary=')) {\n return { summary: arg.slice('--summary='.length), nextIndex: index };\n }\n if (arg === '--source') {\n return { source: argv[index + 1], nextIndex: index + 1 };\n }\n if (arg.startsWith('--source=')) {\n return { source: arg.slice('--source='.length), nextIndex: index };\n }\n return null;\n}\n\nfunction parseUserLocalArgs(\n argv: readonly string[],\n directOptions: {\n readonly format?: string;\n readonly summary?: string;\n readonly source?: string;\n } = {},\n): IParsedUserLocalCommand {\n let format = directOptions.format;\n let summary = directOptions.summary;\n let source = directOptions.source;\n const positional: string[] = [];\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n const option = parseUserLocalOption(arg, argv, index);\n if (option !== null) {\n format = option.format ?? format;\n summary = option.summary ?? summary;\n source = option.source ?? source;\n index = option.nextIndex;\n continue;\n }\n positional.push(arg);\n }\n\n return {\n target: positional[0],\n action: positional[1],\n positional: positional.slice(2),\n format: parseOutputFormat(format),\n summary,\n source,\n };\n}\n\nfunction splitRawArgs(rawArgs: string): readonly string[] {\n return rawArgs.trim().split(/\\s+/).filter(Boolean);\n}\n\nfunction formatStorageInspectionText(\n root: string,\n categories: readonly { category: string }[],\n): string {\n const categoryLines = categories.map((item) => `- ${item.category}`);\n return [`User-local storage root: ${root}`, 'Categories:', ...categoryLines].join('\\n');\n}\n\nasync function executeStorageCommand(\n cwd: string,\n storageRoot: string,\n parsed: IParsedUserLocalCommand,\n): Promise<ICommandResult> {\n if ((parsed.action ?? 'list') !== 'list') {\n return {\n message: USER_LOCAL_COMMAND_USAGE,\n success: false,\n };\n }\n\n const inspection = await inspectUserLocalStorage({ activeRepositoryRoot: cwd, storageRoot });\n return {\n message:\n parsed.format === 'json'\n ? JSON.stringify(inspection, null, 2)\n : formatStorageInspectionText(inspection.root, inspection.categories),\n success: true,\n data: {\n root: inspection.root,\n categories: inspection.categories,\n inspection,\n },\n };\n}\n\nasync function executeParsedUserLocalCommand(\n cwd: string,\n storageRoot: string,\n parsed: IParsedUserLocalCommand,\n): Promise<ICommandResult> {\n if (parsed.target === 'storage') {\n return executeStorageCommand(cwd, storageRoot, parsed);\n }\n if (parsed.target === 'memory') {\n return executeMemoryCommand(cwd, storageRoot, parsed);\n }\n return {\n message: USER_LOCAL_COMMAND_USAGE,\n success: false,\n };\n}\n\nfunction formatCommandErrorMessage(errorMessage: string): string {\n if (errorMessage.includes('ENOENT')) {\n return 'User-local memory item not found.';\n }\n return errorMessage;\n}\n\nexport async function executeUserLocalDirectCommand(\n options: IUserLocalDirectCommandOptions,\n): Promise<ICommandResult> {\n try {\n return await executeParsedUserLocalCommand(\n options.cwd,\n options.storageRoot,\n parseUserLocalArgs(options.argv, {\n format: options.format,\n summary: options.summary,\n source: options.source,\n }),\n );\n } catch (error) {\n return {\n message: formatCommandErrorMessage(error instanceof Error ? error.message : String(error)),\n success: false,\n };\n }\n}\n\nexport async function executeUserLocalCommand(\n context: ICommandHostWorkspace,\n rawArgs: string,\n storageRoot: string,\n): Promise<ICommandResult> {\n try {\n return await executeParsedUserLocalCommand(\n context.getCwd(),\n storageRoot,\n parseUserLocalArgs(splitRawArgs(rawArgs)),\n );\n } catch (error) {\n return {\n message: formatCommandErrorMessage(error instanceof Error ? error.message : String(error)),\n success: false,\n };\n }\n}\n","import {\n USER_LOCAL_COMMAND_ARGUMENT_HINT,\n USER_LOCAL_COMMAND_DESCRIPTION,\n executeUserLocalCommand,\n} from './user-local-command.js';\n\nimport type { ICommandModule, ISystemCommand } from '@robota-sdk/agent-framework';\nimport type { ICommand, ICommandSource } from '@robota-sdk/agent-interface-command';\n\nexport function createUserLocalCommandEntry(): ICommand {\n return {\n name: 'user-local',\n displayName: 'User Config',\n description: USER_LOCAL_COMMAND_DESCRIPTION,\n source: 'user-local',\n argumentHint: USER_LOCAL_COMMAND_ARGUMENT_HINT,\n // User-only: the user's private cross-project storage.\n modelInvocable: false,\n safety: 'read-only',\n subcommands: [\n {\n name: 'storage',\n description: 'Inspect user-local storage categories',\n source: 'user-local',\n },\n {\n name: 'memory',\n description: 'Inspect and manage user-local memory items',\n source: 'user-local',\n },\n ],\n };\n}\n\nfunction createUserLocalSystemCommand(storageRoot: string): ISystemCommand {\n const entry = createUserLocalCommandEntry();\n return {\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n requiresPermission: false,\n userInvocable: true,\n modelInvocable: false,\n argumentHint: entry.argumentHint,\n safety: entry.safety,\n subcommands: entry.subcommands,\n execute: (context, rawArgs) => executeUserLocalCommand(context, rawArgs, storageRoot),\n };\n}\n\nexport class UserLocalCommandSource implements ICommandSource {\n readonly name = 'user-local';\n\n getCommands(): ICommand[] {\n return [createUserLocalCommandEntry()];\n }\n}\n\nexport function createUserLocalCommandModule(storageRoot: string): ICommandModule {\n return {\n name: 'agent-command-user-local',\n commandSources: [new UserLocalCommandSource()],\n systemCommands: [createUserLocalSystemCommand(storageRoot)],\n };\n}\n","import { findUnknownModuleNames, selectCommandModules } from '@robota-sdk/agent-framework';\n\nimport { createAgentCommandModule } from '../agent/index.js';\nimport { createBackgroundCommandModule } from '../background/index.js';\nimport { createCompactCommandModule } from '../compact/index.js';\nimport { createContextCommandModule } from '../context/index.js';\nimport { createDevicesCommandModule } from '../devices/index.js';\nimport { createDoctorCommandModule } from '../doctor/index.js';\nimport { createEditorCommandModule } from '../editor/index.js';\nimport { createAdvisorCommandModule } from '../advisor/index.js';\nimport { createEffortCommandModule } from '../effort/index.js';\nimport { createExitCommandModule } from '../exit/index.js';\nimport { createForkCommandModule } from '../fork/index.js';\nimport { createGitCommandModule } from '../git/index.js';\nimport { createGoalCommandModule } from '../goal/index.js';\nimport { createHandoffCommandModule } from '../handoff/index.js';\nimport { createHelpCommandModule } from '../help/index.js';\nimport { createKeybindingsCommandModule } from '../keybindings/index.js';\nimport { createLanguageCommandModule } from '../language/index.js';\nimport { createMCPActivationCommandModule } from '../mcp-activation/index.js';\nimport { createMemoryCommandModule } from '../memory/index.js';\nimport { createModeCommandModule } from '../mode/index.js';\nimport { createSandboxCommandModule } from '../sandbox/index.js';\nimport { createOutputStyleCommandModule } from '../output-style/index.js';\nimport { createPeersCommandModule } from '../peers/index.js';\nimport { createPermissionsCommandModule } from '../permissions/index.js';\nimport { createPlanCommandModule } from '../plan/index.js';\nimport { createPluginCommandModule } from '../plugin/index.js';\nimport { createPresetCommandModule } from '../preset/index.js';\nimport { createProviderCommandModule } from '../provider/index.js';\nimport { createRemoteControlCommandModule } from '../remote-control/index.js';\nimport { createResetCommandModule } from '../reset/index.js';\nimport { createRewindCommandModule } from '../rewind/index.js';\nimport { createScheduleCommandModule } from '../schedule/index.js';\nimport { createSessionCommandModule } from '../session/index.js';\nimport { createSettingsCommandModule } from '../settings/index.js';\nimport { createShellCommandModule } from '../shell/index.js';\nimport { createSkillsCommandModule } from '../skills/index.js';\nimport { createStatusLineCommandModule } from '../statusline/index.js';\nimport { createThemeCommandModule } from '../theme/index.js';\nimport { createUserLocalCommandModule } from '../user-local/index.js';\n\nimport type { IDevicesCommandPort } from '../devices/index.js';\nimport type { IDoctorDisplayVocabulary, IDoctorInputs } from '../doctor/index.js';\nimport type { IKeybindingsFilePort } from '../keybindings/index.js';\nimport type { IProviderDefinition } from '@robota-sdk/agent-core';\nimport type {\n IOrgPolicy,\n IContributionSource,\n ISkillRootDescriptor,\n ICommandModule,\n IProviderCommandSettingsAdapter,\n IUnknownCommandModuleName,\n} from '@robota-sdk/agent-framework';\nimport type { IThemeCataloguePort } from '@robota-sdk/agent-interface-command';\n\nexport interface IDefaultCommandModulesOptions {\n cwd: string;\n userLocalStorageRoot: string;\n /** Product-owned prefix for the interactive editor's temporary directory. */\n editorTemporaryDirectoryPrefix?: string;\n contributionSources?: readonly IContributionSource[];\n skillRoots?: readonly ISkillRootDescriptor[];\n providerDefinitions: readonly IProviderDefinition[];\n providerSettingsAdapter: IProviderCommandSettingsAdapter;\n /**\n * CLI-083 (issue #2287) — the org policy, so `allowedProviders` and `requireApiKeyFromEnv` are\n * reachable. This parameter existed, was removed by `92596bc6f` along with its only caller, and\n * the consumer never stopped reading it: `provider-command-profile-operations.ts` still\n * destructures `orgPolicy` from its options and enforces on it. Optional, so its absence stays\n * distinguishable from a policy that allows everything — and that optionality is why nothing went\n * red when the producer dropped it.\n */\n orgPolicy?: IOrgPolicy;\n /** Optional TUI-owned file capability; absence means `/keybindings` is not registered. */\n keybindingsFilePort?: IKeybindingsFilePort;\n /**\n * SCREEN-2002: the surface's theme catalogue. Absence means `/theme` is not registered at all —\n * print mode and `--serve` render no themes, and a command that cannot do anything is better\n * missing than present-and-failing.\n */\n themeCataloguePort?: IThemeCataloguePort;\n /**\n * The host that keeps this device's identity (its terminal, credential store and state files).\n * Absence means `/devices` is not registered: without it the command could do nothing.\n */\n devicesPort?: IDevicesCommandPort;\n /** OBSERVABILITY-1991: host-composed doctor inputs; absence means `/doctor` is not registered. */\n doctorInputs?: IDoctorInputs;\n /** Product-owned diagnostic wording; absent keeps `/doctor` product-neutral. */\n doctorDisplay?: IDoctorDisplayVocabulary;\n /** Product-owned command to resume a saved fork; absent yields neutral host guidance. */\n formatForkResumeCommand?: (sessionId: string) => string;\n /** Host-owned fallback text and kill switch for session-local repeat. */\n loopOptions?: { defaultPrompt?: string; resolveDefaultPrompt?: () => string; disabled?: boolean };\n /**\n * Whitelist of module `name`s to keep. When provided, only modules whose `name`\n * appears here survive. Omitted → all modules kept (no-regression).\n */\n enabledCommandModules?: readonly string[];\n /**\n * Blacklist of module `name`s to remove. Applied after the whitelist, so a name\n * present in both is removed (deny > allow). Omitted → no modules removed.\n */\n disabledCommandModules?: readonly string[];\n}\n\n/**\n * Apply the preset module-selection delta to the default module set.\n *\n * Rules: if `enabled` is provided, keep only modules whose `name` is in it; then\n * remove any module whose `name` is in `disabled` (deny > allow). Neither given →\n * the full default set is returned unchanged (no-regression).\n *\n * INFRA-032: delegates to agent-framework's `selectCommandModules` (the allowed command→framework\n * edge) so the filter body exists once — the previously byte-identical copy here is collapsed.\n */\nfunction applyModuleSelection(\n modules: readonly ICommandModule[],\n enabled: readonly string[] | undefined,\n disabled: readonly string[] | undefined,\n): readonly ICommandModule[] {\n return selectCommandModules(modules, enabled, disabled);\n}\n\n/**\n * Result of {@link createDefaultCommandModules} (INFRA-032): the selected `modules` plus any preset\n * `enabledCommandModules`/`disabledCommandModules` names that matched no built module. Unknown names\n * are returned as data (not dropped silently) so the CLI startup path can surface a non-fatal notice.\n */\nexport interface IDefaultCommandModulesResult {\n readonly modules: readonly ICommandModule[];\n readonly unknownModuleNames: readonly IUnknownCommandModuleName[];\n}\n\nexport function createDefaultCommandModules({\n cwd: _cwd,\n userLocalStorageRoot,\n editorTemporaryDirectoryPrefix,\n contributionSources,\n skillRoots,\n providerDefinitions,\n providerSettingsAdapter,\n orgPolicy,\n keybindingsFilePort,\n themeCataloguePort,\n devicesPort,\n doctorInputs,\n doctorDisplay,\n formatForkResumeCommand,\n loopOptions,\n enabledCommandModules,\n disabledCommandModules,\n}: IDefaultCommandModulesOptions): IDefaultCommandModulesResult {\n const modules: readonly ICommandModule[] = [\n createSkillsCommandModule({ contributionSources: contributionSources ?? [], skillRoots }),\n createHelpCommandModule(),\n createAgentCommandModule(),\n createEffortCommandModule(),\n createAdvisorCommandModule(),\n createPermissionsCommandModule(),\n createModeCommandModule(),\n createSandboxCommandModule(),\n createPresetCommandModule(),\n createOutputStyleCommandModule(),\n createLanguageCommandModule(),\n createBackgroundCommandModule(),\n // CLI-1994: beside `/background`, because a fork IS a background job — the one it starts is\n // listed, peeked at, stopped and attached to through that command and its panel.\n createForkCommandModule(formatForkResumeCommand),\n createGoalCommandModule(),\n createPlanCommandModule(),\n createShellCommandModule(),\n createEditorCommandModule(editorTemporaryDirectoryPrefix),\n createGitCommandModule(),\n ...(keybindingsFilePort === undefined\n ? []\n : [createKeybindingsCommandModule(keybindingsFilePort)]),\n ...(themeCataloguePort === undefined ? [] : [createThemeCommandModule(themeCataloguePort)]),\n ...(doctorInputs === undefined\n ? []\n : [createDoctorCommandModule(doctorInputs, undefined, doctorDisplay)]),\n createMemoryCommandModule(),\n createMCPActivationCommandModule(),\n createUserLocalCommandModule(userLocalStorageRoot),\n createCompactCommandModule(),\n createContextCommandModule(),\n createExitCommandModule(),\n createSessionCommandModule(),\n createResetCommandModule(),\n createRewindCommandModule(),\n createScheduleCommandModule(loopOptions),\n createStatusLineCommandModule(),\n createPluginCommandModule(),\n createSettingsCommandModule(),\n createPeersCommandModule(),\n // HANDOFF-001 (issue #1864). Registered even though no product wires the carrier adapter yet:\n // the command's own answer to a host without one is to say so, which is a better state than a\n // capability nobody can see. It is also what makes the carrier's arrival observable.\n createHandoffCommandModule(),\n createRemoteControlCommandModule(),\n ...(devicesPort === undefined ? [] : [createDevicesCommandModule(devicesPort)]),\n createProviderCommandModule({\n providerDefinitions,\n settings: providerSettingsAdapter,\n ...(orgPolicy === undefined ? {} : { orgPolicy }),\n }),\n ];\n const builtModuleNames = modules.map((module) => module.name);\n return {\n modules: applyModuleSelection(modules, enabledCommandModules, disabledCommandModules),\n unknownModuleNames: findUnknownModuleNames(\n builtModuleNames,\n enabledCommandModules,\n disabledCommandModules,\n ),\n };\n}\n"],"mappings":"o9JAEA,MAAM,GAAqB,kBAoB3B,SAAgB,GAAa,EAAwB,CACnD,IAAM,EAAmB,CAAC,EACtB,EAAU,GACV,EACA,EAAU,GAEd,IAAK,IAAM,KAAQ,EAAM,CACvB,GAAI,EAAS,CACX,GAAW,EACX,EAAU,GACV,QACF,CACA,GAAI,GAAS,IAAS,KAAM,CAC1B,EAAU,GACV,QACF,CACA,GAAI,EAAO,CACL,I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