@dreb/coding-agent 2.51.0 → 2.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +8 -6
  2. package/dist/cli/args.d.ts.map +1 -1
  3. package/dist/cli/args.js +11 -6
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/core/extensions/types.d.ts +31 -11
  6. package/dist/core/extensions/types.d.ts.map +1 -1
  7. package/dist/core/extensions/types.js.map +1 -1
  8. package/dist/core/slash-commands.d.ts +14 -0
  9. package/dist/core/slash-commands.d.ts.map +1 -1
  10. package/dist/core/slash-commands.js +28 -3
  11. package/dist/core/slash-commands.js.map +1 -1
  12. package/dist/core/tools/ask-user.d.ts +28 -20
  13. package/dist/core/tools/ask-user.d.ts.map +1 -1
  14. package/dist/core/tools/ask-user.js +130 -106
  15. package/dist/core/tools/ask-user.js.map +1 -1
  16. package/dist/core/tools/index.d.ts +9 -7
  17. package/dist/core/tools/index.d.ts.map +1 -1
  18. package/dist/core/tools/index.js.map +1 -1
  19. package/dist/modes/interactive/components/ask-wizard.d.ts +83 -0
  20. package/dist/modes/interactive/components/ask-wizard.d.ts.map +1 -0
  21. package/dist/modes/interactive/components/ask-wizard.js +464 -0
  22. package/dist/modes/interactive/components/ask-wizard.js.map +1 -0
  23. package/dist/modes/interactive/interactive-mode.d.ts +4 -2
  24. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  25. package/dist/modes/interactive/interactive-mode.js +7 -5
  26. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  27. package/dist/modes/rpc/rpc-client.d.ts +11 -1
  28. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  29. package/dist/modes/rpc/rpc-client.js +15 -1
  30. package/dist/modes/rpc/rpc-client.js.map +1 -1
  31. package/dist/modes/rpc/rpc-mode.d.ts +3 -1
  32. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  33. package/dist/modes/rpc/rpc-mode.js +230 -47
  34. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  35. package/dist/modes/rpc/rpc-types.d.ts +66 -11
  36. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  37. package/dist/modes/rpc/rpc-types.js.map +1 -1
  38. package/docs/dashboard.md +1 -3
  39. package/docs/extensions.md +39 -22
  40. package/docs/rpc.md +84 -25
  41. package/examples/extensions/rpc-demo.ts +29 -0
  42. package/examples/rpc-extension-ui.ts +162 -6
  43. package/package.json +1 -1
  44. package/dist/modes/interactive/components/ask-user.d.ts +0 -59
  45. package/dist/modes/interactive/components/ask-user.d.ts.map +0 -1
  46. package/dist/modes/interactive/components/ask-user.js +0 -240
  47. package/dist/modes/interactive/components/ask-user.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/extensions/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAq0BH,kCAAkC;AAClC,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,iBAAiB,CAAC,CAAkB,EAA6B;IAChF,OAAO,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;AAAA,CAC9B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,cAAc,CAAC,CAAkB,EAA0B;IAC1E,OAAO,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC;AAAA,CAC3B;AAiCD,MAAM,UAAU,mBAAmB,CAAC,QAAgB,EAAE,KAAoB,EAAW;IACpF,OAAO,KAAK,CAAC,QAAQ,KAAK,QAAQ,CAAC;AAAA,CACnC","sourcesContent":["/**\n * Extension system types.\n *\n * Extensions are TypeScript modules that can:\n * - Subscribe to agent lifecycle events\n * - Register LLM-callable tools\n * - Register commands, keyboard shortcuts, and CLI flags\n * - Interact with the user via UI primitives\n */\n\nimport type { AgentMessage, AgentToolResult, AgentToolUpdateCallback, ThinkingLevel } from \"@dreb/agent-core\";\nimport type {\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n} from \"@dreb/ai\";\nimport type {\n\tAutocompleteItem,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@dreb/tui\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { BashResult } from \"../bash-executor.js\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.js\";\nimport type { EventBus } from \"../event-bus.js\";\nimport type { ExecOptions, ExecResult } from \"../exec.js\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.js\";\nimport type { KeybindingsManager } from \"../keybindings.js\";\nimport type { CustomMessage } from \"../messages.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.js\";\nimport type { SlashCommandInfo } from \"../slash-commands.js\";\nimport type { SourceInfo } from \"../source-info.js\";\nimport type { BashOperations } from \"../tools/bash.js\";\nimport type { EditToolDetails } from \"../tools/edit.js\";\nimport type {\n\tBashToolDetails,\n\tBashToolInput,\n\tEditToolInput,\n\tFindToolDetails,\n\tFindToolInput,\n\tGrepToolDetails,\n\tGrepToolInput,\n\tLsToolDetails,\n\tLsToolInput,\n\tReadToolDetails,\n\tReadToolInput,\n\tWriteToolInput,\n} from \"../tools/index.js\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.js\";\nexport type { AgentToolResult, AgentToolUpdateCallback };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.js\";\n\n// ============================================================================\n// UI Context\n// ============================================================================\n\n/** Options for extension UI dialogs. */\nexport interface ExtensionUIDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\n/**\n * A rich question for {@link ExtensionUIContext.ask}. Presents optional\n * suggested options (single- or multi-select) alongside an optional free-text\n * field, rendered natively in every surface (TUI, Dashboard, RPC host).\n */\nexport interface AskRequest {\n\t/** The Markdown-formatted question to ask the user. */\n\tquestion: string;\n\t/** Short bold header. Defaults to a generic prompt title when omitted. */\n\ttitle?: string;\n\t/** 2-4 suggested options. */\n\toptions?: string[];\n\t/** Offer a \"type your own answer\" field. Defaults to true. */\n\tallowFreeText?: boolean;\n\t/** Render options as checkboxes (multiple answers) instead of radios. */\n\tmultiSelect?: boolean;\n\t/** Use a multi-line text area for the free-text field. */\n\tmultiline?: boolean;\n}\n\n/**\n * The user's answer to an {@link AskRequest}. Stopping or timing out the\n * question stops the current agent turn and resolves to `undefined`.\n */\nexport interface AskResult {\n\t/** Options the user selected (empty when only free text was provided). */\n\tselected: string[];\n\t/** Free-text answer, when the user typed one. */\n\tcustomText?: string;\n}\n\n/** Placement for extension widgets. */\nexport type WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\n\n/** Options for extension widgets. */\nexport interface ExtensionWidgetOptions {\n\t/** Where the widget is rendered. Defaults to \"aboveEditor\". */\n\tplacement?: WidgetPlacement;\n}\n\n/** Raw terminal input listener for extensions. */\nexport type TerminalInputHandler = (data: string) => { consume?: boolean; data?: string } | undefined;\n\n/**\n * UI context for extensions to request interactive UI.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface ExtensionUIContext {\n\t/** Show a selector and return the user's choice. */\n\tselect(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/** Show a confirmation dialog. */\n\tconfirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise<boolean>;\n\n\t/** Show a text input dialog. */\n\tinput(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/**\n\t * Show a rich question with suggested options, optional free text, and\n\t * single- or multi-select. Resolves to the user's answer, or `undefined`\n\t * while stopping the current agent turn when dismissed or timed out.\n\t */\n\task(request: AskRequest, opts?: ExtensionUIDialogOptions): Promise<AskResult | undefined>;\n\n\t/** Show a notification to the user. */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */\n\tonTerminalInput(handler: TerminalInputHandler): () => void;\n\n\t/** Set status text in the footer/status bar. Pass undefined to clear. */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/** Set the working/loading message shown during streaming. Call with no argument to restore default. */\n\tsetWorkingMessage(message?: string): void;\n\n\t/** Set a widget to display above or below the editor. Accepts string array or component factory. */\n\tsetWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void;\n\n\t/** Set a custom footer component, or undefined to restore the built-in footer.\n\t *\n\t * The factory receives a FooterDataProvider for data not otherwise accessible:\n\t * git branch and extension statuses from setStatus(). Token stats, model info,\n\t * etc. are available via ctx.sessionManager and ctx.model.\n\t */\n\tsetFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void;\n\n\t/** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */\n\tsetHeader(factory: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined): void;\n\n\t/** Set the terminal window/tab title. */\n\tsetTitle(title: string): void;\n\n\t/** Show a custom component with keyboard focus. */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\t/** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\t/** Called with the overlay handle after the overlay is shown. Use to control visibility. */\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise<T>;\n\n\t/** Paste text into the editor, triggering paste handling (collapse for large content). */\n\tpasteToEditor(text: string): void;\n\n\t/** Set the text in the core input editor. */\n\tsetEditorText(text: string): void;\n\n\t/** Get the current text from the core input editor. */\n\tgetEditorText(): string;\n\n\t/** Show a multi-line editor for text editing. */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/**\n\t * Set a custom editor component via factory function.\n\t * Pass undefined to restore the default editor.\n\t *\n\t * The factory receives:\n\t * - `theme`: EditorTheme for styling borders and autocomplete\n\t * - `keybindings`: KeybindingsManager for app-level keybindings\n\t *\n\t * For full app keybinding support (escape, ctrl+d, model switching, etc.),\n\t * extend `CustomEditor` from `@dreb/coding-agent` and call\n\t * `super.handleInput(data)` for keys you don't handle.\n\t *\n\t * @example\n\t * ```ts\n\t * import { CustomEditor } from \"@dreb/coding-agent\";\n\t *\n\t * class VimEditor extends CustomEditor {\n\t * private mode: \"normal\" | \"insert\" = \"insert\";\n\t *\n\t * handleInput(data: string): void {\n\t * if (this.mode === \"normal\") {\n\t * // Handle vim normal mode keys...\n\t * if (data === \"i\") { this.mode = \"insert\"; return; }\n\t * }\n\t * super.handleInput(data); // App keybindings + text editing\n\t * }\n\t * }\n\t *\n\t * ctx.ui.setEditorComponent((tui, theme, keybindings) =>\n\t * new VimEditor(tui, theme, keybindings)\n\t * );\n\t * ```\n\t */\n\tsetEditorComponent(\n\t\tfactory: ((tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent) | undefined,\n\t): void;\n\n\t/** Get the current theme for styling. */\n\treadonly theme: Theme;\n\n\t/** Get all available themes with their names and file paths. */\n\tgetAllThemes(): { name: string; path: string | undefined }[];\n\n\t/** Load a theme by name without switching to it. Returns undefined if not found. */\n\tgetTheme(name: string): Theme | undefined;\n\n\t/** Set the current theme by name or Theme object. */\n\tsetTheme(theme: string | Theme): { success: boolean; error?: string };\n\n\t/** Get current tool output expansion state. */\n\tgetToolsExpanded(): boolean;\n\n\t/** Set tool output expansion state. */\n\tsetToolsExpanded(expanded: boolean): void;\n}\n\n// ============================================================================\n// Extension Context\n// ============================================================================\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\tcustomInstructions?: string;\n\tonComplete?: (result: CompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Context passed to extension event handlers.\n */\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Whether UI is available (false in print/RPC mode) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model<any> | undefined;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown dreb and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(entryId: string): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(sessionPath: string): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, and themes. */\n\treload(): Promise<void>;\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\n/** Rendering options for tool results */\nexport interface ToolRenderResultOptions {\n\t/** Whether the result view is expanded */\n\texpanded: boolean;\n\t/** Whether this is a partial/streaming result */\n\tisPartial: boolean;\n}\n\n/** Context passed to tool renderers. */\nexport interface ToolRenderContext<TState = any, TArgs = any> {\n\t/** Current tool call arguments. Shared across call/result renders for the same tool call. */\n\targs: TArgs;\n\t/** Unique id for this tool execution. Stable across call/result renders for the same tool call. */\n\ttoolCallId: string;\n\t/** Invalidate just this tool execution component for redraw. */\n\tinvalidate: () => void;\n\t/** Previously returned component for this render slot, if any. */\n\tlastComponent: Component | undefined;\n\t/** Shared renderer state for this tool row. Initialized by tool-execution.ts. */\n\tstate: TState;\n\t/** Working directory for this tool execution. */\n\tcwd: string;\n\t/** Whether the tool execution has started. */\n\texecutionStarted: boolean;\n\t/** Whether the tool call arguments are complete. */\n\targsComplete: boolean;\n\t/** Whether the tool result is partial/streaming. */\n\tisPartial: boolean;\n\t/** Whether the result view is expanded. */\n\texpanded: boolean;\n\t/** Whether inline images are currently shown in the TUI. */\n\tshowImages: boolean;\n\t/** Whether the current result is an error. */\n\tisError: boolean;\n}\n\n/**\n * Tool definition for registerTool().\n */\nexport interface ToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any> {\n\t/** Tool name (used in LLM tool calls) */\n\tname: string;\n\t/** Human-readable label for UI */\n\tlabel: string;\n\t/** Description for LLM */\n\tdescription: string;\n\t/** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */\n\tpromptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\tpromptGuidelines?: string[];\n\t/** Parameter schema (TypeBox) */\n\tparameters: TParams;\n\n\t/** Execute the tool. */\n\texecute(\n\t\ttoolCallId: string,\n\t\tparams: Static<TParams>,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: AgentToolUpdateCallback<TDetails> | undefined,\n\t\tctx: ExtensionContext,\n\t): Promise<AgentToolResult<TDetails>>;\n\n\t/** Custom rendering for tool call display */\n\trenderCall?: (args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>) => Component;\n\n\t/** Custom rendering for tool result display */\n\trenderResult?: (\n\t\tresult: AgentToolResult<TDetails>,\n\t\toptions: ToolRenderResultOptions,\n\t\ttheme: Theme,\n\t\tcontext: ToolRenderContext<TState, Static<TParams>>,\n\t) => Component;\n}\n\n// ============================================================================\n// Resource Events\n// ============================================================================\n\n/** Fired after session_start to allow extensions to provide additional resource paths. */\nexport interface ResourcesDiscoverEvent {\n\ttype: \"resources_discover\";\n\tcwd: string;\n\treason: \"startup\" | \"reload\";\n}\n\n/** Result from resources_discover event handler */\nexport interface ResourcesDiscoverResult {\n\tskillPaths?: string[];\n\tpromptPaths?: string[];\n\tthemePaths?: string[];\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired before session manager creation to allow custom session directory resolution */\nexport interface SessionDirectoryEvent {\n\ttype: \"session_directory\";\n\tcwd: string;\n}\n\n/** Fired on initial session load */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\treason: \"new\" | \"resume\";\n\ttargetSessionFile?: string;\n}\n\n/** Fired after switching to another session */\nexport interface SessionSwitchEvent {\n\ttype: \"session_switch\";\n\treason: \"new\" | \"resume\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n}\n\n/** Fired after forking a session */\nexport interface SessionForkEvent {\n\ttype: \"session_fork\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionEntry[];\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n}\n\n/** Fired on process exit */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n}\n\n/** Preparation data for tree navigation */\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionEntry[];\n\tuserWantsSummary: boolean;\n\t/** Custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n/** Fired before navigating in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromExtension?: boolean;\n}\n\nexport type SessionEvent =\n\t| SessionDirectoryEvent\n\t| SessionStartEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionSwitchEvent\n\t| SessionBeforeForkEvent\n\t| SessionForkEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\tprompt: string;\n\timages?: ImageContent[];\n\tsystemPrompt: string;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a dropped stream is discarded and retried. */\nexport interface StreamRetryEvent {\n\ttype: \"stream_retry\";\n\tattempt: number;\n\tmaxAttempts: number;\n\terror: string;\n\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\tdiscardedPartial?: AgentMessage;\n}\n\n/** Fired when a turn ends with stopReason \"length\" and is retried with a larger token budget. */\nexport interface LengthRetryEvent {\n\ttype: \"length_retry\";\n\tattempt: number;\n\tmaxAttempts: number;\n\t/** The maxTokens budget used for the truncated attempt. */\n\tpreviousMaxTokens: number;\n\t/** The escalated maxTokens budget the retry will request. */\n\tnextMaxTokens: number;\n\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\tdiscardedPartial?: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\tpartialResult: any;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: any;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: ModelSelectSource;\n}\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n\n// ============================================================================\n// Tool Events\n// ============================================================================\n\ninterface ToolCallEventBase {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n}\n\nexport interface BashToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"bash\";\n\tinput: BashToolInput;\n}\n\nexport interface ReadToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"read\";\n\tinput: ReadToolInput;\n}\n\nexport interface EditToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"edit\";\n\tinput: EditToolInput;\n}\n\nexport interface WriteToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"write\";\n\tinput: WriteToolInput;\n}\n\nexport interface GrepToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"grep\";\n\tinput: GrepToolInput;\n}\n\nexport interface FindToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"find\";\n\tinput: FindToolInput;\n}\n\nexport interface LsToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"ls\";\n\tinput: LsToolInput;\n}\n\nexport interface CustomToolCallEvent extends ToolCallEventBase {\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\n/** Fired before a tool executes. Can block. */\nexport type ToolCallEvent =\n\t| BashToolCallEvent\n\t| ReadToolCallEvent\n\t| EditToolCallEvent\n\t| WriteToolCallEvent\n\t| GrepToolCallEvent\n\t| FindToolCallEvent\n\t| LsToolCallEvent\n\t| CustomToolCallEvent;\n\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\tinput: Record<string, unknown>;\n\tcontent: (TextContent | ImageContent)[];\n\tisError: boolean;\n}\n\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/** Fired after a tool executes. Can modify result. */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for ToolResultEvent\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Type guard for narrowing ToolCallEvent by tool name.\n *\n * Built-in tools narrow automatically (no type params needed):\n * ```ts\n * if (isToolCallEventType(\"bash\", event)) {\n * event.input.command; // string\n * }\n * ```\n *\n * Custom tools require explicit type parameters:\n * ```ts\n * if (isToolCallEventType<\"my_tool\", MyToolInput>(\"my_tool\", event)) {\n * event.input.action; // typed\n * }\n * ```\n *\n * Note: Direct narrowing via `event.toolName === \"bash\"` doesn't work because\n * CustomToolCallEvent.toolName is `string` which overlaps with all literals.\n */\nexport function isToolCallEventType(toolName: \"bash\", event: ToolCallEvent): event is BashToolCallEvent;\nexport function isToolCallEventType(toolName: \"read\", event: ToolCallEvent): event is ReadToolCallEvent;\nexport function isToolCallEventType(toolName: \"edit\", event: ToolCallEvent): event is EditToolCallEvent;\nexport function isToolCallEventType(toolName: \"write\", event: ToolCallEvent): event is WriteToolCallEvent;\nexport function isToolCallEventType(toolName: \"grep\", event: ToolCallEvent): event is GrepToolCallEvent;\nexport function isToolCallEventType(toolName: \"find\", event: ToolCallEvent): event is FindToolCallEvent;\nexport function isToolCallEventType(toolName: \"ls\", event: ToolCallEvent): event is LsToolCallEvent;\nexport function isToolCallEventType<TName extends string, TInput extends Record<string, unknown>>(\n\ttoolName: TName,\n\tevent: ToolCallEvent,\n): event is ToolCallEvent & { toolName: TName; input: TInput };\nexport function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {\n\treturn event.toolName === toolName;\n}\n\n/** Union of all event types */\nexport type ExtensionEvent =\n\t| ResourcesDiscoverEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| StreamRetryEvent\n\t| LengthRetryEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| UserBashEvent\n\t| InputEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\nexport interface ContextEventResult {\n\tmessages?: AgentMessage[];\n}\n\nexport type BeforeProviderRequestEventResult = unknown;\n\nexport interface ToolCallEventResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/** Result from user_bash event handler */\nexport interface UserBashEventResult {\n\t/** Custom operations to use for execution */\n\toperations?: BashOperations;\n\t/** Full replacement: extension handled execution, use this result */\n\tresult?: BashResult;\n}\n\nexport interface ToolResultEventResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\nexport interface BeforeAgentStartEventResult {\n\tmessage?: Pick<CustomMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n\t/** Replace the system prompt for this turn. If multiple extensions return this, they are chained. */\n\tsystemPrompt?: string;\n}\n\nexport interface SessionDirectoryResult {\n\t/** Custom session directory path. If multiple extensions return this, the last one wins. */\n\tsessionDir?: string;\n}\n\n/** Special startup-only handler. Unlike other events, this receives no ExtensionContext. */\nexport type SessionDirectoryHandler = (\n\tevent: SessionDirectoryEvent,\n) => Promise<SessionDirectoryResult | undefined> | SessionDirectoryResult | undefined;\n\nexport interface SessionBeforeSwitchResult {\n\tcancel?: boolean;\n}\n\nexport interface SessionBeforeForkResult {\n\tcancel?: boolean;\n\tskipConversationRestore?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactionResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t};\n\t/** Override custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** Override whether customInstructions replaces the default prompt */\n\treplaceInstructions?: boolean;\n\t/** Override label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n// ============================================================================\n// Message Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer<T = unknown> = (\n\tmessage: CustomMessage<T>,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\nexport interface RegisteredCommand {\n\tname: string;\n\tsourceInfo: SourceInfo;\n\tdescription?: string;\n\tgetArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null;\n\thandler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;\n}\n\nexport interface ResolvedCommand extends RegisteredCommand {\n\tinvocationName: string;\n}\n\n// ============================================================================\n// Extension API\n// ============================================================================\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_directory\", handler: SessionDirectoryHandler): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_switch\", handler: ExtensionHandler<SessionSwitchEvent>): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): void;\n\ton(event: \"session_fork\", handler: ExtensionHandler<SessionForkEvent>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent>): void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent>): void;\n\ton(event: \"stream_retry\", handler: ExtensionHandler<StreamRetryEvent>): void;\n\ton(event: \"length_retry\", handler: ExtensionHandler<LengthRetryEvent>): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model<any>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * dreb.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * dreb.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * dreb.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * dreb.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n\n// ============================================================================\n// Provider Registration Types\n// ============================================================================\n\n/** Configuration for registering a provider via dreb.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key or environment variable name. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** Use Authorization: Bearer with the resolved API key instead of the provider's API-key auth channel. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Optional: modify models for this provider (e.g., update baseUrl based on credentials). */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Cost per token (for tracking, can be 0). */\n\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t/** Maximum context window size in tokens. */\n\tcontextWindow: number;\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (dreb: ExtensionAPI) => void | Promise<void>;\n\n// ============================================================================\n// Loaded Extension Types\n// ============================================================================\n\nexport interface RegisteredTool {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface ExtensionFlag {\n\tname: string;\n\tdescription?: string;\n\ttype: \"boolean\" | \"string\";\n\tdefault?: boolean | string;\n\textensionPath: string;\n}\n\nexport interface ExtensionShortcut {\n\tshortcut: KeyId;\n\tdescription?: string;\n\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\textensionPath: string;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\nexport type SendMessageHandler = <T = unknown>(\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n) => void;\n\nexport type SendUserMessageHandler = (\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n) => void;\n\nexport type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;\n\nexport type SetSessionNameHandler = (name: string) => void;\n\nexport type GetSessionNameHandler = () => string | undefined;\n\nexport type GetActiveToolsHandler = () => string[];\n\n/** Tool info with name, description, parameter schema, and source metadata */\nexport type ToolInfo = Pick<ToolDefinition, \"name\" | \"description\" | \"parameters\"> & {\n\tsourceInfo: SourceInfo;\n};\n\nexport type GetAllToolsHandler = () => ToolInfo[];\n\nexport type GetCommandsHandler = () => SlashCommandInfo[];\n\nexport type SetActiveToolsHandler = (toolNames: string[]) => void;\n\nexport type RefreshToolsHandler = () => void;\n\nexport type SetModelHandler = (model: Model<any>) => Promise<boolean>;\n\nexport type GetThinkingLevelHandler = () => ThinkingLevel;\n\nexport type SetThinkingLevelHandler = (level: ThinkingLevel) => void;\n\nexport type SetLabelHandler = (entryId: string, label: string | undefined) => void;\n\n/**\n * Shared state created by loader, used during registration and runtime.\n * Contains flag values (defaults set during registration, CLI values set after).\n */\nexport interface ExtensionRuntimeState {\n\tflagValues: Map<string, boolean | string>;\n\t/** Provider registrations queued during extension loading, processed when runner binds */\n\tpendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n\t/**\n\t * Register or unregister a provider.\n\t *\n\t * Before bindCore(): queues registrations / removes from queue.\n\t * After bindCore(): calls ModelRegistry directly for immediate effect.\n\t */\n\tregisterProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;\n\tunregisterProvider: (name: string, extensionPath?: string) => void;\n}\n\n/**\n * Action implementations for dreb.* API methods.\n * Provided to runner.initialize(), copied into the shared runtime.\n */\nexport interface ExtensionActions {\n\tsendMessage: SendMessageHandler;\n\tsendUserMessage: SendUserMessageHandler;\n\tappendEntry: AppendEntryHandler;\n\tsetSessionName: SetSessionNameHandler;\n\tgetSessionName: GetSessionNameHandler;\n\tsetLabel: SetLabelHandler;\n\tgetActiveTools: GetActiveToolsHandler;\n\tgetAllTools: GetAllToolsHandler;\n\tsetActiveTools: SetActiveToolsHandler;\n\trefreshTools: RefreshToolsHandler;\n\tgetCommands: GetCommandsHandler;\n\tsetModel: SetModelHandler;\n\tgetThinkingLevel: GetThinkingLevelHandler;\n\tsetThinkingLevel: SetThinkingLevelHandler;\n}\n\n/**\n * Actions for ExtensionContext (ctx.* in event handlers).\n * Required by all modes.\n */\nexport interface ExtensionContextActions {\n\tgetModel: () => Model<any> | undefined;\n\tisIdle: () => boolean;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n}\n\n/**\n * Actions for ExtensionCommandContext (ctx.* in command handlers).\n * Only needed for interactive mode where extension commands are invokable.\n */\nexport interface ExtensionCommandContextActions {\n\twaitForIdle: () => Promise<void>;\n\tnewSession: (options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (entryId: string) => Promise<{ cancelled: boolean }>;\n\tnavigateTree: (\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t) => Promise<{ cancelled: boolean }>;\n\tswitchSession: (sessionPath: string) => Promise<{ cancelled: boolean }>;\n\treload: () => Promise<void>;\n}\n\n/**\n * Full runtime = state + actions.\n * Created by loader with throwing action stubs, completed by runner.initialize().\n */\nexport interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}\n\n/** Loaded extension with all registered items. */\nexport interface Extension {\n\tpath: string;\n\tresolvedPath: string;\n\tsourceInfo: SourceInfo;\n\thandlers: Map<string, HandlerFn[]>;\n\ttools: Map<string, RegisteredTool>;\n\tmessageRenderers: Map<string, MessageRenderer>;\n\tcommands: Map<string, RegisteredCommand>;\n\tflags: Map<string, ExtensionFlag>;\n\tshortcuts: Map<KeyId, ExtensionShortcut>;\n}\n\n/** Result of loading extensions. */\nexport interface LoadExtensionsResult {\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n\t/** Shared runtime - actions are throwing stubs until runner.initialize() */\n\truntime: ExtensionRuntime;\n}\n\n// ============================================================================\n// Extension Error\n// ============================================================================\n\nexport interface ExtensionError {\n\textensionPath: string;\n\tevent: string;\n\terror: string;\n\tstack?: string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/extensions/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA21BH,kCAAkC;AAClC,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,iBAAiB,CAAC,CAAkB,EAA6B;IAChF,OAAO,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;AAAA,CAC9B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,cAAc,CAAC,CAAkB,EAA0B;IAC1E,OAAO,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC;AAAA,CAC3B;AAiCD,MAAM,UAAU,mBAAmB,CAAC,QAAgB,EAAE,KAAoB,EAAW;IACpF,OAAO,KAAK,CAAC,QAAQ,KAAK,QAAQ,CAAC;AAAA,CACnC","sourcesContent":["/**\n * Extension system types.\n *\n * Extensions are TypeScript modules that can:\n * - Subscribe to agent lifecycle events\n * - Register LLM-callable tools\n * - Register commands, keyboard shortcuts, and CLI flags\n * - Interact with the user via UI primitives\n */\n\nimport type { AgentMessage, AgentToolResult, AgentToolUpdateCallback, ThinkingLevel } from \"@dreb/agent-core\";\nimport type {\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n} from \"@dreb/ai\";\nimport type {\n\tAutocompleteItem,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@dreb/tui\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { BashResult } from \"../bash-executor.js\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.js\";\nimport type { EventBus } from \"../event-bus.js\";\nimport type { ExecOptions, ExecResult } from \"../exec.js\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.js\";\nimport type { KeybindingsManager } from \"../keybindings.js\";\nimport type { CustomMessage } from \"../messages.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.js\";\nimport type { SlashCommandInfo } from \"../slash-commands.js\";\nimport type { SourceInfo } from \"../source-info.js\";\nimport type { BashOperations } from \"../tools/bash.js\";\nimport type { EditToolDetails } from \"../tools/edit.js\";\nimport type {\n\tBashToolDetails,\n\tBashToolInput,\n\tEditToolInput,\n\tFindToolDetails,\n\tFindToolInput,\n\tGrepToolDetails,\n\tGrepToolInput,\n\tLsToolDetails,\n\tLsToolInput,\n\tReadToolDetails,\n\tReadToolInput,\n\tWriteToolInput,\n} from \"../tools/index.js\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.js\";\nexport type { AgentToolResult, AgentToolUpdateCallback };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.js\";\n\n// ============================================================================\n// UI Context\n// ============================================================================\n\n/** Options for extension UI dialogs. */\nexport interface ExtensionUIDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\n/**\n * A single question inside an {@link AskRequest}. Presents optional suggested\n * options (single- or multi-select) alongside an optional free-text field.\n */\nexport interface AskQuestion {\n\t/** The Markdown-formatted question to ask the user. */\n\tquestion: string;\n\t/** Short bold header for this question. Defaults to a generic title. */\n\ttitle?: string;\n\t/** 2-4 suggested options. */\n\toptions?: string[];\n\t/** Offer a \"type your own answer\" field. Defaults to true. */\n\tallowFreeText?: boolean;\n\t/** Render options as checkboxes (multiple answers) instead of radios. */\n\tmultiSelect?: boolean;\n\t/** Use a multi-line text area for the free-text field. */\n\tmultiline?: boolean;\n}\n\n/**\n * A rich multi-question request for {@link ExtensionUIContext.ask}. One request\n * carries one or more questions, collected together in a single wizard and\n * returned as a batch of answers, rendered natively in every surface (TUI,\n * Dashboard, RPC host).\n */\nexport interface AskRequest {\n\t/** Optional overall header for the wizard. */\n\ttitle?: string;\n\t/** One or more questions to ask, presented as a single batch. */\n\tquestions: AskQuestion[];\n}\n\n/** The user's answer to a single {@link AskQuestion}. */\nexport interface AskAnswer {\n\t/** Options the user selected (empty when only free text was provided). */\n\tselected: string[];\n\t/** Free-text answer, when the user typed one. */\n\tcustomText?: string;\n\t/** True when this question was submitted without any answer. */\n\tskipped?: boolean;\n}\n\n/**\n * The user's batch answer to an {@link AskRequest}, one {@link AskAnswer} per\n * question in order. Stopping or timing out the wizard stops the current agent\n * turn and resolves to `undefined`.\n */\nexport interface AskResult {\n\t/** One answer per question, in the same order as the request. */\n\tanswers: AskAnswer[];\n}\n\n/** Placement for extension widgets. */\nexport type WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\n\n/** Options for extension widgets. */\nexport interface ExtensionWidgetOptions {\n\t/** Where the widget is rendered. Defaults to \"aboveEditor\". */\n\tplacement?: WidgetPlacement;\n}\n\n/** Raw terminal input listener for extensions. */\nexport type TerminalInputHandler = (data: string) => { consume?: boolean; data?: string } | undefined;\n\n/**\n * UI context for extensions to request interactive UI.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface ExtensionUIContext {\n\t/** Show a selector and return the user's choice. */\n\tselect(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/** Show a confirmation dialog. */\n\tconfirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise<boolean>;\n\n\t/** Show a text input dialog. */\n\tinput(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/**\n\t * Show a rich multi-question wizard with suggested options, optional free\n\t * text, and single- or multi-select per question. Resolves to a batch of\n\t * answers, or `undefined` while stopping the current agent turn when\n\t * dismissed or timed out.\n\t */\n\task(request: AskRequest, opts?: ExtensionUIDialogOptions): Promise<AskResult | undefined>;\n\n\t/** Show a notification to the user. */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */\n\tonTerminalInput(handler: TerminalInputHandler): () => void;\n\n\t/** Set status text in the footer/status bar. Pass undefined to clear. */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/** Set the working/loading message shown during streaming. Call with no argument to restore default. */\n\tsetWorkingMessage(message?: string): void;\n\n\t/** Set a widget to display above or below the editor. Accepts string array or component factory. */\n\tsetWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void;\n\n\t/** Set a custom footer component, or undefined to restore the built-in footer.\n\t *\n\t * The factory receives a FooterDataProvider for data not otherwise accessible:\n\t * git branch and extension statuses from setStatus(). Token stats, model info,\n\t * etc. are available via ctx.sessionManager and ctx.model.\n\t */\n\tsetFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void;\n\n\t/** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */\n\tsetHeader(factory: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined): void;\n\n\t/** Set the terminal window/tab title. */\n\tsetTitle(title: string): void;\n\n\t/** Show a custom component with keyboard focus. */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\t/** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\t/** Called with the overlay handle after the overlay is shown. Use to control visibility. */\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise<T>;\n\n\t/** Paste text into the editor, triggering paste handling (collapse for large content). */\n\tpasteToEditor(text: string): void;\n\n\t/** Set the text in the core input editor. */\n\tsetEditorText(text: string): void;\n\n\t/** Get the current text from the core input editor. */\n\tgetEditorText(): string;\n\n\t/** Show a multi-line editor for text editing. */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/**\n\t * Set a custom editor component via factory function.\n\t * Pass undefined to restore the default editor.\n\t *\n\t * The factory receives:\n\t * - `theme`: EditorTheme for styling borders and autocomplete\n\t * - `keybindings`: KeybindingsManager for app-level keybindings\n\t *\n\t * For full app keybinding support (escape, ctrl+d, model switching, etc.),\n\t * extend `CustomEditor` from `@dreb/coding-agent` and call\n\t * `super.handleInput(data)` for keys you don't handle.\n\t *\n\t * @example\n\t * ```ts\n\t * import { CustomEditor } from \"@dreb/coding-agent\";\n\t *\n\t * class VimEditor extends CustomEditor {\n\t * private mode: \"normal\" | \"insert\" = \"insert\";\n\t *\n\t * handleInput(data: string): void {\n\t * if (this.mode === \"normal\") {\n\t * // Handle vim normal mode keys...\n\t * if (data === \"i\") { this.mode = \"insert\"; return; }\n\t * }\n\t * super.handleInput(data); // App keybindings + text editing\n\t * }\n\t * }\n\t *\n\t * ctx.ui.setEditorComponent((tui, theme, keybindings) =>\n\t * new VimEditor(tui, theme, keybindings)\n\t * );\n\t * ```\n\t */\n\tsetEditorComponent(\n\t\tfactory: ((tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent) | undefined,\n\t): void;\n\n\t/** Get the current theme for styling. */\n\treadonly theme: Theme;\n\n\t/** Get all available themes with their names and file paths. */\n\tgetAllThemes(): { name: string; path: string | undefined }[];\n\n\t/** Load a theme by name without switching to it. Returns undefined if not found. */\n\tgetTheme(name: string): Theme | undefined;\n\n\t/** Set the current theme by name or Theme object. */\n\tsetTheme(theme: string | Theme): { success: boolean; error?: string };\n\n\t/** Get current tool output expansion state. */\n\tgetToolsExpanded(): boolean;\n\n\t/** Set tool output expansion state. */\n\tsetToolsExpanded(expanded: boolean): void;\n}\n\n// ============================================================================\n// Extension Context\n// ============================================================================\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\tcustomInstructions?: string;\n\tonComplete?: (result: CompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Context passed to extension event handlers.\n */\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Whether UI is available (false in print/RPC mode) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model<any> | undefined;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown dreb and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(entryId: string): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(sessionPath: string): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, and themes. */\n\treload(): Promise<void>;\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\n/** Rendering options for tool results */\nexport interface ToolRenderResultOptions {\n\t/** Whether the result view is expanded */\n\texpanded: boolean;\n\t/** Whether this is a partial/streaming result */\n\tisPartial: boolean;\n}\n\n/** Context passed to tool renderers. */\nexport interface ToolRenderContext<TState = any, TArgs = any> {\n\t/** Current tool call arguments. Shared across call/result renders for the same tool call. */\n\targs: TArgs;\n\t/** Unique id for this tool execution. Stable across call/result renders for the same tool call. */\n\ttoolCallId: string;\n\t/** Invalidate just this tool execution component for redraw. */\n\tinvalidate: () => void;\n\t/** Previously returned component for this render slot, if any. */\n\tlastComponent: Component | undefined;\n\t/** Shared renderer state for this tool row. Initialized by tool-execution.ts. */\n\tstate: TState;\n\t/** Working directory for this tool execution. */\n\tcwd: string;\n\t/** Whether the tool execution has started. */\n\texecutionStarted: boolean;\n\t/** Whether the tool call arguments are complete. */\n\targsComplete: boolean;\n\t/** Whether the tool result is partial/streaming. */\n\tisPartial: boolean;\n\t/** Whether the result view is expanded. */\n\texpanded: boolean;\n\t/** Whether inline images are currently shown in the TUI. */\n\tshowImages: boolean;\n\t/** Whether the current result is an error. */\n\tisError: boolean;\n}\n\n/**\n * Tool definition for registerTool().\n */\nexport interface ToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any> {\n\t/** Tool name (used in LLM tool calls) */\n\tname: string;\n\t/** Human-readable label for UI */\n\tlabel: string;\n\t/** Description for LLM */\n\tdescription: string;\n\t/** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */\n\tpromptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\tpromptGuidelines?: string[];\n\t/** Parameter schema (TypeBox) */\n\tparameters: TParams;\n\n\t/** Execute the tool. */\n\texecute(\n\t\ttoolCallId: string,\n\t\tparams: Static<TParams>,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: AgentToolUpdateCallback<TDetails> | undefined,\n\t\tctx: ExtensionContext,\n\t): Promise<AgentToolResult<TDetails>>;\n\n\t/** Custom rendering for tool call display */\n\trenderCall?: (args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>) => Component;\n\n\t/** Custom rendering for tool result display */\n\trenderResult?: (\n\t\tresult: AgentToolResult<TDetails>,\n\t\toptions: ToolRenderResultOptions,\n\t\ttheme: Theme,\n\t\tcontext: ToolRenderContext<TState, Static<TParams>>,\n\t) => Component;\n}\n\n// ============================================================================\n// Resource Events\n// ============================================================================\n\n/** Fired after session_start to allow extensions to provide additional resource paths. */\nexport interface ResourcesDiscoverEvent {\n\ttype: \"resources_discover\";\n\tcwd: string;\n\treason: \"startup\" | \"reload\";\n}\n\n/** Result from resources_discover event handler */\nexport interface ResourcesDiscoverResult {\n\tskillPaths?: string[];\n\tpromptPaths?: string[];\n\tthemePaths?: string[];\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired before session manager creation to allow custom session directory resolution */\nexport interface SessionDirectoryEvent {\n\ttype: \"session_directory\";\n\tcwd: string;\n}\n\n/** Fired on initial session load */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\treason: \"new\" | \"resume\";\n\ttargetSessionFile?: string;\n}\n\n/** Fired after switching to another session */\nexport interface SessionSwitchEvent {\n\ttype: \"session_switch\";\n\treason: \"new\" | \"resume\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n}\n\n/** Fired after forking a session */\nexport interface SessionForkEvent {\n\ttype: \"session_fork\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionEntry[];\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n}\n\n/** Fired on process exit */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n}\n\n/** Preparation data for tree navigation */\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionEntry[];\n\tuserWantsSummary: boolean;\n\t/** Custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n/** Fired before navigating in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromExtension?: boolean;\n}\n\nexport type SessionEvent =\n\t| SessionDirectoryEvent\n\t| SessionStartEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionSwitchEvent\n\t| SessionBeforeForkEvent\n\t| SessionForkEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\tprompt: string;\n\timages?: ImageContent[];\n\tsystemPrompt: string;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a dropped stream is discarded and retried. */\nexport interface StreamRetryEvent {\n\ttype: \"stream_retry\";\n\tattempt: number;\n\tmaxAttempts: number;\n\terror: string;\n\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\tdiscardedPartial?: AgentMessage;\n}\n\n/** Fired when a turn ends with stopReason \"length\" and is retried with a larger token budget. */\nexport interface LengthRetryEvent {\n\ttype: \"length_retry\";\n\tattempt: number;\n\tmaxAttempts: number;\n\t/** The maxTokens budget used for the truncated attempt. */\n\tpreviousMaxTokens: number;\n\t/** The escalated maxTokens budget the retry will request. */\n\tnextMaxTokens: number;\n\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\tdiscardedPartial?: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\tpartialResult: any;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: any;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: ModelSelectSource;\n}\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n\n// ============================================================================\n// Tool Events\n// ============================================================================\n\ninterface ToolCallEventBase {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n}\n\nexport interface BashToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"bash\";\n\tinput: BashToolInput;\n}\n\nexport interface ReadToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"read\";\n\tinput: ReadToolInput;\n}\n\nexport interface EditToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"edit\";\n\tinput: EditToolInput;\n}\n\nexport interface WriteToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"write\";\n\tinput: WriteToolInput;\n}\n\nexport interface GrepToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"grep\";\n\tinput: GrepToolInput;\n}\n\nexport interface FindToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"find\";\n\tinput: FindToolInput;\n}\n\nexport interface LsToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"ls\";\n\tinput: LsToolInput;\n}\n\nexport interface CustomToolCallEvent extends ToolCallEventBase {\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\n/** Fired before a tool executes. Can block. */\nexport type ToolCallEvent =\n\t| BashToolCallEvent\n\t| ReadToolCallEvent\n\t| EditToolCallEvent\n\t| WriteToolCallEvent\n\t| GrepToolCallEvent\n\t| FindToolCallEvent\n\t| LsToolCallEvent\n\t| CustomToolCallEvent;\n\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\tinput: Record<string, unknown>;\n\tcontent: (TextContent | ImageContent)[];\n\tisError: boolean;\n}\n\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/** Fired after a tool executes. Can modify result. */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for ToolResultEvent\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Type guard for narrowing ToolCallEvent by tool name.\n *\n * Built-in tools narrow automatically (no type params needed):\n * ```ts\n * if (isToolCallEventType(\"bash\", event)) {\n * event.input.command; // string\n * }\n * ```\n *\n * Custom tools require explicit type parameters:\n * ```ts\n * if (isToolCallEventType<\"my_tool\", MyToolInput>(\"my_tool\", event)) {\n * event.input.action; // typed\n * }\n * ```\n *\n * Note: Direct narrowing via `event.toolName === \"bash\"` doesn't work because\n * CustomToolCallEvent.toolName is `string` which overlaps with all literals.\n */\nexport function isToolCallEventType(toolName: \"bash\", event: ToolCallEvent): event is BashToolCallEvent;\nexport function isToolCallEventType(toolName: \"read\", event: ToolCallEvent): event is ReadToolCallEvent;\nexport function isToolCallEventType(toolName: \"edit\", event: ToolCallEvent): event is EditToolCallEvent;\nexport function isToolCallEventType(toolName: \"write\", event: ToolCallEvent): event is WriteToolCallEvent;\nexport function isToolCallEventType(toolName: \"grep\", event: ToolCallEvent): event is GrepToolCallEvent;\nexport function isToolCallEventType(toolName: \"find\", event: ToolCallEvent): event is FindToolCallEvent;\nexport function isToolCallEventType(toolName: \"ls\", event: ToolCallEvent): event is LsToolCallEvent;\nexport function isToolCallEventType<TName extends string, TInput extends Record<string, unknown>>(\n\ttoolName: TName,\n\tevent: ToolCallEvent,\n): event is ToolCallEvent & { toolName: TName; input: TInput };\nexport function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {\n\treturn event.toolName === toolName;\n}\n\n/** Union of all event types */\nexport type ExtensionEvent =\n\t| ResourcesDiscoverEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| StreamRetryEvent\n\t| LengthRetryEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| UserBashEvent\n\t| InputEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\nexport interface ContextEventResult {\n\tmessages?: AgentMessage[];\n}\n\nexport type BeforeProviderRequestEventResult = unknown;\n\nexport interface ToolCallEventResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/** Result from user_bash event handler */\nexport interface UserBashEventResult {\n\t/** Custom operations to use for execution */\n\toperations?: BashOperations;\n\t/** Full replacement: extension handled execution, use this result */\n\tresult?: BashResult;\n}\n\nexport interface ToolResultEventResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\nexport interface BeforeAgentStartEventResult {\n\tmessage?: Pick<CustomMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n\t/** Replace the system prompt for this turn. If multiple extensions return this, they are chained. */\n\tsystemPrompt?: string;\n}\n\nexport interface SessionDirectoryResult {\n\t/** Custom session directory path. If multiple extensions return this, the last one wins. */\n\tsessionDir?: string;\n}\n\n/** Special startup-only handler. Unlike other events, this receives no ExtensionContext. */\nexport type SessionDirectoryHandler = (\n\tevent: SessionDirectoryEvent,\n) => Promise<SessionDirectoryResult | undefined> | SessionDirectoryResult | undefined;\n\nexport interface SessionBeforeSwitchResult {\n\tcancel?: boolean;\n}\n\nexport interface SessionBeforeForkResult {\n\tcancel?: boolean;\n\tskipConversationRestore?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactionResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t};\n\t/** Override custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** Override whether customInstructions replaces the default prompt */\n\treplaceInstructions?: boolean;\n\t/** Override label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n// ============================================================================\n// Message Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer<T = unknown> = (\n\tmessage: CustomMessage<T>,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\nexport interface RegisteredCommand {\n\tname: string;\n\tsourceInfo: SourceInfo;\n\tdescription?: string;\n\tgetArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null;\n\thandler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;\n}\n\nexport interface ResolvedCommand extends RegisteredCommand {\n\tinvocationName: string;\n}\n\n// ============================================================================\n// Extension API\n// ============================================================================\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_directory\", handler: SessionDirectoryHandler): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_switch\", handler: ExtensionHandler<SessionSwitchEvent>): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): void;\n\ton(event: \"session_fork\", handler: ExtensionHandler<SessionForkEvent>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent>): void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent>): void;\n\ton(event: \"stream_retry\", handler: ExtensionHandler<StreamRetryEvent>): void;\n\ton(event: \"length_retry\", handler: ExtensionHandler<LengthRetryEvent>): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model<any>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * dreb.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * dreb.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * dreb.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * dreb.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n\n// ============================================================================\n// Provider Registration Types\n// ============================================================================\n\n/** Configuration for registering a provider via dreb.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key or environment variable name. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** Use Authorization: Bearer with the resolved API key instead of the provider's API-key auth channel. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Optional: modify models for this provider (e.g., update baseUrl based on credentials). */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Cost per token (for tracking, can be 0). */\n\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t/** Maximum context window size in tokens. */\n\tcontextWindow: number;\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (dreb: ExtensionAPI) => void | Promise<void>;\n\n// ============================================================================\n// Loaded Extension Types\n// ============================================================================\n\nexport interface RegisteredTool {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface ExtensionFlag {\n\tname: string;\n\tdescription?: string;\n\ttype: \"boolean\" | \"string\";\n\tdefault?: boolean | string;\n\textensionPath: string;\n}\n\nexport interface ExtensionShortcut {\n\tshortcut: KeyId;\n\tdescription?: string;\n\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\textensionPath: string;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\nexport type SendMessageHandler = <T = unknown>(\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n) => void;\n\nexport type SendUserMessageHandler = (\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n) => void;\n\nexport type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;\n\nexport type SetSessionNameHandler = (name: string) => void;\n\nexport type GetSessionNameHandler = () => string | undefined;\n\nexport type GetActiveToolsHandler = () => string[];\n\n/** Tool info with name, description, parameter schema, and source metadata */\nexport type ToolInfo = Pick<ToolDefinition, \"name\" | \"description\" | \"parameters\"> & {\n\tsourceInfo: SourceInfo;\n};\n\nexport type GetAllToolsHandler = () => ToolInfo[];\n\nexport type GetCommandsHandler = () => SlashCommandInfo[];\n\nexport type SetActiveToolsHandler = (toolNames: string[]) => void;\n\nexport type RefreshToolsHandler = () => void;\n\nexport type SetModelHandler = (model: Model<any>) => Promise<boolean>;\n\nexport type GetThinkingLevelHandler = () => ThinkingLevel;\n\nexport type SetThinkingLevelHandler = (level: ThinkingLevel) => void;\n\nexport type SetLabelHandler = (entryId: string, label: string | undefined) => void;\n\n/**\n * Shared state created by loader, used during registration and runtime.\n * Contains flag values (defaults set during registration, CLI values set after).\n */\nexport interface ExtensionRuntimeState {\n\tflagValues: Map<string, boolean | string>;\n\t/** Provider registrations queued during extension loading, processed when runner binds */\n\tpendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n\t/**\n\t * Register or unregister a provider.\n\t *\n\t * Before bindCore(): queues registrations / removes from queue.\n\t * After bindCore(): calls ModelRegistry directly for immediate effect.\n\t */\n\tregisterProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;\n\tunregisterProvider: (name: string, extensionPath?: string) => void;\n}\n\n/**\n * Action implementations for dreb.* API methods.\n * Provided to runner.initialize(), copied into the shared runtime.\n */\nexport interface ExtensionActions {\n\tsendMessage: SendMessageHandler;\n\tsendUserMessage: SendUserMessageHandler;\n\tappendEntry: AppendEntryHandler;\n\tsetSessionName: SetSessionNameHandler;\n\tgetSessionName: GetSessionNameHandler;\n\tsetLabel: SetLabelHandler;\n\tgetActiveTools: GetActiveToolsHandler;\n\tgetAllTools: GetAllToolsHandler;\n\tsetActiveTools: SetActiveToolsHandler;\n\trefreshTools: RefreshToolsHandler;\n\tgetCommands: GetCommandsHandler;\n\tsetModel: SetModelHandler;\n\tgetThinkingLevel: GetThinkingLevelHandler;\n\tsetThinkingLevel: SetThinkingLevelHandler;\n}\n\n/**\n * Actions for ExtensionContext (ctx.* in event handlers).\n * Required by all modes.\n */\nexport interface ExtensionContextActions {\n\tgetModel: () => Model<any> | undefined;\n\tisIdle: () => boolean;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n}\n\n/**\n * Actions for ExtensionCommandContext (ctx.* in command handlers).\n * Only needed for interactive mode where extension commands are invokable.\n */\nexport interface ExtensionCommandContextActions {\n\twaitForIdle: () => Promise<void>;\n\tnewSession: (options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (entryId: string) => Promise<{ cancelled: boolean }>;\n\tnavigateTree: (\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t) => Promise<{ cancelled: boolean }>;\n\tswitchSession: (sessionPath: string) => Promise<{ cancelled: boolean }>;\n\treload: () => Promise<void>;\n}\n\n/**\n * Full runtime = state + actions.\n * Created by loader with throwing action stubs, completed by runner.initialize().\n */\nexport interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}\n\n/** Loaded extension with all registered items. */\nexport interface Extension {\n\tpath: string;\n\tresolvedPath: string;\n\tsourceInfo: SourceInfo;\n\thandlers: Map<string, HandlerFn[]>;\n\ttools: Map<string, RegisteredTool>;\n\tmessageRenderers: Map<string, MessageRenderer>;\n\tcommands: Map<string, RegisteredCommand>;\n\tflags: Map<string, ExtensionFlag>;\n\tshortcuts: Map<KeyId, ExtensionShortcut>;\n}\n\n/** Result of loading extensions. */\nexport interface LoadExtensionsResult {\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n\t/** Shared runtime - actions are throwing stubs until runner.initialize() */\n\truntime: ExtensionRuntime;\n}\n\n// ============================================================================\n// Extension Error\n// ============================================================================\n\nexport interface ExtensionError {\n\textensionPath: string;\n\tevent: string;\n\terror: string;\n\tstack?: string;\n}\n"]}
