@mariozechner/pi-coding-agent 0.31.1 → 0.32.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/README.md +56 -5
- package/dist/cli/file-processor.d.ts +5 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js +28 -8
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/core/agent-session.d.ts +45 -17
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +93 -42
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +6 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +16 -1
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/custom-tools/types.d.ts +1 -1
- package/dist/core/custom-tools/types.d.ts.map +1 -1
- package/dist/core/custom-tools/types.js.map +1 -1
- package/dist/core/hooks/loader.d.ts +4 -1
- package/dist/core/hooks/loader.d.ts.map +1 -1
- package/dist/core/hooks/loader.js +2 -2
- package/dist/core/hooks/loader.js.map +1 -1
- package/dist/core/hooks/runner.d.ts +2 -2
- package/dist/core/hooks/runner.d.ts.map +1 -1
- package/dist/core/hooks/runner.js +3 -3
- package/dist/core/hooks/runner.js.map +1 -1
- package/dist/core/hooks/types.d.ts +10 -4
- package/dist/core/hooks/types.d.ts.map +1 -1
- package/dist/core/hooks/types.js.map +1 -1
- package/dist/core/messages.d.ts +2 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +4 -0
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-registry.d.ts +5 -2
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +85 -49
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -0
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +9 -6
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +17 -3
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +41 -6
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/index.d.ts +9 -4
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +6 -6
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/read.d.ts +5 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +22 -5
- package/dist/core/tools/read.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +5 -5
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +6 -4
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +1 -0
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +7 -1
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/hook-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/hook-editor.js +3 -3
- package/dist/modes/interactive/components/hook-editor.js.map +1 -1
- package/dist/modes/interactive/components/hook-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/hook-input.js +3 -3
- package/dist/modes/interactive/components/hook-input.js.map +1 -1
- package/dist/modes/interactive/components/hook-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/hook-selector.js +3 -3
- package/dist/modes/interactive/components/hook-selector.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +3 -3
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +3 -3
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +8 -2
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +37 -6
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +7 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +74 -26
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +3 -3
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +12 -4
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +18 -6
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +21 -12
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +25 -6
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/utils/image-resize.d.ts +29 -0
- package/dist/utils/image-resize.d.ts.map +1 -0
- package/dist/utils/image-resize.js +111 -0
- package/dist/utils/image-resize.js.map +1 -0
- package/docs/hooks.md +16 -9
- package/examples/README.md +6 -0
- package/examples/custom-tools/README.md +2 -0
- package/examples/hooks/README.md +1 -0
- package/examples/hooks/file-trigger.ts +1 -1
- package/examples/hooks/todo/index.ts +134 -0
- package/package.json +6 -5
- package/dist/modes/interactive/components/queue-mode-selector.d.ts +0 -10
- package/dist/modes/interactive/components/queue-mode-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/queue-mode-selector.js +0 -42
- package/dist/modes/interactive/components/queue-mode-selector.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../src/core/hooks/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAmC/D,mDAAmD;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,oDAAoD;AACpD,MAAM,aAAa,GAAkB;IACpC,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS;IAC7B,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;IAC1B,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS;IAC5B,MAAM,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC;IAChB,SAAS,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC;IACnB,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,SAAkB;IACtC,aAAa,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC;IACvB,aAAa,EAAE,GAAG,EAAE,CAAC,EAAE;IACvB,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS;IAC7B,IAAI,KAAK,GAAG;QACX,OAAO,KAAK,CAAC;IAAA,CACb;CACD,CAAC;AAEF;;GAEG;AACH,MAAM,OAAO,UAAU;IACd,KAAK,CAAe;IACpB,SAAS,CAAgB;IACzB,KAAK,CAAU;IACf,GAAG,CAAS;IACZ,cAAc,CAAiB;IAC/B,aAAa,CAAgB;IAC7B,cAAc,GAA2B,IAAI,GAAG,EAAE,CAAC;IACnD,QAAQ,GAAiC,GAAG,EAAE,CAAC,SAAS,CAAC;IACzD,QAAQ,GAAkB,GAAG,EAAE,CAAC,IAAI,CAAC;IACrC,aAAa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EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;oBACpF,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;oBAEhD,kCAAkC;oBAClC,IAAI,aAAa,IAAK,aAA6C,CAAC,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;wBACxF,MAAM,GAAG,aAA4C,CAAC;oBACvD,CAAC;gBACF,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACd,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACjE,IAAI,CAAC,SAAS,CAAC;wBACd,QAAQ,EAAE,IAAI,CAAC,IAAI;wBACnB,KAAK,EAAE,oBAAoB;wBAC3B,KAAK,EAAE,OAAO;qBACd,CAAC,CAAC;gBACJ,CAAC;YACF,CAAC;QACF,CAAC;QAED,OAAO,MAAM,CAAC;IAAA,CACd;CACD","sourcesContent":["/**\n * Hook runner - executes hooks and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { Model } from \"@mariozechner/pi-ai\";\nimport { theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type { SessionManager } from \"../session-manager.js\";\nimport type {\n\tAppendEntryHandler,\n\tBranchHandler,\n\tLoadedHook,\n\tNavigateTreeHandler,\n\tNewSessionHandler,\n\tSendMessageHandler,\n} from \"./loader.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tContextEvent,\n\tContextEventResult,\n\tHookCommandContext,\n\tHookContext,\n\tHookError,\n\tHookEvent,\n\tHookMessageRenderer,\n\tHookUIContext,\n\tRegisteredCommand,\n\tSessionBeforeCompactResult,\n\tSessionBeforeTreeResult,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEventResult,\n} from \"./types.js\";\n\n/**\n * Listener for hook errors.\n */\nexport type HookErrorListener = (error: HookError) => void;\n\n// Re-export execCommand for backward compatibility\nexport { execCommand } from \"../exec.js\";\n\n/** No-op UI context used when no UI is available */\nconst noOpUIContext: HookUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tsetStatus: () => {},\n\tcustom: async () => undefined as never,\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n};\n\n/**\n * HookRunner executes hooks and manages event emission.\n */\nexport class HookRunner {\n\tprivate hooks: LoadedHook[];\n\tprivate uiContext: HookUIContext;\n\tprivate hasUI: boolean;\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<HookErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasQueuedMessagesFn: () => boolean = () => false;\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate branchHandler: BranchHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\n\tconstructor(hooks: LoadedHook[], cwd: string, sessionManager: SessionManager, modelRegistry: ModelRegistry) {\n\t\tthis.hooks = hooks;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.hasUI = false;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\t/**\n\t * Initialize HookRunner with all required context.\n\t * Modes call this once the agent session is fully set up.\n\t */\n\tinitialize(options: {\n\t\t/** Function to get the current model */\n\t\tgetModel: () => Model<any> | undefined;\n\t\t/** Handler for hooks to send messages */\n\t\tsendMessageHandler: SendMessageHandler;\n\t\t/** Handler for hooks to append entries */\n\t\tappendEntryHandler: AppendEntryHandler;\n\t\t/** Handler for creating new sessions (for HookCommandContext) */\n\t\tnewSessionHandler?: NewSessionHandler;\n\t\t/** Handler for branching sessions (for HookCommandContext) */\n\t\tbranchHandler?: BranchHandler;\n\t\t/** Handler for navigating session tree (for HookCommandContext) */\n\t\tnavigateTreeHandler?: NavigateTreeHandler;\n\t\t/** Function to check if agent is idle */\n\t\tisIdle?: () => boolean;\n\t\t/** Function to wait for agent to be idle */\n\t\twaitForIdle?: () => Promise<void>;\n\t\t/** Function to abort current operation (fire-and-forget) */\n\t\tabort?: () => void;\n\t\t/** Function to check if there are queued messages */\n\t\thasQueuedMessages?: () => boolean;\n\t\t/** UI context for interactive prompts */\n\t\tuiContext?: HookUIContext;\n\t\t/** Whether UI is available */\n\t\thasUI?: boolean;\n\t}): void {\n\t\tthis.getModel = options.getModel;\n\t\tthis.isIdleFn = options.isIdle ?? (() => true);\n\t\tthis.waitForIdleFn = options.waitForIdle ?? (async () => {});\n\t\tthis.abortFn = options.abort ?? (() => {});\n\t\tthis.hasQueuedMessagesFn = options.hasQueuedMessages ?? (() => false);\n\t\t// Store session handlers for HookCommandContext\n\t\tif (options.newSessionHandler) {\n\t\t\tthis.newSessionHandler = options.newSessionHandler;\n\t\t}\n\t\tif (options.branchHandler) {\n\t\t\tthis.branchHandler = options.branchHandler;\n\t\t}\n\t\tif (options.navigateTreeHandler) {\n\t\t\tthis.navigateTreeHandler = options.navigateTreeHandler;\n\t\t}\n\t\t// Set per-hook handlers for pi.sendMessage() and pi.appendEntry()\n\t\tfor (const hook of this.hooks) {\n\t\t\thook.setSendMessageHandler(options.sendMessageHandler);\n\t\t\thook.setAppendEntryHandler(options.appendEntryHandler);\n\t\t}\n\t\tthis.uiContext = options.uiContext ?? noOpUIContext;\n\t\tthis.hasUI = options.hasUI ?? false;\n\t}\n\n\t/**\n\t * Get the UI context (set by mode).\n\t */\n\tgetUIContext(): HookUIContext | null {\n\t\treturn this.uiContext;\n\t}\n\n\t/**\n\t * Get whether UI is available.\n\t */\n\tgetHasUI(): boolean {\n\t\treturn this.hasUI;\n\t}\n\n\t/**\n\t * Get the paths of all loaded hooks.\n\t */\n\tgetHookPaths(): string[] {\n\t\treturn this.hooks.map((h) => h.path);\n\t}\n\n\t/**\n\t * Subscribe to hook errors.\n\t * @returns Unsubscribe function\n\t */\n\tonError(listener: HookErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\t/**\n\t * Emit an error to all listeners.\n\t */\n\t/**\n\t * Emit an error to all error listeners.\n\t */\n\temitError(error: HookError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\t/**\n\t * Check if any hooks have handlers for the given event type.\n\t */\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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\t/**\n\t * Get a message renderer for the given customType.\n\t * Returns the first renderer found across all hooks, or undefined if none.\n\t */\n\tgetMessageRenderer(customType: string): HookMessageRenderer | undefined {\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst renderer = hook.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\t/**\n\t * Get all registered commands from all hooks.\n\t */\n\tgetRegisteredCommands(): RegisteredCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tfor (const hook of this.hooks) {\n\t\t\tfor (const command of hook.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t}\n\t\t}\n\t\treturn commands;\n\t}\n\n\t/**\n\t * Get a registered command by name.\n\t * Returns the first command found across all hooks, or undefined if none.\n\t */\n\tgetCommand(name: string): RegisteredCommand | undefined {\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst command = hook.commands.get(name);\n\t\t\tif (command) {\n\t\t\t\treturn command;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Create the event context for handlers.\n\t */\n\tprivate createContext(): HookContext {\n\t\treturn {\n\t\t\tui: this.uiContext,\n\t\t\thasUI: this.hasUI,\n\t\t\tcwd: this.cwd,\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: this.modelRegistry,\n\t\t\tmodel: this.getModel(),\n\t\t\tisIdle: () => this.isIdleFn(),\n\t\t\tabort: () => this.abortFn(),\n\t\t\thasQueuedMessages: () => this.hasQueuedMessagesFn(),\n\t\t};\n\t}\n\n\t/**\n\t * Create the command context for slash command handlers.\n\t * Extends HookContext with session control methods that are only safe in commands.\n\t */\n\tcreateCommandContext(): HookCommandContext {\n\t\treturn {\n\t\t\t...this.createContext(),\n\t\t\twaitForIdle: () => this.waitForIdleFn(),\n\t\t\tnewSession: (options) => this.newSessionHandler(options),\n\t\t\tbranch: (entryId) => this.branchHandler(entryId),\n\t\t\tnavigateTree: (targetId, options) => this.navigateTreeHandler(targetId, options),\n\t\t};\n\t}\n\n\t/**\n\t * Check if event type is a session \"before_*\" event that can be cancelled.\n\t */\n\tprivate isSessionBeforeEvent(\n\t\ttype: string,\n\t): type is \"session_before_switch\" | \"session_before_branch\" | \"session_before_compact\" | \"session_before_tree\" {\n\t\treturn (\n\t\t\ttype === \"session_before_switch\" ||\n\t\t\ttype === \"session_before_branch\" ||\n\t\t\ttype === \"session_before_compact\" ||\n\t\t\ttype === \"session_before_tree\"\n\t\t);\n\t}\n\n\t/**\n\t * Emit an event to all hooks.\n\t * Returns the result from session before_* / tool_result events (if any handler returns one).\n\t */\n\tasync emit(\n\t\tevent: HookEvent,\n\t): Promise<SessionBeforeCompactResult | SessionBeforeTreeResult | ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeCompactResult | SessionBeforeTreeResult | ToolResultEventResult | undefined;\n\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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\t// For session before_* events, capture the result (for cancellation)\n\t\t\t\t\tif (this.isSessionBeforeEvent(event.type) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeCompactResult | SessionBeforeTreeResult;\n\t\t\t\t\t\t// If cancelled, stop processing further hooks\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// For tool_result events, capture the result\n\t\t\t\t\tif (event.type === \"tool_result\" && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as ToolResultEventResult;\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\tthis.emitError({\n\t\t\t\t\t\thookPath: hook.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\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\t/**\n\t * Emit a tool_call event to all hooks.\n\t * No timeout - user prompts can take as long as needed.\n\t * Errors are thrown (not swallowed) so caller can block on failure.\n\t */\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 hook of this.hooks) {\n\t\t\tconst handlers = hook.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\t// No timeout - let user take their time\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\t// If blocked, stop processing further hooks\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\t/**\n\t * Emit a context event to all hooks.\n\t * Handlers are chained - each gets the previous handler's output (if any).\n\t * Returns the final modified messages, or the original if no modifications.\n\t *\n\t * Note: Messages are already deep-copied by the caller (pi-ai preprocessor).\n\t */\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = messages;\n\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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\tthis.emitError({\n\t\t\t\t\t\thookPath: hook.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\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\t/**\n\t * Emit before_agent_start event to all hooks.\n\t * Returns the first message to inject (if any handler returns one).\n\t */\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages?: import(\"@mariozechner/pi-ai\").ImageContent[],\n\t): Promise<BeforeAgentStartEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: BeforeAgentStartEventResult | undefined;\n\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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 = { type: \"before_agent_start\", prompt, images };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\t// Take the first message returned\n\t\t\t\t\tif (handlerResult && (handlerResult as BeforeAgentStartEventResult).message && !result) {\n\t\t\t\t\t\tresult = handlerResult as BeforeAgentStartEventResult;\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\tthis.emitError({\n\t\t\t\t\t\thookPath: hook.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});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../src/core/hooks/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAmC/D,mDAAmD;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,oDAAoD;AACpD,MAAM,aAAa,GAAkB;IACpC,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS;IAC7B,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;IAC1B,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS;IAC5B,MAAM,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC;IAChB,SAAS,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC;IACnB,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,SAAkB;IACtC,aAAa,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC;IACvB,aAAa,EAAE,GAAG,E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CACzB,MAAc,EACd,MAAqD,EACF;QACnD,MAAM,GAAG,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QACjC,IAAI,MAA+C,CAAC;QAEpD,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;YACzD,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YAEjD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;gBAChC,IAAI,CAAC;oBACJ,MAAM,KAAK,GAA0B,EAAE,IAAI,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;oBACpF,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;oBAEhD,kCAAkC;oBAClC,IAAI,aAAa,IAAK,aAA6C,CAAC,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;wBACxF,MAAM,GAAG,aAA4C,CAAC;oBACvD,CAAC;gBACF,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACd,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACjE,IAAI,CAAC,SAAS,CAAC;wBACd,QAAQ,EAAE,IAAI,CAAC,IAAI;wBACnB,KAAK,EAAE,oBAAoB;wBAC3B,KAAK,EAAE,OAAO;qBACd,CAAC,CAAC;gBACJ,CAAC;YACF,CAAC;QACF,CAAC;QAED,OAAO,MAAM,CAAC;IAAA,CACd;CACD","sourcesContent":["/**\n * Hook runner - executes hooks and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { Model } from \"@mariozechner/pi-ai\";\nimport { theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type { SessionManager } from \"../session-manager.js\";\nimport type {\n\tAppendEntryHandler,\n\tBranchHandler,\n\tLoadedHook,\n\tNavigateTreeHandler,\n\tNewSessionHandler,\n\tSendMessageHandler,\n} from \"./loader.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tContextEvent,\n\tContextEventResult,\n\tHookCommandContext,\n\tHookContext,\n\tHookError,\n\tHookEvent,\n\tHookMessageRenderer,\n\tHookUIContext,\n\tRegisteredCommand,\n\tSessionBeforeCompactResult,\n\tSessionBeforeTreeResult,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEventResult,\n} from \"./types.js\";\n\n/**\n * Listener for hook errors.\n */\nexport type HookErrorListener = (error: HookError) => void;\n\n// Re-export execCommand for backward compatibility\nexport { execCommand } from \"../exec.js\";\n\n/** No-op UI context used when no UI is available */\nconst noOpUIContext: HookUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tsetStatus: () => {},\n\tcustom: async () => undefined as never,\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n};\n\n/**\n * HookRunner executes hooks and manages event emission.\n */\nexport class HookRunner {\n\tprivate hooks: LoadedHook[];\n\tprivate uiContext: HookUIContext;\n\tprivate hasUI: boolean;\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<HookErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate branchHandler: BranchHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\n\tconstructor(hooks: LoadedHook[], cwd: string, sessionManager: SessionManager, modelRegistry: ModelRegistry) {\n\t\tthis.hooks = hooks;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.hasUI = false;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\t/**\n\t * Initialize HookRunner with all required context.\n\t * Modes call this once the agent session is fully set up.\n\t */\n\tinitialize(options: {\n\t\t/** Function to get the current model */\n\t\tgetModel: () => Model<any> | undefined;\n\t\t/** Handler for hooks to send messages */\n\t\tsendMessageHandler: SendMessageHandler;\n\t\t/** Handler for hooks to append entries */\n\t\tappendEntryHandler: AppendEntryHandler;\n\t\t/** Handler for creating new sessions (for HookCommandContext) */\n\t\tnewSessionHandler?: NewSessionHandler;\n\t\t/** Handler for branching sessions (for HookCommandContext) */\n\t\tbranchHandler?: BranchHandler;\n\t\t/** Handler for navigating session tree (for HookCommandContext) */\n\t\tnavigateTreeHandler?: NavigateTreeHandler;\n\t\t/** Function to check if agent is idle */\n\t\tisIdle?: () => boolean;\n\t\t/** Function to wait for agent to be idle */\n\t\twaitForIdle?: () => Promise<void>;\n\t\t/** Function to abort current operation (fire-and-forget) */\n\t\tabort?: () => void;\n\t\t/** Function to check if there are queued messages */\n\t\thasPendingMessages?: () => boolean;\n\t\t/** UI context for interactive prompts */\n\t\tuiContext?: HookUIContext;\n\t\t/** Whether UI is available */\n\t\thasUI?: boolean;\n\t}): void {\n\t\tthis.getModel = options.getModel;\n\t\tthis.isIdleFn = options.isIdle ?? (() => true);\n\t\tthis.waitForIdleFn = options.waitForIdle ?? (async () => {});\n\t\tthis.abortFn = options.abort ?? (() => {});\n\t\tthis.hasPendingMessagesFn = options.hasPendingMessages ?? (() => false);\n\t\t// Store session handlers for HookCommandContext\n\t\tif (options.newSessionHandler) {\n\t\t\tthis.newSessionHandler = options.newSessionHandler;\n\t\t}\n\t\tif (options.branchHandler) {\n\t\t\tthis.branchHandler = options.branchHandler;\n\t\t}\n\t\tif (options.navigateTreeHandler) {\n\t\t\tthis.navigateTreeHandler = options.navigateTreeHandler;\n\t\t}\n\t\t// Set per-hook handlers for pi.sendMessage() and pi.appendEntry()\n\t\tfor (const hook of this.hooks) {\n\t\t\thook.setSendMessageHandler(options.sendMessageHandler);\n\t\t\thook.setAppendEntryHandler(options.appendEntryHandler);\n\t\t}\n\t\tthis.uiContext = options.uiContext ?? noOpUIContext;\n\t\tthis.hasUI = options.hasUI ?? false;\n\t}\n\n\t/**\n\t * Get the UI context (set by mode).\n\t */\n\tgetUIContext(): HookUIContext | null {\n\t\treturn this.uiContext;\n\t}\n\n\t/**\n\t * Get whether UI is available.\n\t */\n\tgetHasUI(): boolean {\n\t\treturn this.hasUI;\n\t}\n\n\t/**\n\t * Get the paths of all loaded hooks.\n\t */\n\tgetHookPaths(): string[] {\n\t\treturn this.hooks.map((h) => h.path);\n\t}\n\n\t/**\n\t * Subscribe to hook errors.\n\t * @returns Unsubscribe function\n\t */\n\tonError(listener: HookErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\t/**\n\t * Emit an error to all listeners.\n\t */\n\t/**\n\t * Emit an error to all error listeners.\n\t */\n\temitError(error: HookError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\t/**\n\t * Check if any hooks have handlers for the given event type.\n\t */\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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\t/**\n\t * Get a message renderer for the given customType.\n\t * Returns the first renderer found across all hooks, or undefined if none.\n\t */\n\tgetMessageRenderer(customType: string): HookMessageRenderer | undefined {\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst renderer = hook.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\t/**\n\t * Get all registered commands from all hooks.\n\t */\n\tgetRegisteredCommands(): RegisteredCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tfor (const hook of this.hooks) {\n\t\t\tfor (const command of hook.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t}\n\t\t}\n\t\treturn commands;\n\t}\n\n\t/**\n\t * Get a registered command by name.\n\t * Returns the first command found across all hooks, or undefined if none.\n\t */\n\tgetCommand(name: string): RegisteredCommand | undefined {\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst command = hook.commands.get(name);\n\t\t\tif (command) {\n\t\t\t\treturn command;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Create the event context for handlers.\n\t */\n\tprivate createContext(): HookContext {\n\t\treturn {\n\t\t\tui: this.uiContext,\n\t\t\thasUI: this.hasUI,\n\t\t\tcwd: this.cwd,\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: this.modelRegistry,\n\t\t\tmodel: this.getModel(),\n\t\t\tisIdle: () => this.isIdleFn(),\n\t\t\tabort: () => this.abortFn(),\n\t\t\thasPendingMessages: () => this.hasPendingMessagesFn(),\n\t\t};\n\t}\n\n\t/**\n\t * Create the command context for slash command handlers.\n\t * Extends HookContext with session control methods that are only safe in commands.\n\t */\n\tcreateCommandContext(): HookCommandContext {\n\t\treturn {\n\t\t\t...this.createContext(),\n\t\t\twaitForIdle: () => this.waitForIdleFn(),\n\t\t\tnewSession: (options) => this.newSessionHandler(options),\n\t\t\tbranch: (entryId) => this.branchHandler(entryId),\n\t\t\tnavigateTree: (targetId, options) => this.navigateTreeHandler(targetId, options),\n\t\t};\n\t}\n\n\t/**\n\t * Check if event type is a session \"before_*\" event that can be cancelled.\n\t */\n\tprivate isSessionBeforeEvent(\n\t\ttype: string,\n\t): type is \"session_before_switch\" | \"session_before_branch\" | \"session_before_compact\" | \"session_before_tree\" {\n\t\treturn (\n\t\t\ttype === \"session_before_switch\" ||\n\t\t\ttype === \"session_before_branch\" ||\n\t\t\ttype === \"session_before_compact\" ||\n\t\t\ttype === \"session_before_tree\"\n\t\t);\n\t}\n\n\t/**\n\t * Emit an event to all hooks.\n\t * Returns the result from session before_* / tool_result events (if any handler returns one).\n\t */\n\tasync emit(\n\t\tevent: HookEvent,\n\t): Promise<SessionBeforeCompactResult | SessionBeforeTreeResult | ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeCompactResult | SessionBeforeTreeResult | ToolResultEventResult | undefined;\n\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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\t// For session before_* events, capture the result (for cancellation)\n\t\t\t\t\tif (this.isSessionBeforeEvent(event.type) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeCompactResult | SessionBeforeTreeResult;\n\t\t\t\t\t\t// If cancelled, stop processing further hooks\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// For tool_result events, capture the result\n\t\t\t\t\tif (event.type === \"tool_result\" && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as ToolResultEventResult;\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\tthis.emitError({\n\t\t\t\t\t\thookPath: hook.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\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\t/**\n\t * Emit a tool_call event to all hooks.\n\t * No timeout - user prompts can take as long as needed.\n\t * Errors are thrown (not swallowed) so caller can block on failure.\n\t */\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 hook of this.hooks) {\n\t\t\tconst handlers = hook.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\t// No timeout - let user take their time\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\t// If blocked, stop processing further hooks\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\t/**\n\t * Emit a context event to all hooks.\n\t * Handlers are chained - each gets the previous handler's output (if any).\n\t * Returns the final modified messages, or the original if no modifications.\n\t *\n\t * Note: Messages are already deep-copied by the caller (pi-ai preprocessor).\n\t */\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = messages;\n\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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\tthis.emitError({\n\t\t\t\t\t\thookPath: hook.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\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\t/**\n\t * Emit before_agent_start event to all hooks.\n\t * Returns the first message to inject (if any handler returns one).\n\t */\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages?: import(\"@mariozechner/pi-ai\").ImageContent[],\n\t): Promise<BeforeAgentStartEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: BeforeAgentStartEventResult | undefined;\n\n\t\tfor (const hook of this.hooks) {\n\t\t\tconst handlers = hook.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 = { type: \"before_agent_start\", prompt, images };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\t// Take the first message returned\n\t\t\t\t\tif (handlerResult && (handlerResult as BeforeAgentStartEventResult).message && !result) {\n\t\t\t\t\t\tresult = handlerResult as BeforeAgentStartEventResult;\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\tthis.emitError({\n\t\t\t\t\t\thookPath: hook.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});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n"]}
|
|
@@ -132,7 +132,7 @@ export interface HookContext {
|
|
|
132
132
|
/** Abort the current agent operation (fire-and-forget, does not wait) */
|
|
133
133
|
abort(): void;
|
|
134
134
|
/** Whether there are queued messages waiting to be processed */
|
|
135
|
-
|
|
135
|
+
hasPendingMessages(): boolean;
|
|
136
136
|
}
|
|
137
137
|
/**
|
|
138
138
|
* Extended context for slash command handlers.
|
|
@@ -556,10 +556,16 @@ export interface HookAPI {
|
|
|
556
556
|
* @param message.content - Message content (string or TextContent/ImageContent array)
|
|
557
557
|
* @param message.display - Whether to show in TUI (true = styled display, false = hidden)
|
|
558
558
|
* @param message.details - Optional hook-specific metadata (not sent to LLM)
|
|
559
|
-
* @param triggerTurn - If true and agent is idle, triggers a new LLM turn. Default: false.
|
|
560
|
-
*
|
|
559
|
+
* @param options.triggerTurn - If true and agent is idle, triggers a new LLM turn. Default: false.
|
|
560
|
+
* If agent is streaming, message is queued and triggerTurn is ignored.
|
|
561
|
+
* @param options.deliverAs - How to deliver when agent is streaming. Default: "steer".
|
|
562
|
+
* - "steer": Interrupt mid-run, delivered after current tool execution.
|
|
563
|
+
* - "followUp": Wait until agent finishes all work before delivery.
|
|
561
564
|
*/
|
|
562
|
-
sendMessage<T = unknown>(message: Pick<HookMessage<T>, "customType" | "content" | "display" | "details">,
|
|
565
|
+
sendMessage<T = unknown>(message: Pick<HookMessage<T>, "customType" | "content" | "display" | "details">, options?: {
|
|
566
|
+
triggerTurn?: boolean;
|
|
567
|
+
deliverAs?: "steer" | "followUp";
|
|
568
|
+
}): void;
|
|
563
569
|
/**
|
|
564
570
|
* Append a custom entry to the session for hook state persistence.
|
|
565
571
|
* Creates a CustomEntry that does NOT participate in LLM context.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/core/hooks/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxG,OAAO,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KA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ooks are TypeScript modules that can subscribe to agent lifecycle events\n * and interact with the user via UI primitives.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Message, Model, TextContent, ToolResultMessage } from \"@mariozechner/pi-ai\";\nimport type { Component, TUI } from \"@mariozechner/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.js\";\nimport type { ExecOptions, ExecResult } from \"../exec.js\";\nimport type { HookMessage } from \"../messages.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.js\";\n\nimport type { EditToolDetails } from \"../tools/edit.js\";\nimport type {\n\tBashToolDetails,\n\tFindToolDetails,\n\tGrepToolDetails,\n\tLsToolDetails,\n\tReadToolDetails,\n} from \"../tools/index.js\";\n\n// Re-export for backward compatibility\nexport type { ExecOptions, ExecResult } from \"../exec.js\";\n\n/**\n * UI context for hooks to request interactive UI from the harness.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface HookUIContext {\n\t/**\n\t * Show a selector and return the user's choice.\n\t * @param title - Title to display\n\t * @param options - Array of string options\n\t * @returns Selected option string, or null if cancelled\n\t */\n\tselect(title: string, options: string[]): Promise<string | undefined>;\n\n\t/**\n\t * Show a confirmation dialog.\n\t * @returns true if confirmed, false if cancelled\n\t */\n\tconfirm(title: string, message: string): Promise<boolean>;\n\n\t/**\n\t * Show a text input dialog.\n\t * @returns User input, or undefined if cancelled\n\t */\n\tinput(title: string, placeholder?: string): Promise<string | undefined>;\n\n\t/**\n\t * Show a notification to the user.\n\t */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/**\n\t * Set status text in the footer/status bar.\n\t * Pass undefined as text to clear the status for this key.\n\t * Text can include ANSI escape codes for styling.\n\t * Note: Newlines, tabs, and carriage returns are replaced with spaces.\n\t * The combined status line is truncated to terminal width.\n\t * @param key - Unique key to identify this status (e.g., hook name)\n\t * @param text - Status text to display, or undefined to clear\n\t */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/**\n\t * Show a custom component with keyboard focus.\n\t * The factory receives TUI, theme, and a done() callback to close the component.\n\t * Can be async for fire-and-forget work (don't await the work, just start it).\n\t *\n\t * @param factory - Function that creates the component. Call done() when finished.\n\t * @returns Promise that resolves with the value passed to done()\n\t *\n\t * @example\n\t * // Sync factory\n\t * const result = await ctx.ui.custom((tui, theme, done) => {\n\t * const component = new MyComponent(tui, theme);\n\t * component.onFinish = (value) => done(value);\n\t * return component;\n\t * });\n\t *\n\t * // Async factory with fire-and-forget work\n\t * const result = await ctx.ui.custom(async (tui, theme, done) => {\n\t * const loader = new CancellableLoader(tui, theme.fg(\"accent\"), theme.fg(\"muted\"), \"Working...\");\n\t * loader.onAbort = () => done(null);\n\t * doWork(loader.signal).then(done); // Don't await - fire and forget\n\t * return loader;\n\t * });\n\t */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t): Promise<T>;\n\n\t/**\n\t * Set the text in the core input editor.\n\t * Use this to pre-fill the input box with generated content (e.g., prompt templates, extracted questions).\n\t * @param text - Text to set in the editor\n\t */\n\tsetEditorText(text: string): void;\n\n\t/**\n\t * Get the current text from the core input editor.\n\t * @returns Current editor text\n\t */\n\tgetEditorText(): string;\n\n\t/**\n\t * Show a multi-line editor for text editing.\n\t * Supports Ctrl+G to open external editor ($VISUAL or $EDITOR).\n\t * @param title - Title describing what is being edited\n\t * @param prefill - Optional initial text\n\t * @returns Edited text, or undefined if cancelled (Escape)\n\t */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/**\n\t * Get the current theme for styling text with ANSI codes.\n\t * Use theme.fg() and theme.bg() to style status text.\n\t *\n\t * @example\n\t * const theme = ctx.ui.theme;\n\t * ctx.ui.setStatus(\"my-hook\", theme.fg(\"success\", \"✓\") + \" Ready\");\n\t */\n\treadonly theme: Theme;\n}\n\n/**\n * Context passed to hook event handlers.\n * For command handlers, see HookCommandContext which extends this with session control methods.\n */\nexport interface HookContext {\n\t/** UI methods for user interaction */\n\tui: HookUIContext;\n\t/** Whether UI is available (false in print mode) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) - use pi.sendMessage()/pi.appendEntry() for writes */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry - use for API key resolution and model retrieval */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined if no model is selected yet) */\n\tmodel: Model<any> | undefined;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Abort the current agent operation (fire-and-forget, does not wait) */\n\tabort(): void;\n\t/** Whether there are queued messages waiting to be processed */\n\thasQueuedMessages(): boolean;\n}\n\n/**\n * Extended context for slash command handlers.\n * Includes session control methods that are only safe in user-initiated commands.\n *\n * These methods are not available in event handlers because they can cause\n * deadlocks when called from within the agent loop (e.g., tool_call, context events).\n */\nexport interface HookCommandContext extends HookContext {\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/**\n\t * Start a new session, optionally with a setup callback to initialize it.\n\t * The setup callback receives a writable SessionManager for the new session.\n\t *\n\t * @param options.parentSession - Path to parent session for lineage tracking\n\t * @param options.setup - Async callback to initialize the new session (e.g., append messages)\n\t * @returns Object with `cancelled: true` if a hook cancelled the new session\n\t *\n\t * @example\n\t * // Handoff: summarize current session and start fresh with context\n\t * await ctx.newSession({\n\t * parentSession: ctx.sessionManager.getSessionFile(),\n\t * setup: async (sm) => {\n\t * sm.appendMessage({ role: \"user\", content: [{ type: \"text\", text: summary }] });\n\t * }\n\t * });\n\t */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Branch from a specific entry, creating a new session file.\n\t *\n\t * @param entryId - ID of the entry to branch from\n\t * @returns Object with `cancelled: true` if a hook cancelled the branch\n\t */\n\tbranch(entryId: string): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Navigate to a different point in the session tree (in-place).\n\t *\n\t * @param targetId - ID of the entry to navigate to\n\t * @param options.summarize - Whether to summarize the abandoned branch\n\t * @returns Object with `cancelled: true` if a hook cancelled the navigation\n\t */\n\tnavigateTree(targetId: string, options?: { summarize?: boolean }): Promise<{ cancelled: boolean }>;\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired on initial session load */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we're switching to (only for \"resume\") */\n\ttargetSessionFile?: string;\n}\n\n/** Fired after switching to another session */\nexport interface SessionSwitchEvent {\n\ttype: \"session_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we came from */\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before branching a session (can be cancelled) */\nexport interface SessionBeforeBranchEvent {\n\ttype: \"session_before_branch\";\n\t/** ID of the entry to branch from */\n\tentryId: string;\n}\n\n/** Fired after branching a session */\nexport interface SessionBranchEvent {\n\ttype: \"session_branch\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\t/** Compaction preparation with messages to summarize, file ops, previous summary, etc. */\n\tpreparation: CompactionPreparation;\n\t/** Branch entries (root to current leaf). Use to inspect custom state or previous compactions. */\n\tbranchEntries: SessionEntry[];\n\t/** Optional user-provided instructions for the summary */\n\tcustomInstructions?: string;\n\t/** Abort signal - hooks should pass this to LLM calls and check it periodically */\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\t/** Whether the compaction entry was provided by a hook */\n\tfromHook: boolean;\n}\n\n/** Fired on process exit (SIGINT/SIGTERM) */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n}\n\n/** Preparation data for tree navigation (used by session_before_tree event) */\nexport interface TreePreparation {\n\t/** Node being switched to */\n\ttargetId: string;\n\t/** Current active leaf (being abandoned), null if no current position */\n\toldLeafId: string | null;\n\t/** Common ancestor of target and old leaf, null if no common ancestor */\n\tcommonAncestorId: string | null;\n\t/** Entries to summarize (old leaf back to common ancestor or compaction) */\n\tentriesToSummarize: SessionEntry[];\n\t/** Whether user chose to summarize */\n\tuserWantsSummary: boolean;\n}\n\n/** Fired before navigating to a different node in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\t/** Preparation data for the navigation */\n\tpreparation: TreePreparation;\n\t/** Abort signal - honors Escape during summarization (model available via ctx.model) */\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating to a different node in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\t/** The new active leaf, null if navigated to before first entry */\n\tnewLeafId: string | null;\n\t/** Previous active leaf, null if there was no position */\n\toldLeafId: string | null;\n\t/** Branch summary entry if one was created */\n\tsummaryEntry?: BranchSummaryEntry;\n\t/** Whether summary came from hook */\n\tfromHook?: boolean;\n}\n\n/** Union of all session event types */\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionSwitchEvent\n\t| SessionBeforeBranchEvent\n\t| SessionBranchEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n/**\n * Event data for context event.\n * Fired before each LLM call, allowing hooks to modify context non-destructively.\n * Original session messages are NOT modified - only the messages sent to the LLM are affected.\n */\nexport interface ContextEvent {\n\ttype: \"context\";\n\t/** Messages about to be sent to the LLM (deep copy, safe to modify) */\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for before_agent_start event.\n * Fired after user submits a prompt but before the agent loop starts.\n * Allows hooks to inject context that will be persisted and visible in TUI.\n */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The user's prompt text */\n\tprompt: string;\n\t/** Any images attached to the prompt */\n\timages?: ImageContent[];\n}\n\n/**\n * Event data for agent_start event.\n * Fired when an agent loop starts (once per user prompt).\n */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/**\n * Event data for agent_end event.\n */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for turn_start event.\n */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/**\n * Event data for turn_end event.\n */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/**\n * Event data for tool_call event.\n * Fired before a tool is executed. Hooks can block execution.\n */\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\t/** Tool name (e.g., \"bash\", \"edit\", \"write\") */\n\ttoolName: string;\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n}\n\n/**\n * Base interface for tool_result events.\n */\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n\t/** Full content array (text and images) */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Whether the tool execution was an error */\n\tisError: boolean;\n}\n\n/** Tool result event for bash tool */\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\n/** Tool result event for read tool */\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\n/** Tool result event for edit tool */\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\n/** Tool result event for write tool */\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\n/** Tool result event for grep tool */\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\n/** Tool result event for find tool */\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\n/** Tool result event for ls tool */\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\n/** Tool result event for custom/unknown tools */\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/**\n * Event data for tool_result event.\n * Fired after a tool is executed. Hooks can modify the result.\n * Use toolName to discriminate and get typed details.\n */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for narrowing ToolResultEvent to specific tool types\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Union of all hook event types.\n */\nexport type HookEvent =\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\n/**\n * Return type for context event handlers.\n * Allows hooks to modify messages before they're sent to the LLM.\n */\nexport interface ContextEventResult {\n\t/** Modified messages to send instead of the original */\n\tmessages?: Message[];\n}\n\n/**\n * Return type for tool_call event handlers.\n * Allows hooks to block tool execution.\n */\nexport interface ToolCallEventResult {\n\t/** If true, block the tool from executing */\n\tblock?: boolean;\n\t/** Reason for blocking (returned to LLM as error) */\n\treason?: string;\n}\n\n/**\n * Return type for tool_result event handlers.\n * Allows hooks to modify tool results.\n */\nexport interface ToolResultEventResult {\n\t/** Replacement content array (text and images) */\n\tcontent?: (TextContent | ImageContent)[];\n\t/** Replacement details */\n\tdetails?: unknown;\n\t/** Override isError flag */\n\tisError?: boolean;\n}\n\n/**\n * Return type for before_agent_start event handlers.\n * Allows hooks to inject context before the agent runs.\n */\nexport interface BeforeAgentStartEventResult {\n\t/** Message to inject into context (persisted to session, visible in TUI) */\n\tmessage?: Pick<HookMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n}\n\n/** Return type for session_before_switch handlers */\nexport interface SessionBeforeSwitchResult {\n\t/** If true, cancel the switch */\n\tcancel?: boolean;\n}\n\n/** Return type for session_before_branch handlers */\nexport interface SessionBeforeBranchResult {\n\t/**\n\t * If true, abort the branch entirely. No new session file is created,\n\t * conversation stays unchanged.\n\t */\n\tcancel?: boolean;\n\t/**\n\t * If true, the branch proceeds (new session file created, session state updated)\n\t * but the in-memory conversation is NOT rewound to the branch point.\n\t *\n\t * Use case: git-checkpoint hook that restores code state separately.\n\t * The hook handles state restoration itself, so it doesn't want the\n\t * agent's conversation to be rewound (which would lose recent context).\n\t *\n\t * - `cancel: true` → nothing happens, user stays in current session\n\t * - `skipConversationRestore: true` → branch happens, but messages stay as-is\n\t * - neither → branch happens AND messages rewind to branch point (default)\n\t */\n\tskipConversationRestore?: boolean;\n}\n\n/** Return type for session_before_compact handlers */\nexport interface SessionBeforeCompactResult {\n\t/** If true, cancel the compaction */\n\tcancel?: boolean;\n\t/** Custom compaction result - SessionManager adds id/parentId */\n\tcompaction?: CompactionResult;\n}\n\n/** Return type for session_before_tree handlers */\nexport interface SessionBeforeTreeResult {\n\t/** If true, cancel the navigation entirely */\n\tcancel?: boolean;\n\t/**\n\t * Custom summary (skips default summarizer).\n\t * Only used if preparation.userWantsSummary is true.\n\t */\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t};\n}\n\n// ============================================================================\n// Hook API\n// ============================================================================\n\n/**\n * Handler function type for each event.\n * Handlers can return R, undefined, or void (bare return statements).\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements in handlers\nexport type HookHandler<E, R = undefined> = (event: E, ctx: HookContext) => Promise<R | void> | R | void;\n\nexport interface HookMessageRenderOptions {\n\t/** Whether the view is expanded */\n\texpanded: boolean;\n}\n\n/**\n * Renderer for hook messages.\n * Hooks register these to provide custom TUI rendering for their message types.\n */\nexport type HookMessageRenderer<T = unknown> = (\n\tmessage: HookMessage<T>,\n\toptions: HookMessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n/**\n * Command registration options.\n */\nexport interface RegisteredCommand {\n\tname: string;\n\tdescription?: string;\n\n\thandler: (args: string, ctx: HookCommandContext) => Promise<void>;\n}\n\n/**\n * HookAPI passed to hook factory functions.\n * Hooks use pi.on() to subscribe to events and pi.sendMessage() to inject messages.\n */\nexport interface HookAPI {\n\t// Session events\n\ton(event: \"session_start\", handler: HookHandler<SessionStartEvent>): void;\n\ton(event: \"session_before_switch\", handler: HookHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>): void;\n\ton(event: \"session_switch\", handler: HookHandler<SessionSwitchEvent>): void;\n\ton(event: \"session_before_branch\", handler: HookHandler<SessionBeforeBranchEvent, SessionBeforeBranchResult>): void;\n\ton(event: \"session_branch\", handler: HookHandler<SessionBranchEvent>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: HookHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: HookHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: HookHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: HookHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: HookHandler<SessionTreeEvent>): void;\n\n\t// Context and agent events\n\ton(event: \"context\", handler: HookHandler<ContextEvent, ContextEventResult>): void;\n\ton(event: \"before_agent_start\", handler: HookHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: HookHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: HookHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: HookHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: HookHandler<TurnEndEvent>): void;\n\ton(event: \"tool_call\", handler: HookHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: HookHandler<ToolResultEvent, ToolResultEventResult>): void;\n\n\t/**\n\t * Send a custom message to the session. Creates a CustomMessageEntry that\n\t * participates in LLM context and can be displayed in the TUI.\n\t *\n\t * Use this when you want the LLM to see the message content.\n\t * For hook state that should NOT be sent to the LLM, use appendEntry() instead.\n\t *\n\t * @param message - The message to send\n\t * @param message.customType - Identifier for your hook (used for filtering on reload)\n\t * @param message.content - Message content (string or TextContent/ImageContent array)\n\t * @param message.display - Whether to show in TUI (true = styled display, false = hidden)\n\t * @param message.details - Optional hook-specific metadata (not sent to LLM)\n\t * @param triggerTurn - If true and agent is idle, triggers a new LLM turn. Default: false.\n\t * If agent is streaming, message is queued and triggerTurn is ignored.\n\t */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<HookMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\ttriggerTurn?: boolean,\n\t): void;\n\n\t/**\n\t * Append a custom entry to the session for hook state persistence.\n\t * Creates a CustomEntry that does NOT participate in LLM context.\n\t *\n\t * Use this to store hook-specific data that should persist across session reloads\n\t * but should NOT be sent to the LLM. On reload, scan session entries for your\n\t * customType to reconstruct hook state.\n\t *\n\t * For messages that SHOULD be sent to the LLM, use sendMessage() instead.\n\t *\n\t * @param customType - Identifier for your hook (used for filtering on reload)\n\t * @param data - Hook-specific data to persist (must be JSON-serializable)\n\t *\n\t * @example\n\t * // Store permission state\n\t * pi.appendEntry(\"permissions\", { level: \"full\", grantedAt: Date.now() });\n\t *\n\t * // On reload, reconstruct state from entries\n\t * pi.on(\"session\", async (event, ctx) => {\n\t * if (event.reason === \"start\") {\n\t * const entries = event.sessionManager.getEntries();\n\t * const myEntries = entries.filter(e => e.type === \"custom\" && e.customType === \"permissions\");\n\t * // Reconstruct state from myEntries...\n\t * }\n\t * });\n\t */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t/**\n\t * Register a custom renderer for CustomMessageEntry with a specific customType.\n\t * The renderer is called when rendering the entry in the TUI.\n\t * Return nothing to use the default renderer.\n\t */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: HookMessageRenderer<T>): void;\n\n\t/**\n\t * Register a custom slash command.\n\t * Handler receives HookCommandContext with session control methods.\n\t */\n\tregisterCommand(name: string, options: { description?: string; handler: RegisteredCommand[\"handler\"] }): void;\n\n\t/**\n\t * Execute a shell command and return stdout/stderr/code.\n\t * Supports timeout and abort signal.\n\t */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n}\n\n/**\n * Hook factory function type.\n * Hooks export a default function that receives the HookAPI.\n */\nexport type HookFactory = (pi: HookAPI) => void;\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Error emitted when a hook fails.\n */\nexport interface HookError {\n\thookPath: string;\n\tevent: string;\n\terror: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/core/hooks/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxG,OAAO,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AACpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACtF,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EACX,kBAAkB,EAClB,eAAe,EACf,sBAAsB,EACtB,YAAY,EACZ,cAAc,EACd,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,KAAK,EACX,eAAe,EACf,eAAe,EACf,eAAe,EACf,aAAa,EACb,eAAe,EACf,MAAM,mBAAmB,CAAC;AAG3B,YAAY,EAAE,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C,GAAG,IAAI,CAAC;IAE7D;;;;OAIG;IACH,uBAAuB,CAAC,CAAC,GAAG,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAEjG;;;OAGG;IACH,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAA;KAAE,GAAG,IAAI,CAAC;IAE9G;;;OAGG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAClF;AAED;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,EAAE,EAAE,OAAO,KAAK,IAAI,CAAC;AAMhD;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACd","sourcesContent":["/**\n * Hook system types.\n *\n * Hooks are TypeScript modules that can subscribe to agent lifecycle events\n * and interact with the user via UI primitives.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Message, Model, TextContent, ToolResultMessage } from \"@mariozechner/pi-ai\";\nimport type { Component, TUI } from \"@mariozechner/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.js\";\nimport type { ExecOptions, ExecResult } from \"../exec.js\";\nimport type { HookMessage } from \"../messages.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.js\";\n\nimport type { EditToolDetails } from \"../tools/edit.js\";\nimport type {\n\tBashToolDetails,\n\tFindToolDetails,\n\tGrepToolDetails,\n\tLsToolDetails,\n\tReadToolDetails,\n} from \"../tools/index.js\";\n\n// Re-export for backward compatibility\nexport type { ExecOptions, ExecResult } from \"../exec.js\";\n\n/**\n * UI context for hooks to request interactive UI from the harness.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface HookUIContext {\n\t/**\n\t * Show a selector and return the user's choice.\n\t * @param title - Title to display\n\t * @param options - Array of string options\n\t * @returns Selected option string, or null if cancelled\n\t */\n\tselect(title: string, options: string[]): Promise<string | undefined>;\n\n\t/**\n\t * Show a confirmation dialog.\n\t * @returns true if confirmed, false if cancelled\n\t */\n\tconfirm(title: string, message: string): Promise<boolean>;\n\n\t/**\n\t * Show a text input dialog.\n\t * @returns User input, or undefined if cancelled\n\t */\n\tinput(title: string, placeholder?: string): Promise<string | undefined>;\n\n\t/**\n\t * Show a notification to the user.\n\t */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/**\n\t * Set status text in the footer/status bar.\n\t * Pass undefined as text to clear the status for this key.\n\t * Text can include ANSI escape codes for styling.\n\t * Note: Newlines, tabs, and carriage returns are replaced with spaces.\n\t * The combined status line is truncated to terminal width.\n\t * @param key - Unique key to identify this status (e.g., hook name)\n\t * @param text - Status text to display, or undefined to clear\n\t */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/**\n\t * Show a custom component with keyboard focus.\n\t * The factory receives TUI, theme, and a done() callback to close the component.\n\t * Can be async for fire-and-forget work (don't await the work, just start it).\n\t *\n\t * @param factory - Function that creates the component. Call done() when finished.\n\t * @returns Promise that resolves with the value passed to done()\n\t *\n\t * @example\n\t * // Sync factory\n\t * const result = await ctx.ui.custom((tui, theme, done) => {\n\t * const component = new MyComponent(tui, theme);\n\t * component.onFinish = (value) => done(value);\n\t * return component;\n\t * });\n\t *\n\t * // Async factory with fire-and-forget work\n\t * const result = await ctx.ui.custom(async (tui, theme, done) => {\n\t * const loader = new CancellableLoader(tui, theme.fg(\"accent\"), theme.fg(\"muted\"), \"Working...\");\n\t * loader.onAbort = () => done(null);\n\t * doWork(loader.signal).then(done); // Don't await - fire and forget\n\t * return loader;\n\t * });\n\t */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t): Promise<T>;\n\n\t/**\n\t * Set the text in the core input editor.\n\t * Use this to pre-fill the input box with generated content (e.g., prompt templates, extracted questions).\n\t * @param text - Text to set in the editor\n\t */\n\tsetEditorText(text: string): void;\n\n\t/**\n\t * Get the current text from the core input editor.\n\t * @returns Current editor text\n\t */\n\tgetEditorText(): string;\n\n\t/**\n\t * Show a multi-line editor for text editing.\n\t * Supports Ctrl+G to open external editor ($VISUAL or $EDITOR).\n\t * @param title - Title describing what is being edited\n\t * @param prefill - Optional initial text\n\t * @returns Edited text, or undefined if cancelled (Escape)\n\t */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/**\n\t * Get the current theme for styling text with ANSI codes.\n\t * Use theme.fg() and theme.bg() to style status text.\n\t *\n\t * @example\n\t * const theme = ctx.ui.theme;\n\t * ctx.ui.setStatus(\"my-hook\", theme.fg(\"success\", \"✓\") + \" Ready\");\n\t */\n\treadonly theme: Theme;\n}\n\n/**\n * Context passed to hook event handlers.\n * For command handlers, see HookCommandContext which extends this with session control methods.\n */\nexport interface HookContext {\n\t/** UI methods for user interaction */\n\tui: HookUIContext;\n\t/** Whether UI is available (false in print mode) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) - use pi.sendMessage()/pi.appendEntry() for writes */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry - use for API key resolution and model retrieval */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined if no model is selected yet) */\n\tmodel: Model<any> | undefined;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Abort the current agent operation (fire-and-forget, does not wait) */\n\tabort(): void;\n\t/** Whether there are queued messages waiting to be processed */\n\thasPendingMessages(): boolean;\n}\n\n/**\n * Extended context for slash command handlers.\n * Includes session control methods that are only safe in user-initiated commands.\n *\n * These methods are not available in event handlers because they can cause\n * deadlocks when called from within the agent loop (e.g., tool_call, context events).\n */\nexport interface HookCommandContext extends HookContext {\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/**\n\t * Start a new session, optionally with a setup callback to initialize it.\n\t * The setup callback receives a writable SessionManager for the new session.\n\t *\n\t * @param options.parentSession - Path to parent session for lineage tracking\n\t * @param options.setup - Async callback to initialize the new session (e.g., append messages)\n\t * @returns Object with `cancelled: true` if a hook cancelled the new session\n\t *\n\t * @example\n\t * // Handoff: summarize current session and start fresh with context\n\t * await ctx.newSession({\n\t * parentSession: ctx.sessionManager.getSessionFile(),\n\t * setup: async (sm) => {\n\t * sm.appendMessage({ role: \"user\", content: [{ type: \"text\", text: summary }] });\n\t * }\n\t * });\n\t */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Branch from a specific entry, creating a new session file.\n\t *\n\t * @param entryId - ID of the entry to branch from\n\t * @returns Object with `cancelled: true` if a hook cancelled the branch\n\t */\n\tbranch(entryId: string): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Navigate to a different point in the session tree (in-place).\n\t *\n\t * @param targetId - ID of the entry to navigate to\n\t * @param options.summarize - Whether to summarize the abandoned branch\n\t * @returns Object with `cancelled: true` if a hook cancelled the navigation\n\t */\n\tnavigateTree(targetId: string, options?: { summarize?: boolean }): Promise<{ cancelled: boolean }>;\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired on initial session load */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we're switching to (only for \"resume\") */\n\ttargetSessionFile?: string;\n}\n\n/** Fired after switching to another session */\nexport interface SessionSwitchEvent {\n\ttype: \"session_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we came from */\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before branching a session (can be cancelled) */\nexport interface SessionBeforeBranchEvent {\n\ttype: \"session_before_branch\";\n\t/** ID of the entry to branch from */\n\tentryId: string;\n}\n\n/** Fired after branching a session */\nexport interface SessionBranchEvent {\n\ttype: \"session_branch\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\t/** Compaction preparation with messages to summarize, file ops, previous summary, etc. */\n\tpreparation: CompactionPreparation;\n\t/** Branch entries (root to current leaf). Use to inspect custom state or previous compactions. */\n\tbranchEntries: SessionEntry[];\n\t/** Optional user-provided instructions for the summary */\n\tcustomInstructions?: string;\n\t/** Abort signal - hooks should pass this to LLM calls and check it periodically */\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\t/** Whether the compaction entry was provided by a hook */\n\tfromHook: boolean;\n}\n\n/** Fired on process exit (SIGINT/SIGTERM) */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n}\n\n/** Preparation data for tree navigation (used by session_before_tree event) */\nexport interface TreePreparation {\n\t/** Node being switched to */\n\ttargetId: string;\n\t/** Current active leaf (being abandoned), null if no current position */\n\toldLeafId: string | null;\n\t/** Common ancestor of target and old leaf, null if no common ancestor */\n\tcommonAncestorId: string | null;\n\t/** Entries to summarize (old leaf back to common ancestor or compaction) */\n\tentriesToSummarize: SessionEntry[];\n\t/** Whether user chose to summarize */\n\tuserWantsSummary: boolean;\n}\n\n/** Fired before navigating to a different node in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\t/** Preparation data for the navigation */\n\tpreparation: TreePreparation;\n\t/** Abort signal - honors Escape during summarization (model available via ctx.model) */\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating to a different node in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\t/** The new active leaf, null if navigated to before first entry */\n\tnewLeafId: string | null;\n\t/** Previous active leaf, null if there was no position */\n\toldLeafId: string | null;\n\t/** Branch summary entry if one was created */\n\tsummaryEntry?: BranchSummaryEntry;\n\t/** Whether summary came from hook */\n\tfromHook?: boolean;\n}\n\n/** Union of all session event types */\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionSwitchEvent\n\t| SessionBeforeBranchEvent\n\t| SessionBranchEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n/**\n * Event data for context event.\n * Fired before each LLM call, allowing hooks to modify context non-destructively.\n * Original session messages are NOT modified - only the messages sent to the LLM are affected.\n */\nexport interface ContextEvent {\n\ttype: \"context\";\n\t/** Messages about to be sent to the LLM (deep copy, safe to modify) */\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for before_agent_start event.\n * Fired after user submits a prompt but before the agent loop starts.\n * Allows hooks to inject context that will be persisted and visible in TUI.\n */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The user's prompt text */\n\tprompt: string;\n\t/** Any images attached to the prompt */\n\timages?: ImageContent[];\n}\n\n/**\n * Event data for agent_start event.\n * Fired when an agent loop starts (once per user prompt).\n */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/**\n * Event data for agent_end event.\n */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for turn_start event.\n */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/**\n * Event data for turn_end event.\n */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/**\n * Event data for tool_call event.\n * Fired before a tool is executed. Hooks can block execution.\n */\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\t/** Tool name (e.g., \"bash\", \"edit\", \"write\") */\n\ttoolName: string;\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n}\n\n/**\n * Base interface for tool_result events.\n */\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n\t/** Full content array (text and images) */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Whether the tool execution was an error */\n\tisError: boolean;\n}\n\n/** Tool result event for bash tool */\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\n/** Tool result event for read tool */\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\n/** Tool result event for edit tool */\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\n/** Tool result event for write tool */\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\n/** Tool result event for grep tool */\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\n/** Tool result event for find tool */\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\n/** Tool result event for ls tool */\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\n/** Tool result event for custom/unknown tools */\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/**\n * Event data for tool_result event.\n * Fired after a tool is executed. Hooks can modify the result.\n * Use toolName to discriminate and get typed details.\n */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for narrowing ToolResultEvent to specific tool types\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Union of all hook event types.\n */\nexport type HookEvent =\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\n/**\n * Return type for context event handlers.\n * Allows hooks to modify messages before they're sent to the LLM.\n */\nexport interface ContextEventResult {\n\t/** Modified messages to send instead of the original */\n\tmessages?: Message[];\n}\n\n/**\n * Return type for tool_call event handlers.\n * Allows hooks to block tool execution.\n */\nexport interface ToolCallEventResult {\n\t/** If true, block the tool from executing */\n\tblock?: boolean;\n\t/** Reason for blocking (returned to LLM as error) */\n\treason?: string;\n}\n\n/**\n * Return type for tool_result event handlers.\n * Allows hooks to modify tool results.\n */\nexport interface ToolResultEventResult {\n\t/** Replacement content array (text and images) */\n\tcontent?: (TextContent | ImageContent)[];\n\t/** Replacement details */\n\tdetails?: unknown;\n\t/** Override isError flag */\n\tisError?: boolean;\n}\n\n/**\n * Return type for before_agent_start event handlers.\n * Allows hooks to inject context before the agent runs.\n */\nexport interface BeforeAgentStartEventResult {\n\t/** Message to inject into context (persisted to session, visible in TUI) */\n\tmessage?: Pick<HookMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n}\n\n/** Return type for session_before_switch handlers */\nexport interface SessionBeforeSwitchResult {\n\t/** If true, cancel the switch */\n\tcancel?: boolean;\n}\n\n/** Return type for session_before_branch handlers */\nexport interface SessionBeforeBranchResult {\n\t/**\n\t * If true, abort the branch entirely. No new session file is created,\n\t * conversation stays unchanged.\n\t */\n\tcancel?: boolean;\n\t/**\n\t * If true, the branch proceeds (new session file created, session state updated)\n\t * but the in-memory conversation is NOT rewound to the branch point.\n\t *\n\t * Use case: git-checkpoint hook that restores code state separately.\n\t * The hook handles state restoration itself, so it doesn't want the\n\t * agent's conversation to be rewound (which would lose recent context).\n\t *\n\t * - `cancel: true` → nothing happens, user stays in current session\n\t * - `skipConversationRestore: true` → branch happens, but messages stay as-is\n\t * - neither → branch happens AND messages rewind to branch point (default)\n\t */\n\tskipConversationRestore?: boolean;\n}\n\n/** Return type for session_before_compact handlers */\nexport interface SessionBeforeCompactResult {\n\t/** If true, cancel the compaction */\n\tcancel?: boolean;\n\t/** Custom compaction result - SessionManager adds id/parentId */\n\tcompaction?: CompactionResult;\n}\n\n/** Return type for session_before_tree handlers */\nexport interface SessionBeforeTreeResult {\n\t/** If true, cancel the navigation entirely */\n\tcancel?: boolean;\n\t/**\n\t * Custom summary (skips default summarizer).\n\t * Only used if preparation.userWantsSummary is true.\n\t */\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t};\n}\n\n// ============================================================================\n// Hook API\n// ============================================================================\n\n/**\n * Handler function type for each event.\n * Handlers can return R, undefined, or void (bare return statements).\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements in handlers\nexport type HookHandler<E, R = undefined> = (event: E, ctx: HookContext) => Promise<R | void> | R | void;\n\nexport interface HookMessageRenderOptions {\n\t/** Whether the view is expanded */\n\texpanded: boolean;\n}\n\n/**\n * Renderer for hook messages.\n * Hooks register these to provide custom TUI rendering for their message types.\n */\nexport type HookMessageRenderer<T = unknown> = (\n\tmessage: HookMessage<T>,\n\toptions: HookMessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n/**\n * Command registration options.\n */\nexport interface RegisteredCommand {\n\tname: string;\n\tdescription?: string;\n\n\thandler: (args: string, ctx: HookCommandContext) => Promise<void>;\n}\n\n/**\n * HookAPI passed to hook factory functions.\n * Hooks use pi.on() to subscribe to events and pi.sendMessage() to inject messages.\n */\nexport interface HookAPI {\n\t// Session events\n\ton(event: \"session_start\", handler: HookHandler<SessionStartEvent>): void;\n\ton(event: \"session_before_switch\", handler: HookHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>): void;\n\ton(event: \"session_switch\", handler: HookHandler<SessionSwitchEvent>): void;\n\ton(event: \"session_before_branch\", handler: HookHandler<SessionBeforeBranchEvent, SessionBeforeBranchResult>): void;\n\ton(event: \"session_branch\", handler: HookHandler<SessionBranchEvent>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: HookHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: HookHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: HookHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: HookHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: HookHandler<SessionTreeEvent>): void;\n\n\t// Context and agent events\n\ton(event: \"context\", handler: HookHandler<ContextEvent, ContextEventResult>): void;\n\ton(event: \"before_agent_start\", handler: HookHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: HookHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: HookHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: HookHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: HookHandler<TurnEndEvent>): void;\n\ton(event: \"tool_call\", handler: HookHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: HookHandler<ToolResultEvent, ToolResultEventResult>): void;\n\n\t/**\n\t * Send a custom message to the session. Creates a CustomMessageEntry that\n\t * participates in LLM context and can be displayed in the TUI.\n\t *\n\t * Use this when you want the LLM to see the message content.\n\t * For hook state that should NOT be sent to the LLM, use appendEntry() instead.\n\t *\n\t * @param message - The message to send\n\t * @param message.customType - Identifier for your hook (used for filtering on reload)\n\t * @param message.content - Message content (string or TextContent/ImageContent array)\n\t * @param message.display - Whether to show in TUI (true = styled display, false = hidden)\n\t * @param message.details - Optional hook-specific metadata (not sent to LLM)\n\t * @param options.triggerTurn - If true and agent is idle, triggers a new LLM turn. Default: false.\n\t * If agent is streaming, message is queued and triggerTurn is ignored.\n\t * @param options.deliverAs - How to deliver when agent is streaming. Default: \"steer\".\n\t * - \"steer\": Interrupt mid-run, delivered after current tool execution.\n\t * - \"followUp\": Wait until agent finishes all work before delivery.\n\t */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<HookMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/**\n\t * Append a custom entry to the session for hook state persistence.\n\t * Creates a CustomEntry that does NOT participate in LLM context.\n\t *\n\t * Use this to store hook-specific data that should persist across session reloads\n\t * but should NOT be sent to the LLM. On reload, scan session entries for your\n\t * customType to reconstruct hook state.\n\t *\n\t * For messages that SHOULD be sent to the LLM, use sendMessage() instead.\n\t *\n\t * @param customType - Identifier for your hook (used for filtering on reload)\n\t * @param data - Hook-specific data to persist (must be JSON-serializable)\n\t *\n\t * @example\n\t * // Store permission state\n\t * pi.appendEntry(\"permissions\", { level: \"full\", grantedAt: Date.now() });\n\t *\n\t * // On reload, reconstruct state from entries\n\t * pi.on(\"session\", async (event, ctx) => {\n\t * if (event.reason === \"start\") {\n\t * const entries = event.sessionManager.getEntries();\n\t * const myEntries = entries.filter(e => e.type === \"custom\" && e.customType === \"permissions\");\n\t * // Reconstruct state from myEntries...\n\t * }\n\t * });\n\t */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t/**\n\t * Register a custom renderer for CustomMessageEntry with a specific customType.\n\t * The renderer is called when rendering the entry in the TUI.\n\t * Return nothing to use the default renderer.\n\t */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: HookMessageRenderer<T>): void;\n\n\t/**\n\t * Register a custom slash command.\n\t * Handler receives HookCommandContext with session control methods.\n\t */\n\tregisterCommand(name: string, options: { description?: string; handler: RegisteredCommand[\"handler\"] }): void;\n\n\t/**\n\t * Execute a shell command and return stdout/stderr/code.\n\t * Supports timeout and abort signal.\n\t */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n}\n\n/**\n * Hook factory function type.\n * Hooks export a default function that receives the HookAPI.\n */\nexport type HookFactory = (pi: HookAPI) => void;\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Error emitted when a hook fails.\n */\nexport interface HookError {\n\thookPath: string;\n\tevent: string;\n\terror: string;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/hooks/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA8dH,mEAAmE;AACnE,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,iBAAiB,CAAC,CAAkB,EAA6B;IAChF,OAAO,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;AAAA,CAC9B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,cAAc,CAAC,CAAkB,EAA0B;IAC1E,OAAO,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC;AAAA,CAC3B","sourcesContent":["/**\n * Hook system types.\n *\n * Hooks are TypeScript modules that can subscribe to agent lifecycle events\n * and interact with the user via UI primitives.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Message, Model, TextContent, ToolResultMessage } from \"@mariozechner/pi-ai\";\nimport type { Component, TUI } from \"@mariozechner/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.js\";\nimport type { ExecOptions, ExecResult } from \"../exec.js\";\nimport type { HookMessage } from \"../messages.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.js\";\n\nimport type { EditToolDetails } from \"../tools/edit.js\";\nimport type {\n\tBashToolDetails,\n\tFindToolDetails,\n\tGrepToolDetails,\n\tLsToolDetails,\n\tReadToolDetails,\n} from \"../tools/index.js\";\n\n// Re-export for backward compatibility\nexport type { ExecOptions, ExecResult } from \"../exec.js\";\n\n/**\n * UI context for hooks to request interactive UI from the harness.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface HookUIContext {\n\t/**\n\t * Show a selector and return the user's choice.\n\t * @param title - Title to display\n\t * @param options - Array of string options\n\t * @returns Selected option string, or null if cancelled\n\t */\n\tselect(title: string, options: string[]): Promise<string | undefined>;\n\n\t/**\n\t * Show a confirmation dialog.\n\t * @returns true if confirmed, false if cancelled\n\t */\n\tconfirm(title: string, message: string): Promise<boolean>;\n\n\t/**\n\t * Show a text input dialog.\n\t * @returns User input, or undefined if cancelled\n\t */\n\tinput(title: string, placeholder?: string): Promise<string | undefined>;\n\n\t/**\n\t * Show a notification to the user.\n\t */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/**\n\t * Set status text in the footer/status bar.\n\t * Pass undefined as text to clear the status for this key.\n\t * Text can include ANSI escape codes for styling.\n\t * Note: Newlines, tabs, and carriage returns are replaced with spaces.\n\t * The combined status line is truncated to terminal width.\n\t * @param key - Unique key to identify this status (e.g., hook name)\n\t * @param text - Status text to display, or undefined to clear\n\t */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/**\n\t * Show a custom component with keyboard focus.\n\t * The factory receives TUI, theme, and a done() callback to close the component.\n\t * Can be async for fire-and-forget work (don't await the work, just start it).\n\t *\n\t * @param factory - Function that creates the component. Call done() when finished.\n\t * @returns Promise that resolves with the value passed to done()\n\t *\n\t * @example\n\t * // Sync factory\n\t * const result = await ctx.ui.custom((tui, theme, done) => {\n\t * const component = new MyComponent(tui, theme);\n\t * component.onFinish = (value) => done(value);\n\t * return component;\n\t * });\n\t *\n\t * // Async factory with fire-and-forget work\n\t * const result = await ctx.ui.custom(async (tui, theme, done) => {\n\t * const loader = new CancellableLoader(tui, theme.fg(\"accent\"), theme.fg(\"muted\"), \"Working...\");\n\t * loader.onAbort = () => done(null);\n\t * doWork(loader.signal).then(done); // Don't await - fire and forget\n\t * return loader;\n\t * });\n\t */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t): Promise<T>;\n\n\t/**\n\t * Set the text in the core input editor.\n\t * Use this to pre-fill the input box with generated content (e.g., prompt templates, extracted questions).\n\t * @param text - Text to set in the editor\n\t */\n\tsetEditorText(text: string): void;\n\n\t/**\n\t * Get the current text from the core input editor.\n\t * @returns Current editor text\n\t */\n\tgetEditorText(): string;\n\n\t/**\n\t * Show a multi-line editor for text editing.\n\t * Supports Ctrl+G to open external editor ($VISUAL or $EDITOR).\n\t * @param title - Title describing what is being edited\n\t * @param prefill - Optional initial text\n\t * @returns Edited text, or undefined if cancelled (Escape)\n\t */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/**\n\t * Get the current theme for styling text with ANSI codes.\n\t * Use theme.fg() and theme.bg() to style status text.\n\t *\n\t * @example\n\t * const theme = ctx.ui.theme;\n\t * ctx.ui.setStatus(\"my-hook\", theme.fg(\"success\", \"✓\") + \" Ready\");\n\t */\n\treadonly theme: Theme;\n}\n\n/**\n * Context passed to hook event handlers.\n * For command handlers, see HookCommandContext which extends this with session control methods.\n */\nexport interface HookContext {\n\t/** UI methods for user interaction */\n\tui: HookUIContext;\n\t/** Whether UI is available (false in print mode) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) - use pi.sendMessage()/pi.appendEntry() for writes */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry - use for API key resolution and model retrieval */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined if no model is selected yet) */\n\tmodel: Model<any> | undefined;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Abort the current agent operation (fire-and-forget, does not wait) */\n\tabort(): void;\n\t/** Whether there are queued messages waiting to be processed */\n\thasQueuedMessages(): boolean;\n}\n\n/**\n * Extended context for slash command handlers.\n * Includes session control methods that are only safe in user-initiated commands.\n *\n * These methods are not available in event handlers because they can cause\n * deadlocks when called from within the agent loop (e.g., tool_call, context events).\n */\nexport interface HookCommandContext extends HookContext {\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/**\n\t * Start a new session, optionally with a setup callback to initialize it.\n\t * The setup callback receives a writable SessionManager for the new session.\n\t *\n\t * @param options.parentSession - Path to parent session for lineage tracking\n\t * @param options.setup - Async callback to initialize the new session (e.g., append messages)\n\t * @returns Object with `cancelled: true` if a hook cancelled the new session\n\t *\n\t * @example\n\t * // Handoff: summarize current session and start fresh with context\n\t * await ctx.newSession({\n\t * parentSession: ctx.sessionManager.getSessionFile(),\n\t * setup: async (sm) => {\n\t * sm.appendMessage({ role: \"user\", content: [{ type: \"text\", text: summary }] });\n\t * }\n\t * });\n\t */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Branch from a specific entry, creating a new session file.\n\t *\n\t * @param entryId - ID of the entry to branch from\n\t * @returns Object with `cancelled: true` if a hook cancelled the branch\n\t */\n\tbranch(entryId: string): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Navigate to a different point in the session tree (in-place).\n\t *\n\t * @param targetId - ID of the entry to navigate to\n\t * @param options.summarize - Whether to summarize the abandoned branch\n\t * @returns Object with `cancelled: true` if a hook cancelled the navigation\n\t */\n\tnavigateTree(targetId: string, options?: { summarize?: boolean }): Promise<{ cancelled: boolean }>;\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired on initial session load */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we're switching to (only for \"resume\") */\n\ttargetSessionFile?: string;\n}\n\n/** Fired after switching to another session */\nexport interface SessionSwitchEvent {\n\ttype: \"session_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we came from */\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before branching a session (can be cancelled) */\nexport interface SessionBeforeBranchEvent {\n\ttype: \"session_before_branch\";\n\t/** ID of the entry to branch from */\n\tentryId: string;\n}\n\n/** Fired after branching a session */\nexport interface SessionBranchEvent {\n\ttype: \"session_branch\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\t/** Compaction preparation with messages to summarize, file ops, previous summary, etc. */\n\tpreparation: CompactionPreparation;\n\t/** Branch entries (root to current leaf). Use to inspect custom state or previous compactions. */\n\tbranchEntries: SessionEntry[];\n\t/** Optional user-provided instructions for the summary */\n\tcustomInstructions?: string;\n\t/** Abort signal - hooks should pass this to LLM calls and check it periodically */\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\t/** Whether the compaction entry was provided by a hook */\n\tfromHook: boolean;\n}\n\n/** Fired on process exit (SIGINT/SIGTERM) */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n}\n\n/** Preparation data for tree navigation (used by session_before_tree event) */\nexport interface TreePreparation {\n\t/** Node being switched to */\n\ttargetId: string;\n\t/** Current active leaf (being abandoned), null if no current position */\n\toldLeafId: string | null;\n\t/** Common ancestor of target and old leaf, null if no common ancestor */\n\tcommonAncestorId: string | null;\n\t/** Entries to summarize (old leaf back to common ancestor or compaction) */\n\tentriesToSummarize: SessionEntry[];\n\t/** Whether user chose to summarize */\n\tuserWantsSummary: boolean;\n}\n\n/** Fired before navigating to a different node in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\t/** Preparation data for the navigation */\n\tpreparation: TreePreparation;\n\t/** Abort signal - honors Escape during summarization (model available via ctx.model) */\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating to a different node in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\t/** The new active leaf, null if navigated to before first entry */\n\tnewLeafId: string | null;\n\t/** Previous active leaf, null if there was no position */\n\toldLeafId: string | null;\n\t/** Branch summary entry if one was created */\n\tsummaryEntry?: BranchSummaryEntry;\n\t/** Whether summary came from hook */\n\tfromHook?: boolean;\n}\n\n/** Union of all session event types */\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionSwitchEvent\n\t| SessionBeforeBranchEvent\n\t| SessionBranchEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n/**\n * Event data for context event.\n * Fired before each LLM call, allowing hooks to modify context non-destructively.\n * Original session messages are NOT modified - only the messages sent to the LLM are affected.\n */\nexport interface ContextEvent {\n\ttype: \"context\";\n\t/** Messages about to be sent to the LLM (deep copy, safe to modify) */\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for before_agent_start event.\n * Fired after user submits a prompt but before the agent loop starts.\n * Allows hooks to inject context that will be persisted and visible in TUI.\n */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The user's prompt text */\n\tprompt: string;\n\t/** Any images attached to the prompt */\n\timages?: ImageContent[];\n}\n\n/**\n * Event data for agent_start event.\n * Fired when an agent loop starts (once per user prompt).\n */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/**\n * Event data for agent_end event.\n */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for turn_start event.\n */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/**\n * Event data for turn_end event.\n */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/**\n * Event data for tool_call event.\n * Fired before a tool is executed. Hooks can block execution.\n */\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\t/** Tool name (e.g., \"bash\", \"edit\", \"write\") */\n\ttoolName: string;\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n}\n\n/**\n * Base interface for tool_result events.\n */\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n\t/** Full content array (text and images) */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Whether the tool execution was an error */\n\tisError: boolean;\n}\n\n/** Tool result event for bash tool */\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\n/** Tool result event for read tool */\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\n/** Tool result event for edit tool */\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\n/** Tool result event for write tool */\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\n/** Tool result event for grep tool */\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\n/** Tool result event for find tool */\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\n/** Tool result event for ls tool */\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\n/** Tool result event for custom/unknown tools */\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/**\n * Event data for tool_result event.\n * Fired after a tool is executed. Hooks can modify the result.\n * Use toolName to discriminate and get typed details.\n */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for narrowing ToolResultEvent to specific tool types\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Union of all hook event types.\n */\nexport type HookEvent =\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\n/**\n * Return type for context event handlers.\n * Allows hooks to modify messages before they're sent to the LLM.\n */\nexport interface ContextEventResult {\n\t/** Modified messages to send instead of the original */\n\tmessages?: Message[];\n}\n\n/**\n * Return type for tool_call event handlers.\n * Allows hooks to block tool execution.\n */\nexport interface ToolCallEventResult {\n\t/** If true, block the tool from executing */\n\tblock?: boolean;\n\t/** Reason for blocking (returned to LLM as error) */\n\treason?: string;\n}\n\n/**\n * Return type for tool_result event handlers.\n * Allows hooks to modify tool results.\n */\nexport interface ToolResultEventResult {\n\t/** Replacement content array (text and images) */\n\tcontent?: (TextContent | ImageContent)[];\n\t/** Replacement details */\n\tdetails?: unknown;\n\t/** Override isError flag */\n\tisError?: boolean;\n}\n\n/**\n * Return type for before_agent_start event handlers.\n * Allows hooks to inject context before the agent runs.\n */\nexport interface BeforeAgentStartEventResult {\n\t/** Message to inject into context (persisted to session, visible in TUI) */\n\tmessage?: Pick<HookMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n}\n\n/** Return type for session_before_switch handlers */\nexport interface SessionBeforeSwitchResult {\n\t/** If true, cancel the switch */\n\tcancel?: boolean;\n}\n\n/** Return type for session_before_branch handlers */\nexport interface SessionBeforeBranchResult {\n\t/**\n\t * If true, abort the branch entirely. No new session file is created,\n\t * conversation stays unchanged.\n\t */\n\tcancel?: boolean;\n\t/**\n\t * If true, the branch proceeds (new session file created, session state updated)\n\t * but the in-memory conversation is NOT rewound to the branch point.\n\t *\n\t * Use case: git-checkpoint hook that restores code state separately.\n\t * The hook handles state restoration itself, so it doesn't want the\n\t * agent's conversation to be rewound (which would lose recent context).\n\t *\n\t * - `cancel: true` → nothing happens, user stays in current session\n\t * - `skipConversationRestore: true` → branch happens, but messages stay as-is\n\t * - neither → branch happens AND messages rewind to branch point (default)\n\t */\n\tskipConversationRestore?: boolean;\n}\n\n/** Return type for session_before_compact handlers */\nexport interface SessionBeforeCompactResult {\n\t/** If true, cancel the compaction */\n\tcancel?: boolean;\n\t/** Custom compaction result - SessionManager adds id/parentId */\n\tcompaction?: CompactionResult;\n}\n\n/** Return type for session_before_tree handlers */\nexport interface SessionBeforeTreeResult {\n\t/** If true, cancel the navigation entirely */\n\tcancel?: boolean;\n\t/**\n\t * Custom summary (skips default summarizer).\n\t * Only used if preparation.userWantsSummary is true.\n\t */\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t};\n}\n\n// ============================================================================\n// Hook API\n// ============================================================================\n\n/**\n * Handler function type for each event.\n * Handlers can return R, undefined, or void (bare return statements).\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements in handlers\nexport type HookHandler<E, R = undefined> = (event: E, ctx: HookContext) => Promise<R | void> | R | void;\n\nexport interface HookMessageRenderOptions {\n\t/** Whether the view is expanded */\n\texpanded: boolean;\n}\n\n/**\n * Renderer for hook messages.\n * Hooks register these to provide custom TUI rendering for their message types.\n */\nexport type HookMessageRenderer<T = unknown> = (\n\tmessage: HookMessage<T>,\n\toptions: HookMessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n/**\n * Command registration options.\n */\nexport interface RegisteredCommand {\n\tname: string;\n\tdescription?: string;\n\n\thandler: (args: string, ctx: HookCommandContext) => Promise<void>;\n}\n\n/**\n * HookAPI passed to hook factory functions.\n * Hooks use pi.on() to subscribe to events and pi.sendMessage() to inject messages.\n */\nexport interface HookAPI {\n\t// Session events\n\ton(event: \"session_start\", handler: HookHandler<SessionStartEvent>): void;\n\ton(event: \"session_before_switch\", handler: HookHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>): void;\n\ton(event: \"session_switch\", handler: HookHandler<SessionSwitchEvent>): void;\n\ton(event: \"session_before_branch\", handler: HookHandler<SessionBeforeBranchEvent, SessionBeforeBranchResult>): void;\n\ton(event: \"session_branch\", handler: HookHandler<SessionBranchEvent>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: HookHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: HookHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: HookHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: HookHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: HookHandler<SessionTreeEvent>): void;\n\n\t// Context and agent events\n\ton(event: \"context\", handler: HookHandler<ContextEvent, ContextEventResult>): void;\n\ton(event: \"before_agent_start\", handler: HookHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: HookHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: HookHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: HookHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: HookHandler<TurnEndEvent>): void;\n\ton(event: \"tool_call\", handler: HookHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: HookHandler<ToolResultEvent, ToolResultEventResult>): void;\n\n\t/**\n\t * Send a custom message to the session. Creates a CustomMessageEntry that\n\t * participates in LLM context and can be displayed in the TUI.\n\t *\n\t * Use this when you want the LLM to see the message content.\n\t * For hook state that should NOT be sent to the LLM, use appendEntry() instead.\n\t *\n\t * @param message - The message to send\n\t * @param message.customType - Identifier for your hook (used for filtering on reload)\n\t * @param message.content - Message content (string or TextContent/ImageContent array)\n\t * @param message.display - Whether to show in TUI (true = styled display, false = hidden)\n\t * @param message.details - Optional hook-specific metadata (not sent to LLM)\n\t * @param triggerTurn - If true and agent is idle, triggers a new LLM turn. Default: false.\n\t * If agent is streaming, message is queued and triggerTurn is ignored.\n\t */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<HookMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\ttriggerTurn?: boolean,\n\t): void;\n\n\t/**\n\t * Append a custom entry to the session for hook state persistence.\n\t * Creates a CustomEntry that does NOT participate in LLM context.\n\t *\n\t * Use this to store hook-specific data that should persist across session reloads\n\t * but should NOT be sent to the LLM. On reload, scan session entries for your\n\t * customType to reconstruct hook state.\n\t *\n\t * For messages that SHOULD be sent to the LLM, use sendMessage() instead.\n\t *\n\t * @param customType - Identifier for your hook (used for filtering on reload)\n\t * @param data - Hook-specific data to persist (must be JSON-serializable)\n\t *\n\t * @example\n\t * // Store permission state\n\t * pi.appendEntry(\"permissions\", { level: \"full\", grantedAt: Date.now() });\n\t *\n\t * // On reload, reconstruct state from entries\n\t * pi.on(\"session\", async (event, ctx) => {\n\t * if (event.reason === \"start\") {\n\t * const entries = event.sessionManager.getEntries();\n\t * const myEntries = entries.filter(e => e.type === \"custom\" && e.customType === \"permissions\");\n\t * // Reconstruct state from myEntries...\n\t * }\n\t * });\n\t */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t/**\n\t * Register a custom renderer for CustomMessageEntry with a specific customType.\n\t * The renderer is called when rendering the entry in the TUI.\n\t * Return nothing to use the default renderer.\n\t */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: HookMessageRenderer<T>): void;\n\n\t/**\n\t * Register a custom slash command.\n\t * Handler receives HookCommandContext with session control methods.\n\t */\n\tregisterCommand(name: string, options: { description?: string; handler: RegisteredCommand[\"handler\"] }): void;\n\n\t/**\n\t * Execute a shell command and return stdout/stderr/code.\n\t * Supports timeout and abort signal.\n\t */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n}\n\n/**\n * Hook factory function type.\n * Hooks export a default function that receives the HookAPI.\n */\nexport type HookFactory = (pi: HookAPI) => void;\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Error emitted when a hook fails.\n */\nexport interface HookError {\n\thookPath: string;\n\tevent: string;\n\terror: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/hooks/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA8dH,mEAAmE;AACnE,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,iBAAiB,CAAC,CAAkB,EAA6B;IAChF,OAAO,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;AAAA,CAC9B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,cAAc,CAAC,CAAkB,EAA0B;IAC1E,OAAO,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC;AAAA,CAC3B","sourcesContent":["/**\n * Hook system types.\n *\n * Hooks are TypeScript modules that can subscribe to agent lifecycle events\n * and interact with the user via UI primitives.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Message, Model, TextContent, ToolResultMessage } from \"@mariozechner/pi-ai\";\nimport type { Component, TUI } from \"@mariozechner/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.js\";\nimport type { ExecOptions, ExecResult } from \"../exec.js\";\nimport type { HookMessage } from \"../messages.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.js\";\n\nimport type { EditToolDetails } from \"../tools/edit.js\";\nimport type {\n\tBashToolDetails,\n\tFindToolDetails,\n\tGrepToolDetails,\n\tLsToolDetails,\n\tReadToolDetails,\n} from \"../tools/index.js\";\n\n// Re-export for backward compatibility\nexport type { ExecOptions, ExecResult } from \"../exec.js\";\n\n/**\n * UI context for hooks to request interactive UI from the harness.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface HookUIContext {\n\t/**\n\t * Show a selector and return the user's choice.\n\t * @param title - Title to display\n\t * @param options - Array of string options\n\t * @returns Selected option string, or null if cancelled\n\t */\n\tselect(title: string, options: string[]): Promise<string | undefined>;\n\n\t/**\n\t * Show a confirmation dialog.\n\t * @returns true if confirmed, false if cancelled\n\t */\n\tconfirm(title: string, message: string): Promise<boolean>;\n\n\t/**\n\t * Show a text input dialog.\n\t * @returns User input, or undefined if cancelled\n\t */\n\tinput(title: string, placeholder?: string): Promise<string | undefined>;\n\n\t/**\n\t * Show a notification to the user.\n\t */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/**\n\t * Set status text in the footer/status bar.\n\t * Pass undefined as text to clear the status for this key.\n\t * Text can include ANSI escape codes for styling.\n\t * Note: Newlines, tabs, and carriage returns are replaced with spaces.\n\t * The combined status line is truncated to terminal width.\n\t * @param key - Unique key to identify this status (e.g., hook name)\n\t * @param text - Status text to display, or undefined to clear\n\t */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/**\n\t * Show a custom component with keyboard focus.\n\t * The factory receives TUI, theme, and a done() callback to close the component.\n\t * Can be async for fire-and-forget work (don't await the work, just start it).\n\t *\n\t * @param factory - Function that creates the component. Call done() when finished.\n\t * @returns Promise that resolves with the value passed to done()\n\t *\n\t * @example\n\t * // Sync factory\n\t * const result = await ctx.ui.custom((tui, theme, done) => {\n\t * const component = new MyComponent(tui, theme);\n\t * component.onFinish = (value) => done(value);\n\t * return component;\n\t * });\n\t *\n\t * // Async factory with fire-and-forget work\n\t * const result = await ctx.ui.custom(async (tui, theme, done) => {\n\t * const loader = new CancellableLoader(tui, theme.fg(\"accent\"), theme.fg(\"muted\"), \"Working...\");\n\t * loader.onAbort = () => done(null);\n\t * doWork(loader.signal).then(done); // Don't await - fire and forget\n\t * return loader;\n\t * });\n\t */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t): Promise<T>;\n\n\t/**\n\t * Set the text in the core input editor.\n\t * Use this to pre-fill the input box with generated content (e.g., prompt templates, extracted questions).\n\t * @param text - Text to set in the editor\n\t */\n\tsetEditorText(text: string): void;\n\n\t/**\n\t * Get the current text from the core input editor.\n\t * @returns Current editor text\n\t */\n\tgetEditorText(): string;\n\n\t/**\n\t * Show a multi-line editor for text editing.\n\t * Supports Ctrl+G to open external editor ($VISUAL or $EDITOR).\n\t * @param title - Title describing what is being edited\n\t * @param prefill - Optional initial text\n\t * @returns Edited text, or undefined if cancelled (Escape)\n\t */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/**\n\t * Get the current theme for styling text with ANSI codes.\n\t * Use theme.fg() and theme.bg() to style status text.\n\t *\n\t * @example\n\t * const theme = ctx.ui.theme;\n\t * ctx.ui.setStatus(\"my-hook\", theme.fg(\"success\", \"✓\") + \" Ready\");\n\t */\n\treadonly theme: Theme;\n}\n\n/**\n * Context passed to hook event handlers.\n * For command handlers, see HookCommandContext which extends this with session control methods.\n */\nexport interface HookContext {\n\t/** UI methods for user interaction */\n\tui: HookUIContext;\n\t/** Whether UI is available (false in print mode) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) - use pi.sendMessage()/pi.appendEntry() for writes */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry - use for API key resolution and model retrieval */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined if no model is selected yet) */\n\tmodel: Model<any> | undefined;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Abort the current agent operation (fire-and-forget, does not wait) */\n\tabort(): void;\n\t/** Whether there are queued messages waiting to be processed */\n\thasPendingMessages(): boolean;\n}\n\n/**\n * Extended context for slash command handlers.\n * Includes session control methods that are only safe in user-initiated commands.\n *\n * These methods are not available in event handlers because they can cause\n * deadlocks when called from within the agent loop (e.g., tool_call, context events).\n */\nexport interface HookCommandContext extends HookContext {\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/**\n\t * Start a new session, optionally with a setup callback to initialize it.\n\t * The setup callback receives a writable SessionManager for the new session.\n\t *\n\t * @param options.parentSession - Path to parent session for lineage tracking\n\t * @param options.setup - Async callback to initialize the new session (e.g., append messages)\n\t * @returns Object with `cancelled: true` if a hook cancelled the new session\n\t *\n\t * @example\n\t * // Handoff: summarize current session and start fresh with context\n\t * await ctx.newSession({\n\t * parentSession: ctx.sessionManager.getSessionFile(),\n\t * setup: async (sm) => {\n\t * sm.appendMessage({ role: \"user\", content: [{ type: \"text\", text: summary }] });\n\t * }\n\t * });\n\t */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Branch from a specific entry, creating a new session file.\n\t *\n\t * @param entryId - ID of the entry to branch from\n\t * @returns Object with `cancelled: true` if a hook cancelled the branch\n\t */\n\tbranch(entryId: string): Promise<{ cancelled: boolean }>;\n\n\t/**\n\t * Navigate to a different point in the session tree (in-place).\n\t *\n\t * @param targetId - ID of the entry to navigate to\n\t * @param options.summarize - Whether to summarize the abandoned branch\n\t * @returns Object with `cancelled: true` if a hook cancelled the navigation\n\t */\n\tnavigateTree(targetId: string, options?: { summarize?: boolean }): Promise<{ cancelled: boolean }>;\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired on initial session load */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we're switching to (only for \"resume\") */\n\ttargetSessionFile?: string;\n}\n\n/** Fired after switching to another session */\nexport interface SessionSwitchEvent {\n\ttype: \"session_switch\";\n\t/** Reason for the switch */\n\treason: \"new\" | \"resume\";\n\t/** Session file we came from */\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before branching a session (can be cancelled) */\nexport interface SessionBeforeBranchEvent {\n\ttype: \"session_before_branch\";\n\t/** ID of the entry to branch from */\n\tentryId: string;\n}\n\n/** Fired after branching a session */\nexport interface SessionBranchEvent {\n\ttype: \"session_branch\";\n\tpreviousSessionFile: string | undefined;\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\t/** Compaction preparation with messages to summarize, file ops, previous summary, etc. */\n\tpreparation: CompactionPreparation;\n\t/** Branch entries (root to current leaf). Use to inspect custom state or previous compactions. */\n\tbranchEntries: SessionEntry[];\n\t/** Optional user-provided instructions for the summary */\n\tcustomInstructions?: string;\n\t/** Abort signal - hooks should pass this to LLM calls and check it periodically */\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\t/** Whether the compaction entry was provided by a hook */\n\tfromHook: boolean;\n}\n\n/** Fired on process exit (SIGINT/SIGTERM) */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n}\n\n/** Preparation data for tree navigation (used by session_before_tree event) */\nexport interface TreePreparation {\n\t/** Node being switched to */\n\ttargetId: string;\n\t/** Current active leaf (being abandoned), null if no current position */\n\toldLeafId: string | null;\n\t/** Common ancestor of target and old leaf, null if no common ancestor */\n\tcommonAncestorId: string | null;\n\t/** Entries to summarize (old leaf back to common ancestor or compaction) */\n\tentriesToSummarize: SessionEntry[];\n\t/** Whether user chose to summarize */\n\tuserWantsSummary: boolean;\n}\n\n/** Fired before navigating to a different node in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\t/** Preparation data for the navigation */\n\tpreparation: TreePreparation;\n\t/** Abort signal - honors Escape during summarization (model available via ctx.model) */\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating to a different node in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\t/** The new active leaf, null if navigated to before first entry */\n\tnewLeafId: string | null;\n\t/** Previous active leaf, null if there was no position */\n\toldLeafId: string | null;\n\t/** Branch summary entry if one was created */\n\tsummaryEntry?: BranchSummaryEntry;\n\t/** Whether summary came from hook */\n\tfromHook?: boolean;\n}\n\n/** Union of all session event types */\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionSwitchEvent\n\t| SessionBeforeBranchEvent\n\t| SessionBranchEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n/**\n * Event data for context event.\n * Fired before each LLM call, allowing hooks to modify context non-destructively.\n * Original session messages are NOT modified - only the messages sent to the LLM are affected.\n */\nexport interface ContextEvent {\n\ttype: \"context\";\n\t/** Messages about to be sent to the LLM (deep copy, safe to modify) */\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for before_agent_start event.\n * Fired after user submits a prompt but before the agent loop starts.\n * Allows hooks to inject context that will be persisted and visible in TUI.\n */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The user's prompt text */\n\tprompt: string;\n\t/** Any images attached to the prompt */\n\timages?: ImageContent[];\n}\n\n/**\n * Event data for agent_start event.\n * Fired when an agent loop starts (once per user prompt).\n */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/**\n * Event data for agent_end event.\n */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/**\n * Event data for turn_start event.\n */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/**\n * Event data for turn_end event.\n */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/**\n * Event data for tool_call event.\n * Fired before a tool is executed. Hooks can block execution.\n */\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\t/** Tool name (e.g., \"bash\", \"edit\", \"write\") */\n\ttoolName: string;\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n}\n\n/**\n * Base interface for tool_result events.\n */\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\t/** Tool call ID */\n\ttoolCallId: string;\n\t/** Tool input parameters */\n\tinput: Record<string, unknown>;\n\t/** Full content array (text and images) */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Whether the tool execution was an error */\n\tisError: boolean;\n}\n\n/** Tool result event for bash tool */\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\n/** Tool result event for read tool */\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\n/** Tool result event for edit tool */\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\n/** Tool result event for write tool */\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\n/** Tool result event for grep tool */\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\n/** Tool result event for find tool */\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\n/** Tool result event for ls tool */\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\n/** Tool result event for custom/unknown tools */\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/**\n * Event data for tool_result event.\n * Fired after a tool is executed. Hooks can modify the result.\n * Use toolName to discriminate and get typed details.\n */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for narrowing ToolResultEvent to specific tool types\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Union of all hook event types.\n */\nexport type HookEvent =\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\n/**\n * Return type for context event handlers.\n * Allows hooks to modify messages before they're sent to the LLM.\n */\nexport interface ContextEventResult {\n\t/** Modified messages to send instead of the original */\n\tmessages?: Message[];\n}\n\n/**\n * Return type for tool_call event handlers.\n * Allows hooks to block tool execution.\n */\nexport interface ToolCallEventResult {\n\t/** If true, block the tool from executing */\n\tblock?: boolean;\n\t/** Reason for blocking (returned to LLM as error) */\n\treason?: string;\n}\n\n/**\n * Return type for tool_result event handlers.\n * Allows hooks to modify tool results.\n */\nexport interface ToolResultEventResult {\n\t/** Replacement content array (text and images) */\n\tcontent?: (TextContent | ImageContent)[];\n\t/** Replacement details */\n\tdetails?: unknown;\n\t/** Override isError flag */\n\tisError?: boolean;\n}\n\n/**\n * Return type for before_agent_start event handlers.\n * Allows hooks to inject context before the agent runs.\n */\nexport interface BeforeAgentStartEventResult {\n\t/** Message to inject into context (persisted to session, visible in TUI) */\n\tmessage?: Pick<HookMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n}\n\n/** Return type for session_before_switch handlers */\nexport interface SessionBeforeSwitchResult {\n\t/** If true, cancel the switch */\n\tcancel?: boolean;\n}\n\n/** Return type for session_before_branch handlers */\nexport interface SessionBeforeBranchResult {\n\t/**\n\t * If true, abort the branch entirely. No new session file is created,\n\t * conversation stays unchanged.\n\t */\n\tcancel?: boolean;\n\t/**\n\t * If true, the branch proceeds (new session file created, session state updated)\n\t * but the in-memory conversation is NOT rewound to the branch point.\n\t *\n\t * Use case: git-checkpoint hook that restores code state separately.\n\t * The hook handles state restoration itself, so it doesn't want the\n\t * agent's conversation to be rewound (which would lose recent context).\n\t *\n\t * - `cancel: true` → nothing happens, user stays in current session\n\t * - `skipConversationRestore: true` → branch happens, but messages stay as-is\n\t * - neither → branch happens AND messages rewind to branch point (default)\n\t */\n\tskipConversationRestore?: boolean;\n}\n\n/** Return type for session_before_compact handlers */\nexport interface SessionBeforeCompactResult {\n\t/** If true, cancel the compaction */\n\tcancel?: boolean;\n\t/** Custom compaction result - SessionManager adds id/parentId */\n\tcompaction?: CompactionResult;\n}\n\n/** Return type for session_before_tree handlers */\nexport interface SessionBeforeTreeResult {\n\t/** If true, cancel the navigation entirely */\n\tcancel?: boolean;\n\t/**\n\t * Custom summary (skips default summarizer).\n\t * Only used if preparation.userWantsSummary is true.\n\t */\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t};\n}\n\n// ============================================================================\n// Hook API\n// ============================================================================\n\n/**\n * Handler function type for each event.\n * Handlers can return R, undefined, or void (bare return statements).\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements in handlers\nexport type HookHandler<E, R = undefined> = (event: E, ctx: HookContext) => Promise<R | void> | R | void;\n\nexport interface HookMessageRenderOptions {\n\t/** Whether the view is expanded */\n\texpanded: boolean;\n}\n\n/**\n * Renderer for hook messages.\n * Hooks register these to provide custom TUI rendering for their message types.\n */\nexport type HookMessageRenderer<T = unknown> = (\n\tmessage: HookMessage<T>,\n\toptions: HookMessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n/**\n * Command registration options.\n */\nexport interface RegisteredCommand {\n\tname: string;\n\tdescription?: string;\n\n\thandler: (args: string, ctx: HookCommandContext) => Promise<void>;\n}\n\n/**\n * HookAPI passed to hook factory functions.\n * Hooks use pi.on() to subscribe to events and pi.sendMessage() to inject messages.\n */\nexport interface HookAPI {\n\t// Session events\n\ton(event: \"session_start\", handler: HookHandler<SessionStartEvent>): void;\n\ton(event: \"session_before_switch\", handler: HookHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>): void;\n\ton(event: \"session_switch\", handler: HookHandler<SessionSwitchEvent>): void;\n\ton(event: \"session_before_branch\", handler: HookHandler<SessionBeforeBranchEvent, SessionBeforeBranchResult>): void;\n\ton(event: \"session_branch\", handler: HookHandler<SessionBranchEvent>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: HookHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: HookHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: HookHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: HookHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: HookHandler<SessionTreeEvent>): void;\n\n\t// Context and agent events\n\ton(event: \"context\", handler: HookHandler<ContextEvent, ContextEventResult>): void;\n\ton(event: \"before_agent_start\", handler: HookHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: HookHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: HookHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: HookHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: HookHandler<TurnEndEvent>): void;\n\ton(event: \"tool_call\", handler: HookHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: HookHandler<ToolResultEvent, ToolResultEventResult>): void;\n\n\t/**\n\t * Send a custom message to the session. Creates a CustomMessageEntry that\n\t * participates in LLM context and can be displayed in the TUI.\n\t *\n\t * Use this when you want the LLM to see the message content.\n\t * For hook state that should NOT be sent to the LLM, use appendEntry() instead.\n\t *\n\t * @param message - The message to send\n\t * @param message.customType - Identifier for your hook (used for filtering on reload)\n\t * @param message.content - Message content (string or TextContent/ImageContent array)\n\t * @param message.display - Whether to show in TUI (true = styled display, false = hidden)\n\t * @param message.details - Optional hook-specific metadata (not sent to LLM)\n\t * @param options.triggerTurn - If true and agent is idle, triggers a new LLM turn. Default: false.\n\t * If agent is streaming, message is queued and triggerTurn is ignored.\n\t * @param options.deliverAs - How to deliver when agent is streaming. Default: \"steer\".\n\t * - \"steer\": Interrupt mid-run, delivered after current tool execution.\n\t * - \"followUp\": Wait until agent finishes all work before delivery.\n\t */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<HookMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/**\n\t * Append a custom entry to the session for hook state persistence.\n\t * Creates a CustomEntry that does NOT participate in LLM context.\n\t *\n\t * Use this to store hook-specific data that should persist across session reloads\n\t * but should NOT be sent to the LLM. On reload, scan session entries for your\n\t * customType to reconstruct hook state.\n\t *\n\t * For messages that SHOULD be sent to the LLM, use sendMessage() instead.\n\t *\n\t * @param customType - Identifier for your hook (used for filtering on reload)\n\t * @param data - Hook-specific data to persist (must be JSON-serializable)\n\t *\n\t * @example\n\t * // Store permission state\n\t * pi.appendEntry(\"permissions\", { level: \"full\", grantedAt: Date.now() });\n\t *\n\t * // On reload, reconstruct state from entries\n\t * pi.on(\"session\", async (event, ctx) => {\n\t * if (event.reason === \"start\") {\n\t * const entries = event.sessionManager.getEntries();\n\t * const myEntries = entries.filter(e => e.type === \"custom\" && e.customType === \"permissions\");\n\t * // Reconstruct state from myEntries...\n\t * }\n\t * });\n\t */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t/**\n\t * Register a custom renderer for CustomMessageEntry with a specific customType.\n\t * The renderer is called when rendering the entry in the TUI.\n\t * Return nothing to use the default renderer.\n\t */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: HookMessageRenderer<T>): void;\n\n\t/**\n\t * Register a custom slash command.\n\t * Handler receives HookCommandContext with session control methods.\n\t */\n\tregisterCommand(name: string, options: { description?: string; handler: RegisteredCommand[\"handler\"] }): void;\n\n\t/**\n\t * Execute a shell command and return stdout/stderr/code.\n\t * Supports timeout and abort signal.\n\t */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n}\n\n/**\n * Hook factory function type.\n * Hooks export a default function that receives the HookAPI.\n */\nexport type HookFactory = (pi: HookAPI) => void;\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Error emitted when a hook fails.\n */\nexport interface HookError {\n\thookPath: string;\n\tevent: string;\n\terror: string;\n}\n"]}
|
package/dist/core/messages.d.ts
CHANGED
|
@@ -22,6 +22,8 @@ export interface BashExecutionMessage {
|
|
|
22
22
|
truncated: boolean;
|
|
23
23
|
fullOutputPath?: string;
|
|
24
24
|
timestamp: number;
|
|
25
|
+
/** If true, this message is excluded from LLM context (!! prefix) */
|
|
26
|
+
excludeFromContext?: boolean;
|
|
25
27
|
}
|
|
26
28
|
/**
|
|
27
29
|
* Message type for hook-injected messages via sendMessage().
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAE9E,eAAO,MAAM,yBAAyB,wGAGrC,CAAC;AAEF,eAAO,MAAM,yBAAyB,iBAC3B,CAAC;AAEZ,eAAO,MAAM,qBAAqB,iGAGjC,CAAC;AAEF,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE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AAO,QAAQ,6BAA6B,CAAC,CAAC;IAC7C,UAAU,mBAAmB;QAC5B,aAAa,EAAE,oBAAoB,CAAC;QACpC,WAAW,EAAE,WAAW,CAAC;QACzB,aAAa,EAAE,oBAAoB,CAAC;QACpC,iBAAiB,EAAE,wBAAwB,CAAC;KAC5C;CACD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,oBAAoB,GAAG,MAAM,CAgBrE;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,oBAAoB,CAOnH;AAED,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,GACf,wBAAwB,CAO1B;AAED,wDAAwD;AACxD,wBAAgB,iBAAiB,CAChC,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,GACf,WAAW,CASb;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,EAAE,CA+ChE","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Message, TextContent } from \"@mariozechner/pi-ai\";\n\nexport const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:\n\n<summary>\n`;\n\nexport const COMPACTION_SUMMARY_SUFFIX = `\n</summary>`;\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for hook-injected messages via sendMessage().\n * These are custom messages that hooks can inject into the conversation.\n */\nexport interface HookMessage<T = unknown> {\n\trole: \"hookMessage\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string;\n\ttimestamp: number;\n}\n\nexport interface CompactionSummaryMessage {\n\trole: \"compactionSummary\";\n\tsummary: string;\n\ttokensBefore: number;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@mariozechner/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\thookMessage: HookMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t\tcompactionSummary: CompactionSummaryMessage;\n\t}\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\nexport function createCompactionSummaryMessage(\n\tsummary: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n): CompactionSummaryMessage {\n\treturn {\n\t\trole: \"compactionSummary\",\n\t\tsummary: summary,\n\t\ttokensBefore,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createHookMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n): HookMessage {\n\treturn {\n\t\trole: \"hookMessage\",\n\t\tcustomType,\n\t\tcontent,\n\t\tdisplay,\n\t\tdetails,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Compaction's generateSummary (for summarization)\n * - Custom hooks and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages\n\t\t.map((m): Message | undefined => {\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\t// Skip messages excluded from context (!! prefix)\n\t\t\t\t\tif (m.excludeFromContext) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"hookMessage\": {\n\t\t\t\t\tconst content = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\" as const, text: COMPACTION_SUMMARY_PREFIX + m.summary + COMPACTION_SUMMARY_SUFFIX },\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\":\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault:\n\t\t\t\t\t// biome-ignore lint/correctness/noSwitchDeclarations: fine\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\treturn undefined;\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n}\n"]}
|
package/dist/core/messages.js
CHANGED
|
@@ -77,6 +77,10 @@ export function convertToLlm(messages) {
|
|
|
77
77
|
.map((m) => {
|
|
78
78
|
switch (m.role) {
|
|
79
79
|
case "bashExecution":
|
|
80
|
+
// Skip messages excluded from context (!! prefix)
|
|
81
|
+
if (m.excludeFromContext) {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
80
84
|
return {
|
|
81
85
|
role: "user",
|
|
82
86
|
content: [{ type: "text", text: bashExecutionToText(m) }],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.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AAC,CAAC,SAAS;iBACtB,CAAC;YACH,KAAK,aAAa,EAAE,CAAC;gBACpB,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;gBACzG,OAAO;oBACN,IAAI,EAAE,MAAM;oBACZ,OAAO;oBACP,SAAS,EAAE,CAAC,CAAC,SAAS;iBACtB,CAAC;YACH,CAAC;YACD,KAAK,eAAe;gBACnB,OAAO;oBACN,IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,qBAAqB,GAAG,CAAC,CAAC,OAAO,GAAG,qBAAqB,EAAE,CAAC;oBACrG,SAAS,EAAE,CAAC,CAAC,SAAS;iBACtB,CAAC;YACH,KAAK,mBAAmB;gBACvB,OAAO;oBACN,IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE;wBACR,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,yBAAyB,GAAG,CAAC,CAAC,OAAO,GAAG,yBAAyB,EAAE;qBAClG;oBACD,SAAS,EAAE,CAAC,CAAC,SAAS;iBACtB,CAAC;YACH,KAAK,MAAM,CAAC;YACZ,KAAK,WAAW,CAAC;YACjB,KAAK,YAAY;gBAChB,OAAO,CAAC,CAAC;YACV;gBACC,2DAA2D;gBAC3D,MAAM,gBAAgB,GAAU,CAAC,CAAC;gBAClC,OAAO,SAAS,CAAC;QACnB,CAAC;IAAA,CACD,CAAC;SACD,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;AAAA,CACjC","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Message, TextContent } from \"@mariozechner/pi-ai\";\n\nexport const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:\n\n<summary>\n`;\n\nexport const COMPACTION_SUMMARY_SUFFIX = `\n</summary>`;\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for hook-injected messages via sendMessage().\n * These are custom messages that hooks can inject into the conversation.\n */\nexport interface HookMessage<T = unknown> {\n\trole: \"hookMessage\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string;\n\ttimestamp: number;\n}\n\nexport interface CompactionSummaryMessage {\n\trole: \"compactionSummary\";\n\tsummary: string;\n\ttokensBefore: number;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@mariozechner/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\thookMessage: HookMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t\tcompactionSummary: CompactionSummaryMessage;\n\t}\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\nexport function createCompactionSummaryMessage(\n\tsummary: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n): CompactionSummaryMessage {\n\treturn {\n\t\trole: \"compactionSummary\",\n\t\tsummary: summary,\n\t\ttokensBefore,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createHookMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n): HookMessage {\n\treturn {\n\t\trole: \"hookMessage\",\n\t\tcustomType,\n\t\tcontent,\n\t\tdisplay,\n\t\tdetails,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Compaction's generateSummary (for summarization)\n * - Custom hooks and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages\n\t\t.map((m): Message | undefined => {\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\t// Skip messages excluded from context (!! prefix)\n\t\t\t\t\tif (m.excludeFromContext) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"hookMessage\": {\n\t\t\t\t\tconst content = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\" as const, text: COMPACTION_SUMMARY_PREFIX + m.summary + COMPACTION_SUMMARY_SUFFIX },\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\":\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault:\n\t\t\t\t\t// biome-ignore lint/correctness/noSwitchDeclarations: fine\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\treturn undefined;\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n}\n"]}
|