@robota-sdk/agent-command 3.0.0-beta.76 → 3.0.0-beta.77
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -21
- package/README.md +12 -6
- package/dist/node/index.cjs +38 -33
- package/dist/node/index.d.ts +68 -6
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +40 -35
- package/dist/node/index.js.map +1 -1
- package/package.json +7 -7
- package/src/agent/agent-command-parser.ts +1 -1
- package/src/agent/agent-command.ts +2 -1
- package/src/background/__tests__/background-command-module.test.ts +2 -5
- package/src/default/__tests__/default-command-modules.test.ts +5 -2
- package/src/default/default-command-modules.ts +6 -0
- package/src/editor/__tests__/editor-command-functional.test.ts +91 -0
- package/src/editor/editor-command-module.ts +47 -0
- package/src/editor/editor-command.ts +53 -0
- package/src/editor/index.ts +7 -0
- package/src/editor/resolve-editor.ts +21 -0
- package/src/exit/__tests__/exit-command-module.test.ts +21 -2
- package/src/exit/exit-command-module.ts +1 -10
- package/src/exit/exit-command.ts +15 -1
- package/src/goal/__tests__/goal-command.test.ts +75 -0
- package/src/goal/goal-command-module.ts +48 -0
- package/src/goal/goal-command.ts +70 -0
- package/src/goal/index.ts +6 -0
- package/src/index.ts +3 -0
- package/src/language/__tests__/language-command-module.test.ts +16 -0
- package/src/language/language-command-module.ts +1 -18
- package/src/language/language-command.ts +35 -9
- package/src/mode/__tests__/mode-command-module.test.ts +34 -0
- package/src/mode/mode-command-module.ts +1 -18
- package/src/mode/mode-command.ts +31 -8
- package/src/preset/__tests__/preset-command-module.test.ts +36 -0
- package/src/preset/preset-command-module.ts +1 -18
- package/src/preset/preset-command.ts +37 -8
- package/src/provider/__tests__/org-policy.test.ts +19 -13
- package/src/provider/__tests__/provider-command-module.test.ts +151 -80
- package/src/provider/__tests__/scripted-interaction.ts +28 -0
- package/src/provider/provider-command-execution.ts +67 -50
- package/src/provider/provider-command-module.ts +3 -19
- package/src/provider/provider-command-profile-lifecycle.ts +52 -72
- package/src/provider/provider-command-profile-operations.ts +15 -51
- package/src/provider/provider-command-profile.ts +44 -49
- package/src/provider/provider-command-setup.ts +56 -51
- package/src/session/__tests__/session-command-module.test.ts +38 -0
- package/src/session/session-command-module.ts +1 -10
- package/src/session/session-command.ts +14 -1
- package/src/shell/__tests__/shell-command-functional.test.ts +96 -0
- package/src/shell/index.ts +8 -0
- package/src/shell/resolve-shell.ts +25 -0
- package/src/shell/shell-command-module.ts +47 -0
- package/src/shell/shell-command.ts +44 -0
- package/src/shell/spawn-inherited.ts +32 -0
package/dist/node/index.js.map
CHANGED
|
@@ -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/exit/exit-command.ts","../../src/exit/exit-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/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-framework';\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, ISubagentJobState } from '@robota-sdk/agent-framework';\nimport type { ICommandResult } 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","import { 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 function executeExitCommand(_context: ICommandHostContext, _args: string): ICommandResult {\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 {\n ICommand,\n ICommandInteractionHint,\n ICommandSource,\n} 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\nconst EXIT_INTERACTION_HINTS: Record<string, ICommandInteractionHint> = {\n exit: { type: 'confirm', message: 'Exit the session?' },\n};\n\nexport function createExitCommandModule(): ICommandModule {\n return {\n name: 'agent-command-exit',\n commandSources: [new ExitCommandSource()],\n systemCommands: [createExitSystemCommand()],\n interactionHints: EXIT_INTERACTION_HINTS,\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 { formatLanguageUsageMessage, parseLanguageArgument } 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 executeLanguageCommand(\n _context: ICommandHostContext,\n args: string,\n): ICommandResult {\n const language = parseLanguageArgument(args);\n if (language === undefined) {\n return {\n message: formatLanguageUsageMessage(),\n success: false,\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 {\n ICommand,\n ICommandInteractionHint,\n ICommandSource,\n} 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\nconst LANGUAGE_INTERACTION_HINTS: Record<string, ICommandInteractionHint> = {\n language: {\n type: 'pick',\n getItems: () =>\n buildLanguageCommandSubcommands().map((sub) => ({\n label: `${sub.name} ${sub.description ?? ''}`.trimEnd(),\n value: sub.name,\n description: sub.description,\n })),\n },\n};\n\nexport function createLanguageCommandModule(): ICommandModule {\n return {\n name: 'agent-command-language',\n commandSources: [new LanguageCommandSource()],\n systemCommands: [createLanguageSystemCommand()],\n interactionHints: LANGUAGE_INTERACTION_HINTS,\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 {\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\nexport function executeModeCommand(context: ICommandHostContext, args: string): ICommandResult {\n const arg = parsePermissionModeArgument(args);\n if (arg === undefined) {\n const mode = readCommandPermissionMode(context);\n return {\n message: `Current mode: ${mode}`,\n success: true,\n 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 {\n ICommand,\n ICommandInteractionHint,\n ICommandSource,\n} 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\nconst MODE_INTERACTION_HINTS: Record<string, ICommandInteractionHint> = {\n mode: {\n type: 'pick',\n getItems: () =>\n buildPermissionModeSubcommands().map((sub) => ({\n label: sub.name,\n value: sub.name,\n description: sub.description,\n })),\n },\n};\n\nexport function createModeCommandModule(): ICommandModule {\n return {\n name: 'agent-command-mode',\n commandSources: [new ModeCommandSource()],\n systemCommands: [createModeSystemCommand()],\n interactionHints: MODE_INTERACTION_HINTS,\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 { 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\nexport async function executePresetCommand(\n context: ICommandHostContext,\n args: string,\n): Promise<ICommandResult> {\n const id = args.trim().split(/\\s+/)[0];\n\n if (id === undefined || id.length === 0 || id === 'list') {\n const active = readActivePresetId(context);\n return {\n message: formatPresetList(active),\n success: true,\n data: { presets: listPresets(), active },\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 {\n ICommand,\n ICommandInteractionHint,\n ICommandSource,\n} 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\nconst PRESET_INTERACTION_HINTS: Record<string, ICommandInteractionHint> = {\n preset: {\n type: 'pick',\n getItems: () =>\n buildPresetSubcommands().map((sub) => ({\n label: sub.name,\n value: sub.name,\n description: sub.description,\n })),\n },\n};\n\nexport function createPresetCommandModule(): ICommandModule {\n return {\n name: 'agent-command-preset',\n commandSources: [new PresetCommandSource()],\n systemCommands: [createPresetSystemCommand()],\n interactionHints: PRESET_INTERACTION_HINTS,\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 { buildProviderSetupPatch, mergeProviderPatch } from '@robota-sdk/agent-framework';\n\nimport {\n createProviderSetupFlow,\n formatProviderSetupHelpLinks,\n getProviderSetupStep,\n submitProviderSetupValue,\n validateProviderSetupValue,\n} from './provider-setup-flow.js';\n\nimport type { IProviderSetupFlowState } from './provider-setup-flow.js';\nimport type {\n IProviderCommandModuleOptions,\n IProviderSetupInput,\n} from '@robota-sdk/agent-framework';\nimport type {\n ICommandInteraction,\n ICommandResult,\n TCommandInteractionPrompt,\n} 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\nexport function createProviderSetupInteraction(\n flow: IProviderSetupFlowState,\n options: IProviderCommandModuleOptions,\n): ICommandInteraction {\n return {\n prompt: toProviderSetupStepPrompt(flow),\n submit: (value) => submitProviderSetupInteractionValue(flow, value, options),\n cancel: () => ({ message: 'Provider setup cancelled.', success: true }),\n };\n}\n\nexport function toProviderSetupStepPrompt(\n flow: IProviderSetupFlowState,\n): TCommandInteractionPrompt {\n const step = getProviderSetupStep(flow);\n const placeholder =\n step.masked === true && step.defaultValue !== undefined ? '(unchanged)' : step.defaultValue;\n return {\n kind: 'text',\n title: step.title,\n ...toProviderSetupPromptDescription(flow),\n ...(placeholder !== undefined ? { placeholder } : {}),\n ...(step.defaultValue !== undefined ? { allowEmpty: true } : {}),\n ...(step.masked !== undefined ? { masked: step.masked } : {}),\n validate: (value) => validateProviderSetupValue(step, value),\n };\n}\n\nfunction toProviderSetupPromptDescription(\n flow: IProviderSetupFlowState,\n): { description: string } | Record<string, never> {\n const description = formatProviderSetupHelpLinks(flow.setupHelpLinks);\n return description.length > 0 ? { description } : {};\n}\n\nfunction submitProviderSetupInteractionValue(\n flow: IProviderSetupFlowState,\n value: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const result = submitProviderSetupValue(flow, value);\n if (result.status === 'error') {\n return {\n message: result.message,\n success: false,\n interaction: createProviderSetupInteraction(flow, options),\n };\n }\n if (result.status === 'complete') {\n return completeProviderSetup(result.input, options);\n }\n return {\n message: '',\n success: true,\n interaction: createProviderSetupInteraction(result.state, options),\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 {\n createProviderSetupInteraction,\n toProviderSetupStepPrompt,\n} from './provider-command-setup.js';\nimport { createProviderSetupFlow, submitProviderSetupValue } from './provider-setup-flow.js';\n\nimport type { IProviderSetupFlowState } from './provider-setup-flow.js';\nimport type {\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n IProviderSetupInput,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandInteraction, 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 function buildProviderEdit(\n profileName: string,\n options: IProviderCommandModuleOptions,\n): 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 try {\n const flow = createProviderSetupFlow(profile.type, options.providerDefinitions, {\n profileName,\n setCurrent: false,\n initialValues: getProviderProfileSetupValues(profile),\n });\n return {\n message: `Provider edit requested: ${profileName}`,\n success: true,\n interaction: createProviderEditInteraction(flow, profileName, options),\n };\n } catch (error) {\n return { message: error instanceof Error ? error.message : String(error), success: false };\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 createProviderEditInteraction(\n flow: IProviderSetupFlowState,\n profileName: string,\n options: IProviderCommandModuleOptions,\n): ICommandInteraction {\n return {\n prompt: toProviderSetupStepPrompt(flow),\n submit: (value) => submitProviderEditInteractionValue(flow, profileName, value, options),\n cancel: () => ({ message: 'Provider edit cancelled.', success: true }),\n };\n}\n\nfunction submitProviderEditInteractionValue(\n flow: IProviderSetupFlowState,\n profileName: string,\n value: string,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const result = submitProviderSetupValue(flow, value);\n if (result.status === 'error') {\n return {\n message: result.message,\n success: false,\n interaction: createProviderEditInteraction(flow, profileName, options),\n };\n }\n if (result.status === 'complete') {\n return completeProviderEdit(result.input, profileName, options);\n }\n return {\n message: '',\n success: true,\n interaction: createProviderEditInteraction(result.state, profileName, options),\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 {\n deleteProviderProfile,\n sanitizeProviderProfileName,\n upsertProviderProfile,\n} from '@robota-sdk/agent-framework';\n\nimport { formatProviderChoiceLabel } from './provider-command-profile-operations.js';\n\nimport type { IProviderCommandModuleOptions } from '@robota-sdk/agent-framework';\nimport type { ICommandInteraction, ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nconst YES = 'yes';\nconst MAX_DUPLICATE_PROFILE_SUFFIX = 1000;\nconst PROVIDER_RESTART_EFFECT = {\n type: 'session-restart-requested',\n reason: 'other',\n} as const;\n\nexport function buildProviderDuplicate(\n profileName: string,\n options: IProviderCommandModuleOptions,\n): 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 return {\n message: `Provider duplicate requested: ${profileName}`,\n success: true,\n interaction: createProviderDuplicateInteraction(profileName, defaultName, options),\n };\n}\n\nfunction createProviderDuplicateInteraction(\n profileName: string,\n defaultName: string,\n options: IProviderCommandModuleOptions,\n): ICommandInteraction {\n return {\n prompt: {\n kind: 'text',\n title: `Duplicate ${profileName} as`,\n placeholder: defaultName,\n allowEmpty: true,\n validate: (value) => validateDuplicateProfileName(value, defaultName, options),\n },\n submit: (value) => completeProviderDuplicate(profileName, value, defaultName, options),\n cancel: () => ({ message: 'Provider duplicate cancelled.', success: true }),\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 function buildProviderDelete(\n profileName: string,\n options: IProviderCommandModuleOptions,\n): 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 return {\n message: `Provider delete requested: ${profileName}`,\n success: true,\n interaction: createProviderDeleteConfirmationInteraction(profileName, options),\n };\n}\n\nfunction createProviderDeleteConfirmationInteraction(\n profileName: string,\n options: IProviderCommandModuleOptions,\n): ICommandInteraction {\n return {\n prompt: {\n kind: 'choice',\n title: `Delete provider profile ${profileName}?`,\n options: [\n { value: YES, label: 'Yes' },\n { value: 'no', label: 'No' },\n ],\n },\n submit: (value) => {\n if (value !== YES) {\n return { message: 'Provider delete cancelled.', success: true };\n }\n return confirmProviderDelete(profileName, options);\n },\n cancel: () => ({ message: 'Provider delete cancelled.', success: true }),\n };\n}\n\nfunction confirmProviderDelete(\n profileName: string,\n options: IProviderCommandModuleOptions,\n): 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 return {\n message: `Select a replacement provider before deleting ${profileName}.`,\n success: true,\n interaction: {\n prompt: {\n kind: 'choice',\n title: `Replacement provider for ${profileName}`,\n options: replacementOptions,\n maxVisible: 8,\n },\n submit: (replacementName) =>\n completeActiveProviderDelete(profileName, replacementName, options),\n cancel: () => ({ message: 'Provider delete cancelled.', success: true }),\n },\n };\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 { 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 {\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandInteraction, 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\nexport function createProviderProfileSelectionInteraction(\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n options: IProviderCommandModuleOptions,\n): ICommandInteraction {\n return {\n prompt: {\n kind: 'choice',\n title: 'Select provider profile',\n options: Object.entries(providers ?? {}).map(([name, profile]) => ({\n value: name,\n label: formatProviderChoiceLabel(name, profile, currentProvider),\n })),\n maxVisible: 8,\n },\n submit: (value) => buildProviderProfileActionMenu(value, options),\n cancel: () => ({ message: 'Provider profile selection cancelled.', success: true }),\n };\n}\n\nfunction buildProviderProfileActionMenu(\n profileName: string,\n options: IProviderCommandModuleOptions,\n): 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 return {\n message: `Provider profile selected: ${profileName}`,\n success: true,\n interaction: createProviderProfileActionInteraction(profileName, options),\n };\n}\n\nfunction createProviderProfileActionInteraction(\n profileName: string,\n options: IProviderCommandModuleOptions,\n): ICommandInteraction {\n return {\n prompt: {\n kind: 'choice',\n title: `Provider profile: ${profileName}`,\n options: [\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 submit: (value) => executeProviderProfileAction(profileName, value, options),\n cancel: () => ({ message: 'Provider profile action cancelled.', success: true }),\n };\n}\n\nasync function executeProviderProfileAction(\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(profileName, options);\n case ACTION_TEST:\n return await testProviderProfileCommand(\n settings.currentProvider,\n settings.providers,\n profileName,\n options,\n );\n case ACTION_DUPLICATE:\n return buildProviderDuplicate(profileName, options);\n case ACTION_DELETE:\n return buildProviderDelete(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 { findProviderDefinition, formatSupportedProviderTypes } from '@robota-sdk/agent-core';\nimport { testProviderProfileCommand } from '@robota-sdk/agent-framework';\n\nimport { buildProviderSwitch } from './provider-command-profile-operations.js';\nimport { createProviderProfileSelectionInteraction } from './provider-command-profile.js';\nimport { createSetupFlow, createProviderSetupInteraction } from './provider-command-setup.js';\nimport { formatProviderSetupChoiceLabel } from './provider-setup-flow.js';\n\nimport type {\n IProviderCommandModuleOptions,\n IProviderProfileSettings,\n} from '@robota-sdk/agent-framework';\nimport type { ICommandInteraction, ICommandResult } from '@robota-sdk/agent-interface-transport';\n\nexport async function executeProviderCommand(\n args: string,\n options: IProviderCommandModuleOptions,\n): Promise<ICommandResult> {\n const settings = options.settings.readMergedSettings();\n const trimmedArgs = args.trim();\n if (trimmedArgs.length === 0) {\n return buildProviderProfilePicker(settings.currentProvider, settings.providers, options);\n }\n const [subcommand = 'current', profileArg] = trimmedArgs.split(/\\s+/);\n\n if (subcommand === 'list') {\n return buildProviderProfilePicker(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 await testProviderProfileCommand(\n settings.currentProvider,\n settings.providers,\n profileArg,\n options,\n );\n }\n if (subcommand === 'add') {\n return buildProviderSetup(profileArg, options);\n }\n\n return {\n message: 'Usage: provider [current|list|switch <profile>|add <type>|test [profile]]',\n success: false,\n };\n}\n\nfunction buildProviderProfilePicker(\n currentProvider: string | undefined,\n providers: Record<string, IProviderProfileSettings> | undefined,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n const message = formatProviderList(currentProvider, providers);\n if (Object.keys(providers ?? {}).length === 0) {\n return { message, success: true };\n }\n return {\n message,\n success: true,\n interaction: createProviderProfileSelectionInteraction(currentProvider, providers, options),\n };\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\nfunction buildProviderSetup(\n type: string | undefined,\n options: IProviderCommandModuleOptions,\n): ICommandResult {\n if (type === undefined || type.length === 0) {\n return {\n message: 'Provider setup requested. Select a provider to continue.',\n success: true,\n interaction: createProviderSelectionInteraction(options),\n };\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 return {\n message: `Provider setup requested: ${type}`,\n success: true,\n interaction: createProviderSetupInteraction(createSetupFlow(type, options), options),\n };\n}\n\nfunction createProviderSelectionInteraction(\n options: IProviderCommandModuleOptions,\n): ICommandInteraction {\n return {\n prompt: {\n kind: 'choice' as const,\n title: 'Select provider',\n options: options.providerDefinitions.map((definition) => ({\n value: definition.type,\n label: formatProviderSetupChoiceLabel(definition),\n })),\n maxVisible: 6,\n },\n submit: (value: string) => {\n const flow = createSetupFlow(value, options);\n return {\n message: `Provider setup requested: ${value}`,\n success: true,\n interaction: createProviderSetupInteraction(flow, options),\n };\n },\n cancel: () => ({ message: 'Provider setup cancelled.', success: true }),\n };\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 {\n ICommand,\n ICommandInteractionHint,\n ICommandSource,\n} 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 execute: async (_session, args) => executeProviderCommand(args, options),\n };\n}\n\nconst PROVIDER_INTERACTION_HINTS: Record<string, ICommandInteractionHint> = {\n provider: {\n type: 'pick',\n getItems: () =>\n buildProviderSubcommands().map((sub) => ({\n label: sub.name,\n value: sub.name,\n description: sub.description,\n })),\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 interactionHints: PROVIDER_INTERACTION_HINTS,\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 {\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 function executeClearCommand(context: ICommandHostContext, _args: string): ICommandResult {\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 {\n ICommand,\n ICommandInteractionHint,\n ICommandSource,\n} 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\nconst SESSION_INTERACTION_HINTS: Record<string, ICommandInteractionHint> = {\n clear: { type: 'confirm', message: 'Clear conversation history?' },\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 interactionHints: SESSION_INTERACTION_HINTS,\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","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 { createExitCommandModule } from '../exit/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 { 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 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":"+rIAEA,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,IAAA,GACvB,GAAW,EAChB,QACF,CACA,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,EAAQ,EACR,QACF,CACA,GAAI,KAAK,KAAK,CAAI,EAAG,CACf,EAAQ,OAAS,IACnB,EAAO,KAAK,CAAO,EACnB,EAAU,IAEZ,QACF,CACA,GAAW,CACb,CAGA,OADI,EAAQ,OAAS,GAAG,EAAO,KAAK,CAAO,EACpC,CACT,CAEA,SAAS,GAAa,EAAgD,CACpE,IAAM,EAAuB,CAAC,EAC1B,EACA,EACA,EAEJ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAQ,EAAO,GACjB,OAAU,eAGd,IAAI,IAAU,WAAa,IAAU,UAAY,IAAU,KAAM,CAC/D,EAAY,EAAO,EAAQ,GAC3B,GAAS,EACT,QACF,CACA,GAAI,IAAU,UAAW,CACvB,EAAQ,EAAO,EAA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KAAO,IAAa,EAAS,UAAU,UAAU,CAAQ,EACpE,OAAQ,KAAO,IAAa,EAAS,UAAU,OAAO,CAAQ,EAC9D,QAAS,KAAO,IAAa,EAAS,UAAU,QAAQ,CAAQ,EAChE,eAAgB,KAAO,IACjB,EAAO,SAAS,GAAG,GAAK,CAAC,EAAO,SAAS,GAAG,EACvC,EAAS,YAAY,eAAe,CAAE,KAAM,SAAU,KAAM,CAAO,CAAC,EAEtE,EAAS,YAAY,eAAe,CAAE,KAAM,MAAO,IAAK,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","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,IAAA,GACvB,GAAW,EAChB,QACF,CACA,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,EAAQ,EACR,QACF,CACA,GAAI,KAAK,KAAK,CAAI,EAAG,CACf,EAAQ,OAAS,IACnB,EAAO,KAAK,CAAO,EACnB,EAAU,IAEZ,QACF,CACA,GAAW,CACb,CAGA,OADI,EAAQ,OAAS,GAAG,EAAO,KAAK,CAAO,EACpC,CACT,CAEA,SAAS,GAAa,EAAgD,CACpE,IAAM,EAAuB,CAAC,EAC1B,EACA,EACA,EAEJ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAQ,EAAO,GACjB,OAAU,eAGd,IAAI,IAAU,WAAa,IAAU,UAAY,IAAU,KAAM,CAC/D,EAAY,EAAO,EAAQ,GAC3B,GAAS,EACT,QACF,CACA,GAAI,IAAU,UAAW,CACvB,EAAQ,EAAO,EAAQ,GACvB,GAAS,EACT,QACF,CACA,GAAI,IAAU,cAAe,CAC3B,IAAM,EAAQ,EAAO,EAAQ,IACzB,IAAU,QAAU,IAAU,cAAY,EAAY,GAC1D,GAAS,EACT,QACF,CACI,IAAU,IAAA,IAAW,EAAW,KAAK,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