@@ -9,6 +9,20 @@ export interface SlashCommandInfo {
9
9
  export interface BuiltinSlashCommand {
10
10
  name: string;
11
11
  description: string;
12
+ /** Whether the command is offered in dashboard autocomplete. Typed built-ins are always intercepted. */
13
+ dashboard?: false;
12
14
  }
13
15
  export declare const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand>;
16
+ /**
17
+ * Parse a registered built-in from the first slash token.
18
+ *
19
+ * `/fork` and `/fork anything` match while `/forklift` and unknown slash
20
+ * commands do not. Leading/trailing whitespace follows interactive-mode submit
21
+ * behavior. Hidden development commands are intentionally absent from the
22
+ * registry and therefore never match.
23
+ */
24
+ export declare function parseBuiltinSlashCommand(text: string): {
25
+ command: BuiltinSlashCommand;
26
+ args: string;
27
+ } | undefined;
14
28
  //# sourceMappingURL=slash-commands.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CAqBrE,CAAC","sourcesContent":["import type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous message\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"dream\", description: \"Consolidate and prune memories (backup, merge, scan sessions)\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"buddy\", description: \"Hatch or manage your terminal companion (pet, reroll, off)\" },\n\t{ name: \"quit\", description: \"Quit dreb\" },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,wGAAwG;IACxG,SAAS,CAAC,EAAE,KAAK,CAAC;CAClB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CAyBrE,CAAC;AAIF;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,mBAAmB,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAQjH","sourcesContent":["import type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\t/** Whether the command is offered in dashboard autocomplete. Typed built-ins are always intercepted. */\n\tdashboard?: false;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\", dashboard: false },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\", dashboard: false },\n\t{ name: \"fork\", description: \"Create a new fork from a previous message\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"dream\", description: \"Consolidate and prune memories (backup, merge, scan sessions)\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{\n\t\tname: \"buddy\",\n\t\tdescription: \"Hatch or manage your terminal companion (pet, reroll, off)\",\n\t\tdashboard: false,\n\t},\n\t{ name: \"quit\", description: \"Quit dreb\" },\n];\n\nconst BUILTIN_BY_NAME = new Map(BUILTIN_SLASH_COMMANDS.map((command) => [command.name, command]));\n\n/**\n * Parse a registered built-in from the first slash token.\n *\n * `/fork` and `/fork anything` match while `/forklift` and unknown slash\n * commands do not. Leading/trailing whitespace follows interactive-mode submit\n * behavior. Hidden development commands are intentionally absent from the\n * registry and therefore never match.\n */\nexport function parseBuiltinSlashCommand(text: string): { command: BuiltinSlashCommand; args: string } | undefined {\n\tconst trimmed = text.trim();\n\tif (!trimmed.startsWith(\"/\")) return undefined;\n\tconst match = /^\\/([^\\s]+)(?:\\s+([\\s\\S]*))?$/.exec(trimmed);\n\tif (!match) return undefined;\n\tconst command = BUILTIN_BY_NAME.get(match[1]);\n\tif (!command) return undefined;\n\treturn { command, args: (match[2] ?? \"\").trim() };\n}\n"]}
@@ -4,10 +4,10 @@ export const BUILTIN_SLASH_COMMANDS = [
4
4
  { name: "scoped-models", description: "Enable/disable models for Ctrl+P cycling" },
5
5
  { name: "export", description: "Export session (HTML default, or specify path: .html/.jsonl)" },
6
6
  { name: "import", description: "Import and resume a session from a JSONL file" },
7
- { name: "copy", description: "Copy last agent message to clipboard" },
7
+ { name: "copy", description: "Copy last agent message to clipboard", dashboard: false },
8
8
  { name: "name", description: "Set session display name" },
9
9
  { name: "session", description: "Show session info and stats" },
10
- { name: "hotkeys", description: "Show all keyboard shortcuts" },
10
+ { name: "hotkeys", description: "Show all keyboard shortcuts", dashboard: false },
11
11
  { name: "fork", description: "Create a new fork from a previous message" },
12
12
  { name: "tree", description: "Navigate session tree (switch branches)" },
13
13
  { name: "login", description: "Login with OAuth provider" },
@@ -17,7 +17,32 @@ export const BUILTIN_SLASH_COMMANDS = [
17
17
  { name: "dream", description: "Consolidate and prune memories (backup, merge, scan sessions)" },
18
18
  { name: "resume", description: "Resume a different session" },
19
19
  { name: "reload", description: "Reload keybindings, extensions, skills, prompts, and themes" },
20
- { name: "buddy", description: "Hatch or manage your terminal companion (pet, reroll, off)" },
20
+ {
21
+ name: "buddy",
22
+ description: "Hatch or manage your terminal companion (pet, reroll, off)",
23
+ dashboard: false,
24
+ },
21
25
  { name: "quit", description: "Quit dreb" },
22
26
  ];
27
+ const BUILTIN_BY_NAME = new Map(BUILTIN_SLASH_COMMANDS.map((command) => [command.name, command]));
28
+ /**
29
+ * Parse a registered built-in from the first slash token.
30
+ *
31
+ * `/fork` and `/fork anything` match while `/forklift` and unknown slash
32
+ * commands do not. Leading/trailing whitespace follows interactive-mode submit
33
+ * behavior. Hidden development commands are intentionally absent from the
34
+ * registry and therefore never match.
35
+ */
36
+ export function parseBuiltinSlashCommand(text) {
37
+ const trimmed = text.trim();
38
+ if (!trimmed.startsWith("/"))
39
+ return undefined;
40
+ const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(trimmed);
41
+ if (!match)
42
+ return undefined;
43
+ const command = BUILTIN_BY_NAME.get(match[1]);
44
+ if (!command)
45
+ return undefined;
46
+ return { command, args: (match[2] ?? "").trim() };
47
+ }
23
48
  //# sourceMappingURL=slash-commands.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAgBA,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE;IAClE,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,0CAA0C,EAAE;IAClF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,+CAA+C,EAAE;IAChF,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACrE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,0BAA0B,EAAE;IACzD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,2CAA2C,EAAE;IAC1E,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,2BAA2B,EAAE;IAC3D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,+DAA+D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,6DAA6D,EAAE;IAC9F,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,4DAA4D,EAAE;IAC5F,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE;CAC1C,CAAC","sourcesContent":["import type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous message\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"dream\", description: \"Consolidate and prune memories (backup, merge, scan sessions)\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"buddy\", description: \"Hatch or manage your terminal companion (pet, reroll, off)\" },\n\t{ name: \"quit\", description: \"Quit dreb\" },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAkBA,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE;IAClE,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,0CAA0C,EAAE;IAClF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,+CAA+C,EAAE;IAChF,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,sCAAsC,EAAE,SAAS,EAAE,KAAK,EAAE;IACvF,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,0BAA0B,EAAE;IACzD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE,SAAS,EAAE,KAAK,EAAE;IACjF,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,2CAA2C,EAAE;IAC1E,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,2BAA2B,EAAE;IAC3D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,+DAA+D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,6DAA6D,EAAE;IAC9F;QACC,IAAI,EAAE,OAAO;QACb,WAAW,EAAE,4DAA4D;QACzE,SAAS,EAAE,KAAK;KAChB;IACD,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE;CAC1C,CAAC;AAEF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AAElG;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAAY,EAA8D;IAClH,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC5B,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAC/C,MAAM,KAAK,GAAG,+BAA+B,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9C,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AAAA,CAClD","sourcesContent":["import type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\t/** Whether the command is offered in dashboard autocomplete. Typed built-ins are always intercepted. */\n\tdashboard?: false;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\", dashboard: false },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\", dashboard: false },\n\t{ name: \"fork\", description: \"Create a new fork from a previous message\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"dream\", description: \"Consolidate and prune memories (backup, merge, scan sessions)\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{\n\t\tname: \"buddy\",\n\t\tdescription: \"Hatch or manage your terminal companion (pet, reroll, off)\",\n\t\tdashboard: false,\n\t},\n\t{ name: \"quit\", description: \"Quit dreb\" },\n];\n\nconst BUILTIN_BY_NAME = new Map(BUILTIN_SLASH_COMMANDS.map((command) => [command.name, command]));\n\n/**\n * Parse a registered built-in from the first slash token.\n *\n * `/fork` and `/fork anything` match while `/forklift` and unknown slash\n * commands do not. Leading/trailing whitespace follows interactive-mode submit\n * behavior. Hidden development commands are intentionally absent from the\n * registry and therefore never match.\n */\nexport function parseBuiltinSlashCommand(text: string): { command: BuiltinSlashCommand; args: string } | undefined {\n\tconst trimmed = text.trim();\n\tif (!trimmed.startsWith(\"/\")) return undefined;\n\tconst match = /^\\/([^\\s]+)(?:\\s+([\\s\\S]*))?$/.exec(trimmed);\n\tif (!match) return undefined;\n\tconst command = BUILTIN_BY_NAME.get(match[1]);\n\tif (!command) return undefined;\n\treturn { command, args: (match[2] ?? \"\").trim() };\n}\n"]}
@@ -1,44 +1,52 @@
1
1
  /**
2
2
  * ask_user tool.
3
3
  *
4
- * Lets the agent pause and ask the user a structured clarifying question —
5
- * with optional multiple-choice options, single- or multi-select, and a
6
- * "type your own answer" free-text field — rendered natively in the TUI, the
7
- * Dashboard, and over RPC. Answering, stopping the turn, aborting, or timing
8
- * out always settles cleanly so the agent never deadlocks on an absent user.
9
- *
10
- * Concurrent calls are serialized through a per-session FIFO queue: only one
11
- * question is ever shown at a time, and a queued call whose signal aborts
12
- * settles without opening any UI.
4
+ * Lets the agent pause and ask the user one or more structured clarifying
5
+ * questions in a single call — each with optional multiple-choice options,
6
+ * single- or multi-select, and a "type your own answer" free-text field —
7
+ * rendered natively as a wizard in the TUI, the Dashboard, and over RPC. The
8
+ * whole batch is answered together and returned as one result. Answering,
9
+ * stopping the turn, aborting, or timing out always settles cleanly so the
10
+ * agent never deadlocks on an absent user. Unanswered questions come back
11
+ * flagged as skipped rather than blocking the turn.
13
12
  */
14
13
  import { type Static } from "@sinclair/typebox";
15
14
  import type { ToolDefinition } from "../extensions/types.js";
16
- export interface AskUserDetails {
15
+ /** One question's outcome, surfaced in the tool result details. */
16
+ export interface AskUserAnswerDetail {
17
17
  question: string;
18
18
  title?: string;
19
19
  selected: string[];
20
20
  customText?: string;
21
- /** True when the question closed without an answer. */
21
+ /** True when this question closed without an answer. */
22
22
  skipped: boolean;
23
+ }
24
+ export interface AskUserDetails {
25
+ /** One entry per question asked, in order. */
26
+ answers: AskUserAnswerDetail[];
23
27
  /** True when no interactive UI was available (headless/print mode). */
24
28
  unavailable: boolean;
25
29
  /** True when the UI host or response protocol failed. */
26
30
  failed?: boolean;
27
31
  }
28
32
  declare const askUserSchema: import("@sinclair/typebox").TObject<{
29
- question: import("@sinclair/typebox").TString;
30
- title: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
31
- options: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TArray<import("@sinclair/typebox").TString>>;
32
- allowFreeText: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
33
- multiSelect: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
34
- multiline: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
33
+ questions: import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<{
34
+ question: import("@sinclair/typebox").TString;
35
+ title: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
36
+ options: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TArray<import("@sinclair/typebox").TString>>;
37
+ allowFreeText: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
38
+ multiSelect: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
39
+ multiline: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
40
+ }>>;
35
41
  timeoutSeconds: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
36
42
  }>;
37
43
  export type AskUserInput = Static<typeof askUserSchema>;
38
44
  /**
39
- * Create an `ask_user` tool definition. Each call creates an isolated FIFO
40
- * queue, so concurrent `ask_user` calls in a single session are shown strictly
41
- * one at a time.
45
+ * Create an `ask_user` tool definition.
46
+ *
47
+ * One call carries one or more questions, collected together in a single
48
+ * wizard and returned as a batch of answers. Every path — answer, skip, abort,
49
+ * timeout, or host failure — settles gracefully and never orphans a promise.
42
50
  */
43
51
  export declare function createAskUserToolDefinition(): ToolDefinition<typeof askUserSchema, AskUserDetails | undefined>;
44
52
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"ask-user.d.ts","sourceRoot":"","sources":["../../../src/core/tools/ask-user.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAA2C,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAKtG,MAAM,WAAW,cAAc;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,OAAO,EAAE,OAAO,CAAC;IACjB,uEAAuE;IACvE,WAAW,EAAE,OAAO,CAAC;IACrB,yDAAyD;IACzD,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAKD,QAAA,MAAM,aAAa;;;;;;;;EAwCjB,CAAC;AAEH,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC;AA0FxD;;;;GAIG;AACH,wBAAgB,2BAA2B,IAAI,cAAc,CAAC,OAAO,aAAa,EAAE,cAAc,GAAG,SAAS,CAAC,CA+F9G","sourcesContent":["/**\n * ask_user tool.\n *\n * Lets the agent pause and ask the user a structured clarifying question —\n * with optional multiple-choice options, single- or multi-select, and a\n * \"type your own answer\" free-text field — rendered natively in the TUI, the\n * Dashboard, and over RPC. Answering, stopping the turn, aborting, or timing\n * out always settles cleanly so the agent never deadlocks on an absent user.\n *\n * Concurrent calls are serialized through a per-session FIFO queue: only one\n * question is ever shown at a time, and a queued call whose signal aborts\n * settles without opening any UI.\n */\n\nimport { Text } from \"@dreb/tui\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport type { AskRequest, AskResult, ExtensionContext, ToolDefinition } from \"../extensions/types.js\";\n\n// ============================================================================\n// Types\n\nexport interface AskUserDetails {\n\tquestion: string;\n\ttitle?: string;\n\tselected: string[];\n\tcustomText?: string;\n\t/** True when the question closed without an answer. */\n\tskipped: boolean;\n\t/** True when no interactive UI was available (headless/print mode). */\n\tunavailable: boolean;\n\t/** True when the UI host or response protocol failed. */\n\tfailed?: boolean;\n}\n\n// ============================================================================\n// Schema\n\nconst askUserSchema = Type.Object({\n\tquestion: Type.String({\n\t\tdescription: \"The Markdown-formatted question to ask the user. Be specific about what you need to decide.\",\n\t}),\n\ttitle: Type.Optional(\n\t\tType.String({\n\t\t\tdescription: \"Short bold header shown above the question.\",\n\t\t}),\n\t),\n\toptions: Type.Optional(\n\t\tType.Array(Type.String({ minLength: 1, pattern: \"^.*[^ \\\\t\\\\r\\\\n].*$\" }), {\n\t\t\tminItems: 2,\n\t\t\tmaxItems: 4,\n\t\t\tdescription: \"2-4 nonblank suggested answers the user can pick from.\",\n\t\t}),\n\t),\n\tallowFreeText: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"Offer a 'type your own answer' field. Defaults to true.\",\n\t\t}),\n\t),\n\tmultiSelect: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"Allow selecting multiple options (checkboxes). Only meaningful with options.\",\n\t\t}),\n\t),\n\tmultiline: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"Use a large multi-line text area for open-ended answers.\",\n\t\t}),\n\t),\n\ttimeoutSeconds: Type.Optional(\n\t\tType.Number({\n\t\t\tminimum: 5,\n\t\t\tmaximum: 3600,\n\t\t\tdescription:\n\t\t\t\t\"Optional: stop the current agent turn after this many seconds if the user does not respond. \" +\n\t\t\t\t\"Shows a live countdown. Omit to wait indefinitely.\",\n\t\t}),\n\t),\n});\n\nexport type AskUserInput = Static<typeof askUserSchema>;\n\n// ============================================================================\n// Result helpers\n\nfunction textResult(text: string, details: AskUserDetails) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text }],\n\t\tdetails,\n\t};\n}\n\nfunction baseDetails(input: AskUserInput): Omit<AskUserDetails, \"selected\" | \"skipped\" | \"unavailable\"> {\n\treturn { question: input.question, title: input.title };\n}\n\nfunction unavailableResult(input: AskUserInput) {\n\treturn textResult(\n\t\t\"The ask_user tool requires an interactive UI, which is not available in this mode. \" +\n\t\t\t\"Proceed using your best judgment without waiting for an answer.\",\n\t\t{ ...baseDetails(input), selected: [], skipped: true, unavailable: true },\n\t);\n}\n\nfunction unansweredResult(input: AskUserInput) {\n\treturn textResult(\"The question closed without an answer.\", {\n\t\t...baseDetails(input),\n\t\tselected: [],\n\t\tskipped: true,\n\t\tunavailable: false,\n\t});\n}\n\nfunction failedResult(input: AskUserInput) {\n\treturn textResult(\n\t\t\"The question could not be delivered because the interactive UI or response protocol failed. \" +\n\t\t\t\"Continue without this input.\",\n\t\t{\n\t\t\t...baseDetails(input),\n\t\t\tselected: [],\n\t\t\tskipped: false,\n\t\t\tunavailable: false,\n\t\t\tfailed: true,\n\t\t},\n\t);\n}\n\nfunction answeredResult(input: AskUserInput, answer: AskResult) {\n\tconst customText = answer.customText?.trim() || undefined;\n\tconst selected = answer.selected;\n\tconst parts: string[] = [];\n\tif (selected.length > 0) {\n\t\tparts.push(\n\t\t\tselected.length === 1 ? `The user selected: ${selected[0]}` : `The user selected: ${selected.join(\", \")}`,\n\t\t);\n\t}\n\tif (customText) {\n\t\tparts.push(selected.length > 0 ? `They also wrote: \"${customText}\"` : `The user answered: \"${customText}\"`);\n\t}\n\treturn textResult(parts.join(\" \"), {\n\t\t...baseDetails(input),\n\t\tselected,\n\t\tcustomText,\n\t\tskipped: false,\n\t\tunavailable: false,\n\t});\n}\n\n// ============================================================================\n// Render helpers\n\nfunction formatCall(args: { question?: string; title?: string } | undefined, theme: any): string {\n\tconst label = (args?.title || args?.question || \"\").replace(/\\s+/g, \" \").trim();\n\tconst shown = label.length > 80 ? `${label.slice(0, 79)}…` : label;\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"ask_user\"))} ${theme.fg(\"accent\", shown)}`;\n}\n\nfunction formatResult(details: AskUserDetails, theme: any): string {\n\tif (details.unavailable) return theme.fg(\"toolOutput\", \"no interactive UI — continued without asking\");\n\tif (details.failed) return theme.fg(\"toolOutput\", \"interactive UI failed — continued without an answer\");\n\tif (details.skipped) return theme.fg(\"toolOutput\", \"question closed without an answer\");\n\tconst parts: string[] = [];\n\tif (details.selected.length > 0) parts.push(details.selected.join(\", \"));\n\tif (details.customText) parts.push(`\"${details.customText}\"`);\n\treturn theme.fg(\"toolOutput\", `→ ${parts.join(\" + \")}`);\n}\n\n// ============================================================================\n// Tool definition factory\n\n/**\n * Create an `ask_user` tool definition. Each call creates an isolated FIFO\n * queue, so concurrent `ask_user` calls in a single session are shown strictly\n * one at a time.\n */\nexport function createAskUserToolDefinition(): ToolDefinition<typeof askUserSchema, AskUserDetails | undefined> {\n\t// Per-session serialization: only one question is ever open at a time.\n\tlet tail: Promise<void> = Promise.resolve();\n\tconst serialize = <T>(run: () => Promise<T>): Promise<T> => {\n\t\tconst result = tail.then(run, run);\n\t\t// Always advance the queue, whether the call resolved, cancelled, timed\n\t\t// out, or threw — so a failure can never wedge later questions.\n\t\ttail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t};\n\n\treturn {\n\t\tname: \"ask_user\",\n\t\tlabel: \"ask_user\",\n\t\tdescription:\n\t\t\t\"Pause and ask the user a structured clarifying question with optional multiple-choice options and a \" +\n\t\t\t\"free-text answer. Use only when genuinely blocked by ambiguity with multiple viable paths — not for routine confirmation.\",\n\n\t\tparameters: askUserSchema,\n\n\t\tpromptSnippet: \"Ask the user a clarifying question with optional multiple-choice options and free text\",\n\n\t\tpromptGuidelines: [\n\t\t\t\"Call ask_user ONLY when you are genuinely blocked by ambiguity and there are multiple viable paths forward\",\n\t\t\t\"Do NOT use it for routine confirmation, permission, or things you can reasonably decide yourself\",\n\t\t\t\"Provide 2-4 concrete `options` when there are clear candidate answers; the user can always type their own\",\n\t\t\t\"Set `multiSelect: true` when several options can be combined; `multiline: true` for open-ended answers\",\n\t\t\t\"The user may stop the current turn instead of answering; never treat that as an answer\",\n\t\t\t\"Prefer one focused question over many; the question blocks the turn until the user responds or stops it\",\n\t\t],\n\n\t\tasync execute(_toolCallId, input: AskUserInput, signal, _onUpdate, ctx?: ExtensionContext) {\n\t\t\tconst hasOptions = (input.options?.length ?? 0) > 0;\n\t\t\tconst request: AskRequest = {\n\t\t\t\tquestion: input.question,\n\t\t\t\ttitle: input.title,\n\t\t\t\toptions: input.options,\n\t\t\t\t// Guarantee at least one answer control: with no options, free text\n\t\t\t\t// must be offered regardless of the requested flag, otherwise both\n\t\t\t\t// surfaces would render only a Skip button and no way to answer.\n\t\t\t\tallowFreeText: hasOptions ? input.allowFreeText : true,\n\t\t\t\t// multiSelect is only meaningful with options; multiline only with\n\t\t\t\t// free text — normalize away impossible combinations.\n\t\t\t\tmultiSelect: hasOptions ? input.multiSelect : undefined,\n\t\t\t\tmultiline: hasOptions ? (input.allowFreeText === false ? undefined : input.multiline) : input.multiline,\n\t\t\t};\n\n\t\t\t// Optional auto-stop timeout, forwarded to every UI surface (TUI\n\t\t\t// countdown, RPC/Dashboard). Model-facing units are seconds.\n\t\t\tconst timeout = input.timeoutSeconds && input.timeoutSeconds > 0 ? input.timeoutSeconds * 1000 : undefined;\n\n\t\t\t// Headless / print / no-host modes: never block on an unreachable UI.\n\t\t\tif (!ctx?.hasUI) {\n\t\t\t\treturn unavailableResult(input);\n\t\t\t}\n\n\t\t\treturn serialize(async () => {\n\t\t\t\t// A queued call whose signal already aborted settles without ever\n\t\t\t\t// opening the UI; the parent turn is already stopping.\n\t\t\t\tif (signal?.aborted) return unansweredResult(input);\n\t\t\t\ttry {\n\t\t\t\t\tconst answer = await ctx.ui.ask(request, { signal, timeout });\n\t\t\t\t\tif (!answer || (answer.selected.length === 0 && !answer.customText?.trim())) {\n\t\t\t\t\t\treturn unansweredResult(input);\n\t\t\t\t\t}\n\t\t\t\t\treturn answeredResult(input, answer);\n\t\t\t\t} catch {\n\t\t\t\t\t// Host/protocol failure must still release the queue and never\n\t\t\t\t\t// deadlock, but it must not masquerade as an intentional user skip.\n\t\t\t\t\treturn failedResult(input);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\tconst details = (result as any).details as AskUserDetails | undefined;\n\t\t\tif (details) {\n\t\t\t\ttext.setText(formatResult(details, theme));\n\t\t\t} else {\n\t\t\t\tconst content = result.content?.[0];\n\t\t\t\ttext.setText(theme.fg(\"toolOutput\", content?.type === \"text\" ? content.text : \"\"));\n\t\t\t}\n\t\t\treturn text;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"ask-user.d.ts","sourceRoot":"","sources":["../../../src/core/tools/ask-user.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAwD,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAKnH,mEAAmE;AACnE,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wDAAwD;IACxD,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC9B,8CAA8C;IAC9C,OAAO,EAAE,mBAAmB,EAAE,CAAC;IAC/B,uEAAuE;IACvE,WAAW,EAAE,OAAO,CAAC;IACrB,yDAAyD;IACzD,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAsCD,QAAA,MAAM,aAAa;;;;;;;;;;EAiBjB,CAAC;AAEH,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC;AAiIxD;;;;;;GAMG;AACH,wBAAgB,2BAA2B,IAAI,cAAc,CAAC,OAAO,aAAa,EAAE,cAAc,GAAG,SAAS,CAAC,CAsE9G","sourcesContent":["/**\n * ask_user tool.\n *\n * Lets the agent pause and ask the user one or more structured clarifying\n * questions in a single call — each with optional multiple-choice options,\n * single- or multi-select, and a \"type your own answer\" free-text field —\n * rendered natively as a wizard in the TUI, the Dashboard, and over RPC. The\n * whole batch is answered together and returned as one result. Answering,\n * stopping the turn, aborting, or timing out always settles cleanly so the\n * agent never deadlocks on an absent user. Unanswered questions come back\n * flagged as skipped rather than blocking the turn.\n */\n\nimport { Text } from \"@dreb/tui\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport type { AskQuestion, AskRequest, AskResult, ExtensionContext, ToolDefinition } from \"../extensions/types.js\";\n\n// ============================================================================\n// Types\n\n/** One question's outcome, surfaced in the tool result details. */\nexport interface AskUserAnswerDetail {\n\tquestion: string;\n\ttitle?: string;\n\tselected: string[];\n\tcustomText?: string;\n\t/** True when this question closed without an answer. */\n\tskipped: boolean;\n}\n\nexport interface AskUserDetails {\n\t/** One entry per question asked, in order. */\n\tanswers: AskUserAnswerDetail[];\n\t/** True when no interactive UI was available (headless/print mode). */\n\tunavailable: boolean;\n\t/** True when the UI host or response protocol failed. */\n\tfailed?: boolean;\n}\n\n// ============================================================================\n// Schema\n\nconst questionSchema = Type.Object({\n\tquestion: Type.String({\n\t\tdescription: \"The Markdown-formatted question to ask the user. Be specific about what you need to decide.\",\n\t}),\n\ttitle: Type.Optional(\n\t\tType.String({\n\t\t\tdescription: \"Short bold header shown above this question.\",\n\t\t}),\n\t),\n\toptions: Type.Optional(\n\t\tType.Array(Type.String({ minLength: 1, pattern: \"^.*[^ \\\\t\\\\r\\\\n].*$\" }), {\n\t\t\tminItems: 2,\n\t\t\tmaxItems: 4,\n\t\t\tdescription: \"2-4 nonblank suggested answers the user can pick from.\",\n\t\t}),\n\t),\n\tallowFreeText: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"Offer a 'type your own answer' field. Defaults to true.\",\n\t\t}),\n\t),\n\tmultiSelect: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"Allow selecting multiple options (checkboxes). Only meaningful with options.\",\n\t\t}),\n\t),\n\tmultiline: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"Use a large multi-line text area for open-ended answers.\",\n\t\t}),\n\t),\n});\n\nconst askUserSchema = Type.Object({\n\tquestions: Type.Array(questionSchema, {\n\t\tminItems: 1,\n\t\tmaxItems: 10,\n\t\tdescription:\n\t\t\t\"One or more clarifying questions to ask together in a single wizard. \" +\n\t\t\t\"Batch every question you need answered in one call — the user answers them all and submits once.\",\n\t}),\n\ttimeoutSeconds: Type.Optional(\n\t\tType.Number({\n\t\t\tminimum: 5,\n\t\t\tmaximum: 3600,\n\t\t\tdescription:\n\t\t\t\t\"Optional: stop the current agent turn after this many seconds if the user does not respond. \" +\n\t\t\t\t\"Shows a live countdown. Omit to wait indefinitely.\",\n\t\t}),\n\t),\n});\n\nexport type AskUserInput = Static<typeof askUserSchema>;\ntype AskUserQuestion = Static<typeof questionSchema>;\n\n// ============================================================================\n// Normalization\n\n/**\n * Normalize a single question so every rendered surface has at least one usable\n * answer control and no impossible flag combinations survive.\n */\nfunction normalizeQuestion(q: AskUserQuestion): AskQuestion {\n\tconst hasOptions = (q.options?.length ?? 0) > 0;\n\treturn {\n\t\tquestion: q.question,\n\t\ttitle: q.title,\n\t\toptions: q.options,\n\t\t// Guarantee at least one answer control: with no options, free text must\n\t\t// be offered regardless of the requested flag, otherwise a question would\n\t\t// render only a Skip control and no way to answer.\n\t\tallowFreeText: hasOptions ? q.allowFreeText : true,\n\t\t// multiSelect is only meaningful with options; multiline only with free\n\t\t// text — normalize away impossible combinations.\n\t\tmultiSelect: hasOptions ? q.multiSelect : undefined,\n\t\tmultiline: hasOptions ? (q.allowFreeText === false ? undefined : q.multiline) : q.multiline,\n\t};\n}\n\n// ============================================================================\n// Result helpers\n\nfunction textResult(text: string, details: AskUserDetails) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text }],\n\t\tdetails,\n\t};\n}\n\nfunction skippedAnswer(q: AskQuestion): AskUserAnswerDetail {\n\treturn { question: q.question, title: q.title, selected: [], skipped: true };\n}\n\nfunction unavailableResult(questions: AskQuestion[]) {\n\treturn textResult(\n\t\t\"The ask_user tool requires an interactive UI, which is not available in this mode. \" +\n\t\t\t\"Proceed using your best judgment without waiting for an answer.\",\n\t\t{ answers: questions.map(skippedAnswer), unavailable: true },\n\t);\n}\n\nfunction unansweredResult(questions: AskQuestion[]) {\n\treturn textResult(\"The questions closed without an answer.\", {\n\t\tanswers: questions.map(skippedAnswer),\n\t\tunavailable: false,\n\t});\n}\n\nfunction failedResult(questions: AskQuestion[]) {\n\treturn textResult(\n\t\t\"The questions could not be delivered because the interactive UI or response protocol failed. \" +\n\t\t\t\"Continue without this input.\",\n\t\t{ answers: questions.map(skippedAnswer), unavailable: false, failed: true },\n\t);\n}\n\n/** Build a per-question detail entry from the user's answer. */\nfunction toAnswerDetail(q: AskQuestion, answer: AskResult[\"answers\"][number] | undefined): AskUserAnswerDetail {\n\tif (!answer || answer.skipped) return skippedAnswer(q);\n\tconst customText = answer.customText?.trim() || undefined;\n\tconst selected = answer.selected ?? [];\n\tif (selected.length === 0 && !customText) return skippedAnswer(q);\n\treturn { question: q.question, title: q.title, selected, customText, skipped: false };\n}\n\n/** Compose the model-facing summary, one block per question. */\nfunction summarizeAnswers(details: AskUserAnswerDetail[]): string {\n\tconst blocks = details.map((d) => {\n\t\tconst heading = (d.title || d.question || \"\").replace(/\\s+/g, \" \").trim();\n\t\tif (d.skipped) return `**${heading}** → (no answer)`;\n\t\tconst parts: string[] = [];\n\t\tif (d.selected.length > 0) parts.push(`Selected: ${d.selected.join(\", \")}`);\n\t\tif (d.customText) parts.push(`wrote: \"${d.customText}\"`);\n\t\treturn `**${heading}** → ${parts.join(\" / \")}`;\n\t});\n\treturn blocks.join(\"\\n\");\n}\n\nfunction answeredResult(questions: AskQuestion[], result: AskResult) {\n\tconst details = questions.map((q, i) => toAnswerDetail(q, result.answers[i]));\n\treturn textResult(summarizeAnswers(details), { answers: details, unavailable: false });\n}\n\n// ============================================================================\n// Render helpers\n\nfunction callLabel(args: { questions?: Array<{ title?: string; question?: string }> } | undefined): string {\n\tconst questions = args?.questions ?? [];\n\tconst count = questions.length;\n\tif (count === 1) {\n\t\tconst first = questions[0];\n\t\tconst label = (first?.title || first?.question || \"\").replace(/\\s+/g, \" \").trim();\n\t\treturn label.length > 80 ? `${label.slice(0, 79)}…` : label;\n\t}\n\treturn `${count} questions`;\n}\n\nfunction formatCall(\n\targs: { questions?: Array<{ title?: string; question?: string }> } | undefined,\n\ttheme: any,\n): string {\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"ask_user\"))} ${theme.fg(\"accent\", callLabel(args))}`;\n}\n\nfunction formatResult(details: AskUserDetails, theme: any): string {\n\tif (details.unavailable) return theme.fg(\"toolOutput\", \"no interactive UI — continued without asking\");\n\tif (details.failed) return theme.fg(\"toolOutput\", \"interactive UI failed — continued without an answer\");\n\tconst answered = details.answers.filter((a) => !a.skipped);\n\tif (answered.length === 0) return theme.fg(\"toolOutput\", \"closed without an answer\");\n\tif (details.answers.length === 1) {\n\t\tconst parts: string[] = [];\n\t\tif (answered[0].selected.length > 0) parts.push(answered[0].selected.join(\", \"));\n\t\tif (answered[0].customText) parts.push(`\"${answered[0].customText}\"`);\n\t\treturn theme.fg(\"toolOutput\", `→ ${parts.join(\" + \")}`);\n\t}\n\treturn theme.fg(\"toolOutput\", `→ answered ${answered.length} of ${details.answers.length}`);\n}\n\n// ============================================================================\n// Tool definition factory\n\n/**\n * Create an `ask_user` tool definition.\n *\n * One call carries one or more questions, collected together in a single\n * wizard and returned as a batch of answers. Every path — answer, skip, abort,\n * timeout, or host failure — settles gracefully and never orphans a promise.\n */\nexport function createAskUserToolDefinition(): ToolDefinition<typeof askUserSchema, AskUserDetails | undefined> {\n\treturn {\n\t\tname: \"ask_user\",\n\t\tlabel: \"ask_user\",\n\t\tdescription:\n\t\t\t\"Pause and ask the user one or more structured clarifying questions in a single call, each with \" +\n\t\t\t\"optional multiple-choice options and a free-text answer. The questions are shown together as one \" +\n\t\t\t\"wizard and answered as a batch. Use only when genuinely blocked by ambiguity with multiple viable \" +\n\t\t\t\"paths — not for routine confirmation.\",\n\n\t\tparameters: askUserSchema,\n\n\t\tpromptSnippet:\n\t\t\t\"Ask the user one or more clarifying questions with optional multiple-choice options and free text\",\n\n\t\tpromptGuidelines: [\n\t\t\t\"Call ask_user ONLY when you are genuinely blocked by ambiguity and there are multiple viable paths forward\",\n\t\t\t\"Do NOT use it for routine confirmation, permission, or things you can reasonably decide yourself\",\n\t\t\t\"Batch everything you need in ONE call: put each distinct decision in the `questions` array — the user answers them all and submits once\",\n\t\t\t\"Provide 2-4 concrete `options` per question when there are clear candidate answers; the user can always type their own\",\n\t\t\t\"Set `multiSelect: true` when several options can be combined; `multiline: true` for open-ended answers\",\n\t\t\t\"The user may stop the current turn instead of answering; never treat that as an answer, and unanswered questions come back as skipped\",\n\t\t],\n\n\t\tasync execute(_toolCallId, input: AskUserInput, signal, _onUpdate, ctx?: ExtensionContext) {\n\t\t\tconst questions = input.questions.map(normalizeQuestion);\n\t\t\tconst request: AskRequest = { questions };\n\n\t\t\t// Optional auto-stop timeout, forwarded to every UI surface (TUI\n\t\t\t// countdown, RPC/Dashboard). Model-facing units are seconds.\n\t\t\tconst timeout = input.timeoutSeconds && input.timeoutSeconds > 0 ? input.timeoutSeconds * 1000 : undefined;\n\n\t\t\t// Headless / print / no-host modes: never block on an unreachable UI.\n\t\t\tif (!ctx?.hasUI) {\n\t\t\t\treturn unavailableResult(questions);\n\t\t\t}\n\n\t\t\t// A call whose signal already aborted settles without ever opening the\n\t\t\t// UI; the parent turn is already stopping.\n\t\t\tif (signal?.aborted) return unansweredResult(questions);\n\n\t\t\ttry {\n\t\t\t\tconst answer = await ctx.ui.ask(request, { signal, timeout });\n\t\t\t\tif (!answer) return unansweredResult(questions);\n\t\t\t\treturn answeredResult(questions, answer);\n\t\t\t} catch {\n\t\t\t\t// Host/protocol failure must still settle and never deadlock, but it\n\t\t\t\t// must not masquerade as an intentional user skip.\n\t\t\t\treturn failedResult(questions);\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\tconst details = (result as any).details as AskUserDetails | undefined;\n\t\t\tif (details) {\n\t\t\t\ttext.setText(formatResult(details, theme));\n\t\t\t} else {\n\t\t\t\tconst content = result.content?.[0];\n\t\t\t\ttext.setText(theme.fg(\"toolOutput\", content?.type === \"text\" ? content.text : \"\"));\n\t\t\t}\n\t\t\treturn text;\n\t\t},\n\t};\n}\n"]}