@caupulican/pi-adaptative 0.80.58 → 0.80.60

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 (49) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/core/agent-session.d.ts +58 -1
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +155 -5
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/extension-metadata.d.ts +20 -0
  7. package/dist/core/extension-metadata.d.ts.map +1 -0
  8. package/dist/core/extension-metadata.js +115 -0
  9. package/dist/core/extension-metadata.js.map +1 -0
  10. package/dist/core/extensions/runner.d.ts +1 -0
  11. package/dist/core/extensions/runner.d.ts.map +1 -1
  12. package/dist/core/extensions/runner.js +3 -0
  13. package/dist/core/extensions/runner.js.map +1 -1
  14. package/dist/core/learning/reflection-engine.d.ts +57 -0
  15. package/dist/core/learning/reflection-engine.d.ts.map +1 -0
  16. package/dist/core/learning/reflection-engine.js +118 -0
  17. package/dist/core/learning/reflection-engine.js.map +1 -0
  18. package/dist/core/memory/memory-manager.d.ts +8 -0
  19. package/dist/core/memory/memory-manager.d.ts.map +1 -1
  20. package/dist/core/memory/memory-manager.js +14 -2
  21. package/dist/core/memory/memory-manager.js.map +1 -1
  22. package/dist/core/resource-loader.d.ts +26 -0
  23. package/dist/core/resource-loader.d.ts.map +1 -1
  24. package/dist/core/resource-loader.js +53 -14
  25. package/dist/core/resource-loader.js.map +1 -1
  26. package/dist/core/system-prompt.d.ts +3 -0
  27. package/dist/core/system-prompt.d.ts.map +1 -1
  28. package/dist/core/system-prompt.js +54 -7
  29. package/dist/core/system-prompt.js.map +1 -1
  30. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  31. package/dist/modes/interactive/components/profile-resource-editor.js +6 -2
  32. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  33. package/dist/modes/interactive/interactive-mode.d.ts +13 -0
  34. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  35. package/dist/modes/interactive/interactive-mode.js +69 -4
  36. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  37. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  38. package/dist/modes/rpc/rpc-mode.js +1 -1
  39. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  40. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  41. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  42. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  43. package/examples/extensions/sandbox/package-lock.json +2 -2
  44. package/examples/extensions/sandbox/package.json +1 -1
  45. package/examples/extensions/with-deps/package-lock.json +2 -2
  46. package/examples/extensions/with-deps/package.json +1 -1
  47. package/examples/sdk/12-full-control.ts +3 -0
  48. package/npm-shrinkwrap.json +12 -12
  49. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,EAAc,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAoD3E,mFAAmF;AACnF,oFAAoF;AACpF,MAAM,4CAA4C,GAAG;IACpD,eAAe;IACf,WAAW;IACX,UAAU;IACV,aAAa;IACb,oBAAoB;IACpB,wBAAwB;IACxB,yBAAyB;IACzB,kBAAkB;IAClB,kBAAkB;IAClB,qBAAqB;IACrB,qBAAqB;IACrB,sBAAsB;IACtB,kBAAkB;IAClB,oBAAoB;IACpB,mBAAmB;IACnB,gBAAgB;IAChB,4BAA4B;CACnB,CAAC;AAIX,MAAM,uBAAuB,GAAG,CAAC,mBAAsC,EAAsB,EAAE,CAAC;IAC/F,MAAM,kBAAkB,GAAG,EAAwB,CAAC;IACpD,KAAK,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,CAAC;QACtE,IAAI,IAAI,KAAK,SAAS;YA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AC,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE;YACnE,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAAA,CAC1B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport type { ImageContent, Model } from \"@caupulican/pi-ai\";\nimport type { KeyId } from \"@caupulican/pi-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"../diagnostics.ts\";\nimport type { KeybindingsConfig } from \"../keybindings.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEvent,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tMessageEndEvent,\n\tMessageEndEventResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tSessionShutdownEvent,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.ts\";\n\n// Extension shortcuts compete with canonical keybinding ids from keybindings.json.\n// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.\nconst RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [\n\t\"app.interrupt\",\n\t\"app.clear\",\n\t\"app.exit\",\n\t\"app.suspend\",\n\t\"app.thinking.cycle\",\n\t\"app.model.cycleForward\",\n\t\"app.model.cycleBackward\",\n\t\"app.model.select\",\n\t\"app.tools.expand\",\n\t\"app.thinking.toggle\",\n\t\"app.editor.external\",\n\t\"app.message.followUp\",\n\t\"tui.input.submit\",\n\t\"tui.select.confirm\",\n\t\"tui.select.cancel\",\n\t\"tui.input.copy\",\n\t\"tui.editor.deleteToLineEnd\",\n] as const;\n\ntype BuiltInKeyBindings = Partial<Record<KeyId, { keybinding: string; restrictOverride: boolean }>>;\n\nconst buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {\n\t\tif (keys === undefined) continue;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\t// If multiple actions bind the same key, the reserved action wins so extensions\n\t\t\t// remain blocked by reserved shortcuts regardless of iteration order.\n\t\t\tconst existing = builtinKeybindings[normalizedKey];\n\t\t\tif (existing?.restrictOverride && !restrictOverride) continue;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\tkeybinding,\n\t\t\t\trestrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable<BeforeAgentStartEventResult[\"message\"]>[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeAgentStartEvent\n\t| MessageEndEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (\n\tentryId: string,\n\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (\n\tsessionPath: string,\n\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise<void>;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(\n\textensionRunner: ExtensionRunner,\n\tevent: SessionShutdownEvent,\n): Promise<boolean> {\n\tif (extensionRunner.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit(event);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWorkingVisible: () => {},\n\tsetWorkingIndicator: () => {},\n\tsetHiddenThinkingLabel: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\taddAutocompleteProvider: () => {},\n\tsetEditorComponent: () => {},\n\tgetEditorComponent: () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate mode: ExtensionContext[\"mode\"] = \"print\";\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<ExtensionErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate getSignalFn: () => AbortSignal | undefined = () => undefined;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\tprivate staleMessage: string | undefined;\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(\n\t\tactions: ExtensionActions,\n\t\tcontextActions: ExtensionContextActions,\n\t\tproviderActions?: {\n\t\t\tregisterProvider?: (name: string, config: ProviderConfig) => void;\n\t\t\tunregisterProvider?: (name: string) => void;\n\t\t},\n\t): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.refreshTools = actions.refreshTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\t\tthis.runtime.getExternalResourceRoots = actions.getExternalResourceRoots;\n\t\tthis.runtime.registerMemoryProvider = actions.registerMemoryProvider;\n\t\tthis.runtime.reportSpawnedUsage = actions.reportSpawnedUsage;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.getSignalFn = contextActions.getSignal;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.reloadHandler = contextActions.reload;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\n\t\t// Flush provider registrations queued during extension loading\n\t\tfor (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t\t}\n\t\t\t\t// Track which extension owns this provider for later cleanup\n\t\t\t\tif (!this.runtime.providersByExtension.has(extensionPath)) {\n\t\t\t\t\tthis.runtime.providersByExtension.set(extensionPath, new Set());\n\t\t\t\t}\n\t\t\t\tthis.runtime.providersByExtension.get(extensionPath)!.add(name);\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\n\t\t// From this point on, provider registration/unregistration takes effect immediately\n\t\t// without requiring a /reload.\n\t\tthis.runtime.registerProvider = (name, config, extensionPath) => {\n\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t} else {\n\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t}\n\t\t\t// Track provider ownership when extensionPath is provided\n\t\t\tif (extensionPath) {\n\t\t\t\tif (!this.runtime.providersByExtension.has(extensionPath)) {\n\t\t\t\t\tthis.runtime.providersByExtension.set(extensionPath, new Set());\n\t\t\t\t}\n\t\t\t\tthis.runtime.providersByExtension.get(extensionPath)!.add(name);\n\t\t\t}\n\t\t};\n\t\tthis.runtime.unregisterProvider = (name, extensionPath) => {\n\t\t\tif (providerActions?.unregisterProvider) {\n\t\t\t\tproviderActions.unregisterProvider(name);\n\t\t\t} else {\n\t\t\t\tthis.modelRegistry.unregisterProvider(name);\n\t\t\t}\n\t\t\t// Remove provider from the ownership map when extensionPath is provided\n\t\t\tif (extensionPath) {\n\t\t\t\tconst providers = this.runtime.providersByExtension.get(extensionPath);\n\t\t\t\tif (providers) {\n\t\t\t\t\tproviders.delete(name);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t}\n\n\tsetMode(mode: ExtensionContext[\"mode\"]): void {\n\t\tthis.mode = mode;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions (first registration per name wins). */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst toolsByName = new Map<string, RegisteredTool>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\tif (!toolsByName.has(tool.definition.name)) {\n\t\t\t\t\ttoolsByName.set(tool.definition.name, tool);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Array.from(toolsByName.values());\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map<string, ExtensionFlag> {\n\t\tconst allFlags = new Map<string, ExtensionFlag>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tif (!allFlags.has(name)) {\n\t\t\t\t\tallFlags.set(name, flag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map<string, boolean | string> {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(resolvedKeybindings: KeybindingsConfig): Map<KeyId, ExtensionShortcut> {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings);\n\t\tconst extensionShortcuts = new Map<KeyId, ExtensionShortcut>();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tinvalidate(\n\t\tmessage = \"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t): void {\n\t\tif (!this.staleMessage) {\n\t\t\tthis.staleMessage = message;\n\t\t\tthis.runtime.invalidate(message);\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.staleMessage) {\n\t\t\tthrow new Error(this.staleMessage);\n\t\t}\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveRegisteredCommands(): ResolvedCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tconst counts = new Map<string, number>();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t\tcounts.set(command.name, (counts.get(command.name) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst seen = new Map<string, number>();\n\t\tconst takenInvocationNames = new Set<string>();\n\n\t\treturn commands.map((command) => {\n\t\t\tconst occurrence = (seen.get(command.name) ?? 0) + 1;\n\t\t\tseen.set(command.name, occurrence);\n\n\t\t\tlet invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name;\n\n\t\t\tif (takenInvocationNames.has(invocationName)) {\n\t\t\t\tlet suffix = occurrence;\n\t\t\t\tdo {\n\t\t\t\t\tsuffix++;\n\t\t\t\t\tinvocationName = `${command.name}:${suffix}`;\n\t\t\t\t} while (takenInvocationNames.has(invocationName));\n\t\t\t}\n\n\t\t\ttakenInvocationNames.add(invocationName);\n\t\t\treturn {\n\t\t\t\t...command,\n\t\t\t\tinvocationName,\n\t\t\t};\n\t\t});\n\t}\n\n\tgetRegisteredCommands(): ResolvedCommand[] {\n\t\tthis.commandDiagnostics = [];\n\t\treturn this.resolveRegisteredCommands();\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetCommand(name: string): ResolvedCommand | undefined {\n\t\treturn this.resolveRegisteredCommands().find((command) => command.invocationName === name);\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst runner = this;\n\t\tconst getModel = this.getModel;\n\t\treturn {\n\t\t\tget ui() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.uiContext;\n\t\t\t},\n\t\t\tget hasUI() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasUI();\n\t\t\t},\n\t\t\tget mode() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.mode;\n\t\t\t},\n\t\t\tget cwd() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.cwd;\n\t\t\t},\n\t\t\tget sessionManager() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.sessionManager;\n\t\t\t},\n\t\t\tget modelRegistry() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.modelRegistry;\n\t\t\t},\n\t\t\tget model() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tisIdle: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isIdleFn();\n\t\t\t},\n\t\t\tget signal() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSignalFn();\n\t\t\t},\n\t\t\tabort: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.abortFn();\n\t\t\t},\n\t\t\thasPendingMessages: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasPendingMessagesFn();\n\t\t\t},\n\t\t\tshutdown: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.shutdownHandler();\n\t\t\t},\n\t\t\tgetContextUsage: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getContextUsageFn();\n\t\t\t},\n\t\t\tcompact: (options) => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.compactFn(options);\n\t\t\t},\n\t\t\treload: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.reloadHandler();\n\t\t\t},\n\t\t\tgetSystemPrompt: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSystemPromptFn();\n\t\t\t},\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\t// Use property descriptors instead of object spread so the guarded getters from\n\t\t// createContext() stay lazy. A spread would eagerly read them once and freeze the\n\t\t// old values into the returned object, bypassing stale-instance checks.\n\t\tconst context = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionCommandContext;\n\t\tcontext.waitForIdle = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.waitForIdleFn();\n\t\t};\n\t\tcontext.newSession = (options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.newSessionHandler(options);\n\t\t};\n\t\tcontext.fork = (entryId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.forkHandler(entryId, options);\n\t\t};\n\t\tcontext.navigateTree = (targetId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.navigateTreeHandler(targetId, options);\n\t\t};\n\t\tcontext.switchSession = (sessionPath, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.switchSessionHandler(sessionPath, options);\n\t\t};\n\t\tcontext.reload = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.reloadHandler();\n\t\t};\n\t\treturn context;\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult<TEvent>;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult<TEvent>;\n\t}\n\n\t/**\n\t * Emit an event to a single extension only.\n\t * Used for granular load/unload lifecycle events (session_start/session_shutdown)\n\t * without triggering all other extensions' handlers.\n\t */\n\tasync emitToExtension(extension: Extension, event: RunnerEmitEvent): Promise<void> {\n\t\tconst ctx = this.createContext();\n\t\tconst handlers = extension.handlers.get(event.type);\n\t\tif (!handlers || handlers.length === 0) return;\n\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tawait handler(event, ctx);\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath: extension.path,\n\t\t\t\t\tevent: event.type,\n\t\t\t\t\terror: message,\n\t\t\t\t\tstack,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tasync emitMessageEnd(event: MessageEndEvent): Promise<AgentMessage | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessage = event.message;\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"message_end\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst currentEvent: MessageEndEvent = { ...event, message: currentMessage };\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as MessageEndEventResult | undefined;\n\t\t\t\t\tif (!handlerResult?.message) continue;\n\n\t\t\t\t\tif (handlerResult.message.role !== currentMessage.role) {\n\t\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\t\terror: \"message_end handlers must return a message with the same role\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentMessage = handlerResult.message;\n\t\t\t\t\tmodified = true;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn modified ? currentMessage : undefined;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeProviderRequest(payload: unknown): Promise<unknown> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentPayload = payload;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_request\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeProviderRequestEvent = {\n\t\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\t\tpayload: currentPayload,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult !== undefined) {\n\t\t\t\t\t\tcurrentPayload = handlerResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_request\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentPayload;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t\tsystemPromptOptions: BuildSystemPromptOptions,\n\t): Promise<BeforeAgentStartCombinedResult | undefined> {\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tconst ctx = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionContext;\n\t\tctx.getSystemPrompt = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn currentSystemPrompt;\n\t\t};\n\t\tconst messages: NonNullable<BeforeAgentStartEventResult[\"message\"]>[] = [];\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t\tsystemPromptOptions,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(\n\t\ttext: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsource: InputSource,\n\t\tstreamingBehavior?: \"steer\" | \"followUp\",\n\t): Promise<InputEventResult> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = {\n\t\t\t\t\t\ttype: \"input\",\n\t\t\t\t\t\ttext: currentText,\n\t\t\t\t\t\timages: currentImages,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstreamingBehavior,\n\t\t\t\t\t};\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]}
1
+ {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,EAAc,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAoD3E,mFAAmF;AACnF,oFAAoF;AACpF,MAAM,4CAA4C,GAAG;IACpD,eAAe;IACf,WAAW;IACX,UAAU;IACV,aAAa;IACb,oBAAoB;IACpB,wBAAwB;IACxB,yBAAyB;IACzB,kBAAkB;IAClB,kBAAkB;IAClB,qBAAqB;IACrB,qBAAqB;IACrB,sBAAsB;IACtB,k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,aAAa,EAAE,GAAG,CAAC,IAAI;wBACvB,KAAK,EAAE,OAAO;wBACd,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;wBACvD,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;qBACnD,CAAC,CAAC;gBACJ,CAAC;YACF,CAAC;QACF,CAAC;QACD,OAAO,WAAW,KAAK,IAAI,IAAI,aAAa,KAAK,MAAM;YACtD,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE;YACnE,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAAA,CAC1B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport type { ImageContent, Model } from \"@caupulican/pi-ai\";\nimport type { KeyId } from \"@caupulican/pi-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"../diagnostics.ts\";\nimport type { KeybindingsConfig } from \"../keybindings.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEvent,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tMessageEndEvent,\n\tMessageEndEventResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tSessionShutdownEvent,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.ts\";\n\n// Extension shortcuts compete with canonical keybinding ids from keybindings.json.\n// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.\nconst RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [\n\t\"app.interrupt\",\n\t\"app.clear\",\n\t\"app.exit\",\n\t\"app.suspend\",\n\t\"app.thinking.cycle\",\n\t\"app.model.cycleForward\",\n\t\"app.model.cycleBackward\",\n\t\"app.model.select\",\n\t\"app.tools.expand\",\n\t\"app.thinking.toggle\",\n\t\"app.editor.external\",\n\t\"app.message.followUp\",\n\t\"tui.input.submit\",\n\t\"tui.select.confirm\",\n\t\"tui.select.cancel\",\n\t\"tui.input.copy\",\n\t\"tui.editor.deleteToLineEnd\",\n] as const;\n\ntype BuiltInKeyBindings = Partial<Record<KeyId, { keybinding: string; restrictOverride: boolean }>>;\n\nconst buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {\n\t\tif (keys === undefined) continue;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\t// If multiple actions bind the same key, the reserved action wins so extensions\n\t\t\t// remain blocked by reserved shortcuts regardless of iteration order.\n\t\t\tconst existing = builtinKeybindings[normalizedKey];\n\t\t\tif (existing?.restrictOverride && !restrictOverride) continue;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\tkeybinding,\n\t\t\t\trestrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable<BeforeAgentStartEventResult[\"message\"]>[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeAgentStartEvent\n\t| MessageEndEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (\n\tentryId: string,\n\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (\n\tsessionPath: string,\n\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise<void>;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(\n\textensionRunner: ExtensionRunner,\n\tevent: SessionShutdownEvent,\n): Promise<boolean> {\n\tif (extensionRunner.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit(event);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWorkingVisible: () => {},\n\tsetWorkingIndicator: () => {},\n\tsetHiddenThinkingLabel: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\taddAutocompleteProvider: () => {},\n\tsetEditorComponent: () => {},\n\tgetEditorComponent: () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tget activeExtensions(): ReadonlyArray<Extension> {\n\t\treturn this.extensions;\n\t}\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate mode: ExtensionContext[\"mode\"] = \"print\";\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<ExtensionErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate getSignalFn: () => AbortSignal | undefined = () => undefined;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\tprivate staleMessage: string | undefined;\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(\n\t\tactions: ExtensionActions,\n\t\tcontextActions: ExtensionContextActions,\n\t\tproviderActions?: {\n\t\t\tregisterProvider?: (name: string, config: ProviderConfig) => void;\n\t\t\tunregisterProvider?: (name: string) => void;\n\t\t},\n\t): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.refreshTools = actions.refreshTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\t\tthis.runtime.getExternalResourceRoots = actions.getExternalResourceRoots;\n\t\tthis.runtime.registerMemoryProvider = actions.registerMemoryProvider;\n\t\tthis.runtime.reportSpawnedUsage = actions.reportSpawnedUsage;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.getSignalFn = contextActions.getSignal;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.reloadHandler = contextActions.reload;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\n\t\t// Flush provider registrations queued during extension loading\n\t\tfor (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t\t}\n\t\t\t\t// Track which extension owns this provider for later cleanup\n\t\t\t\tif (!this.runtime.providersByExtension.has(extensionPath)) {\n\t\t\t\t\tthis.runtime.providersByExtension.set(extensionPath, new Set());\n\t\t\t\t}\n\t\t\t\tthis.runtime.providersByExtension.get(extensionPath)!.add(name);\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\n\t\t// From this point on, provider registration/unregistration takes effect immediately\n\t\t// without requiring a /reload.\n\t\tthis.runtime.registerProvider = (name, config, extensionPath) => {\n\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t} else {\n\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t}\n\t\t\t// Track provider ownership when extensionPath is provided\n\t\t\tif (extensionPath) {\n\t\t\t\tif (!this.runtime.providersByExtension.has(extensionPath)) {\n\t\t\t\t\tthis.runtime.providersByExtension.set(extensionPath, new Set());\n\t\t\t\t}\n\t\t\t\tthis.runtime.providersByExtension.get(extensionPath)!.add(name);\n\t\t\t}\n\t\t};\n\t\tthis.runtime.unregisterProvider = (name, extensionPath) => {\n\t\t\tif (providerActions?.unregisterProvider) {\n\t\t\t\tproviderActions.unregisterProvider(name);\n\t\t\t} else {\n\t\t\t\tthis.modelRegistry.unregisterProvider(name);\n\t\t\t}\n\t\t\t// Remove provider from the ownership map when extensionPath is provided\n\t\t\tif (extensionPath) {\n\t\t\t\tconst providers = this.runtime.providersByExtension.get(extensionPath);\n\t\t\t\tif (providers) {\n\t\t\t\t\tproviders.delete(name);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t}\n\n\tsetMode(mode: ExtensionContext[\"mode\"]): void {\n\t\tthis.mode = mode;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions (first registration per name wins). */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst toolsByName = new Map<string, RegisteredTool>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\tif (!toolsByName.has(tool.definition.name)) {\n\t\t\t\t\ttoolsByName.set(tool.definition.name, tool);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Array.from(toolsByName.values());\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map<string, ExtensionFlag> {\n\t\tconst allFlags = new Map<string, ExtensionFlag>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tif (!allFlags.has(name)) {\n\t\t\t\t\tallFlags.set(name, flag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map<string, boolean | string> {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(resolvedKeybindings: KeybindingsConfig): Map<KeyId, ExtensionShortcut> {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings);\n\t\tconst extensionShortcuts = new Map<KeyId, ExtensionShortcut>();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tinvalidate(\n\t\tmessage = \"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t): void {\n\t\tif (!this.staleMessage) {\n\t\t\tthis.staleMessage = message;\n\t\t\tthis.runtime.invalidate(message);\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.staleMessage) {\n\t\t\tthrow new Error(this.staleMessage);\n\t\t}\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveRegisteredCommands(): ResolvedCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tconst counts = new Map<string, number>();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t\tcounts.set(command.name, (counts.get(command.name) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst seen = new Map<string, number>();\n\t\tconst takenInvocationNames = new Set<string>();\n\n\t\treturn commands.map((command) => {\n\t\t\tconst occurrence = (seen.get(command.name) ?? 0) + 1;\n\t\t\tseen.set(command.name, occurrence);\n\n\t\t\tlet invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name;\n\n\t\t\tif (takenInvocationNames.has(invocationName)) {\n\t\t\t\tlet suffix = occurrence;\n\t\t\t\tdo {\n\t\t\t\t\tsuffix++;\n\t\t\t\t\tinvocationName = `${command.name}:${suffix}`;\n\t\t\t\t} while (takenInvocationNames.has(invocationName));\n\t\t\t}\n\n\t\t\ttakenInvocationNames.add(invocationName);\n\t\t\treturn {\n\t\t\t\t...command,\n\t\t\t\tinvocationName,\n\t\t\t};\n\t\t});\n\t}\n\n\tgetRegisteredCommands(): ResolvedCommand[] {\n\t\tthis.commandDiagnostics = [];\n\t\treturn this.resolveRegisteredCommands();\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetCommand(name: string): ResolvedCommand | undefined {\n\t\treturn this.resolveRegisteredCommands().find((command) => command.invocationName === name);\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst runner = this;\n\t\tconst getModel = this.getModel;\n\t\treturn {\n\t\t\tget ui() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.uiContext;\n\t\t\t},\n\t\t\tget hasUI() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasUI();\n\t\t\t},\n\t\t\tget mode() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.mode;\n\t\t\t},\n\t\t\tget cwd() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.cwd;\n\t\t\t},\n\t\t\tget sessionManager() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.sessionManager;\n\t\t\t},\n\t\t\tget modelRegistry() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.modelRegistry;\n\t\t\t},\n\t\t\tget model() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tisIdle: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isIdleFn();\n\t\t\t},\n\t\t\tget signal() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSignalFn();\n\t\t\t},\n\t\t\tabort: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.abortFn();\n\t\t\t},\n\t\t\thasPendingMessages: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasPendingMessagesFn();\n\t\t\t},\n\t\t\tshutdown: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.shutdownHandler();\n\t\t\t},\n\t\t\tgetContextUsage: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getContextUsageFn();\n\t\t\t},\n\t\t\tcompact: (options) => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.compactFn(options);\n\t\t\t},\n\t\t\treload: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.reloadHandler();\n\t\t\t},\n\t\t\tgetSystemPrompt: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSystemPromptFn();\n\t\t\t},\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\t// Use property descriptors instead of object spread so the guarded getters from\n\t\t// createContext() stay lazy. A spread would eagerly read them once and freeze the\n\t\t// old values into the returned object, bypassing stale-instance checks.\n\t\tconst context = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionCommandContext;\n\t\tcontext.waitForIdle = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.waitForIdleFn();\n\t\t};\n\t\tcontext.newSession = (options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.newSessionHandler(options);\n\t\t};\n\t\tcontext.fork = (entryId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.forkHandler(entryId, options);\n\t\t};\n\t\tcontext.navigateTree = (targetId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.navigateTreeHandler(targetId, options);\n\t\t};\n\t\tcontext.switchSession = (sessionPath, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.switchSessionHandler(sessionPath, options);\n\t\t};\n\t\tcontext.reload = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.reloadHandler();\n\t\t};\n\t\treturn context;\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult<TEvent>;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult<TEvent>;\n\t}\n\n\t/**\n\t * Emit an event to a single extension only.\n\t * Used for granular load/unload lifecycle events (session_start/session_shutdown)\n\t * without triggering all other extensions' handlers.\n\t */\n\tasync emitToExtension(extension: Extension, event: RunnerEmitEvent): Promise<void> {\n\t\tconst ctx = this.createContext();\n\t\tconst handlers = extension.handlers.get(event.type);\n\t\tif (!handlers || handlers.length === 0) return;\n\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tawait handler(event, ctx);\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath: extension.path,\n\t\t\t\t\tevent: event.type,\n\t\t\t\t\terror: message,\n\t\t\t\t\tstack,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tasync emitMessageEnd(event: MessageEndEvent): Promise<AgentMessage | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessage = event.message;\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"message_end\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst currentEvent: MessageEndEvent = { ...event, message: currentMessage };\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as MessageEndEventResult | undefined;\n\t\t\t\t\tif (!handlerResult?.message) continue;\n\n\t\t\t\t\tif (handlerResult.message.role !== currentMessage.role) {\n\t\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\t\terror: \"message_end handlers must return a message with the same role\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentMessage = handlerResult.message;\n\t\t\t\t\tmodified = true;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn modified ? currentMessage : undefined;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeProviderRequest(payload: unknown): Promise<unknown> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentPayload = payload;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_request\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeProviderRequestEvent = {\n\t\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\t\tpayload: currentPayload,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult !== undefined) {\n\t\t\t\t\t\tcurrentPayload = handlerResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_request\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentPayload;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t\tsystemPromptOptions: BuildSystemPromptOptions,\n\t): Promise<BeforeAgentStartCombinedResult | undefined> {\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tconst ctx = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionContext;\n\t\tctx.getSystemPrompt = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn currentSystemPrompt;\n\t\t};\n\t\tconst messages: NonNullable<BeforeAgentStartEventResult[\"message\"]>[] = [];\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t\tsystemPromptOptions,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(\n\t\ttext: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsource: InputSource,\n\t\tstreamingBehavior?: \"steer\" | \"followUp\",\n\t): Promise<InputEventResult> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = {\n\t\t\t\t\t\ttype: \"input\",\n\t\t\t\t\t\ttext: currentText,\n\t\t\t\t\t\timages: currentImages,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstreamingBehavior,\n\t\t\t\t\t};\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]}
@@ -0,0 +1,57 @@
1
+ import type { Usage } from "@caupulican/pi-ai";
2
+ export type StopReason = "stop" | "toolUse" | "aborted" | "error" | string;
3
+ export interface IsolatedCompletionResult {
4
+ text: string;
5
+ usage: Usage;
6
+ stopReason: StopReason;
7
+ }
8
+ export type ReflectionTrigger = "complex" | "corrective" | "session-end" | "none";
9
+ export interface DemandSignals {
10
+ trigger: ReflectionTrigger;
11
+ toolCallCount: number;
12
+ hadCorrection: boolean;
13
+ contextHeadroomPct: number;
14
+ usefulLately: number;
15
+ }
16
+ export interface DemandPlan {
17
+ act: "skip" | "reflect";
18
+ reason: string;
19
+ tokenBudget: number;
20
+ }
21
+ /**
22
+ * Pure zero-I/O heuristic to decide whether the current turn justifies a reflection run
23
+ * and determine the token budget under the cheap-tool net-negative doctrine.
24
+ */
25
+ export declare function decideDemand(signals: DemandSignals): DemandPlan;
26
+ export interface ReflectionInput {
27
+ recentTurnText: string;
28
+ existingMemory: string;
29
+ plan: DemandPlan;
30
+ complete: (systemPrompt: string, userPrompt: string) => Promise<IsolatedCompletionResult>;
31
+ }
32
+ export type ReflectionWrite = {
33
+ kind: "memory_add";
34
+ section: "MEMORY" | "USER";
35
+ text: string;
36
+ } | {
37
+ kind: "memory_replace";
38
+ target: string;
39
+ text: string;
40
+ } | {
41
+ kind: "memory_remove";
42
+ target: string;
43
+ };
44
+ export interface ReflectionResult {
45
+ writes: ReflectionWrite[];
46
+ usage: Usage;
47
+ rationale: string;
48
+ }
49
+ export declare class ReflectionEngine {
50
+ /**
51
+ * Build the reflection prompt, call the injected isolated complete(),
52
+ * parse the response, confront existing memory, and return memory writes.
53
+ * Zero direct I/O.
54
+ */
55
+ reflect(input: ReflectionInput): Promise<ReflectionResult>;
56
+ }
57
+ //# sourceMappingURL=reflection-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refl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AE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACxD;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE7C,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,eAAe,EAAE,CAAC;IAC1B,KAAK,EAAE,KAAK,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CAClB;AAED,qBAAa,gBAAgB;IAC5B;;;;OAIG;IACG,OAAO,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAyF/D;CACD","sourcesContent":["import type { Usage } from \"@caupulican/pi-ai\";\n\nexport type StopReason = \"stop\" | \"toolUse\" | \"aborted\" | \"error\" | string;\n\nexport interface IsolatedCompletionResult {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: StopReason;\n}\n\nexport type ReflectionTrigger = \"complex\" | \"corrective\" | \"session-end\" | \"none\";\n\nexport interface DemandSignals {\n\ttrigger: ReflectionTrigger;\n\ttoolCallCount: number;\n\thadCorrection: boolean;\n\tcontextHeadroomPct: number; // 0..100\n\tusefulLately: number; // 0..1 rolling score\n}\n\nexport interface DemandPlan {\n\tact: \"skip\" | \"reflect\";\n\treason: string;\n\ttokenBudget: number;\n}\n\n/**\n * Pure zero-I/O heuristic to decide whether the current turn justifies a reflection run\n * and determine the token budget under the cheap-tool net-negative doctrine.\n */\nexport function decideDemand(signals: DemandSignals): DemandPlan {\n\tif (signals.trigger === \"none\") {\n\t\treturn { act: \"skip\", reason: \"No trigger detected\", tokenBudget: 0 };\n\t}\n\tif (signals.contextHeadroomPct < 10) {\n\t\treturn { act: \"skip\", reason: \"Context headroom is critically low (< 10%)\", tokenBudget: 0 };\n\t}\n\n\t// Dynamic token budget based on headroom (keep reflection bounded between 500 and 1500 tokens)\n\tconst baseBudget = 1000;\n\tconst tokenBudget = Math.max(500, Math.min(1500, Math.round(baseBudget * (signals.contextHeadroomPct / 100))));\n\n\tif (signals.hadCorrection) {\n\t\treturn { act: \"reflect\", reason: \"Correction detected in the turn\", tokenBudget };\n\t}\n\tif (signals.trigger === \"session-end\") {\n\t\treturn { act: \"reflect\", reason: \"Session end reflection triggered\", tokenBudget };\n\t}\n\tif (signals.trigger === \"complex\") {\n\t\tif (signals.toolCallCount >= 3) {\n\t\t\treturn { act: \"reflect\", reason: `Complex turn with ${signals.toolCallCount} tool calls`, tokenBudget };\n\t\t}\n\t}\n\n\treturn { act: \"skip\", reason: \"Signals do not justify reflection overhead\", tokenBudget: 0 };\n}\n\nexport interface ReflectionInput {\n\trecentTurnText: string; // host serializes the just-finished turn\n\texistingMemory: string; // current MEMORY.md + USER.md snapshot\n\tplan: DemandPlan;\n\t// host-injected isolated completion function:\n\tcomplete: (systemPrompt: string, userPrompt: string) => Promise<IsolatedCompletionResult>;\n}\n\nexport type ReflectionWrite =\n\t| { kind: \"memory_add\"; section: \"MEMORY\" | \"USER\"; text: string }\n\t| { kind: \"memory_replace\"; target: string; text: string }\n\t| { kind: \"memory_remove\"; target: string };\n\nexport interface ReflectionResult {\n\twrites: ReflectionWrite[];\n\tusage: Usage;\n\trationale: string;\n}\n\nexport class ReflectionEngine {\n\t/**\n\t * Build the reflection prompt, call the injected isolated complete(),\n\t * parse the response, confront existing memory, and return memory writes.\n\t * Zero direct I/O.\n\t */\n\tasync reflect(input: ReflectionInput): Promise<ReflectionResult> {\n\t\tconst systemPrompt = `You are a reflection engine. Your job is to analyze the recent conversation turn, compare it against the agent's existing memory, and decide if any memory updates are needed.\n\nExisting Memory snapshot:\n${input.existingMemory}\n\nMemory guidelines:\n- \"MEMORY\" is for project facts, configuration, repeatable workflows, and coding findings.\n- \"USER\" is for user preferences, patterns, and style specifications.\n- Avoid duplicate facts. If the fact is already represented, do not add it.\n- CONFRONT existing memory: if the new turn contradicts or updates an existing fact, use \"memory_replace\" or \"memory_remove\" to supersede the old fact rather than blindly appending.\n- Keep memories short, factual, and direct. No fluff.\n\nYou must output your analysis and writes in the following JSON format inside a \\`\\`\\`json\\`\\`\\` code fence:\n{\n \"rationale\": \"Explanation of your reasoning\",\n \"writes\": [\n { \"kind\": \"memory_add\", \"section\": \"MEMORY\" | \"USER\", \"text\": \"New direct fact to append\" },\n { \"kind\": \"memory_replace\", \"target\": \"Exact text substring to replace\", \"text\": \"New replacement text\" },\n { \"kind\": \"memory_remove\", \"target\": \"Exact text substring to remove\" }\n ]\n}\n`;\n\n\t\tconst userPrompt = `Recent turn transcript:\n${input.recentTurnText}\n\nAnalyze this turn and output your memory updates.`;\n\n\t\ttry {\n\t\t\tconst compResult = await input.complete(systemPrompt, userPrompt);\n\t\t\tconst text = compResult.text;\n\n\t\t\tconst jsonMatch = text.match(/```json\\s*([\\s\\S]*?)\\s*```/) || text.match(/{[\\s\\S]*}/);\n\t\t\tif (!jsonMatch) {\n\t\t\t\treturn {\n\t\t\t\t\twrites: [],\n\t\t\t\t\tusage: compResult.usage,\n\t\t\t\t\trationale: `Failed to locate JSON response. Raw text:\\n${text}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst parsed = JSON.parse(jsonMatch[1] || jsonMatch[0]);\n\t\t\tconst rationale = parsed.rationale || \"\";\n\t\t\tconst writes: ReflectionWrite[] = [];\n\n\t\t\tif (Array.isArray(parsed.writes)) {\n\t\t\t\tfor (const w of parsed.writes) {\n\t\t\t\t\tif (w && typeof w === \"object\") {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tw.kind === \"memory_add\" &&\n\t\t\t\t\t\t\t(w.section === \"MEMORY\" || w.section === \"USER\") &&\n\t\t\t\t\t\t\ttypeof w.text === \"string\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\twrites.push({ kind: \"memory_add\", section: w.section, text: w.text });\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\tw.kind === \"memory_replace\" &&\n\t\t\t\t\t\t\ttypeof w.target === \"string\" &&\n\t\t\t\t\t\t\ttypeof w.text === \"string\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\twrites.push({ kind: \"memory_replace\", target: w.target, text: w.text });\n\t\t\t\t\t\t} else if (w.kind === \"memory_remove\" && typeof w.target === \"string\") {\n\t\t\t\t\t\t\twrites.push({ kind: \"memory_remove\", target: w.target });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\twrites,\n\t\t\t\tusage: compResult.usage,\n\t\t\t\trationale,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\t// Zeroed/fallback usage representation\n\t\t\tconst emptyUsage: Usage = {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t\treturn {\n\t\t\t\twrites: [],\n\t\t\t\tusage: emptyUsage,\n\t\t\t\trationale: `Error during reflection: ${String(err)}`,\n\t\t\t};\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Pure zero-I/O heuristic to decide whether the current turn justifies a reflection run
3
+ * and determine the token budget under the cheap-tool net-negative doctrine.
4
+ */
5
+ export function decideDemand(signals) {
6
+ if (signals.trigger === "none") {
7
+ return { act: "skip", reason: "No trigger detected", tokenBudget: 0 };
8
+ }
9
+ if (signals.contextHeadroomPct < 10) {
10
+ return { act: "skip", reason: "Context headroom is critically low (< 10%)", tokenBudget: 0 };
11
+ }
12
+ // Dynamic token budget based on headroom (keep reflection bounded between 500 and 1500 tokens)
13
+ const baseBudget = 1000;
14
+ const tokenBudget = Math.max(500, Math.min(1500, Math.round(baseBudget * (signals.contextHeadroomPct / 100))));
15
+ if (signals.hadCorrection) {
16
+ return { act: "reflect", reason: "Correction detected in the turn", tokenBudget };
17
+ }
18
+ if (signals.trigger === "session-end") {
19
+ return { act: "reflect", reason: "Session end reflection triggered", tokenBudget };
20
+ }
21
+ if (signals.trigger === "complex") {
22
+ if (signals.toolCallCount >= 3) {
23
+ return { act: "reflect", reason: `Complex turn with ${signals.toolCallCount} tool calls`, tokenBudget };
24
+ }
25
+ }
26
+ return { act: "skip", reason: "Signals do not justify reflection overhead", tokenBudget: 0 };
27
+ }
28
+ export class ReflectionEngine {
29
+ /**
30
+ * Build the reflection prompt, call the injected isolated complete(),
31
+ * parse the response, confront existing memory, and return memory writes.
32
+ * Zero direct I/O.
33
+ */
34
+ async reflect(input) {
35
+ const systemPrompt = `You are a reflection engine. Your job is to analyze the recent conversation turn, compare it against the agent's existing memory, and decide if any memory updates are needed.
36
+
37
+ Existing Memory snapshot:
38
+ ${input.existingMemory}
39
+
40
+ Memory guidelines:
41
+ - "MEMORY" is for project facts, configuration, repeatable workflows, and coding findings.
42
+ - "USER" is for user preferences, patterns, and style specifications.
43
+ - Avoid duplicate facts. If the fact is already represented, do not add it.
44
+ - CONFRONT existing memory: if the new turn contradicts or updates an existing fact, use "memory_replace" or "memory_remove" to supersede the old fact rather than blindly appending.
45
+ - Keep memories short, factual, and direct. No fluff.
46
+
47
+ You must output your analysis and writes in the following JSON format inside a \`\`\`json\`\`\` code fence:
48
+ {
49
+ "rationale": "Explanation of your reasoning",
50
+ "writes": [
51
+ { "kind": "memory_add", "section": "MEMORY" | "USER", "text": "New direct fact to append" },
52
+ { "kind": "memory_replace", "target": "Exact text substring to replace", "text": "New replacement text" },
53
+ { "kind": "memory_remove", "target": "Exact text substring to remove" }
54
+ ]
55
+ }
56
+ `;
57
+ const userPrompt = `Recent turn transcript:
58
+ ${input.recentTurnText}
59
+
60
+ Analyze this turn and output your memory updates.`;
61
+ try {
62
+ const compResult = await input.complete(systemPrompt, userPrompt);
63
+ const text = compResult.text;
64
+ const jsonMatch = text.match(/```json\s*([\s\S]*?)\s*```/) || text.match(/{[\s\S]*}/);
65
+ if (!jsonMatch) {
66
+ return {
67
+ writes: [],
68
+ usage: compResult.usage,
69
+ rationale: `Failed to locate JSON response. Raw text:\n${text}`,
70
+ };
71
+ }
72
+ const parsed = JSON.parse(jsonMatch[1] || jsonMatch[0]);
73
+ const rationale = parsed.rationale || "";
74
+ const writes = [];
75
+ if (Array.isArray(parsed.writes)) {
76
+ for (const w of parsed.writes) {
77
+ if (w && typeof w === "object") {
78
+ if (w.kind === "memory_add" &&
79
+ (w.section === "MEMORY" || w.section === "USER") &&
80
+ typeof w.text === "string") {
81
+ writes.push({ kind: "memory_add", section: w.section, text: w.text });
82
+ }
83
+ else if (w.kind === "memory_replace" &&
84
+ typeof w.target === "string" &&
85
+ typeof w.text === "string") {
86
+ writes.push({ kind: "memory_replace", target: w.target, text: w.text });
87
+ }
88
+ else if (w.kind === "memory_remove" && typeof w.target === "string") {
89
+ writes.push({ kind: "memory_remove", target: w.target });
90
+ }
91
+ }
92
+ }
93
+ }
94
+ return {
95
+ writes,
96
+ usage: compResult.usage,
97
+ rationale,
98
+ };
99
+ }
100
+ catch (err) {
101
+ // Zeroed/fallback usage representation
102
+ const emptyUsage = {
103
+ input: 0,
104
+ output: 0,
105
+ cacheRead: 0,
106
+ cacheWrite: 0,
107
+ totalTokens: 0,
108
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
109
+ };
110
+ return {
111
+ writes: [],
112
+ usage: emptyUsage,
113
+ rationale: `Error during reflection: ${String(err)}`,
114
+ };
115
+ }
116
+ }
117
+ }
118
+ //# sourceMappingURL=reflection-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reflection-engine.js","sourceRoot":"","sources":["../../../src/core/learning/reflection-engine.ts"],"names":[],"mappings":"AA0BA;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,OAAsB,EAAc;IAChE,IAAI,OAAO,CAAC,OAAO,KAAK,MAAM,EAAE,CAAC;QAChC,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,qBAAqB,EAAE,WAAW,EAAE,CAAC,EAAE,CAAC;IACvE,CAAC;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export type StopReason = \"stop\" | \"toolUse\" | \"aborted\" | \"error\" | string;\n\nexport interface IsolatedCompletionResult {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: StopReason;\n}\n\nexport type ReflectionTrigger = \"complex\" | \"corrective\" | \"session-end\" | \"none\";\n\nexport interface DemandSignals {\n\ttrigger: ReflectionTrigger;\n\ttoolCallCount: number;\n\thadCorrection: boolean;\n\tcontextHeadroomPct: number; // 0..100\n\tusefulLately: number; // 0..1 rolling score\n}\n\nexport interface DemandPlan {\n\tact: \"skip\" | \"reflect\";\n\treason: string;\n\ttokenBudget: number;\n}\n\n/**\n * Pure zero-I/O heuristic to decide whether the current turn justifies a reflection run\n * and determine the token budget under the cheap-tool net-negative doctrine.\n */\nexport function decideDemand(signals: DemandSignals): DemandPlan {\n\tif (signals.trigger === \"none\") {\n\t\treturn { act: \"skip\", reason: \"No trigger detected\", tokenBudget: 0 };\n\t}\n\tif (signals.contextHeadroomPct < 10) {\n\t\treturn { act: \"skip\", reason: \"Context headroom is critically low (< 10%)\", tokenBudget: 0 };\n\t}\n\n\t// Dynamic token budget based on headroom (keep reflection bounded between 500 and 1500 tokens)\n\tconst baseBudget = 1000;\n\tconst tokenBudget = Math.max(500, Math.min(1500, Math.round(baseBudget * (signals.contextHeadroomPct / 100))));\n\n\tif (signals.hadCorrection) {\n\t\treturn { act: \"reflect\", reason: \"Correction detected in the turn\", tokenBudget };\n\t}\n\tif (signals.trigger === \"session-end\") {\n\t\treturn { act: \"reflect\", reason: \"Session end reflection triggered\", tokenBudget };\n\t}\n\tif (signals.trigger === \"complex\") {\n\t\tif (signals.toolCallCount >= 3) {\n\t\t\treturn { act: \"reflect\", reason: `Complex turn with ${signals.toolCallCount} tool calls`, tokenBudget };\n\t\t}\n\t}\n\n\treturn { act: \"skip\", reason: \"Signals do not justify reflection overhead\", tokenBudget: 0 };\n}\n\nexport interface ReflectionInput {\n\trecentTurnText: string; // host serializes the just-finished turn\n\texistingMemory: string; // current MEMORY.md + USER.md snapshot\n\tplan: DemandPlan;\n\t// host-injected isolated completion function:\n\tcomplete: (systemPrompt: string, userPrompt: string) => Promise<IsolatedCompletionResult>;\n}\n\nexport type ReflectionWrite =\n\t| { kind: \"memory_add\"; section: \"MEMORY\" | \"USER\"; text: string }\n\t| { kind: \"memory_replace\"; target: string; text: string }\n\t| { kind: \"memory_remove\"; target: string };\n\nexport interface ReflectionResult {\n\twrites: ReflectionWrite[];\n\tusage: Usage;\n\trationale: string;\n}\n\nexport class ReflectionEngine {\n\t/**\n\t * Build the reflection prompt, call the injected isolated complete(),\n\t * parse the response, confront existing memory, and return memory writes.\n\t * Zero direct I/O.\n\t */\n\tasync reflect(input: ReflectionInput): Promise<ReflectionResult> {\n\t\tconst systemPrompt = `You are a reflection engine. Your job is to analyze the recent conversation turn, compare it against the agent's existing memory, and decide if any memory updates are needed.\n\nExisting Memory snapshot:\n${input.existingMemory}\n\nMemory guidelines:\n- \"MEMORY\" is for project facts, configuration, repeatable workflows, and coding findings.\n- \"USER\" is for user preferences, patterns, and style specifications.\n- Avoid duplicate facts. If the fact is already represented, do not add it.\n- CONFRONT existing memory: if the new turn contradicts or updates an existing fact, use \"memory_replace\" or \"memory_remove\" to supersede the old fact rather than blindly appending.\n- Keep memories short, factual, and direct. No fluff.\n\nYou must output your analysis and writes in the following JSON format inside a \\`\\`\\`json\\`\\`\\` code fence:\n{\n \"rationale\": \"Explanation of your reasoning\",\n \"writes\": [\n { \"kind\": \"memory_add\", \"section\": \"MEMORY\" | \"USER\", \"text\": \"New direct fact to append\" },\n { \"kind\": \"memory_replace\", \"target\": \"Exact text substring to replace\", \"text\": \"New replacement text\" },\n { \"kind\": \"memory_remove\", \"target\": \"Exact text substring to remove\" }\n ]\n}\n`;\n\n\t\tconst userPrompt = `Recent turn transcript:\n${input.recentTurnText}\n\nAnalyze this turn and output your memory updates.`;\n\n\t\ttry {\n\t\t\tconst compResult = await input.complete(systemPrompt, userPrompt);\n\t\t\tconst text = compResult.text;\n\n\t\t\tconst jsonMatch = text.match(/```json\\s*([\\s\\S]*?)\\s*```/) || text.match(/{[\\s\\S]*}/);\n\t\t\tif (!jsonMatch) {\n\t\t\t\treturn {\n\t\t\t\t\twrites: [],\n\t\t\t\t\tusage: compResult.usage,\n\t\t\t\t\trationale: `Failed to locate JSON response. Raw text:\\n${text}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst parsed = JSON.parse(jsonMatch[1] || jsonMatch[0]);\n\t\t\tconst rationale = parsed.rationale || \"\";\n\t\t\tconst writes: ReflectionWrite[] = [];\n\n\t\t\tif (Array.isArray(parsed.writes)) {\n\t\t\t\tfor (const w of parsed.writes) {\n\t\t\t\t\tif (w && typeof w === \"object\") {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tw.kind === \"memory_add\" &&\n\t\t\t\t\t\t\t(w.section === \"MEMORY\" || w.section === \"USER\") &&\n\t\t\t\t\t\t\ttypeof w.text === \"string\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\twrites.push({ kind: \"memory_add\", section: w.section, text: w.text });\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\tw.kind === \"memory_replace\" &&\n\t\t\t\t\t\t\ttypeof w.target === \"string\" &&\n\t\t\t\t\t\t\ttypeof w.text === \"string\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\twrites.push({ kind: \"memory_replace\", target: w.target, text: w.text });\n\t\t\t\t\t\t} else if (w.kind === \"memory_remove\" && typeof w.target === \"string\") {\n\t\t\t\t\t\t\twrites.push({ kind: \"memory_remove\", target: w.target });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\twrites,\n\t\t\t\tusage: compResult.usage,\n\t\t\t\trationale,\n\t\t\t};\n\t\t} catch (err) {\n\t\t\t// Zeroed/fallback usage representation\n\t\t\tconst emptyUsage: Usage = {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t\treturn {\n\t\t\t\twrites: [],\n\t\t\t\tusage: emptyUsage,\n\t\t\t\trationale: `Error during reflection: ${String(err)}`,\n\t\t\t};\n\t\t}\n\t}\n}\n"]}
@@ -10,6 +10,14 @@ export declare class MemoryManager {
10
10
  registerProvider(p: MemoryProvider): void;
11
11
  initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void>;
12
12
  buildSystemPromptBlock(): string;
13
+ /**
14
+ * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the
15
+ * system prompt. Used by end-of-loop reflection so its confront-before-write sees the live memory
16
+ * (including writes made earlier in the same session) without churning the prefix-cache-stable
17
+ * system prompt block.
18
+ */
19
+ buildSystemPromptBlockFresh(): string;
20
+ private _composeSystemPromptBlock;
13
21
  prefetch(query: string): Promise<string>;
14
22
  syncTurn(user: string, assistant: string): Promise<void>;
15
23
  onPreCompress(): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"memory-manager.d.ts","sourceRoot":"","sources":["../../../src/core/memory/memory-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEnF,qBAAa,aAAa;IACzB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAwB;IAClD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAA0B;IAC1D,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAA0B;IAC9D,OAAO,CAAC,GAAG,CAAC,CAAyB;IACrC,OAAO,CAAC,sBAAsB,CAAC,CAAS;IAGxC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,wBAAwB,CAY7C;IAEI,gBAAgB,CAAC,CAAC,EAAE,cAAc,GAAG,IAAI,CA8B/C;IAEY,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxF;IAEM,sBAAsB,IAAI,MAAM,CAsBtC;IAEY,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBpD;IAEY,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAepE;IAEY,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC,CAgB5C;IAEY,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAezC;IAEY,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAcxC;IAEM,kBAAkB,IAAI,cAAc,EAAE,CAa5C;IAEM,iBAAiB,IAAI,MAAM,EAAE,CAgBnC;IAEM,KAAK,IAAI,IAAI,CAMnB;CACD","sourcesContent":["import type { ToolDefinition } from \"../extensions/types.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"./memory-provider.ts\";\n\nexport class MemoryManager {\n\tprivate readonly providers: MemoryProvider[] = [];\n\tprivate readonly activeProviders: Set<string> = new Set();\n\tprivate readonly registeredToolNames: Set<string> = new Set();\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate systemPromptBlockCache?: string;\n\n\t// Core reserved tool names to prevent hijacking or schema corruption.\n\tprivate static readonly RESERVED_CORE_TOOL_NAMES = new Set([\n\t\t\"read\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"bash\",\n\t\t\"ask_user\",\n\t\t\"skillify\",\n\t\t\"skill_audit\",\n\t\t\"skill_search\",\n\t\t\"skill_open\",\n\t]);\n\n\tpublic registerProvider(p: MemoryProvider): void {\n\t\tif (this.providers.some((prov) => prov.name === p.name)) {\n\t\t\tthrow new Error(`Memory provider ${p.name} is already registered.`);\n\t\t}\n\n\t\tif (p.getToolDefinitions) {\n\t\t\tlet tools: ToolDefinition[] = [];\n\t\t\ttry {\n\t\t\t\ttools = p.getToolDefinitions() ?? [];\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to get tool definitions from provider ${p.name}: ${String(err)}`);\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tif (MemoryManager.RESERVED_CORE_TOOL_NAMES.has(tool.name)) {\n\t\t\t\t\tthrow new Error(`Memory provider ${p.name} tried to register reserved core tool: ${tool.name}`);\n\t\t\t\t}\n\t\t\t\tif (this.registeredToolNames.has(tool.name)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Memory provider tool name collision: ${tool.name} is already registered. First-registration-wins.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tthis.registeredToolNames.add(tool.name);\n\t\t\t}\n\t\t}\n\n\t\tthis.providers.push(p);\n\t}\n\n\tpublic async initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.activeProviders.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\n\t\tfor (const p of this.providers) {\n\t\t\ttry {\n\t\t\t\tconst available = await p.isAvailable();\n\t\t\t\tif (!available) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait p.initialize(sessionId, ctx);\n\t\t\t\tthis.activeProviders.add(p.name);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to initialize and was deactivated:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic buildSystemPromptBlock(): string {\n\t\tif (this.systemPromptBlockCache !== undefined) {\n\t\t\treturn this.systemPromptBlockCache;\n\t\t}\n\n\t\tconst blocks: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.systemPromptBlock) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst block = p.systemPromptBlock();\n\t\t\t\tif (block) {\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to generate system prompt block:`, err);\n\t\t\t}\n\t\t}\n\n\t\tthis.systemPromptBlockCache = blocks.join(\"\\n\\n\");\n\t\treturn this.systemPromptBlockCache;\n\t}\n\n\tpublic async prefetch(query: string): Promise<string> {\n\t\tconst results: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.prefetch) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst text = await p.prefetch(query);\n\t\t\t\tif (text) {\n\t\t\t\t\tresults.push(text);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during prefetch:`, err);\n\t\t\t}\n\t\t}\n\t\treturn results.join(\"\\n\\n\");\n\t}\n\n\tpublic async syncTurn(user: string, assistant: string): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.syncTurn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.syncTurn(user, assistant);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during syncTurn:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async onPreCompress(): Promise<string> {\n\t\tconst insights: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onPreCompress) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst insight = await p.onPreCompress();\n\t\t\t\tif (insight) {\n\t\t\t\t\tinsights.push(insight);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onPreCompress:`, err);\n\t\t\t}\n\t\t}\n\t\treturn insights.join(\"\\n\\n\");\n\t}\n\n\tpublic async onSessionEnd(): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onSessionEnd) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.onSessionEnd();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onSessionEnd:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async shutdownAll(): Promise<void> {\n\t\t// Shutdown in reverse registration order\n\t\tconst reversed = [...this.providers].reverse();\n\t\tfor (const p of reversed) {\n\t\t\tif (!this.activeProviders.has(p.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.shutdown();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to shutdown cleanly:`, err);\n\t\t\t}\n\t\t}\n\t\tthis.activeProviders.clear();\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\tconst tools: ToolDefinition[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getToolDefinitions) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\ttools.push(...p.getToolDefinitions());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get tool definitions from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn tools;\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\tconst markers = new Set<string>();\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getContextMarkers) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst list = p.getContextMarkers() ?? [];\n\t\t\t\tfor (const m of list) {\n\t\t\t\t\tmarkers.add(m);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get context markers from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn [...markers];\n\t}\n\n\tpublic reset(): void {\n\t\tthis.providers.length = 0;\n\t\tthis.activeProviders.clear();\n\t\tthis.registeredToolNames.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\t\tthis.ctx = undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory-manager.d.ts","sourceRoot":"","sources":["../../../src/core/memory/memory-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEnF,qBAAa,aAAa;IACzB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAwB;IAClD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAA0B;IAC1D,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAA0B;IAC9D,OAAO,CAAC,GAAG,CAAC,CAAyB;IACrC,OAAO,CAAC,sBAAsB,CAAC,CAAS;IAGxC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,wBAAwB,CAY7C;IAEI,gBAAgB,CAAC,CAAC,EAAE,cAAc,GAAG,IAAI,CA8B/C;IAEY,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxF;IAEM,sBAAsB,IAAI,MAAM,CAOtC;IAED;;;;;OAKG;IACI,2BAA2B,IAAI,MAAM,CAE3C;IAED,OAAO,CAAC,yBAAyB;IAkBpB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBpD;IAEY,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAepE;IAEY,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC,CAgB5C;IAEY,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAezC;IAEY,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAcxC;IAEM,kBAAkB,IAAI,cAAc,EAAE,CAa5C;IAEM,iBAAiB,IAAI,MAAM,EAAE,CAgBnC;IAEM,KAAK,IAAI,IAAI,CAMnB;CACD","sourcesContent":["import type { ToolDefinition } from \"../extensions/types.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"./memory-provider.ts\";\n\nexport class MemoryManager {\n\tprivate readonly providers: MemoryProvider[] = [];\n\tprivate readonly activeProviders: Set<string> = new Set();\n\tprivate readonly registeredToolNames: Set<string> = new Set();\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate systemPromptBlockCache?: string;\n\n\t// Core reserved tool names to prevent hijacking or schema corruption.\n\tprivate static readonly RESERVED_CORE_TOOL_NAMES = new Set([\n\t\t\"read\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"bash\",\n\t\t\"ask_user\",\n\t\t\"skillify\",\n\t\t\"skill_audit\",\n\t\t\"skill_search\",\n\t\t\"skill_open\",\n\t]);\n\n\tpublic registerProvider(p: MemoryProvider): void {\n\t\tif (this.providers.some((prov) => prov.name === p.name)) {\n\t\t\tthrow new Error(`Memory provider ${p.name} is already registered.`);\n\t\t}\n\n\t\tif (p.getToolDefinitions) {\n\t\t\tlet tools: ToolDefinition[] = [];\n\t\t\ttry {\n\t\t\t\ttools = p.getToolDefinitions() ?? [];\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to get tool definitions from provider ${p.name}: ${String(err)}`);\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tif (MemoryManager.RESERVED_CORE_TOOL_NAMES.has(tool.name)) {\n\t\t\t\t\tthrow new Error(`Memory provider ${p.name} tried to register reserved core tool: ${tool.name}`);\n\t\t\t\t}\n\t\t\t\tif (this.registeredToolNames.has(tool.name)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Memory provider tool name collision: ${tool.name} is already registered. First-registration-wins.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tthis.registeredToolNames.add(tool.name);\n\t\t\t}\n\t\t}\n\n\t\tthis.providers.push(p);\n\t}\n\n\tpublic async initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.activeProviders.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\n\t\tfor (const p of this.providers) {\n\t\t\ttry {\n\t\t\t\tconst available = await p.isAvailable();\n\t\t\t\tif (!available) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait p.initialize(sessionId, ctx);\n\t\t\t\tthis.activeProviders.add(p.name);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to initialize and was deactivated:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic buildSystemPromptBlock(): string {\n\t\tif (this.systemPromptBlockCache !== undefined) {\n\t\t\treturn this.systemPromptBlockCache;\n\t\t}\n\n\t\tthis.systemPromptBlockCache = this._composeSystemPromptBlock();\n\t\treturn this.systemPromptBlockCache;\n\t}\n\n\t/**\n\t * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the\n\t * system prompt. Used by end-of-loop reflection so its confront-before-write sees the live memory\n\t * (including writes made earlier in the same session) without churning the prefix-cache-stable\n\t * system prompt block.\n\t */\n\tpublic buildSystemPromptBlockFresh(): string {\n\t\treturn this._composeSystemPromptBlock();\n\t}\n\n\tprivate _composeSystemPromptBlock(): string {\n\t\tconst blocks: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.systemPromptBlock) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst block = p.systemPromptBlock();\n\t\t\t\tif (block) {\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to generate system prompt block:`, err);\n\t\t\t}\n\t\t}\n\t\treturn blocks.join(\"\\n\\n\");\n\t}\n\n\tpublic async prefetch(query: string): Promise<string> {\n\t\tconst results: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.prefetch) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst text = await p.prefetch(query);\n\t\t\t\tif (text) {\n\t\t\t\t\tresults.push(text);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during prefetch:`, err);\n\t\t\t}\n\t\t}\n\t\treturn results.join(\"\\n\\n\");\n\t}\n\n\tpublic async syncTurn(user: string, assistant: string): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.syncTurn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.syncTurn(user, assistant);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during syncTurn:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async onPreCompress(): Promise<string> {\n\t\tconst insights: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onPreCompress) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst insight = await p.onPreCompress();\n\t\t\t\tif (insight) {\n\t\t\t\t\tinsights.push(insight);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onPreCompress:`, err);\n\t\t\t}\n\t\t}\n\t\treturn insights.join(\"\\n\\n\");\n\t}\n\n\tpublic async onSessionEnd(): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onSessionEnd) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.onSessionEnd();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onSessionEnd:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async shutdownAll(): Promise<void> {\n\t\t// Shutdown in reverse registration order\n\t\tconst reversed = [...this.providers].reverse();\n\t\tfor (const p of reversed) {\n\t\t\tif (!this.activeProviders.has(p.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.shutdown();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to shutdown cleanly:`, err);\n\t\t\t}\n\t\t}\n\t\tthis.activeProviders.clear();\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\tconst tools: ToolDefinition[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getToolDefinitions) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\ttools.push(...p.getToolDefinitions());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get tool definitions from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn tools;\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\tconst markers = new Set<string>();\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getContextMarkers) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst list = p.getContextMarkers() ?? [];\n\t\t\t\tfor (const m of list) {\n\t\t\t\t\tmarkers.add(m);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get context markers from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn [...markers];\n\t}\n\n\tpublic reset(): void {\n\t\tthis.providers.length = 0;\n\t\tthis.activeProviders.clear();\n\t\tthis.registeredToolNames.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\t\tthis.ctx = undefined;\n\t}\n}\n"]}