@ashx-j/lunr 0.2.14 → 0.2.16

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 (215) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +4 -4
  3. package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
  4. package/dist/builtin-extensions/ashxj-tui.js +4 -4
  5. package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
  6. package/dist/builtin-extensions/index.d.ts.map +1 -1
  7. package/dist/builtin-extensions/index.js +2 -0
  8. package/dist/builtin-extensions/index.js.map +1 -1
  9. package/dist/builtin-extensions/lunr-settings-tools.d.ts +4 -0
  10. package/dist/builtin-extensions/lunr-settings-tools.d.ts.map +1 -0
  11. package/dist/builtin-extensions/lunr-settings-tools.js +120 -0
  12. package/dist/builtin-extensions/lunr-settings-tools.js.map +1 -0
  13. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.d.ts.map +1 -1
  14. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js +6 -2
  15. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js.map +1 -1
  16. package/dist/builtin-extensions/pi-prompt-template-model/subagent-runtime.d.ts +2 -2
  17. package/dist/builtin-extensions/pi-prompt-template-model/subagent-runtime.d.ts.map +1 -1
  18. package/dist/builtin-extensions/pi-prompt-template-model/subagent-runtime.js.map +1 -1
  19. package/dist/builtin-extensions/pi-prompt-template-model/subagent-step.d.ts.map +1 -1
  20. package/dist/builtin-extensions/pi-prompt-template-model/subagent-step.js +3 -3
  21. package/dist/builtin-extensions/pi-prompt-template-model/subagent-step.js.map +1 -1
  22. package/dist/builtin-extensions/pi-subagents/src/api/delegation.d.ts +2 -2
  23. package/dist/builtin-extensions/pi-subagents/src/api/delegation.d.ts.map +1 -1
  24. package/dist/builtin-extensions/pi-subagents/src/api/delegation.js +1 -1
  25. package/dist/builtin-extensions/pi-subagents/src/api/delegation.js.map +1 -1
  26. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  27. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +2 -1
  28. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  29. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts +5 -11
  30. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
  31. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +12 -15
  32. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
  33. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +3 -3
  34. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
  35. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +14 -27
  36. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
  37. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
  38. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +6 -4
  39. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
  40. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.d.ts.map +1 -1
  41. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js +2 -1
  42. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js.map +1 -1
  43. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts.map +1 -1
  44. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js +6 -4
  45. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js.map +1 -1
  46. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.d.ts.map +1 -1
  47. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.js +4 -2
  48. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.js.map +1 -1
  49. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.d.ts.map +1 -1
  50. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.js +3 -35
  51. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.js.map +1 -1
  52. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts.map +1 -1
  53. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js +5 -12
  54. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js.map +1 -1
  55. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  56. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +14 -31
  57. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  58. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts +2 -0
  59. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts.map +1 -1
  60. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js +28 -22
  61. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js.map +1 -1
  62. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts +1 -0
  63. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts.map +1 -1
  64. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.js.map +1 -1
  65. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts.map +1 -1
  66. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js +9 -4
  67. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
  68. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts +1 -1
  69. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts.map +1 -1
  70. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js +2 -2
  71. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js.map +1 -1
  72. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +4 -7
  73. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
  74. package/dist/builtin-extensions/pi-subagents/src/shared/types.js +1 -1
  75. package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
  76. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.d.ts +3 -3
  77. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.d.ts.map +1 -1
  78. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.js +7 -6
  79. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.js.map +1 -1
  80. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-request.d.ts.map +1 -1
  81. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-request.js +3 -3
  82. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-request.js.map +1 -1
  83. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts +1 -1
  84. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts.map +1 -1
  85. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js +6 -4
  86. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js.map +1 -1
  87. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +1 -1
  88. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
  89. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +15 -10
  90. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
  91. package/dist/builtin-extensions/pi-subagents/src/tui/fleet.d.ts.map +1 -1
  92. package/dist/builtin-extensions/pi-subagents/src/tui/fleet.js +3 -2
  93. package/dist/builtin-extensions/pi-subagents/src/tui/fleet.js.map +1 -1
  94. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +2 -2
  95. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
  96. package/dist/builtin-extensions/pi-subagents/src/tui/render.js +75 -43
  97. package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
  98. package/dist/core/agent-session-runtime.d.ts +5 -1
  99. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  100. package/dist/core/agent-session-runtime.js +7 -2
  101. package/dist/core/agent-session-runtime.js.map +1 -1
  102. package/dist/core/agent-session.d.ts +5 -0
  103. package/dist/core/agent-session.d.ts.map +1 -1
  104. package/dist/core/agent-session.js +68 -10
  105. package/dist/core/agent-session.js.map +1 -1
  106. package/dist/core/compaction/compaction.d.ts.map +1 -1
  107. package/dist/core/compaction/compaction.js +10 -5
  108. package/dist/core/compaction/compaction.js.map +1 -1
  109. package/dist/core/context-breakdown.d.ts +2 -0
  110. package/dist/core/context-breakdown.d.ts.map +1 -1
  111. package/dist/core/context-breakdown.js +6 -2
  112. package/dist/core/context-breakdown.js.map +1 -1
  113. package/dist/core/extensions/types.d.ts +2 -2
  114. package/dist/core/extensions/types.d.ts.map +1 -1
  115. package/dist/core/extensions/types.js.map +1 -1
  116. package/dist/core/injected-prompt.d.ts +3 -3
  117. package/dist/core/injected-prompt.d.ts.map +1 -1
  118. package/dist/core/injected-prompt.js +2 -7
  119. package/dist/core/injected-prompt.js.map +1 -1
  120. package/dist/core/large-subagent-launch.d.ts +13 -0
  121. package/dist/core/large-subagent-launch.d.ts.map +1 -0
  122. package/dist/core/large-subagent-launch.js +54 -0
  123. package/dist/core/large-subagent-launch.js.map +1 -0
  124. package/dist/core/model-instructions.d.ts +24 -0
  125. package/dist/core/model-instructions.d.ts.map +1 -0
  126. package/dist/core/model-instructions.js +123 -0
  127. package/dist/core/model-instructions.js.map +1 -0
  128. package/dist/core/permissions.d.ts +10 -11
  129. package/dist/core/permissions.d.ts.map +1 -1
  130. package/dist/core/permissions.js +107 -40
  131. package/dist/core/permissions.js.map +1 -1
  132. package/dist/core/plan-mode.d.ts.map +1 -1
  133. package/dist/core/plan-mode.js +10 -1
  134. package/dist/core/plan-mode.js.map +1 -1
  135. package/dist/core/resource-loader.d.ts +3 -0
  136. package/dist/core/resource-loader.d.ts.map +1 -1
  137. package/dist/core/resource-loader.js +13 -4
  138. package/dist/core/resource-loader.js.map +1 -1
  139. package/dist/core/runtime-bridges.d.ts +4 -0
  140. package/dist/core/runtime-bridges.d.ts.map +1 -0
  141. package/dist/core/runtime-bridges.js +16 -0
  142. package/dist/core/runtime-bridges.js.map +1 -0
  143. package/dist/core/sdk.d.ts.map +1 -1
  144. package/dist/core/sdk.js +1 -0
  145. package/dist/core/sdk.js.map +1 -1
  146. package/dist/core/settings-manager.d.ts +13 -0
  147. package/dist/core/settings-manager.d.ts.map +1 -1
  148. package/dist/core/settings-manager.js +32 -0
  149. package/dist/core/settings-manager.js.map +1 -1
  150. package/dist/core/settings-tools-bridge.d.ts +35 -0
  151. package/dist/core/settings-tools-bridge.d.ts.map +1 -0
  152. package/dist/core/settings-tools-bridge.js +56 -0
  153. package/dist/core/settings-tools-bridge.js.map +1 -0
  154. package/dist/core/slash-commands.d.ts.map +1 -1
  155. package/dist/core/slash-commands.js +0 -1
  156. package/dist/core/slash-commands.js.map +1 -1
  157. package/dist/core/system-prompt.d.ts.map +1 -1
  158. package/dist/core/system-prompt.js +1 -1
  159. package/dist/core/system-prompt.js.map +1 -1
  160. package/dist/gateway/agent-bridge.d.ts.map +1 -1
  161. package/dist/gateway/agent-bridge.js +3 -2
  162. package/dist/gateway/agent-bridge.js.map +1 -1
  163. package/dist/gateway/approval.d.ts.map +1 -1
  164. package/dist/gateway/approval.js +4 -3
  165. package/dist/gateway/approval.js.map +1 -1
  166. package/dist/gateway/commands.d.ts +1 -1
  167. package/dist/gateway/commands.d.ts.map +1 -1
  168. package/dist/gateway/commands.js +1 -18
  169. package/dist/gateway/commands.js.map +1 -1
  170. package/dist/gateway/cron.d.ts.map +1 -1
  171. package/dist/gateway/cron.js +3 -2
  172. package/dist/gateway/cron.js.map +1 -1
  173. package/dist/gateway/router.d.ts +1 -1
  174. package/dist/gateway/router.d.ts.map +1 -1
  175. package/dist/gateway/router.js +1 -1
  176. package/dist/gateway/router.js.map +1 -1
  177. package/dist/main.d.ts.map +1 -1
  178. package/dist/main.js +3 -9
  179. package/dist/main.js.map +1 -1
  180. package/dist/migrations.d.ts.map +1 -1
  181. package/dist/migrations.js +4 -0
  182. package/dist/migrations.js.map +1 -1
  183. package/dist/modes/interactive/components/injected-prompt-message.d.ts +1 -1
  184. package/dist/modes/interactive/components/injected-prompt-message.d.ts.map +1 -1
  185. package/dist/modes/interactive/components/injected-prompt-message.js +1 -1
  186. package/dist/modes/interactive/components/injected-prompt-message.js.map +1 -1
  187. package/dist/modes/interactive/components/settings-selector.d.ts +8 -1
  188. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  189. package/dist/modes/interactive/components/settings-selector.js +61 -1
  190. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  191. package/dist/modes/interactive/interactive-mode.d.ts +3 -3
  192. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  193. package/dist/modes/interactive/interactive-mode.js +45 -54
  194. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  195. package/docs/compaction.md +5 -3
  196. package/docs/features.md +7 -7
  197. package/docs/quickstart.md +2 -1
  198. package/docs/settings.md +3 -1
  199. package/docs/termux.md +1 -1
  200. package/docs/usage.md +2 -2
  201. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  202. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  203. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  204. package/examples/extensions/gondolin/package-lock.json +2 -2
  205. package/examples/extensions/gondolin/package.json +1 -1
  206. package/examples/extensions/sandbox/package-lock.json +2 -2
  207. package/examples/extensions/sandbox/package.json +1 -1
  208. package/examples/extensions/subagent/README.md +1 -1
  209. package/examples/extensions/with-deps/package-lock.json +2 -2
  210. package/examples/extensions/with-deps/package.json +1 -1
  211. package/package.json +4 -4
  212. package/dist/core/swarm.d.ts +0 -54
  213. package/dist/core/swarm.d.ts.map +0 -1
  214. package/dist/core/swarm.js +0 -119
  215. package/dist/core/swarm.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/extensions/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA6eH;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CACzB,IAA+C,EACiB;IAChE,OAAO,IAAqE,CAAC;AAAA,CAC7E;AA4cD,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 {\n\tAgentMessage,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"@ashx-j/lunr-agent\";\nimport type {\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tProviderHeaders,\n\tRefreshModelsContext,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n} from \"@ashx-j/lunr-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@ashx-j/lunr-tui\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { BashResult } from \"../bash-executor.ts\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.ts\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.ts\";\nimport type { KeybindingsManager } from \"../keybindings.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type { SourceInfo } from \"../source-info.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { BashOperations } from \"../tools/bash.ts\";\nimport type { EditToolDetails } from \"../tools/edit.ts\";\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.ts\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.ts\";\nexport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nexport type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.ts\";\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/** 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/** Working indicator configuration for the interactive streaming loader. */\nexport interface WorkingIndicatorOptions {\n\t/** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */\n\tframes?: string[];\n\t/** Frame interval in milliseconds for animated indicators. */\n\tintervalMs?: number;\n}\n\n/** Wrap the current autocomplete provider with additional behavior. */\nexport type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;\nexport type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent;\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/** 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/** Show or hide the built-in interactive working loader row during streaming. */\n\tsetWorkingVisible(visible: boolean): void;\n\n\t/**\n\t * Configure the interactive working indicator shown during streaming.\n\t *\n\t * - Omit the argument to restore the default animated spinner.\n\t * - Use `frames: [\"●\"]` for a static indicator.\n\t * - Use `frames: []` to hide the indicator entirely.\n\t * - Custom frames are rendered as provided, so extensions must add their own colors.\n\t */\n\tsetWorkingIndicator(options?: WorkingIndicatorOptions): void;\n\n\t/** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */\n\tsetHiddenThinkingLabel(label?: 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/** Stack additional autocomplete behavior on top of the built-in provider. */\n\taddAutocompleteProvider(factory: AutocompleteProviderFactory): void;\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 `@ashx-j/lunr` 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 \"@ashx-j/lunr\";\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(factory: EditorFactory | undefined): void;\n\n\t/** Get the currently configured custom editor factory, or undefined when using the default editor. */\n\tgetEditorComponent(): EditorFactory | undefined;\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 type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\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/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\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 pi 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/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\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\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): 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(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, themes, and context files. */\n\treload(): Promise<void>;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\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): Promise<void>;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): 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/** Position of a tool card in a consecutive same-name run. */\nexport type ToolGroupRole = \"singleton\" | \"first\" | \"middle\" | \"last\";\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/** Repaint the TUI without rebuilding this tool execution component. Cheaper than invalidate() for animation ticks. */\n\trequestRender?: () => 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\t/** Current tool result, when one exists. Call renderers can fold compact status into the header. */\n\tresult?: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: unknown;\n\t\tisError: boolean;\n\t};\n\t/** Consecutive same-name run position. Compact cards use this for tree chrome. */\n\tgroupRole?: ToolGroupRole;\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\t/** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */\n\trenderShell?: \"default\" | \"self\";\n\n\t/** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */\n\tprepareArguments?: (args: unknown) => Static<TParams>;\n\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\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\ntype AnyToolDefinition = ToolDefinition<any, any, any>;\n\n/**\n * Preserve parameter inference for standalone tool definitions.\n *\n * Use this when assigning a tool to a variable or passing it through arrays such\n * as `customTools`, where contextual typing would otherwise widen params to\n * `unknown`.\n */\nexport function defineTool<TParams extends TSchema, TDetails = unknown, TState = any>(\n\ttool: ToolDefinition<TParams, TDetails, TState>,\n): ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition {\n\treturn tool as ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition;\n}\n\n// ============================================================================\n// Startup/Resource Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\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 when a session is started, loaded, or reloaded */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n\t/** Why this session start happened. */\n\treason: \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Previously active session file. Present for \"new\", \"resume\", and \"fork\". */\n\tpreviousSessionFile?: string;\n}\n\n/** Fired when the current session metadata changes. */\nexport interface SessionInfoChangedEvent {\n\ttype: \"session_info_changed\";\n\t/** Current normalized session name. Undefined when the name is cleared. */\n\tname: string | undefined;\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 before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n\tposition: \"before\" | \"at\";\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\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n}\n\n/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n\treason: \"quit\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Destination session file when shutting down due to session replacement. */\n\ttargetSessionFile?: string;\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| SessionStartEvent\n\t| SessionInfoChangedEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionBeforeForkEvent\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/**\n * Fired after request headers are assembled, before the provider HTTP call.\n * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);\n * the return value is ignored. A `null` value deletes that header.\n */\nexport interface BeforeProviderHeadersEvent {\n\ttype: \"before_provider_headers\";\n\theaders: ProviderHeaders;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\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 after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */\nexport interface AgentSettledEvent {\n\ttype: \"agent_settled\";\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 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/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\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\t/** How the input will be delivered during streaming, or undefined when idle */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\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/**\n * Fired before a tool executes. Can block.\n *\n * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.\n * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.\n */\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| ProjectTrustEvent\n\t| ResourcesDiscoverEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| AfterProviderResponseEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| AgentSettledEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\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\t/** Block tool execution. To modify arguments, mutate `event.input` in place instead. */\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 MessageEndEventResult {\n\t/** Replace the finalized message. The replacement must keep the original message role. */\n\tmessage?: AgentMessage;\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 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 and Entry Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n}\n\nexport interface EntryRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer<T = unknown> = (\n\tmessage: CustomMessage<T>,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\nexport type EntryRenderer<T = unknown> = (\n\tentry: CustomEntry<T>,\n\toptions: EntryRenderOptions,\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 | Promise<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: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(event: \"session_info_changed\", handler: ExtensionHandler<SessionInfoChangedEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): 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_provider_headers\", handler: ExtensionHandler<BeforeProviderHeadersEvent>): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): 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: \"agent_settled\", handler: ExtensionHandler<AgentSettledEvent>): 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, MessageEndEventResult>): 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: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): 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/** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */\n\tregisterEntryRenderer<T = unknown>(customType: string, renderer: EntryRenderer<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, prompt guidelines, 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 * pi.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 * pi.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 * pi.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 * pi.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 pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. 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/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/**\n\t * Refresh this provider's model list. The returned list replaces extension-provided models.\n\t * Use context.store explicitly when the catalog should persist across sessions.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<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/** @deprecated Retained for source compatibility; canonical auth flows ignore it. */\n\t\tusesCallbackServer?: boolean;\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/** Legacy synchronous credential-dependent model projection. */\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/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Per-million-token cost rates and optional request-wide input pricing tiers. */\n\tcost: Model<Api>[\"cost\"];\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 = (pi: ExtensionAPI) => void | Promise<void>;\n\nexport type NamedInlineExtension = {\n\t/** Display name shown as `<inline:name>` in the startup Extensions list. */\n\tname: string;\n\tfactory: ExtensionFactory;\n};\n\nexport type InlineExtension = ExtensionFactory | NamedInlineExtension;\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, prompt guidelines, and source metadata. */\nexport type ToolInfo = Pick<ToolDefinition, \"name\" | \"description\" | \"parameters\" | \"promptGuidelines\"> & {\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/** Throws when this extension instance is stale after runtime replacement. */\n\tassertActive: () => void;\n\t/** Marks this extension instance as stale after runtime replacement or reload. */\n\tinvalidate: (message?: string) => void;\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 pi.* 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\tisProjectTrusted: () => boolean;\n\tgetSignal: () => AbortSignal | undefined;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n\tgetSystemPromptOptions?: () => BuildSystemPromptOptions;\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\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => 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: (\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => 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\tentryRenderers?: Map<string, EntryRenderer>;\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;AA6eH;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CACzB,IAA+C,EACiB;IAChE,OAAO,IAAqE,CAAC;AAAA,CAC7E;AA4cD,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 {\n\tAgentMessage,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"@ashx-j/lunr-agent\";\nimport type {\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tProviderHeaders,\n\tRefreshModelsContext,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n} from \"@ashx-j/lunr-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@ashx-j/lunr-tui\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { BashResult } from \"../bash-executor.ts\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.ts\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.ts\";\nimport type { KeybindingsManager } from \"../keybindings.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type { SourceInfo } from \"../source-info.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { BashOperations } from \"../tools/bash.ts\";\nimport type { EditToolDetails } from \"../tools/edit.ts\";\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.ts\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.ts\";\nexport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nexport type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.ts\";\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/** 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/** Working indicator configuration for the interactive streaming loader. */\nexport interface WorkingIndicatorOptions {\n\t/** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */\n\tframes?: string[];\n\t/** Frame interval in milliseconds for animated indicators. */\n\tintervalMs?: number;\n}\n\n/** Wrap the current autocomplete provider with additional behavior. */\nexport type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;\nexport type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent;\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/** 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/** Show or hide the built-in interactive working loader row during streaming. */\n\tsetWorkingVisible(visible: boolean): void;\n\n\t/**\n\t * Configure the interactive working indicator shown during streaming.\n\t *\n\t * - Omit the argument to restore the default animated spinner.\n\t * - Use `frames: [\"●\"]` for a static indicator.\n\t * - Use `frames: []` to hide the indicator entirely.\n\t * - Custom frames are rendered as provided, so extensions must add their own colors.\n\t */\n\tsetWorkingIndicator(options?: WorkingIndicatorOptions): void;\n\n\t/** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */\n\tsetHiddenThinkingLabel(label?: 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/** Stack additional autocomplete behavior on top of the built-in provider. */\n\taddAutocompleteProvider(factory: AutocompleteProviderFactory): void;\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 `@ashx-j/lunr` 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 \"@ashx-j/lunr\";\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(factory: EditorFactory | undefined): void;\n\n\t/** Get the currently configured custom editor factory, or undefined when using the default editor. */\n\tgetEditorComponent(): EditorFactory | undefined;\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 type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\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/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\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 pi 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/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\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\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): 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(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, themes, and context files. */\n\treload(): Promise<void>;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\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): Promise<void>;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): 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/** Position of a tool card in a consecutive same-name run. */\nexport type ToolGroupRole = \"singleton\" | \"first\" | \"middle\" | \"last\";\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/** Repaint the TUI without rebuilding this tool execution component. Cheaper than invalidate() for animation ticks. */\n\trequestRender?: () => 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\t/** Current tool result, when one exists. Call renderers can fold compact status into the header. */\n\tresult?: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: unknown;\n\t\tisError: boolean;\n\t};\n\t/** Consecutive same-name run position. Compact cards use this for tree chrome. */\n\tgroupRole?: ToolGroupRole;\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\t/** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */\n\trenderShell?: \"default\" | \"self\";\n\n\t/** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */\n\tprepareArguments?: (args: unknown) => Static<TParams>;\n\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\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\ntype AnyToolDefinition = ToolDefinition<any, any, any>;\n\n/**\n * Preserve parameter inference for standalone tool definitions.\n *\n * Use this when assigning a tool to a variable or passing it through arrays such\n * as `customTools`, where contextual typing would otherwise widen params to\n * `unknown`.\n */\nexport function defineTool<TParams extends TSchema, TDetails = unknown, TState = any>(\n\ttool: ToolDefinition<TParams, TDetails, TState>,\n): ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition {\n\treturn tool as ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition;\n}\n\n// ============================================================================\n// Startup/Resource Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\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 when a session is started, loaded, or reloaded */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n\t/** Why this session start happened. */\n\treason: \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Previously active session file. Present for \"new\", \"resume\", and \"fork\". */\n\tpreviousSessionFile?: string;\n}\n\n/** Fired when the current session metadata changes. */\nexport interface SessionInfoChangedEvent {\n\ttype: \"session_info_changed\";\n\t/** Current normalized session name. Undefined when the name is cleared. */\n\tname: string | undefined;\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 before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n\tposition: \"before\" | \"at\";\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\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the active run sends another provider request after compaction */\n\twillRetry: boolean;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the active run sends another provider request after compaction */\n\twillRetry: boolean;\n}\n\n/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n\treason: \"quit\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Destination session file when shutting down due to session replacement. */\n\ttargetSessionFile?: string;\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| SessionStartEvent\n\t| SessionInfoChangedEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionBeforeForkEvent\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/**\n * Fired after request headers are assembled, before the provider HTTP call.\n * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);\n * the return value is ignored. A `null` value deletes that header.\n */\nexport interface BeforeProviderHeadersEvent {\n\ttype: \"before_provider_headers\";\n\theaders: ProviderHeaders;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\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 after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */\nexport interface AgentSettledEvent {\n\ttype: \"agent_settled\";\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 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/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\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\t/** How the input will be delivered during streaming, or undefined when idle */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\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/**\n * Fired before a tool executes. Can block.\n *\n * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.\n * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.\n */\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| ProjectTrustEvent\n\t| ResourcesDiscoverEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| AfterProviderResponseEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| AgentSettledEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\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\t/** Block tool execution. To modify arguments, mutate `event.input` in place instead. */\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 MessageEndEventResult {\n\t/** Replace the finalized message. The replacement must keep the original message role. */\n\tmessage?: AgentMessage;\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 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 and Entry Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n}\n\nexport interface EntryRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer<T = unknown> = (\n\tmessage: CustomMessage<T>,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\nexport type EntryRenderer<T = unknown> = (\n\tentry: CustomEntry<T>,\n\toptions: EntryRenderOptions,\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 | Promise<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: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(event: \"session_info_changed\", handler: ExtensionHandler<SessionInfoChangedEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): 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_provider_headers\", handler: ExtensionHandler<BeforeProviderHeadersEvent>): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): 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: \"agent_settled\", handler: ExtensionHandler<AgentSettledEvent>): 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, MessageEndEventResult>): 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: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): 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/** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */\n\tregisterEntryRenderer<T = unknown>(customType: string, renderer: EntryRenderer<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, prompt guidelines, 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 * pi.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 * pi.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 * pi.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 * pi.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 pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. 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/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/**\n\t * Refresh this provider's model list. The returned list replaces extension-provided models.\n\t * Use context.store explicitly when the catalog should persist across sessions.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<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/** @deprecated Retained for source compatibility; canonical auth flows ignore it. */\n\t\tusesCallbackServer?: boolean;\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/** Legacy synchronous credential-dependent model projection. */\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/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Per-million-token cost rates and optional request-wide input pricing tiers. */\n\tcost: Model<Api>[\"cost\"];\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 = (pi: ExtensionAPI) => void | Promise<void>;\n\nexport type NamedInlineExtension = {\n\t/** Display name shown as `<inline:name>` in the startup Extensions list. */\n\tname: string;\n\tfactory: ExtensionFactory;\n};\n\nexport type InlineExtension = ExtensionFactory | NamedInlineExtension;\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, prompt guidelines, and source metadata. */\nexport type ToolInfo = Pick<ToolDefinition, \"name\" | \"description\" | \"parameters\" | \"promptGuidelines\"> & {\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/** Throws when this extension instance is stale after runtime replacement. */\n\tassertActive: () => void;\n\t/** Marks this extension instance as stale after runtime replacement or reload. */\n\tinvalidate: (message?: string) => void;\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 pi.* 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\tisProjectTrusted: () => boolean;\n\tgetSignal: () => AbortSignal | undefined;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n\tgetSystemPromptOptions?: () => BuildSystemPromptOptions;\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\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => 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: (\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => 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\tentryRenderers?: Map<string, EntryRenderer>;\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,15 +1,15 @@
1
1
  /**
2
- * lunr: detect injected prompts (/swarm, /research, /goal) so the transcript can
2
+ * lunr: detect injected prompts (/research, /goal) so the transcript can
3
3
  * render them collapsed instead of dumping the full multi-line prompt verbatim.
4
4
  *
5
5
  * These prompts become plain {role:"user"} messages (PromptOptions.source is not
6
6
  * persisted), so detection is keyed on stable markers that already exist in the
7
- * prompt bodies: the `[SWARM MODE]` / `[DEEP RESEARCH]` literal prefixes and the
7
+ * prompt bodies: the `[DEEP RESEARCH]` literal prefix and the
8
8
  * goal extension's `<!-- pi-goal-prompt:… -->` HTML comment. This is render-time
9
9
  * only — the model still receives the full prompt unchanged, and old session
10
10
  * transcripts are cleaned up retroactively with no schema migration.
11
11
  */
12
- export type InjectedPromptKind = "swarm" | "research" | "goal";
12
+ export type InjectedPromptKind = "research" | "goal";
13
13
  export interface InjectedPromptInfo {
14
14
  kind: InjectedPromptKind;
15
15
  /** One-line summary extracted from the prompt body (task / question / objective). */
@@ -1 +1 @@
1
- {"version":3,"file":"injected-prompt.d.ts","sourceRoot":"","sources":["../../src/core/injected-prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,MAAM,MAAM,kBAAkB,GAAG,OAAO,GAAG,UAAU,GAAG,MAAM,CAAC;AAE/D,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,kBAAkB,CAAC;IACzB,qFAAqF;IACrF,OAAO,EAAE,MAAM,CAAC;CAChB;AA+BD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAoBjF;AAED,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,kBAAkB,EAAE,MAAM,CAIrE,CAAC","sourcesContent":["/**\n * lunr: detect injected prompts (/swarm, /research, /goal) so the transcript can\n * render them collapsed instead of dumping the full multi-line prompt verbatim.\n *\n * These prompts become plain {role:\"user\"} messages (PromptOptions.source is not\n * persisted), so detection is keyed on stable markers that already exist in the\n * prompt bodies: the `[SWARM MODE]` / `[DEEP RESEARCH]` literal prefixes and the\n * goal extension's `<!-- pi-goal-prompt:… -->` HTML comment. This is render-time\n * only — the model still receives the full prompt unchanged, and old session\n * transcripts are cleaned up retroactively with no schema migration.\n */\n\nexport type InjectedPromptKind = \"swarm\" | \"research\" | \"goal\";\n\nexport interface InjectedPromptInfo {\n\tkind: InjectedPromptKind;\n\t/** One-line summary extracted from the prompt body (task / question / objective). */\n\tsummary: string;\n}\n\nfunction firstNonEmptyLine(text: string): string | undefined {\n\tfor (const raw of text.split(/\\r?\\n/)) {\n\t\tconst line = raw.trim();\n\t\tif (line) return line;\n\t}\n\treturn undefined;\n}\n\n/** Extract the value following a `Label:` prefix on the first line, else undefined. */\nfunction extractAfterLabel(text: string, label: string): string | undefined {\n\tconst idx = text.indexOf(label);\n\tif (idx === -1) return undefined;\n\tconst rest = text.slice(idx + label.length).split(/\\r?\\n/)[0] ?? \"\";\n\tconst trimmed = rest.trim();\n\treturn trimmed || undefined;\n}\n\n/** Extract the contents of a `<goal_objective>…</goal_objective>` block. */\nfunction extractGoalObjective(text: string): string | undefined {\n\tconst open = text.indexOf(\"<goal_objective>\");\n\tif (open === -1) return undefined;\n\tconst close = text.indexOf(\"</goal_objective>\", open);\n\tif (close === -1) return undefined;\n\tconst inner = text.slice(open + \"<goal_objective>\".length, close);\n\tconst trimmed = inner.trim();\n\t// Unescape the minimal XML escaping the goal prompt builder applies.\n\treturn trimmed.replace(/&amp;/g, \"&\").replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").trim() || undefined;\n}\n\nexport function detectInjectedPrompt(text: string): InjectedPromptInfo | undefined {\n\tif (!text) return undefined;\n\n\tif (text.startsWith(\"[SWARM MODE]\")) {\n\t\tconst summary = extractAfterLabel(text, \"Task:\") ?? firstNonEmptyLine(text.slice(\"[SWARM MODE]\".length).trim());\n\t\treturn { kind: \"swarm\", summary: summary ?? \"swarm task\" };\n\t}\n\n\tif (text.startsWith(\"[DEEP RESEARCH]\")) {\n\t\tconst summary =\n\t\t\textractAfterLabel(text, \"Question:\") ?? firstNonEmptyLine(text.slice(\"[DEEP RESEARCH]\".length).trim());\n\t\treturn { kind: \"research\", summary: summary ?? \"research question\" };\n\t}\n\n\tif (text.includes(\"pi-goal-prompt:\")) {\n\t\tconst objective = extractGoalObjective(text);\n\t\treturn { kind: \"goal\", summary: objective ?? \"goal\" };\n\t}\n\n\treturn undefined;\n}\n\nexport const INJECTED_PROMPT_LABELS: Record<InjectedPromptKind, string> = {\n\tswarm: \"swarm\",\n\tresearch: \"research\",\n\tgoal: \"goal\",\n};\n"]}
1
+ {"version":3,"file":"injected-prompt.d.ts","sourceRoot":"","sources":["../../src/core/injected-prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,MAAM,CAAC;AAErD,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,kBAAkB,CAAC;IACzB,qFAAqF;IACrF,OAAO,EAAE,MAAM,CAAC;CAChB;AA+BD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAejF;AAED,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,kBAAkB,EAAE,MAAM,CAGrE,CAAC","sourcesContent":["/**\n * lunr: detect injected prompts (/research, /goal) so the transcript can\n * render them collapsed instead of dumping the full multi-line prompt verbatim.\n *\n * These prompts become plain {role:\"user\"} messages (PromptOptions.source is not\n * persisted), so detection is keyed on stable markers that already exist in the\n * prompt bodies: the `[DEEP RESEARCH]` literal prefix and the\n * goal extension's `<!-- pi-goal-prompt:… -->` HTML comment. This is render-time\n * only — the model still receives the full prompt unchanged, and old session\n * transcripts are cleaned up retroactively with no schema migration.\n */\n\nexport type InjectedPromptKind = \"research\" | \"goal\";\n\nexport interface InjectedPromptInfo {\n\tkind: InjectedPromptKind;\n\t/** One-line summary extracted from the prompt body (task / question / objective). */\n\tsummary: string;\n}\n\nfunction firstNonEmptyLine(text: string): string | undefined {\n\tfor (const raw of text.split(/\\r?\\n/)) {\n\t\tconst line = raw.trim();\n\t\tif (line) return line;\n\t}\n\treturn undefined;\n}\n\n/** Extract the value following a `Label:` prefix on the first line, else undefined. */\nfunction extractAfterLabel(text: string, label: string): string | undefined {\n\tconst idx = text.indexOf(label);\n\tif (idx === -1) return undefined;\n\tconst rest = text.slice(idx + label.length).split(/\\r?\\n/)[0] ?? \"\";\n\tconst trimmed = rest.trim();\n\treturn trimmed || undefined;\n}\n\n/** Extract the contents of a `<goal_objective>…</goal_objective>` block. */\nfunction extractGoalObjective(text: string): string | undefined {\n\tconst open = text.indexOf(\"<goal_objective>\");\n\tif (open === -1) return undefined;\n\tconst close = text.indexOf(\"</goal_objective>\", open);\n\tif (close === -1) return undefined;\n\tconst inner = text.slice(open + \"<goal_objective>\".length, close);\n\tconst trimmed = inner.trim();\n\t// Unescape the minimal XML escaping the goal prompt builder applies.\n\treturn trimmed.replace(/&amp;/g, \"&\").replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").trim() || undefined;\n}\n\nexport function detectInjectedPrompt(text: string): InjectedPromptInfo | undefined {\n\tif (!text) return undefined;\n\n\tif (text.startsWith(\"[DEEP RESEARCH]\")) {\n\t\tconst summary =\n\t\t\textractAfterLabel(text, \"Question:\") ?? firstNonEmptyLine(text.slice(\"[DEEP RESEARCH]\".length).trim());\n\t\treturn { kind: \"research\", summary: summary ?? \"research question\" };\n\t}\n\n\tif (text.includes(\"pi-goal-prompt:\")) {\n\t\tconst objective = extractGoalObjective(text);\n\t\treturn { kind: \"goal\", summary: objective ?? \"goal\" };\n\t}\n\n\treturn undefined;\n}\n\nexport const INJECTED_PROMPT_LABELS: Record<InjectedPromptKind, string> = {\n\tresearch: \"research\",\n\tgoal: \"goal\",\n};\n"]}
@@ -1,10 +1,10 @@
1
1
  /**
2
- * lunr: detect injected prompts (/swarm, /research, /goal) so the transcript can
2
+ * lunr: detect injected prompts (/research, /goal) so the transcript can
3
3
  * render them collapsed instead of dumping the full multi-line prompt verbatim.
4
4
  *
5
5
  * These prompts become plain {role:"user"} messages (PromptOptions.source is not
6
6
  * persisted), so detection is keyed on stable markers that already exist in the
7
- * prompt bodies: the `[SWARM MODE]` / `[DEEP RESEARCH]` literal prefixes and the
7
+ * prompt bodies: the `[DEEP RESEARCH]` literal prefix and the
8
8
  * goal extension's `<!-- pi-goal-prompt:… -->` HTML comment. This is render-time
9
9
  * only — the model still receives the full prompt unchanged, and old session
10
10
  * transcripts are cleaned up retroactively with no schema migration.
@@ -42,10 +42,6 @@ function extractGoalObjective(text) {
42
42
  export function detectInjectedPrompt(text) {
43
43
  if (!text)
44
44
  return undefined;
45
- if (text.startsWith("[SWARM MODE]")) {
46
- const summary = extractAfterLabel(text, "Task:") ?? firstNonEmptyLine(text.slice("[SWARM MODE]".length).trim());
47
- return { kind: "swarm", summary: summary ?? "swarm task" };
48
- }
49
45
  if (text.startsWith("[DEEP RESEARCH]")) {
50
46
  const summary = extractAfterLabel(text, "Question:") ?? firstNonEmptyLine(text.slice("[DEEP RESEARCH]".length).trim());
51
47
  return { kind: "research", summary: summary ?? "research question" };
@@ -57,7 +53,6 @@ export function detectInjectedPrompt(text) {
57
53
  return undefined;
58
54
  }
59
55
  export const INJECTED_PROMPT_LABELS = {
60
- swarm: "swarm",
61
56
  research: "research",
62
57
  goal: "goal",
63
58
  };
@@ -1 +1 @@
1
- {"version":3,"file":"injected-prompt.js","sourceRoot":"","sources":["../../src/core/injected-prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,SAAS,iBAAiB,CAAC,IAAY,EAAsB;IAC5D,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC;QACxB,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC;IACvB,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,uFAAuF;AACvF,SAAS,iBAAiB,CAAC,IAAY,EAAE,KAAa,EAAsB;IAC3E,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,GAAG,KAAK,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACjC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACpE,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC5B,OAAO,OAAO,IAAI,SAAS,CAAC;AAAA,CAC5B;AAED,8EAA4E;AAC5E,SAAS,oBAAoB,CAAC,IAAY,EAAsB;IAC/D,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAC9C,IAAI,IAAI,KAAK,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IAClC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,EAAE,IAAI,CAAC,CAAC;IACtD,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACnC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAClE,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,qEAAqE;IACrE,OAAO,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,SAAS,CAAC;AAAA,CACtG;AAED,MAAM,UAAU,oBAAoB,CAAC,IAAY,EAAkC;IAClF,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAE5B,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;QACrC,MAAM,OAAO,GAAG,iBAAiB,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAChH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,CAAC;IAC5D,CAAC;IAED,IAAI,IAAI,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE,CAAC;QACxC,MAAM,OAAO,GACZ,iBAAiB,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QACxG,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,CAAC;IACtE,CAAC;IAED,IAAI,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC;QACtC,MAAM,SAAS,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;QAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,IAAI,MAAM,EAAE,CAAC;IACvD,CAAC;IAED,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,IAAI,EAAE,MAAM;CACZ,CAAC","sourcesContent":["/**\n * lunr: detect injected prompts (/swarm, /research, /goal) so the transcript can\n * render them collapsed instead of dumping the full multi-line prompt verbatim.\n *\n * These prompts become plain {role:\"user\"} messages (PromptOptions.source is not\n * persisted), so detection is keyed on stable markers that already exist in the\n * prompt bodies: the `[SWARM MODE]` / `[DEEP RESEARCH]` literal prefixes and the\n * goal extension's `<!-- pi-goal-prompt:… -->` HTML comment. This is render-time\n * only — the model still receives the full prompt unchanged, and old session\n * transcripts are cleaned up retroactively with no schema migration.\n */\n\nexport type InjectedPromptKind = \"swarm\" | \"research\" | \"goal\";\n\nexport interface InjectedPromptInfo {\n\tkind: InjectedPromptKind;\n\t/** One-line summary extracted from the prompt body (task / question / objective). */\n\tsummary: string;\n}\n\nfunction firstNonEmptyLine(text: string): string | undefined {\n\tfor (const raw of text.split(/\\r?\\n/)) {\n\t\tconst line = raw.trim();\n\t\tif (line) return line;\n\t}\n\treturn undefined;\n}\n\n/** Extract the value following a `Label:` prefix on the first line, else undefined. */\nfunction extractAfterLabel(text: string, label: string): string | undefined {\n\tconst idx = text.indexOf(label);\n\tif (idx === -1) return undefined;\n\tconst rest = text.slice(idx + label.length).split(/\\r?\\n/)[0] ?? \"\";\n\tconst trimmed = rest.trim();\n\treturn trimmed || undefined;\n}\n\n/** Extract the contents of a `<goal_objective>…</goal_objective>` block. */\nfunction extractGoalObjective(text: string): string | undefined {\n\tconst open = text.indexOf(\"<goal_objective>\");\n\tif (open === -1) return undefined;\n\tconst close = text.indexOf(\"</goal_objective>\", open);\n\tif (close === -1) return undefined;\n\tconst inner = text.slice(open + \"<goal_objective>\".length, close);\n\tconst trimmed = inner.trim();\n\t// Unescape the minimal XML escaping the goal prompt builder applies.\n\treturn trimmed.replace(/&amp;/g, \"&\").replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").trim() || undefined;\n}\n\nexport function detectInjectedPrompt(text: string): InjectedPromptInfo | undefined {\n\tif (!text) return undefined;\n\n\tif (text.startsWith(\"[SWARM MODE]\")) {\n\t\tconst summary = extractAfterLabel(text, \"Task:\") ?? firstNonEmptyLine(text.slice(\"[SWARM MODE]\".length).trim());\n\t\treturn { kind: \"swarm\", summary: summary ?? \"swarm task\" };\n\t}\n\n\tif (text.startsWith(\"[DEEP RESEARCH]\")) {\n\t\tconst summary =\n\t\t\textractAfterLabel(text, \"Question:\") ?? firstNonEmptyLine(text.slice(\"[DEEP RESEARCH]\".length).trim());\n\t\treturn { kind: \"research\", summary: summary ?? \"research question\" };\n\t}\n\n\tif (text.includes(\"pi-goal-prompt:\")) {\n\t\tconst objective = extractGoalObjective(text);\n\t\treturn { kind: \"goal\", summary: objective ?? \"goal\" };\n\t}\n\n\treturn undefined;\n}\n\nexport const INJECTED_PROMPT_LABELS: Record<InjectedPromptKind, string> = {\n\tswarm: \"swarm\",\n\tresearch: \"research\",\n\tgoal: \"goal\",\n};\n"]}
1
+ {"version":3,"file":"injected-prompt.js","sourceRoot":"","sources":["../../src/core/injected-prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,SAAS,iBAAiB,CAAC,IAAY,EAAsB;IAC5D,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC;QACxB,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC;IACvB,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,uFAAuF;AACvF,SAAS,iBAAiB,CAAC,IAAY,EAAE,KAAa,EAAsB;IAC3E,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,GAAG,KAAK,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACjC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACpE,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC5B,OAAO,OAAO,IAAI,SAAS,CAAC;AAAA,CAC5B;AAED,8EAA4E;AAC5E,SAAS,oBAAoB,CAAC,IAAY,EAAsB;IAC/D,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAC9C,IAAI,IAAI,KAAK,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IAClC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,EAAE,IAAI,CAAC,CAAC;IACtD,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACnC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAClE,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,qEAAqE;IACrE,OAAO,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,SAAS,CAAC;AAAA,CACtG;AAED,MAAM,UAAU,oBAAoB,CAAC,IAAY,EAAkC;IAClF,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAE5B,IAAI,IAAI,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE,CAAC;QACxC,MAAM,OAAO,GACZ,iBAAiB,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QACxG,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,CAAC;IACtE,CAAC;IAED,IAAI,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC;QACtC,MAAM,SAAS,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;QAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,IAAI,MAAM,EAAE,CAAC;IACvD,CAAC;IAED,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,QAAQ,EAAE,UAAU;IACpB,IAAI,EAAE,MAAM;CACZ,CAAC","sourcesContent":["/**\n * lunr: detect injected prompts (/research, /goal) so the transcript can\n * render them collapsed instead of dumping the full multi-line prompt verbatim.\n *\n * These prompts become plain {role:\"user\"} messages (PromptOptions.source is not\n * persisted), so detection is keyed on stable markers that already exist in the\n * prompt bodies: the `[DEEP RESEARCH]` literal prefix and the\n * goal extension's `<!-- pi-goal-prompt:… -->` HTML comment. This is render-time\n * only — the model still receives the full prompt unchanged, and old session\n * transcripts are cleaned up retroactively with no schema migration.\n */\n\nexport type InjectedPromptKind = \"research\" | \"goal\";\n\nexport interface InjectedPromptInfo {\n\tkind: InjectedPromptKind;\n\t/** One-line summary extracted from the prompt body (task / question / objective). */\n\tsummary: string;\n}\n\nfunction firstNonEmptyLine(text: string): string | undefined {\n\tfor (const raw of text.split(/\\r?\\n/)) {\n\t\tconst line = raw.trim();\n\t\tif (line) return line;\n\t}\n\treturn undefined;\n}\n\n/** Extract the value following a `Label:` prefix on the first line, else undefined. */\nfunction extractAfterLabel(text: string, label: string): string | undefined {\n\tconst idx = text.indexOf(label);\n\tif (idx === -1) return undefined;\n\tconst rest = text.slice(idx + label.length).split(/\\r?\\n/)[0] ?? \"\";\n\tconst trimmed = rest.trim();\n\treturn trimmed || undefined;\n}\n\n/** Extract the contents of a `<goal_objective>…</goal_objective>` block. */\nfunction extractGoalObjective(text: string): string | undefined {\n\tconst open = text.indexOf(\"<goal_objective>\");\n\tif (open === -1) return undefined;\n\tconst close = text.indexOf(\"</goal_objective>\", open);\n\tif (close === -1) return undefined;\n\tconst inner = text.slice(open + \"<goal_objective>\".length, close);\n\tconst trimmed = inner.trim();\n\t// Unescape the minimal XML escaping the goal prompt builder applies.\n\treturn trimmed.replace(/&amp;/g, \"&\").replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").trim() || undefined;\n}\n\nexport function detectInjectedPrompt(text: string): InjectedPromptInfo | undefined {\n\tif (!text) return undefined;\n\n\tif (text.startsWith(\"[DEEP RESEARCH]\")) {\n\t\tconst summary =\n\t\t\textractAfterLabel(text, \"Question:\") ?? firstNonEmptyLine(text.slice(\"[DEEP RESEARCH]\".length).trim());\n\t\treturn { kind: \"research\", summary: summary ?? \"research question\" };\n\t}\n\n\tif (text.includes(\"pi-goal-prompt:\")) {\n\t\tconst objective = extractGoalObjective(text);\n\t\treturn { kind: \"goal\", summary: objective ?? \"goal\" };\n\t}\n\n\treturn undefined;\n}\n\nexport const INJECTED_PROMPT_LABELS: Record<InjectedPromptKind, string> = {\n\tresearch: \"research\",\n\tgoal: \"goal\",\n};\n"]}
@@ -0,0 +1,13 @@
1
+ /** Number of children above which aggregate launch confirmation engages. */
2
+ export declare const LARGE_SUBAGENT_LAUNCH_THRESHOLD = 2;
3
+ export declare function effectiveLargeSubagentLaunchCount(args: Record<string, unknown>): number;
4
+ interface AssistantMessageLike {
5
+ content?: ReadonlyArray<{
6
+ type?: string;
7
+ name?: string;
8
+ arguments?: unknown;
9
+ }>;
10
+ }
11
+ export declare function effectiveLargeSubagentLaunchCountForTurn(args: Record<string, unknown>, assistantMessage?: AssistantMessageLike): number;
12
+ export {};
13
+ //# sourceMappingURL=large-subagent-launch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"large-subagent-launch.d.ts","sourceRoot":"","sources":["../../src/core/large-subagent-launch.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAejD,wBAAgB,iCAAiC,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAcvF;AAaD,UAAU,oBAAoB;IAC7B,OAAO,CAAC,EAAE,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAC/E;AAED,wBAAgB,wCAAwC,CACvD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,gBAAgB,CAAC,EAAE,oBAAoB,GACrC,MAAM,CAWR","sourcesContent":["/** Number of children above which aggregate launch confirmation engages. */\nexport const LARGE_SUBAGENT_LAUNCH_THRESHOLD = 2;\n\nfunction countEntry(item: unknown): number {\n\tconst count = item && typeof item === \"object\" ? (item as { count?: unknown }).count : undefined;\n\treturn typeof count === \"number\" && Number.isInteger(count) && count >= 1 ? count : 1;\n}\n\nfunction isManagementCall(args: Record<string, unknown>): boolean {\n\treturn typeof args.action === \"string\" && args.action.length > 0;\n}\n\nfunction isAsyncDetached(args: Record<string, unknown>): boolean {\n\treturn args.async === true && args.clarify !== true;\n}\n\nexport function effectiveLargeSubagentLaunchCount(args: Record<string, unknown>): number {\n\tlet total = 0;\n\tif (Array.isArray(args.tasks)) {\n\t\tfor (const task of args.tasks) total += countEntry(task);\n\t}\n\tif (Array.isArray(args.chain)) {\n\t\tfor (const step of args.chain) {\n\t\t\tconst parallel = step && typeof step === \"object\" ? (step as { parallel?: unknown }).parallel : undefined;\n\t\t\tif (Array.isArray(parallel)) {\n\t\t\t\tfor (const child of parallel) total += countEntry(child);\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction siblingSingleCount(args: Record<string, unknown>): number {\n\tif (isManagementCall(args) || isAsyncDetached(args)) return 0;\n\tif (Array.isArray(args.tasks) || Array.isArray(args.chain)) return 0;\n\treturn typeof args.task === \"string\" &&\n\t\targs.task.length > 0 &&\n\t\ttypeof args.description === \"string\" &&\n\t\targs.description.length > 0\n\t\t? 1\n\t\t: 0;\n}\n\ninterface AssistantMessageLike {\n\tcontent?: ReadonlyArray<{ type?: string; name?: string; arguments?: unknown }>;\n}\n\nexport function effectiveLargeSubagentLaunchCountForTurn(\n\targs: Record<string, unknown>,\n\tassistantMessage?: AssistantMessageLike,\n): number {\n\tconst own = effectiveLargeSubagentLaunchCount(args);\n\tconst siblingSingles = (assistantMessage?.content ?? []).reduce((total, block) => {\n\t\tif (block.type !== \"toolCall\" || block.name !== \"subagent\") return total;\n\t\tconst siblingArgs =\n\t\t\tblock.arguments && typeof block.arguments === \"object\" && !Array.isArray(block.arguments)\n\t\t\t\t? (block.arguments as Record<string, unknown>)\n\t\t\t\t: undefined;\n\t\treturn siblingArgs ? total + siblingSingleCount(siblingArgs) : total;\n\t}, 0);\n\treturn Math.max(own, siblingSingles);\n}\n"]}
@@ -0,0 +1,54 @@
1
+ /** Number of children above which aggregate launch confirmation engages. */
2
+ export const LARGE_SUBAGENT_LAUNCH_THRESHOLD = 2;
3
+ function countEntry(item) {
4
+ const count = item && typeof item === "object" ? item.count : undefined;
5
+ return typeof count === "number" && Number.isInteger(count) && count >= 1 ? count : 1;
6
+ }
7
+ function isManagementCall(args) {
8
+ return typeof args.action === "string" && args.action.length > 0;
9
+ }
10
+ function isAsyncDetached(args) {
11
+ return args.async === true && args.clarify !== true;
12
+ }
13
+ export function effectiveLargeSubagentLaunchCount(args) {
14
+ let total = 0;
15
+ if (Array.isArray(args.tasks)) {
16
+ for (const task of args.tasks)
17
+ total += countEntry(task);
18
+ }
19
+ if (Array.isArray(args.chain)) {
20
+ for (const step of args.chain) {
21
+ const parallel = step && typeof step === "object" ? step.parallel : undefined;
22
+ if (Array.isArray(parallel)) {
23
+ for (const child of parallel)
24
+ total += countEntry(child);
25
+ }
26
+ }
27
+ }
28
+ return total;
29
+ }
30
+ function siblingSingleCount(args) {
31
+ if (isManagementCall(args) || isAsyncDetached(args))
32
+ return 0;
33
+ if (Array.isArray(args.tasks) || Array.isArray(args.chain))
34
+ return 0;
35
+ return typeof args.task === "string" &&
36
+ args.task.length > 0 &&
37
+ typeof args.description === "string" &&
38
+ args.description.length > 0
39
+ ? 1
40
+ : 0;
41
+ }
42
+ export function effectiveLargeSubagentLaunchCountForTurn(args, assistantMessage) {
43
+ const own = effectiveLargeSubagentLaunchCount(args);
44
+ const siblingSingles = (assistantMessage?.content ?? []).reduce((total, block) => {
45
+ if (block.type !== "toolCall" || block.name !== "subagent")
46
+ return total;
47
+ const siblingArgs = block.arguments && typeof block.arguments === "object" && !Array.isArray(block.arguments)
48
+ ? block.arguments
49
+ : undefined;
50
+ return siblingArgs ? total + siblingSingleCount(siblingArgs) : total;
51
+ }, 0);
52
+ return Math.max(own, siblingSingles);
53
+ }
54
+ //# sourceMappingURL=large-subagent-launch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"large-subagent-launch.js","sourceRoot":"","sources":["../../src/core/large-subagent-launch.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAEjD,SAAS,UAAU,CAAC,IAAa,EAAU;IAC1C,MAAM,KAAK,GAAG,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAE,IAA4B,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACjG,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAAA,CACtF;AAED,SAAS,gBAAgB,CAAC,IAA6B,EAAW;IACjE,OAAO,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;AAAA,CACjE;AAED,SAAS,eAAe,CAAC,IAA6B,EAAW;IAChE,OAAO,IAAI,CAAC,KAAK,KAAK,IAAI,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC;AAAA,CACpD;AAED,MAAM,UAAU,iCAAiC,CAAC,IAA6B,EAAU;IACxF,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC/B,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK;YAAE,KAAK,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC;IAC1D,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC/B,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC/B,MAAM,QAAQ,GAAG,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAE,IAA+B,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;YAC1G,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAC7B,KAAK,MAAM,KAAK,IAAI,QAAQ;oBAAE,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;YAC1D,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb;AAED,SAAS,kBAAkB,CAAC,IAA6B,EAAU;IAClE,IAAI,gBAAgB,CAAC,IAAI,CAAC,IAAI,eAAe,CAAC,IAAI,CAAC;QAAE,OAAO,CAAC,CAAC;IAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,CAAC,CAAC;IACrE,OAAO,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;QACnC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC;QACpB,OAAO,IAAI,CAAC,WAAW,KAAK,QAAQ;QACpC,IAAI,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC;QAC3B,CAAC,CAAC,CAAC;QACH,CAAC,CAAC,CAAC,CAAC;AAAA,CACL;AAMD,MAAM,UAAU,wCAAwC,CACvD,IAA6B,EAC7B,gBAAuC,EAC9B;IACT,MAAM,GAAG,GAAG,iCAAiC,CAAC,IAAI,CAAC,CAAC;IACpD,MAAM,cAAc,GAAG,CAAC,gBAAgB,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC;QACjF,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YAAE,OAAO,KAAK,CAAC;QACzE,MAAM,WAAW,GAChB,KAAK,CAAC,SAAS,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;YACxF,CAAC,CAAE,KAAK,CAAC,SAAqC;YAC9C,CAAC,CAAC,SAAS,CAAC;QACd,OAAO,WAAW,CAAC,CAAC,CAAC,KAAK,GAAG,kBAAkB,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAAA,CACrE,EAAE,CAAC,CAAC,CAAC;IACN,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;AAAA,CACrC","sourcesContent":["/** Number of children above which aggregate launch confirmation engages. */\nexport const LARGE_SUBAGENT_LAUNCH_THRESHOLD = 2;\n\nfunction countEntry(item: unknown): number {\n\tconst count = item && typeof item === \"object\" ? (item as { count?: unknown }).count : undefined;\n\treturn typeof count === \"number\" && Number.isInteger(count) && count >= 1 ? count : 1;\n}\n\nfunction isManagementCall(args: Record<string, unknown>): boolean {\n\treturn typeof args.action === \"string\" && args.action.length > 0;\n}\n\nfunction isAsyncDetached(args: Record<string, unknown>): boolean {\n\treturn args.async === true && args.clarify !== true;\n}\n\nexport function effectiveLargeSubagentLaunchCount(args: Record<string, unknown>): number {\n\tlet total = 0;\n\tif (Array.isArray(args.tasks)) {\n\t\tfor (const task of args.tasks) total += countEntry(task);\n\t}\n\tif (Array.isArray(args.chain)) {\n\t\tfor (const step of args.chain) {\n\t\t\tconst parallel = step && typeof step === \"object\" ? (step as { parallel?: unknown }).parallel : undefined;\n\t\t\tif (Array.isArray(parallel)) {\n\t\t\t\tfor (const child of parallel) total += countEntry(child);\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction siblingSingleCount(args: Record<string, unknown>): number {\n\tif (isManagementCall(args) || isAsyncDetached(args)) return 0;\n\tif (Array.isArray(args.tasks) || Array.isArray(args.chain)) return 0;\n\treturn typeof args.task === \"string\" &&\n\t\targs.task.length > 0 &&\n\t\ttypeof args.description === \"string\" &&\n\t\targs.description.length > 0\n\t\t? 1\n\t\t: 0;\n}\n\ninterface AssistantMessageLike {\n\tcontent?: ReadonlyArray<{ type?: string; name?: string; arguments?: unknown }>;\n}\n\nexport function effectiveLargeSubagentLaunchCountForTurn(\n\targs: Record<string, unknown>,\n\tassistantMessage?: AssistantMessageLike,\n): number {\n\tconst own = effectiveLargeSubagentLaunchCount(args);\n\tconst siblingSingles = (assistantMessage?.content ?? []).reduce((total, block) => {\n\t\tif (block.type !== \"toolCall\" || block.name !== \"subagent\") return total;\n\t\tconst siblingArgs =\n\t\t\tblock.arguments && typeof block.arguments === \"object\" && !Array.isArray(block.arguments)\n\t\t\t\t? (block.arguments as Record<string, unknown>)\n\t\t\t\t: undefined;\n\t\treturn siblingArgs ? total + siblingSingleCount(siblingArgs) : total;\n\t}, 0);\n\treturn Math.max(own, siblingSingles);\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import type { Model } from "@ashx-j/lunr-ai";
2
+ import type { Settings, SettingsManager } from "./settings-manager.ts";
3
+ export type ModelInstructionsMode = "both" | "model-only";
4
+ export interface ModelInstructionsMigrationResult {
5
+ status: "absent" | "migrated" | "conflict" | "failed";
6
+ diagnostic?: string;
7
+ }
8
+ export declare function getInstructionsRoot(agentDir: string): string;
9
+ export declare function getGlobalInstructionsPath(agentDir: string): string;
10
+ export declare function modelInstructionFolderName(modelId: string): string;
11
+ export declare function getModelInstructionsPath(agentDir: string, modelId: string): string;
12
+ export declare function isUserInstructionsPath(filePath: string, agentDir: string): boolean;
13
+ export declare function migrateLegacyGlobalInstructions(agentDir: string): ModelInstructionsMigrationResult;
14
+ export declare function ensureModelInstructionDirs(agentDir: string, settings: Pick<Settings, "defaultModel" | "enabledModels" | "modelTiers">, currentModel?: Pick<Model<any>, "id">): string[];
15
+ export declare function loadSelectedUserInstructions(options: {
16
+ agentDir: string;
17
+ settingsManager: SettingsManager;
18
+ model?: Pick<Model<any>, "id">;
19
+ }): Array<{
20
+ path: string;
21
+ content: string;
22
+ }>;
23
+ export declare function instructionPathLabel(filePath: string, agentDir: string): string | undefined;
24
+ //# sourceMappingURL=model-instructions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-instructions.d.ts","sourceRoot":"","sources":["../../src/core/model-instructions.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAEvE,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,YAAY,CAAC;AAE1D,MAAM,WAAW,gCAAgC;IAChD,MAAM,EAAE,QAAQ,GAAG,UAAU,GAAG,UAAU,GAAG,QAAQ,CAAC;IACtD,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAWlE;AAED,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAElF;AAED,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAGlF;AAED,wBAAgB,+BAA+B,CAAC,QAAQ,EAAE,MAAM,GAAG,gCAAgC,CAoBlG;AASD,wBAAgB,0BAA0B,CACzC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,cAAc,GAAG,eAAe,GAAG,YAAY,CAAC,EACzE,YAAY,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,GACnC,MAAM,EAAE,CAwBV;AAWD,wBAAgB,4BAA4B,CAAC,OAAO,EAAE;IACrD,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,eAAe,CAAC;IACjC,KAAK,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;CAC/B,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAc3C;AAED,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAO3F","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, statSync } from \"node:fs\";\nimport { basename, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport type { Settings, SettingsManager } from \"./settings-manager.ts\";\n\nexport type ModelInstructionsMode = \"both\" | \"model-only\";\n\nexport interface ModelInstructionsMigrationResult {\n\tstatus: \"absent\" | \"migrated\" | \"conflict\" | \"failed\";\n\tdiagnostic?: string;\n}\n\nexport function getInstructionsRoot(agentDir: string): string {\n\treturn join(resolve(agentDir), \"agents\");\n}\n\nexport function getGlobalInstructionsPath(agentDir: string): string {\n\treturn join(getInstructionsRoot(agentDir), \"AGENTS.md\");\n}\n\nexport function modelInstructionFolderName(modelId: string): string {\n\tconst finalSegment = modelId.trim().split(/[\\\\/]/).filter(Boolean).at(-1) ?? \"model\";\n\tconst withoutThinking = finalSegment.replace(/:(?:off|minimal|low|medium|high|xhigh|max)$/i, \"\");\n\tlet safe = withoutThinking.replace(/[<>:\"/\\\\|?*\\u0000-\\u001f]/g, \"_\").replace(/[. ]+$/g, \"\");\n\tif (!safe || safe === \".\" || safe === \"..\") safe = \"model\";\n\tif (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\.|$)/i.test(safe)) safe = `_${safe}`;\n\tif (safe.length > 100 || safe.toLowerCase() !== withoutThinking.toLowerCase()) {\n\t\tconst digest = createHash(\"sha256\").update(withoutThinking.toLowerCase()).digest(\"hex\").slice(0, 8);\n\t\tsafe = `${safe.slice(0, 90)}-${digest}`;\n\t}\n\treturn safe.toLowerCase();\n}\n\nexport function getModelInstructionsPath(agentDir: string, modelId: string): string {\n\treturn join(getInstructionsRoot(agentDir), modelInstructionFolderName(modelId), \"AGENTS.md\");\n}\n\nexport function isUserInstructionsPath(filePath: string, agentDir: string): boolean {\n\tconst rel = relative(resolve(getInstructionsRoot(agentDir)), resolve(filePath));\n\treturn rel === \"\" || (!isAbsolute(rel) && rel !== \"..\" && !rel.startsWith(`..${sep}`));\n}\n\nexport function migrateLegacyGlobalInstructions(agentDir: string): ModelInstructionsMigrationResult {\n\tconst legacyPath = join(resolve(agentDir), \"AGENTS.md\");\n\tconst destinationPath = getGlobalInstructionsPath(agentDir);\n\tif (!existsSync(legacyPath)) return { status: \"absent\" };\n\tif (existsSync(destinationPath)) {\n\t\treturn {\n\t\t\tstatus: \"conflict\",\n\t\t\tdiagnostic: `Both legacy '${legacyPath}' and current '${destinationPath}' exist. Kept both and will use the current file.`,\n\t\t};\n\t}\n\ttry {\n\t\tmkdirSync(getInstructionsRoot(agentDir), { recursive: true });\n\t\trenameSync(legacyPath, destinationPath);\n\t\treturn { status: \"migrated\" };\n\t} catch (error) {\n\t\treturn {\n\t\t\tstatus: \"failed\",\n\t\t\tdiagnostic: `Could not migrate '${legacyPath}' to '${destinationPath}': ${error instanceof Error ? error.message : String(error)}`,\n\t\t};\n\t}\n}\n\nfunction concreteModelId(value: unknown): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\tif (!trimmed || /[*?{}]/.test(trimmed)) return undefined;\n\treturn trimmed.replace(/:(?:off|minimal|low|medium|high|xhigh|max)$/i, \"\");\n}\n\nexport function ensureModelInstructionDirs(\n\tagentDir: string,\n\tsettings: Pick<Settings, \"defaultModel\" | \"enabledModels\" | \"modelTiers\">,\n\tcurrentModel?: Pick<Model<any>, \"id\">,\n): string[] {\n\tconst modelIds = new Set<string>();\n\tconst add = (value: unknown) => {\n\t\tconst id = concreteModelId(value);\n\t\tif (id) modelIds.add(id);\n\t};\n\tadd(currentModel?.id);\n\tadd(settings.defaultModel);\n\tfor (const value of settings.enabledModels ?? []) add(value);\n\tadd(settings.modelTiers?.light);\n\tadd(settings.modelTiers?.standard);\n\tadd(settings.modelTiers?.heavy);\n\n\tconst diagnostics: string[] = [];\n\tfor (const id of modelIds) {\n\t\ttry {\n\t\t\tmkdirSync(join(getInstructionsRoot(agentDir), modelInstructionFolderName(id)), { recursive: true });\n\t\t} catch (error) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`Could not prepare model-instruction folder for '${id}': ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn diagnostics;\n}\n\nfunction safeReadInstruction(path: string): { path: string; content: string } | undefined {\n\ttry {\n\t\tif (!existsSync(path) || !statSync(path).isFile()) return undefined;\n\t\treturn { path, content: readFileSync(path, \"utf8\") };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function loadSelectedUserInstructions(options: {\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n\tmodel?: Pick<Model<any>, \"id\">;\n}): Array<{ path: string; content: string }> {\n\tensureModelInstructionDirs(options.agentDir, options.settingsManager.getGlobalSettings(), options.model);\n\tconst enabled = options.settingsManager.getModelInstructionsEnabled();\n\tconst mode = options.settingsManager.getModelInstructionsMode();\n\tconst files: Array<{ path: string; content: string }> = [];\n\tif (!enabled || mode === \"both\") {\n\t\tconst globalFile = safeReadInstruction(getGlobalInstructionsPath(options.agentDir));\n\t\tif (globalFile) files.push(globalFile);\n\t}\n\tif (enabled && options.model) {\n\t\tconst modelFile = safeReadInstruction(getModelInstructionsPath(options.agentDir, options.model.id));\n\t\tif (modelFile) files.push(modelFile);\n\t}\n\treturn files;\n}\n\nexport function instructionPathLabel(filePath: string, agentDir: string): string | undefined {\n\tconst resolved = resolve(filePath);\n\tif (resolved.toLowerCase() === resolve(getGlobalInstructionsPath(agentDir)).toLowerCase()) {\n\t\treturn \"Global AGENTS.md\";\n\t}\n\tif (!isUserInstructionsPath(resolved, agentDir)) return undefined;\n\treturn `${basename(resolve(resolved, \"..\"))} AGENTS.md`;\n}\n"]}