@caupulican/pi-adaptative 0.80.103 → 0.81.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +120 -0
- package/dist/cli/session-picker.d.ts +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +7 -1
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +6 -6
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +152 -512
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +635 -4590
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/session-lane-record.d.ts +1 -1
- package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
- package/dist/core/autonomy/session-lane-record.js.map +1 -1
- package/dist/core/autonomy/status.d.ts +1 -0
- package/dist/core/autonomy/status.d.ts.map +1 -1
- package/dist/core/autonomy/status.js +1 -0
- package/dist/core/autonomy/status.js.map +1 -1
- package/dist/core/autonomy-telemetry.d.ts +80 -0
- package/dist/core/autonomy-telemetry.d.ts.map +1 -0
- package/dist/core/autonomy-telemetry.js +266 -0
- package/dist/core/autonomy-telemetry.js.map +1 -0
- package/dist/core/background-lane-controller.d.ts +186 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -0
- package/dist/core/background-lane-controller.js +691 -0
- package/dist/core/background-lane-controller.js.map +1 -0
- package/dist/core/bash-execution-controller.d.ts +51 -0
- package/dist/core/bash-execution-controller.d.ts.map +1 -0
- package/dist/core/bash-execution-controller.js +96 -0
- package/dist/core/bash-execution-controller.js.map +1 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +9 -2
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/compaction-support.d.ts +56 -0
- package/dist/core/compaction-support.d.ts.map +1 -0
- package/dist/core/compaction-support.js +99 -0
- package/dist/core/compaction-support.js.map +1 -0
- package/dist/core/context/artifact-retrieval.d.ts +1 -1
- package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
- package/dist/core/context/artifact-retrieval.js +1 -1
- package/dist/core/context/artifact-retrieval.js.map +1 -1
- package/dist/core/context/context-composition.d.ts.map +1 -1
- package/dist/core/context/context-composition.js +1 -1
- package/dist/core/context/context-composition.js.map +1 -1
- package/dist/core/context/tool-output-packer.d.ts +1 -1
- package/dist/core/context/tool-output-packer.d.ts.map +1 -1
- package/dist/core/context/tool-output-packer.js +1 -1
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +1 -1
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +223 -0
- package/dist/core/context-pipeline.d.ts.map +1 -0
- package/dist/core/context-pipeline.js +594 -0
- package/dist/core/context-pipeline.js.map +1 -0
- package/dist/core/cost/daily-usage.d.ts +1 -1
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +1 -1
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/cost/session-usage.d.ts +1 -1
- package/dist/core/cost/session-usage.d.ts.map +1 -1
- package/dist/core/cost/session-usage.js +1 -1
- package/dist/core/cost/session-usage.js.map +1 -1
- package/dist/core/delegation/session-worker-result.d.ts +1 -1
- package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
- package/dist/core/delegation/session-worker-result.js.map +1 -1
- package/dist/core/exec.d.ts +2 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +15 -9
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/index.d.ts +1 -1
- package/dist/core/export-html/index.d.ts.map +1 -1
- package/dist/core/export-html/index.js +2 -2
- package/dist/core/export-html/index.js.map +1 -1
- package/dist/core/extensions/builtin.d.ts.map +1 -1
- package/dist/core/extensions/builtin.js +2 -2
- package/dist/core/extensions/builtin.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -4
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/goal-loop-controller.d.ts +24 -0
- package/dist/core/goal-loop-controller.d.ts.map +1 -0
- package/dist/core/goal-loop-controller.js +83 -0
- package/dist/core/goal-loop-controller.js.map +1 -0
- package/dist/core/goals/goal-runtime-snapshot.d.ts +1 -1
- package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
- package/dist/core/goals/session-goal-state.d.ts +1 -1
- package/dist/core/goals/session-goal-state.d.ts.map +1 -1
- package/dist/core/goals/session-goal-state.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/learning/learning-audit.d.ts +1 -1
- package/dist/core/learning/learning-audit.d.ts.map +1 -1
- package/dist/core/learning/learning-audit.js.map +1 -1
- package/dist/core/learning/session-learning-decision.d.ts +1 -1
- package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
- package/dist/core/learning/session-learning-decision.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts +99 -0
- package/dist/core/local-runtime-controller.d.ts.map +1 -0
- package/dist/core/local-runtime-controller.js +214 -0
- package/dist/core/local-runtime-controller.js.map +1 -0
- package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
- package/dist/core/memory/providers/transcript-recall.js +1 -1
- package/dist/core/memory/providers/transcript-recall.js.map +1 -1
- package/dist/core/memory-controller.d.ts +139 -0
- package/dist/core/memory-controller.d.ts.map +1 -0
- package/dist/core/memory-controller.js +323 -0
- package/dist/core/memory-controller.js.map +1 -0
- package/dist/core/model-router/status.d.ts +1 -1
- package/dist/core/model-router/status.d.ts.map +1 -1
- package/dist/core/model-router/status.js.map +1 -1
- package/dist/core/model-router-controller.d.ts +140 -0
- package/dist/core/model-router-controller.d.ts.map +1 -0
- package/dist/core/model-router-controller.js +623 -0
- package/dist/core/model-router-controller.js.map +1 -0
- package/dist/core/model-selection-controller.d.ts +95 -0
- package/dist/core/model-selection-controller.d.ts.map +1 -0
- package/dist/core/model-selection-controller.js +252 -0
- package/dist/core/model-selection-controller.js.map +1 -0
- package/dist/core/models/model-ref.d.ts +13 -0
- package/dist/core/models/model-ref.d.ts.map +1 -1
- package/dist/core/models/model-ref.js +22 -0
- package/dist/core/models/model-ref.js.map +1 -1
- package/dist/core/profile-filter-controller.d.ts +77 -0
- package/dist/core/profile-filter-controller.d.ts.map +1 -0
- package/dist/core/profile-filter-controller.js +159 -0
- package/dist/core/profile-filter-controller.js.map +1 -0
- package/dist/core/reflection-controller.d.ts +111 -0
- package/dist/core/reflection-controller.d.ts.map +1 -0
- package/dist/core/reflection-controller.js +412 -0
- package/dist/core/reflection-controller.js.map +1 -0
- package/dist/core/research/model-fitness.d.ts +12 -0
- package/dist/core/research/model-fitness.d.ts.map +1 -1
- package/dist/core/research/model-fitness.js +21 -0
- package/dist/core/research/model-fitness.js.map +1 -1
- package/dist/core/research/session-evidence-bundle.d.ts +1 -1
- package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
- package/dist/core/research/session-evidence-bundle.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +222 -0
- package/dist/core/runtime-builder.d.ts.map +1 -0
- package/dist/core/runtime-builder.js +640 -0
- package/dist/core/runtime-builder.js.map +1 -0
- package/dist/core/sdk.d.ts +2 -2
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -4
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-analytics.d.ts +96 -0
- package/dist/core/session-analytics.d.ts.map +1 -0
- package/dist/core/session-analytics.js +331 -0
- package/dist/core/session-analytics.js.map +1 -0
- package/dist/core/session-manager-factory.d.ts +18 -0
- package/dist/core/session-manager-factory.d.ts.map +1 -0
- package/dist/core/session-manager-factory.js +32 -0
- package/dist/core/session-manager-factory.js.map +1 -0
- package/dist/core/session-tree-navigator.d.ts +68 -0
- package/dist/core/session-tree-navigator.d.ts.map +1 -0
- package/dist/core/session-tree-navigator.js +217 -0
- package/dist/core/session-tree-navigator.js.map +1 -0
- package/dist/core/system-prompt-builder.d.ts +63 -0
- package/dist/core/system-prompt-builder.d.ts.map +1 -0
- package/dist/core/system-prompt-builder.js +181 -0
- package/dist/core/system-prompt-builder.js.map +1 -0
- package/dist/core/tool-gate-controller.d.ts +36 -0
- package/dist/core/tool-gate-controller.d.ts.map +1 -0
- package/dist/core/tool-gate-controller.js +94 -0
- package/dist/core/tool-gate-controller.js.map +1 -0
- package/dist/core/tools/artifact-retrieve.d.ts.map +1 -1
- package/dist/core/tools/artifact-retrieve.js +1 -1
- package/dist/core/tools/artifact-retrieve.js.map +1 -1
- package/dist/core/tools/bash.d.ts +4 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +49 -7
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/file-mutation-queue.d.ts +6 -0
- package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-queue.js +61 -1
- package/dist/core/tools/file-mutation-queue.js.map +1 -1
- package/dist/core/tools/find.d.ts +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +1 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +1 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +1 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/read.d.ts +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +1 -1
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +13 -12
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.d.ts +59 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -0
- package/dist/modes/interactive/auth-dialogs-controller.js +398 -0
- package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -0
- package/dist/modes/interactive/auto-learn-controller.d.ts +168 -0
- package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -0
- package/dist/modes/interactive/auto-learn-controller.js +1239 -0
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -0
- package/dist/modes/interactive/autocomplete-provider.d.ts +26 -0
- package/dist/modes/interactive/autocomplete-provider.d.ts.map +1 -0
- package/dist/modes/interactive/autocomplete-provider.js +103 -0
- package/dist/modes/interactive/autocomplete-provider.js.map +1 -0
- package/dist/modes/interactive/autonomy-commands.d.ts +38 -0
- package/dist/modes/interactive/autonomy-commands.d.ts.map +1 -0
- package/dist/modes/interactive/autonomy-commands.js +142 -0
- package/dist/modes/interactive/autonomy-commands.js.map +1 -0
- package/dist/modes/interactive/clipboard-input.d.ts +37 -0
- package/dist/modes/interactive/clipboard-input.d.ts.map +1 -0
- package/dist/modes/interactive/clipboard-input.js +59 -0
- package/dist/modes/interactive/clipboard-input.js.map +1 -0
- package/dist/modes/interactive/compaction-queue.d.ts +30 -0
- package/dist/modes/interactive/compaction-queue.d.ts.map +1 -0
- package/dist/modes/interactive/compaction-queue.js +91 -0
- package/dist/modes/interactive/compaction-queue.js.map +1 -0
- 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 +1 -1
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts +1 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-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 +2 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/config-backup.d.ts +27 -0
- package/dist/modes/interactive/config-backup.d.ts.map +1 -0
- package/dist/modes/interactive/config-backup.js +146 -0
- package/dist/modes/interactive/config-backup.js.map +1 -0
- package/dist/modes/interactive/editor-overlay-host.d.ts +48 -0
- package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -0
- package/dist/modes/interactive/editor-overlay-host.js +43 -0
- package/dist/modes/interactive/editor-overlay-host.js.map +1 -0
- package/dist/modes/interactive/extension-ui-host.d.ts +165 -0
- package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -0
- package/dist/modes/interactive/extension-ui-host.js +610 -0
- package/dist/modes/interactive/extension-ui-host.js.map +1 -0
- package/dist/modes/interactive/external-editor.d.ts +18 -0
- package/dist/modes/interactive/external-editor.d.ts.map +1 -0
- package/dist/modes/interactive/external-editor.js +107 -0
- package/dist/modes/interactive/external-editor.js.map +1 -0
- package/dist/modes/interactive/history-reload-math.d.ts +24 -0
- package/dist/modes/interactive/history-reload-math.d.ts.map +1 -0
- package/dist/modes/interactive/history-reload-math.js +129 -0
- package/dist/modes/interactive/history-reload-math.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +22 -238
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +714 -5910
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/key-handlers.d.ts +46 -0
- package/dist/modes/interactive/key-handlers.d.ts.map +1 -0
- package/dist/modes/interactive/key-handlers.js +80 -0
- package/dist/modes/interactive/key-handlers.js.map +1 -0
- package/dist/modes/interactive/local-model-commands.d.ts +68 -0
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -0
- package/dist/modes/interactive/local-model-commands.js +288 -0
- package/dist/modes/interactive/local-model-commands.js.map +1 -0
- package/dist/modes/interactive/profile-menu-controller.d.ts +77 -0
- package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -0
- package/dist/modes/interactive/profile-menu-controller.js +917 -0
- package/dist/modes/interactive/profile-menu-controller.js.map +1 -0
- package/dist/modes/interactive/report-commands.d.ts +46 -0
- package/dist/modes/interactive/report-commands.d.ts.map +1 -0
- package/dist/modes/interactive/report-commands.js +255 -0
- package/dist/modes/interactive/report-commands.js.map +1 -0
- package/dist/modes/interactive/resource-display.d.ts +73 -0
- package/dist/modes/interactive/resource-display.d.ts.map +1 -0
- package/dist/modes/interactive/resource-display.js +278 -0
- package/dist/modes/interactive/resource-display.js.map +1 -0
- package/dist/modes/interactive/resource-shell-commands.d.ts +64 -0
- package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -0
- package/dist/modes/interactive/resource-shell-commands.js +202 -0
- package/dist/modes/interactive/resource-shell-commands.js.map +1 -0
- package/dist/modes/interactive/session-flow-commands.d.ts +139 -0
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -0
- package/dist/modes/interactive/session-flow-commands.js +458 -0
- package/dist/modes/interactive/session-flow-commands.js.map +1 -0
- package/dist/modes/interactive/session-io-commands.d.ts +73 -0
- package/dist/modes/interactive/session-io-commands.d.ts.map +1 -0
- package/dist/modes/interactive/session-io-commands.js +202 -0
- package/dist/modes/interactive/session-io-commands.js.map +1 -0
- package/dist/modes/interactive/settings-selector-flow.d.ts +42 -0
- package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -0
- package/dist/modes/interactive/settings-selector-flow.js +287 -0
- package/dist/modes/interactive/settings-selector-flow.js.map +1 -0
- package/dist/modes/interactive/signal-lifecycle.d.ts +55 -0
- package/dist/modes/interactive/signal-lifecycle.d.ts.map +1 -0
- package/dist/modes/interactive/signal-lifecycle.js +177 -0
- package/dist/modes/interactive/signal-lifecycle.js.map +1 -0
- package/dist/modes/interactive/startup-checks.d.ts +38 -0
- package/dist/modes/interactive/startup-checks.d.ts.map +1 -0
- package/dist/modes/interactive/startup-checks.js +189 -0
- package/dist/modes/interactive/startup-checks.js.map +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +1 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/utils/paths.d.ts +2 -14
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +5 -30
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/process-memory.d.ts +8 -0
- package/dist/utils/process-memory.d.ts.map +1 -0
- package/dist/utils/process-memory.js +11 -0
- package/dist/utils/process-memory.js.map +1 -0
- package/dist/utils/shell.d.ts +0 -9
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +0 -37
- package/dist/utils/shell.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/11-sessions.ts +8 -8
- package/examples/sdk/13-session-runtime.ts +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/compaction/branch-summarization.d.ts +0 -88
- package/dist/core/compaction/branch-summarization.d.ts.map +0 -1
- package/dist/core/compaction/branch-summarization.js +0 -243
- package/dist/core/compaction/branch-summarization.js.map +0 -1
- package/dist/core/compaction/compaction.d.ts +0 -143
- package/dist/core/compaction/compaction.d.ts.map +0 -1
- package/dist/core/compaction/compaction.js +0 -659
- package/dist/core/compaction/compaction.js.map +0 -1
- package/dist/core/compaction/index.d.ts +0 -7
- package/dist/core/compaction/index.d.ts.map +0 -1
- package/dist/core/compaction/index.js +0 -7
- package/dist/core/compaction/index.js.map +0 -1
- package/dist/core/compaction/utils.d.ts +0 -38
- package/dist/core/compaction/utils.d.ts.map +0 -1
- package/dist/core/compaction/utils.js +0 -153
- package/dist/core/compaction/utils.js.map +0 -1
- package/dist/core/message-retention.d.ts +0 -26
- package/dist/core/message-retention.d.ts.map +0 -1
- package/dist/core/message-retention.js +0 -95
- package/dist/core/message-retention.js.map +0 -1
- package/dist/core/messages.d.ts +0 -77
- package/dist/core/messages.d.ts.map +0 -1
- package/dist/core/messages.js +0 -123
- package/dist/core/messages.js.map +0 -1
- package/dist/core/session-manager.d.ts +0 -337
- package/dist/core/session-manager.d.ts.map +0 -1
- package/dist/core/session-manager.js +0 -1328
- package/dist/core/session-manager.js.map +0 -1
- package/dist/core/tools/truncate.d.ts +0 -70
- package/dist/core/tools/truncate.d.ts.map +0 -1
- package/dist/core/tools/truncate.js +0 -215
- package/dist/core/tools/truncate.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-builder.js","sourceRoot":"","sources":["../../src/core/runtime-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAKH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAStD,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,EAKN,eAAe,EAKf,mBAAmB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAMlE,OAAO,EACN,6BAA6B,GAG7B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,yBAAyB,EAAmB,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EACN,qBAAqB,EACrB,eAAe,EACf,gCAAgC,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EA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AC,EAAE,CAAC;gBACvB,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC;YACjB,CAAC;YAED,iCAAiC;YACjC,IAAI,CAAC,IAAI,CAAC,uBAAuB,EAAE,CAAC;QACrC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,oCAAoC;YACpC,IAAI,CAAC;gBACJ,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;YACrB,CAAC;YAAC,MAAM,CAAC;gBACR,6DAA6D;YAC9D,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Runtime build & reload: the session's tool-registry assembly and the self-modification-safe\n * extension reload path. Owns building the base tool definitions, wrapping them into the live tool\n * registry (`_refreshToolRegistry`), constructing the {@link ExtensionRunner} for a rebuilt runtime\n * (`_buildRuntime`), and the repo's self-modification safety crown jewel: the preflight-guarded\n * `reload()` with its snapshot / doctor / commit-or-rollback sequence, plus the single-extension\n * live load/unload/reconcile operations that rebuild the runtime in place.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns ONLY the tool-registry\n * state — the base tool definitions, the wrapped tool registry, the definition registry, and the\n * per-tool prompt snippet/guideline maps. Everything else the build & reload touch — the live\n * {@link ExtensionRunner}, the agent's tool/system-prompt state, the base system prompt, the\n * resource loader, the session/settings managers, the model registry, the profile tool filter and\n * its warning sinks, the requested-active-tool-names request, the memory subsystem, and the many\n * host callbacks the rebuilt tools/runtime are wired to — is reached through narrow deps accessors\n * that read and write the SAME storage the host owns today.\n *\n * Snapshot-ownership boundary (deliberate, load-bearing for reload safety): the reload snapshot\n * spans state owned by OTHER collaborators — the extension runner and its ref, `agent.state.tools`\n * / `agent.state.systemPrompt`, and `_baseSystemPrompt`. Those are captured and restored through\n * {@link RuntimeBuilderDeps} get/set accessors so save/restore mutate exactly the host/agent fields\n * they mutated before extraction; only the five tool-registry maps are captured by direct field\n * reference here (this builder owns them). The `_extensionRunnerRef.current` update folds into\n * {@link RuntimeBuilderDeps.setExtensionRunner} (the same field-then-ref pattern the host used at\n * every assignment site), so no observer runs between the two writes.\n *\n * Host-binding boundary (deliberate): `_bindExtensionCore` — which exposes the SESSION's own public\n * surface (sendMessage, setModel, compact, abort, reload, …) to the extension runner — stays\n * host-side and is invoked from {@link buildRuntime} via {@link RuntimeBuilderDeps.bindExtensionCore};\n * it is host identity, not build logic, and moving it would only re-export ~30 host methods through\n * deps to hand them straight back. The host keeps one-line delegations for the public reload /\n * load / unload / reconcile API and for `getAllTools` / `getToolDefinition`, and a private\n * `_refreshToolRegistry` delegation for its internal callers.\n */\n\nimport type { Agent, AgentContext, AgentMessage, AgentTool } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model, Usage } from \"@caupulican/pi-ai\";\nimport { resetApiProviders } from \"@caupulican/pi-ai\";\nimport type {\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session.ts\";\nimport type { ArtifactStore } from \"./context/context-artifacts.ts\";\nimport type { MemoryPromptInclusionReport, MemoryRetrievalDiagnostics } from \"./context/memory-diagnostics.ts\";\nimport type { ContextGcReport } from \"./context-gc.ts\";\nimport { createCoreDiagnosticsToolDefinitions } from \"./extensions/builtin.ts\";\nimport {\n\ttype ContextUsage,\n\ttype Extension,\n\ttype ExtensionCommandContextActions,\n\ttype ExtensionErrorListener,\n\tExtensionRunner,\n\ttype ExtensionUIContext,\n\ttype ShutdownHandler,\n\ttype ToolDefinition,\n\ttype ToolInfo,\n\twrapRegisteredTools,\n} from \"./extensions/index.ts\";\nimport { disposeExtensionEventSubscriptions } from \"./extensions/loader.ts\";\nimport { emitSessionShutdownEvent } from \"./extensions/runner.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport {\n\tmatchesResourceProfilePattern,\n\ttype ResourceProfileFilterSettings,\n\ttype SettingsManager,\n} from \"./settings-manager.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\nimport {\n\tbuildReflexUserPrompt,\n\tparseReflexPlan,\n\tREFLEX_INTERPRETER_SYSTEM_PROMPT,\n} from \"./toolkit/reflex-interpreter.ts\";\nimport { executeToolkitScript } from \"./toolkit/script-runner.ts\";\nimport { createDelegateToolDefinition } from \"./tools/delegate.ts\";\nimport { createGoalToolDefinition } from \"./tools/goal.ts\";\nimport { createAllToolDefinitions } from \"./tools/index.ts\";\nimport { createModelFitnessToolDefinition } from \"./tools/model-fitness.ts\";\nimport { createRunToolkitScriptToolDefinition } from \"./tools/run-toolkit-script.ts\";\nimport { createToolDefinitionFromAgentTool } from \"./tools/tool-definition-wrapper.ts\";\n\ninterface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\ninterface ReloadRuntimeSnapshot {\n\textensionRunner: ExtensionRunner;\n\tbaseToolDefinitions: Map<string, ToolDefinition>;\n\ttoolRegistry: Map<string, AgentTool>;\n\ttoolDefinitions: Map<string, ToolDefinitionEntry>;\n\ttoolPromptSnippets: Map<string, string>;\n\ttoolPromptGuidelines: Map<string, string[]>;\n\tagentTools: AgentTool[];\n\tagentSystemPrompt: string;\n\tbaseSystemPrompt: string;\n}\n\nexport interface RuntimeBuilderDeps {\n\t/** Live agent — the snapshot/doctor read and restore its `state.tools` / `state.systemPrompt`. */\n\tgetAgent(): Agent;\n\t/** Workspace root, passed to the tool-definition factory and the extension runner. */\n\tgetCwd(): string;\n\t/** Session log, passed to the extension runner. */\n\tgetSessionManager(): SessionManager;\n\t/** Tool/shell/toolkit/resource settings + reload target (settingsManager.reload()). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Model registry, passed to the extension runner and profile model re-resolution. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Extension/skill/prompt/theme discovery + the reload/commit/rollback generation swap. */\n\tgetResourceLoader(): ResourceLoader;\n\n\t/** Live extension runner (host-owned; pervasive). */\n\tgetExtensionRunner(): ExtensionRunner;\n\t/** Store the extension runner AND update the Agent's mutable `_extensionRunnerRef.current` (both together). */\n\tsetExtensionRunner(runner: ExtensionRunner): void;\n\t/** Base (extension-free) system prompt; captured/restored by the reload snapshot. */\n\tgetBaseSystemPrompt(): string;\n\tsetBaseSystemPrompt(prompt: string): void;\n\n\t/** SDK-provided plain tools, synthesized into the registry alongside built-ins. */\n\tgetCustomTools(): ToolDefinition[];\n\t/** Optional plain-tool override; when set, the built-in factory + core diagnostics are skipped. */\n\tgetBaseToolsOverride(): Record<string, AgentTool> | undefined;\n\t/** Pre-filter tool REQUEST (never the capability/profile-filtered active set) preserved across a rebuild. */\n\tgetRequestedActiveToolNames(): string[] | undefined;\n\tsetRequestedActiveToolNames(names: string[] | undefined): void;\n\n\t/** Resource-profile tool allow/block filter + the raw allow/exclude sets applied during registry build. */\n\tgetToolProfileFilter(): Required<ResourceProfileFilterSettings> | undefined;\n\tsetToolProfileFilter(filter: Required<ResourceProfileFilterSettings> | undefined): void;\n\tgetAllowedToolNames(): Set<string> | undefined;\n\tgetExcludedToolNames(): Set<string> | undefined;\n\t/** Re-derive the profile tool filter from freshly reloaded settings (reload only). */\n\tderiveToolProfileFilter(): Required<ResourceProfileFilterSettings>;\n\t/** True when a tool/command name survives the active profile's allow/block + user allow/exclude. */\n\tisToolOrCommandAllowedByProfile(name: string): boolean;\n\t/** Filter the loaded extensions through the active resource profile (records inert/denied warnings host-side). */\n\tfilterExtensionsForRuntime(extensions: Extension[]): Extension[];\n\t/** Sink for the G13 unbound-profile-tool-grant warnings surfaced in /context. */\n\tsetUnboundToolGrantWarnings(warnings: string[]): void;\n\n\t/** Currently-active tool names (reads agent.state.tools; the pre-filter fallback for a rebuild). */\n\tgetActiveToolNames(): string[];\n\t/** Apply the recomputed active set (capability filter + companion auto-activation live here). */\n\tsetActiveToolsByName(toolNames: string[]): void;\n\t/** Normalize a tool's prompt snippet / guidelines through the system-prompt builder. */\n\tnormalizePromptSnippet(text: string | undefined): string | undefined;\n\tnormalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\n\t/** Wire the session's own public surface into a freshly-built runner (host identity; stays host-side). */\n\tbindExtensionCore(runner: ExtensionRunner): void;\n\t/** Re-apply UI context / mode / command-context / error subscription to a runner. */\n\tapplyExtensionBindings(runner: ExtensionRunner): void;\n\t/** Re-run resource discovery for the active extensions (reload only). */\n\textendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void>;\n\t/** Re-apply the active profile's model/thinking from reloaded settings (reload only). */\n\treapplyActiveProfileModelSettings(): Promise<void>;\n\t/** Notify extensions-changed listeners after a single-extension live op. */\n\tnotifyExtensionsChanged(): void;\n\n\t/** Session-scoped tool-output artifact store for grep/find/artifact_retrieve (gated on the profile). */\n\tgetToolArtifactStore(): ArtifactStore;\n\n\t/** Live memory manager — its provider tools join the registry. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Memory retrieval + prompt-inclusion diagnostics for the core diagnostics tool. */\n\tgetMemoryAuditDiagnostics(): { retrieval: MemoryRetrievalDiagnostics; promptInclusion: MemoryPromptInclusionReport };\n\t/** Drop extension-contributed pending memory providers before a reload re-registers them. */\n\tclearPendingMemoryProviders(): void;\n\t/** (Re)derive the memory subsystem from reloaded settings/providers. */\n\tinitializeMemory(): Promise<void>;\n\n\t/** Goal-tool state accessors. */\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\tsaveGoalStateSnapshot(state: GoalState): string;\n\t/** Context-gc report for the core diagnostics tool. */\n\tgetContextGcReport(messages: AgentMessage[]): ContextGcReport;\n\t/** Worker-delegation runner for the delegate tool. */\n\trunWorkerDelegationOnce(request: {\n\t\tinstructions: string;\n\t\tsystemPrompt?: string;\n\t}): Promise<WorkerDelegationRunOutcome>;\n\t/** Model-fitness probe for the model_fitness tool. */\n\trunModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }>;\n\t/** Fitness-gated reflex-brain model resolver (run_toolkit_script interpretation). */\n\tresolveCurationModelIfFit(): Model<Api> | undefined;\n\t/** One-shot, tool-less LLM call — the reflex-brain interpreter rides this. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Roll reflex-brain spend into spawned-usage accounting. */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\n\t/** Post-rebuild doctor helpers (validate the rebuilt runtime can render a context). */\n\tcreateAgentContextSnapshot(): AgentContext;\n\tgetContextUsage(): ContextUsage | undefined;\n\n\t/** Reload/live-op preflight refusal guards (identical refusal behavior; host-checked). */\n\tisStreaming(): boolean;\n\tisCompacting(): boolean;\n\n\t/** Extension bindings present — gate for re-emitting session_start on reload. */\n\tgetExtensionUIContext(): ExtensionUIContext | undefined;\n\tgetExtensionCommandContextActions(): ExtensionCommandContextActions | undefined;\n\tgetExtensionShutdownHandler(): ShutdownHandler | undefined;\n\tgetExtensionErrorListener(): ExtensionErrorListener | undefined;\n}\n\n/**\n * Owns the tool-registry build and the self-modification-safe extension reload extracted from\n * {@link AgentSession}. See the module header for the snapshot-ownership and host-binding boundaries.\n */\nexport class RuntimeBuilder {\n\t// Tool registry for extension getTools/setTools\n\tprivate _toolRegistry: Map<string, AgentTool> = new Map();\n\tprivate _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();\n\tprivate _toolPromptSnippets: Map<string, string> = new Map();\n\tprivate _toolPromptGuidelines: Map<string, string[]> = new Map();\n\tprivate _baseToolDefinitions: Map<string, ToolDefinition> = new Map();\n\n\tprivate readonly deps: RuntimeBuilderDeps;\n\n\tconstructor(deps: RuntimeBuilderDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Whether a tool name is present in the live wrapped registry. */\n\thasTool(name: string): boolean {\n\t\treturn this._toolRegistry.has(name);\n\t}\n\n\t/** The live wrapped tool for a name, if registered (activation lookup). */\n\tgetRegisteredTool(name: string): AgentTool | undefined {\n\t\treturn this._toolRegistry.get(name);\n\t}\n\n\t/** A registered tool's normalized prompt snippet, if any. */\n\tgetToolPromptSnippet(name: string): string | undefined {\n\t\treturn this._toolPromptSnippets.get(name);\n\t}\n\n\t/** A registered tool's normalized prompt guidelines, if any. */\n\tgetToolPromptGuidelines(name: string): string[] | undefined {\n\t\treturn this._toolPromptGuidelines.get(name);\n\t}\n\n\t/**\n\t * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.\n\t */\n\tgetAllTools(): ToolInfo[] {\n\t\treturn Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({\n\t\t\tname: definition.name,\n\t\t\tdescription: definition.description,\n\t\t\tparameters: definition.parameters,\n\t\t\tpromptGuidelines: definition.promptGuidelines,\n\t\t\tsourceInfo,\n\t\t}));\n\t}\n\n\tgetToolDefinition(name: string): ToolDefinition | undefined {\n\t\treturn this._toolDefinitions.get(name)?.definition;\n\t}\n\n\trefreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void {\n\t\tconst previousRegistryNames = new Set(this._toolRegistry.keys());\n\t\t// Re-derive from the pre-filter REQUEST, never from agent.state.tools: the active set is\n\t\t// capability/profile-filtered, so feeding it back through setActiveToolsByName would\n\t\t// permanently shrink what a later switch to a larger model (or permissive profile) restores.\n\t\tconst previousActiveToolNames = this.deps.getRequestedActiveToolNames() ?? this.deps.getActiveToolNames();\n\t\tconst allowedToolNames = this.deps.getAllowedToolNames();\n\t\tconst excludedToolNames = this.deps.getExcludedToolNames();\n\t\tconst toolProfileFilter = this.deps.getToolProfileFilter();\n\t\tconst isAllowedTool = (name: string): boolean => {\n\t\t\tif (allowedToolNames && !allowedToolNames.has(name)) return false;\n\t\t\tif (excludedToolNames?.has(name)) return false;\n\t\t\tif (!toolProfileFilter) return true;\n\t\t\tif (toolProfileFilter.allow.length > 0 && !matchesResourceProfilePattern(name, toolProfileFilter.allow)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (matchesResourceProfilePattern(name, toolProfileFilter.block)) return false;\n\t\t\treturn true;\n\t\t};\n\n\t\tconst registeredTools = this.deps.getExtensionRunner().getAllRegisteredTools();\n\t\tconst allCustomTools = [\n\t\t\t...registeredTools,\n\t\t\t...this.deps.getCustomTools().map((definition) => ({\n\t\t\t\tdefinition,\n\t\t\t\tsourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: \"sdk\" }),\n\t\t\t})),\n\t\t\t// Memory subsystem provider tools (e.g. file-store's `memory` tool).\n\t\t\t...this.deps\n\t\t\t\t.getMemoryManager()\n\t\t\t\t.getToolDefinitions()\n\t\t\t\t.map((definition) => ({\n\t\t\t\t\tdefinition,\n\t\t\t\t\tsourceInfo: createSyntheticSourceInfo(`<memory:${definition.name}>`, { source: \"sdk\" }),\n\t\t\t\t})),\n\t\t].filter((tool) => isAllowedTool(tool.definition.name));\n\t\tconst definitionRegistry = new Map<string, ToolDefinitionEntry>(\n\t\t\tArray.from(this._baseToolDefinitions.entries())\n\t\t\t\t.filter(([name]) => isAllowedTool(name))\n\t\t\t\t.map(([name, definition]) => [\n\t\t\t\t\tname,\n\t\t\t\t\t{\n\t\t\t\t\t\tdefinition,\n\t\t\t\t\t\tsourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: \"builtin\" }),\n\t\t\t\t\t},\n\t\t\t\t]),\n\t\t);\n\t\tfor (const tool of allCustomTools) {\n\t\t\tdefinitionRegistry.set(tool.definition.name, {\n\t\t\t\tdefinition: tool.definition,\n\t\t\t\tsourceInfo: tool.sourceInfo,\n\t\t\t});\n\t\t}\n\t\tthis._toolDefinitions = definitionRegistry;\n\t\tthis._toolPromptSnippets = new Map(\n\t\t\tArray.from(definitionRegistry.values())\n\t\t\t\t.map(({ definition }) => {\n\t\t\t\t\tconst snippet = this.deps.normalizePromptSnippet(definition.promptSnippet);\n\t\t\t\t\treturn snippet ? ([definition.name, snippet] as const) : undefined;\n\t\t\t\t})\n\t\t\t\t.filter((entry): entry is readonly [string, string] => entry !== undefined),\n\t\t);\n\t\tthis._toolPromptGuidelines = new Map(\n\t\t\tArray.from(definitionRegistry.values())\n\t\t\t\t.map(({ definition }) => {\n\t\t\t\t\tconst guidelines = this.deps.normalizePromptGuidelines(definition.promptGuidelines);\n\t\t\t\t\treturn guidelines.length > 0 ? ([definition.name, guidelines] as const) : undefined;\n\t\t\t\t})\n\t\t\t\t.filter((entry): entry is readonly [string, string[]] => entry !== undefined),\n\t\t);\n\t\tconst runner = this.deps.getExtensionRunner();\n\t\tconst wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);\n\t\tconst wrappedBuiltInTools = wrapRegisteredTools(\n\t\t\tArray.from(this._baseToolDefinitions.values())\n\t\t\t\t.filter((definition) => isAllowedTool(definition.name))\n\t\t\t\t.map((definition) => ({\n\t\t\t\t\tdefinition,\n\t\t\t\t\tsourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: \"builtin\" }),\n\t\t\t\t})),\n\t\t\trunner,\n\t\t);\n\n\t\tconst toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));\n\t\tfor (const tool of wrappedExtensionTools as AgentTool[]) {\n\t\t\ttoolRegistry.set(tool.name, tool);\n\t\t}\n\t\tthis._toolRegistry = toolRegistry;\n\n\t\tconst requestedBase = options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames];\n\t\tconst nextActiveToolNames = requestedBase.filter((name) => isAllowedTool(name));\n\n\t\tconst autoActivated: string[] = [];\n\t\tif (allowedToolNames) {\n\t\t\tfor (const toolName of this._toolRegistry.keys()) {\n\t\t\t\tif (allowedToolNames.has(toolName)) {\n\t\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t\t\tautoActivated.push(toolName);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (options?.includeAllExtensionTools) {\n\t\t\tfor (const tool of wrappedExtensionTools) {\n\t\t\t\tnextActiveToolNames.push(tool.name);\n\t\t\t\tautoActivated.push(tool.name);\n\t\t\t}\n\t\t} else if (!options?.activeToolNames) {\n\t\t\tfor (const toolName of this._toolRegistry.keys()) {\n\t\t\t\tif (!previousRegistryNames.has(toolName)) {\n\t\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t\t\tautoActivated.push(toolName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Strict UAC: the active profile is the COMPLETE grant, so a tool the profile names\n\t\t// explicitly is itself a request for that tool — it must ACTIVATE from the registry even\n\t\t// if the session never requested it. Without this, activation is only ever the requested\n\t\t// defaults ∩ allow-list, and a profile granting non-default tools (a search-only profile's\n\t\t// grep/find) yields an empty or truncated tool set on load and /reload. A blanket \"*\"\n\t\t// stays grant-only: activation then still derives from the request/defaults above.\n\t\tconst explicitAllowPatterns = toolProfileFilter?.allow.filter((pattern) => pattern !== \"*\") ?? [];\n\t\tif (explicitAllowPatterns.length > 0) {\n\t\t\tconst boundPatterns = new Set<string>();\n\t\t\tfor (const toolName of this._toolRegistry.keys()) {\n\t\t\t\tif (!isAllowedTool(toolName)) continue;\n\t\t\t\tfor (const pattern of explicitAllowPatterns) {\n\t\t\t\t\tif (matchesResourceProfilePattern(toolName, [pattern])) boundPatterns.add(pattern);\n\t\t\t\t}\n\t\t\t\tif (matchesResourceProfilePattern(toolName, explicitAllowPatterns)) {\n\t\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t\t\tautoActivated.push(toolName);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// G13: an explicit grant that binds to NO registered tool is a silent no-op — typo'd\n\t\t\t// name, or the owning extension is not granted/loaded. Surface it.\n\t\t\tthis.deps.setUnboundToolGrantWarnings(\n\t\t\t\texplicitAllowPatterns\n\t\t\t\t\t.filter((pattern) => !boundPatterns.has(pattern))\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(pattern) =>\n\t\t\t\t\t\t\t`profile tool grant \"${pattern}\" binds to no registered tool (typo, or the owning extension is not granted/loaded)`,\n\t\t\t\t\t),\n\t\t\t);\n\t\t} else {\n\t\t\tthis.deps.setUnboundToolGrantWarnings([]);\n\t\t}\n\n\t\t// artifact_retrieve companion auto-activation is enforced inside\n\t\t// setActiveToolsByName() itself (not duplicated here), so every activation path --\n\t\t// including the public, extension-exposed setActiveTools() -- gets the same\n\t\t// guarantee, not just this settings/profile refresh flow.\n\t\tthis.deps.setActiveToolsByName([...new Set(nextActiveToolNames)]);\n\t\t// setActiveToolsByName just stored the profile-filtered ACTIVE set as the request; restore\n\t\t// the true pre-filter request (plus this refresh's auto-activations) so an internal refresh\n\t\t// can never permanently narrow it.\n\t\tthis.deps.setRequestedActiveToolNames([...new Set([...requestedBase, ...autoActivated])]);\n\t}\n\n\tprivate _createReloadRuntimeSnapshot(): ReloadRuntimeSnapshot {\n\t\tconst agent = this.deps.getAgent();\n\t\treturn {\n\t\t\textensionRunner: this.deps.getExtensionRunner(),\n\t\t\tbaseToolDefinitions: this._baseToolDefinitions,\n\t\t\ttoolRegistry: this._toolRegistry,\n\t\t\ttoolDefinitions: this._toolDefinitions,\n\t\t\ttoolPromptSnippets: this._toolPromptSnippets,\n\t\t\ttoolPromptGuidelines: this._toolPromptGuidelines,\n\t\t\tagentTools: agent.state.tools,\n\t\t\tagentSystemPrompt: agent.state.systemPrompt,\n\t\t\tbaseSystemPrompt: this.deps.getBaseSystemPrompt(),\n\t\t};\n\t}\n\n\tprivate _restoreReloadRuntimeSnapshot(snapshot: ReloadRuntimeSnapshot): void {\n\t\t// setExtensionRunner restores both _extensionRunner and _extensionRunnerRef.current together\n\t\t// (the same field-then-ref pair the host wrote at every assignment site); nothing reads the\n\t\t// ref between the two writes, so folding them is unobservable.\n\t\tthis.deps.setExtensionRunner(snapshot.extensionRunner);\n\t\tthis._baseToolDefinitions = snapshot.baseToolDefinitions;\n\t\tthis._toolRegistry = snapshot.toolRegistry;\n\t\tthis._toolDefinitions = snapshot.toolDefinitions;\n\t\tthis._toolPromptSnippets = snapshot.toolPromptSnippets;\n\t\tthis._toolPromptGuidelines = snapshot.toolPromptGuidelines;\n\t\tconst agent = this.deps.getAgent();\n\t\tagent.state.tools = snapshot.agentTools;\n\t\tagent.state.systemPrompt = snapshot.agentSystemPrompt;\n\t\tthis.deps.setBaseSystemPrompt(snapshot.baseSystemPrompt);\n\t\tthis.deps.applyExtensionBindings(snapshot.extensionRunner);\n\t}\n\n\tprivate _doctorReloadRuntime(): void {\n\t\tconst extensionErrors = this.deps.getResourceLoader().getExtensions().errors;\n\t\tif (extensionErrors.length > 0) {\n\t\t\tconst summary = extensionErrors\n\t\t\t\t.slice(0, 6)\n\t\t\t\t.map((error) => `${error.path}: ${error.error}`)\n\t\t\t\t.join(\"; \");\n\t\t\tthrow new Error(`Extension reload failed doctor: ${summary}`);\n\t\t}\n\n\t\tconst missingActiveTools = this.deps.getActiveToolNames().filter((name) => !this._toolRegistry.has(name));\n\t\tif (missingActiveTools.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Extension reload failed doctor: active tool(s) missing after reload: ${missingActiveTools.join(\", \")}`,\n\t\t\t);\n\t\t}\n\n\t\tfor (const tool of this.deps.getAgent().state.tools) {\n\t\t\tif (!this._toolDefinitions.has(tool.name)) {\n\t\t\t\tthrow new Error(`Extension reload failed doctor: tool ${tool.name} missing from definition registry`);\n\t\t\t}\n\t\t}\n\n\t\tthis.deps.createAgentContextSnapshot();\n\t\tthis.deps.getContextUsage();\n\t}\n\n\tbuildRuntime(options: {\n\t\tactiveToolNames?: string[];\n\t\tflagValues?: Map<string, boolean | string>;\n\t\tincludeAllExtensionTools?: boolean;\n\t}): void {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst autoResizeImages = settingsManager.getImageAutoResize();\n\t\tconst shellCommandPrefix = settingsManager.getShellCommandPrefix();\n\t\tconst shellPath = settingsManager.getShellPath();\n\t\tconst baseToolsOverride = this.deps.getBaseToolsOverride();\n\t\t// grep/find must not emit a \"Full output: artifact tool-output:<id>\" handle that\n\t\t// nothing can resolve. If artifact_retrieve is explicitly excluded/blocked/outside\n\t\t// an active allowlist, don't hand grep/find an artifact store at all: they fall\n\t\t// back to their pre-existing bounded preview/truncation behavior, with no\n\t\t// payload/meta files ever written and no retrieval promise made.\n\t\tconst toolArtifactStore = this.deps.isToolOrCommandAllowedByProfile(\"artifact_retrieve\")\n\t\t\t? this.deps.getToolArtifactStore()\n\t\t\t: undefined;\n\t\tconst baseToolDefinitions = baseToolsOverride\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.entries(baseToolsOverride).map(([name, tool]) => [name, createToolDefinitionFromAgentTool(tool)]),\n\t\t\t\t)\n\t\t\t: createAllToolDefinitions(this.deps.getCwd(), {\n\t\t\t\t\tread: { autoResizeImages },\n\t\t\t\t\tbash: { commandPrefix: shellCommandPrefix, shellPath },\n\t\t\t\t\tgrep: { artifactStore: toolArtifactStore },\n\t\t\t\t\tfind: { artifactStore: toolArtifactStore },\n\t\t\t\t\tartifact_retrieve: { artifactStore: toolArtifactStore },\n\t\t\t\t});\n\n\t\tthis._baseToolDefinitions = new Map(\n\t\t\tObject.entries(baseToolDefinitions).map(([name, tool]) => [name, tool as ToolDefinition]),\n\t\t);\n\t\tif (!baseToolsOverride) {\n\t\t\tfor (const definition of createCoreDiagnosticsToolDefinitions(\n\t\t\t\t() => this.deps.getActiveToolNames(),\n\t\t\t\t() => this.getAllTools(),\n\t\t\t\t(messages) => this.deps.getContextGcReport(messages),\n\t\t\t\t() => this.deps.getMemoryAuditDiagnostics(),\n\t\t\t)) {\n\t\t\t\tthis._baseToolDefinitions.set(definition.name, definition);\n\t\t\t}\n\t\t\tconst goalToolDefinition = createGoalToolDefinition({\n\t\t\t\tgetGoalState: () => this.deps.getGoalStateSnapshot(),\n\t\t\t\tsaveGoalState: (state) => {\n\t\t\t\t\tthis.deps.saveGoalStateSnapshot(state);\n\t\t\t\t},\n\t\t\t});\n\t\t\tthis._baseToolDefinitions.set(goalToolDefinition.name, goalToolDefinition);\n\t\t\tconst delegateToolDefinition = createDelegateToolDefinition({\n\t\t\t\trunWorkerDelegation: (args) => this.deps.runWorkerDelegationOnce(args),\n\t\t\t});\n\t\t\tthis._baseToolDefinitions.set(delegateToolDefinition.name, delegateToolDefinition);\n\t\t\t// Registered but not default-active: probes spend tokens on the probed model, so\n\t\t\t// activation is an explicit choice (settings/profile/setActiveTools or /autonomy fitness).\n\t\t\tconst modelFitnessToolDefinition = createModelFitnessToolDefinition({\n\t\t\t\trunProbe: (args) => this.deps.runModelFitness(args),\n\t\t\t});\n\t\t\tthis._baseToolDefinitions.set(modelFitnessToolDefinition.name, modelFitnessToolDefinition);\n\t\t\tconst runToolkitScriptToolDefinition = createRunToolkitScriptToolDefinition({\n\t\t\t\tgetScripts: () => this.deps.getSettingsManager().getToolkitScripts(),\n\t\t\t\texecute: (script, scriptArgs) => executeToolkitScript({ script, scriptArgs, cwd: this.deps.getCwd() }),\n\t\t\t\t// Reflex brain (fitness-gated local model): resolves ambiguous requests into a\n\t\t\t\t// registry pick. Best-effort — absent/unfit brain keeps the shortlist behavior.\n\t\t\t\tinterpret: async (request, scripts) => {\n\t\t\t\t\tconst model = this.deps.resolveCurationModelIfFit();\n\t\t\t\t\tif (!model) return undefined;\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt: REFLEX_INTERPRETER_SYSTEM_PROMPT,\n\t\t\t\t\t\tmessages: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: buildReflexUserPrompt(request, scripts) }],\n\t\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\tmaxTokens: 256,\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tif (completion.usage.cost.total > 0 || completion.usage.totalTokens > 0) {\n\t\t\t\t\t\tthis.deps.addSpawnedUsage(completion.usage, { label: \"toolkit-brain\" });\n\t\t\t\t\t}\n\t\t\t\t\treturn parseReflexPlan(completion.text);\n\t\t\t\t},\n\t\t\t});\n\t\t\tthis._baseToolDefinitions.set(runToolkitScriptToolDefinition.name, runToolkitScriptToolDefinition);\n\t\t}\n\n\t\tconst extensionsResult = this.deps.getResourceLoader().getExtensions();\n\t\tif (options.flagValues) {\n\t\t\tfor (const [name, value] of options.flagValues) {\n\t\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\t}\n\t\t}\n\t\tconst extensions = this.deps.filterExtensionsForRuntime(extensionsResult.extensions);\n\t\tconst runtimeExtensionPaths = new Set(extensions.map((extension) => extension.path));\n\t\textensionsResult.runtime.pendingProviderRegistrations =\n\t\t\textensionsResult.runtime.pendingProviderRegistrations.filter((registration) =>\n\t\t\t\truntimeExtensionPaths.has(registration.extensionPath),\n\t\t\t);\n\n\t\tconst runner = new ExtensionRunner(\n\t\t\textensions,\n\t\t\textensionsResult.runtime,\n\t\t\tthis.deps.getCwd(),\n\t\t\tthis.deps.getSessionManager(),\n\t\t\tthis.deps.getModelRegistry(),\n\t\t);\n\t\tthis.deps.setExtensionRunner(runner);\n\t\tthis.deps.bindExtensionCore(runner);\n\t\tthis.deps.applyExtensionBindings(runner);\n\n\t\tconst defaultActiveToolNames = baseToolsOverride\n\t\t\t? Object.keys(baseToolsOverride)\n\t\t\t: [\"read\", \"bash\", \"edit\", \"write\", \"context_audit\", \"goal\", \"delegate\", \"run_toolkit_script\"];\n\t\tconst baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;\n\t\tthis.refreshToolRegistry({\n\t\t\tactiveToolNames: baseActiveToolNames,\n\t\t\tincludeAllExtensionTools: options.includeAllExtensionTools,\n\t\t});\n\t}\n\n\tasync reload(): Promise<void> {\n\t\tif (this.deps.isStreaming()) {\n\t\t\tthrow new Error(\"Cannot reload while the agent is streaming or a tool call is active\");\n\t\t}\n\t\tif (this.deps.isCompacting()) {\n\t\t\tthrow new Error(\"Cannot reload while context compaction or branch summarization is active\");\n\t\t}\n\t\tconst previousRunner = this.deps.getExtensionRunner();\n\t\tconst snapshot = this._createReloadRuntimeSnapshot();\n\t\t// Preserve the pre-filter tool REQUEST across the rebuild, not the capability/profile-filtered\n\t\t// active set — otherwise a reload under a small model permanently shrinks the restorable set.\n\t\tconst activeToolNames = this.deps.getRequestedActiveToolNames() ?? this.deps.getActiveToolNames();\n\t\tconst previousFlagValues = previousRunner.getFlagValues();\n\t\tconst reloadErrors: string[] = [];\n\t\tlet newRunner: ExtensionRunner | undefined;\n\t\ttry {\n\t\t\tawait this.deps.getSettingsManager().reload();\n\t\t\t// Re-derive the resource-profile tool filter from the freshly reloaded settings.\n\t\t\t// Unlike skills/prompts/themes (which re-filter through the resource loader on every\n\t\t\t// reload), the tool filter is held on the session, so without this a live edit to the\n\t\t\t// active profile's tools allow/block — or switching the active profile — would not\n\t\t\t// apply on /reload and allowed tools would stay missing.\n\t\t\tthis.deps.setToolProfileFilter(this.deps.deriveToolProfileFilter());\n\t\t\t// Re-apply the active profile's model/thinking from the freshly reloaded settings, so a live\n\t\t\t// profile edit (or switch) takes effect on /reload. Skipped when the launch used an explicit\n\t\t\t// --model/--thinking flag, which must win over the profile across reloads.\n\t\t\tawait this.deps.reapplyActiveProfileModelSettings();\n\t\t\tawait this.deps.getResourceLoader().reload({ failOnExtensionErrors: true, deferExtensionDispose: true });\n\t\t\tresetApiProviders();\n\t\t\tthis.buildRuntime({\n\t\t\t\tactiveToolNames,\n\t\t\t\tflagValues: previousFlagValues,\n\t\t\t\tincludeAllExtensionTools: true,\n\t\t\t});\n\t\t\tnewRunner = this.deps.getExtensionRunner();\n\t\t\tconst offDoctorErrors = newRunner.onError((error) => {\n\t\t\t\treloadErrors.push(`${error.extensionPath} ${error.event}: ${error.error}`);\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tthis._doctorReloadRuntime();\n\t\t\t\t// Reload starts memory providers fresh; loaded extensions re-register below.\n\t\t\t\tthis.deps.clearPendingMemoryProviders();\n\t\t\t\tconst hasBindings =\n\t\t\t\t\tthis.deps.getExtensionUIContext() ||\n\t\t\t\t\tthis.deps.getExtensionCommandContextActions() ||\n\t\t\t\t\tthis.deps.getExtensionShutdownHandler() ||\n\t\t\t\t\tthis.deps.getExtensionErrorListener();\n\t\t\t\tif (hasBindings) {\n\t\t\t\t\tawait newRunner.emit({ type: \"session_start\", reason: \"reload\" });\n\t\t\t\t\tawait this.deps.extendResourcesFromExtensions(\"reload\");\n\t\t\t\t\tthis._doctorReloadRuntime();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\toffDoctorErrors();\n\t\t\t}\n\t\t\tif (reloadErrors.length > 0) {\n\t\t\t\tthrow new Error(`Extension reload failed doctor: ${reloadErrors.slice(0, 6).join(\"; \")}`);\n\t\t\t}\n\t\t\tawait emitSessionShutdownEvent(previousRunner, { type: \"session_shutdown\", reason: \"reload\" });\n\t\t\tpreviousRunner.invalidate();\n\t\t\tthis.deps.getResourceLoader().commitReload?.();\n\t\t\t// Re-derive the memory subsystem from the reloaded settings/providers.\n\t\t\tawait this.deps.initializeMemory();\n\t\t} catch (error) {\n\t\t\tif (newRunner && newRunner !== previousRunner) {\n\t\t\t\tnewRunner.invalidate(\n\t\t\t\t\t\"This extension ctx was discarded because reload failed and Pi restored the previous valid runtime.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.deps.getResourceLoader().rollbackReload?.();\n\t\t\tthis._restoreReloadRuntimeSnapshot(snapshot);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Unload a single extension without full reload.\n\t * Runs the extension's session_shutdown lifecycle, unregisters its providers,\n\t * disposes its event subscriptions, and rebuilds the runtime.\n\t * Falls back to full reload on error.\n\t */\n\tasync unloadExtensionLive(extensionPath: string): Promise<void> {\n\t\tif (this.deps.isStreaming()) {\n\t\t\tthrow new Error(\"Cannot unload extension while the agent is streaming or a tool call is active\");\n\t\t}\n\t\tif (this.deps.isCompacting()) {\n\t\t\tthrow new Error(\"Cannot unload extension while context compaction or branch summarization is active\");\n\t\t}\n\n\t\tconst ext = this.deps.getResourceLoader().getLoadedExtension(extensionPath);\n\t\tif (!ext) {\n\t\t\treturn; // Nothing to unload\n\t\t}\n\n\t\tconst previousRunner = this.deps.getExtensionRunner();\n\t\ttry {\n\t\t\t// Run session_shutdown lifecycle for this extension only\n\t\t\tawait this.deps.getExtensionRunner().emitToExtension(ext, { type: \"session_shutdown\", reason: \"unload\" });\n\n\t\t\t// Unregister its providers (keyed by the extension's own path, as registered)\n\t\t\tconst runtime = this.deps.getResourceLoader().getExtensions().runtime;\n\t\t\tfor (const name of runtime.getProvidersForExtension(ext.path)) {\n\t\t\t\truntime.unregisterProvider(name, ext.path);\n\t\t\t}\n\n\t\t\t// Dispose its event subscriptions and run disposers\n\t\t\tawait disposeExtensionEventSubscriptions([ext]);\n\n\t\t\t// Remove from loaded extensions\n\t\t\tthis.deps.getResourceLoader().removeLoadedExtension(extensionPath);\n\n\t\t\t// Rebuild runtime with new extension set\n\t\t\tconst activeToolNames = this.deps.getRequestedActiveToolNames() ?? this.deps.getActiveToolNames();\n\t\t\tconst previousFlagValues = previousRunner.getFlagValues();\n\t\t\tthis.buildRuntime({\n\t\t\t\tactiveToolNames,\n\t\t\t\tflagValues: previousFlagValues,\n\t\t\t\tincludeAllExtensionTools: true,\n\t\t\t});\n\t\t\tpreviousRunner.invalidate();\n\n\t\t\t// Notify extensions-changed listeners\n\t\t\tthis.deps.notifyExtensionsChanged();\n\t\t} catch (error) {\n\t\t\t// Fall back to full reload on error\n\t\t\ttry {\n\t\t\t\tawait this.reload();\n\t\t\t} catch {\n\t\t\t\t// Suppress nested error; original error will be thrown below\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Load a single extension without full reload.\n\t * Loads the extension with fresh import, rebuilds the runtime,\n\t * and runs the extension's session_start lifecycle.\n\t * Falls back to full reload on error.\n\t */\n\tasync loadExtensionLive(extensionPath: string): Promise<void> {\n\t\tif (this.deps.isStreaming()) {\n\t\t\tthrow new Error(\"Cannot load extension while the agent is streaming or a tool call is active\");\n\t\t}\n\t\tif (this.deps.isCompacting()) {\n\t\t\tthrow new Error(\"Cannot load extension while context compaction or branch summarization is active\");\n\t\t}\n\n\t\tconst previousRunner = this.deps.getExtensionRunner();\n\t\ttry {\n\t\t\t// Load the extension with fresh import\n\t\t\tconst { extension, error } = await this.deps.getResourceLoader().loadSingleExtension(extensionPath);\n\t\t\tif (error || !extension) {\n\t\t\t\tthrow new Error(error || `Failed to load extension: ${extensionPath}`);\n\t\t\t}\n\n\t\t\t// Rebuild runtime to aggregate tools/commands/handlers/providers\n\t\t\tconst activeToolNames = this.deps.getRequestedActiveToolNames() ?? this.deps.getActiveToolNames();\n\t\t\tconst previousFlagValues = previousRunner.getFlagValues();\n\t\t\tthis.buildRuntime({\n\t\t\t\tactiveToolNames,\n\t\t\t\tflagValues: previousFlagValues,\n\t\t\t\tincludeAllExtensionTools: true,\n\t\t\t});\n\n\t\t\t// Run session_start lifecycle for the new extension only\n\t\t\tawait this.deps.getExtensionRunner().emitToExtension(extension, { type: \"session_start\", reason: \"load\" });\n\n\t\t\t// Notify extensions-changed listeners\n\t\t\tthis.deps.notifyExtensionsChanged();\n\t\t} catch (error) {\n\t\t\t// Fall back to full reload on error\n\t\t\ttry {\n\t\t\t\tawait this.reload();\n\t\t\t} catch {\n\t\t\t\t// Suppress nested error; original error will be thrown below\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Reconcile loaded extensions with the active profile.\n\t * Loads extensions that should be enabled but aren't, and unloads extensions that shouldn't be.\n\t * Falls back to full reload if any individual load/unload fails.\n\t */\n\tasync reconcileLoadedExtensions(): Promise<void> {\n\t\tif (this.deps.isStreaming()) {\n\t\t\tthrow new Error(\"Cannot reconcile extensions while the agent is streaming or a tool call is active\");\n\t\t}\n\t\tif (this.deps.isCompacting()) {\n\t\t\tthrow new Error(\"Cannot reconcile extensions while context compaction or branch summarization is active\");\n\t\t}\n\n\t\ttry {\n\t\t\t// Get all discoverable extension paths\n\t\t\tconst allDiscoverablePaths = await this.deps.getResourceLoader().getDiscoverableExtensionPaths();\n\n\t\t\t// Get the target enabled set based on profile filters\n\t\t\tconst targetEnabledSet = new Set<string>();\n\t\t\tfor (const path of allDiscoverablePaths) {\n\t\t\t\tif (this.deps.getSettingsManager().isResourceAllowedByProfile(\"extensions\", path)) {\n\t\t\t\t\ttargetEnabledSet.add(path);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Get currently loaded set\n\t\t\tconst loadedExtensions = this.deps.getResourceLoader().getExtensions().extensions;\n\t\t\tconst loadedSet = new Set<string>();\n\t\t\tfor (const ext of loadedExtensions) {\n\t\t\t\tloadedSet.add(ext.path);\n\t\t\t}\n\n\t\t\t// Collect unloads and loads\n\t\t\tconst toUnload: string[] = [];\n\t\t\tconst toLoad: string[] = [];\n\n\t\t\tfor (const path of loadedSet) {\n\t\t\t\tif (!targetEnabledSet.has(path)) {\n\t\t\t\t\ttoUnload.push(path);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const path of targetEnabledSet) {\n\t\t\t\tif (!loadedSet.has(path)) {\n\t\t\t\t\ttoLoad.push(path);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Apply unloads first, then loads, to minimize churn\n\t\t\t// Collect errors but continue through all operations\n\t\t\tconst errors: Error[] = [];\n\n\t\t\tfor (const path of toUnload) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.unloadExtensionLive(path);\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const path of toLoad) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.loadExtensionLive(path);\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If any errors occurred, throw the first one (already fell back to full reload in load/unload)\n\t\t\tif (errors.length > 0) {\n\t\t\t\tthrow errors[0];\n\t\t\t}\n\n\t\t\t// Single notification at the end\n\t\t\tthis.deps.notifyExtensionsChanged();\n\t\t} catch (error) {\n\t\t\t// Fall back to full reload on error\n\t\t\ttry {\n\t\t\t\tawait this.reload();\n\t\t\t} catch {\n\t\t\t\t// Suppress nested error; original error will be thrown below\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
|
package/dist/core/sdk.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { type ThinkingLevel } from "@caupulican/pi-agent-core";
|
|
2
|
+
import { SessionManager } from "@caupulican/pi-agent-core/node";
|
|
2
3
|
import { type Model } from "@caupulican/pi-ai";
|
|
3
4
|
import { AgentSession } from "./agent-session.ts";
|
|
4
5
|
import { AuthStorage } from "./auth-storage.ts";
|
|
5
6
|
import type { LoadExtensionsResult, SessionStartEvent, ToolDefinition } from "./extensions/index.ts";
|
|
6
7
|
import { ModelRegistry } from "./model-registry.ts";
|
|
7
8
|
import type { ResourceLoader } from "./resource-loader.ts";
|
|
8
|
-
import { SessionManager } from "./session-manager.ts";
|
|
9
9
|
import type { ResourceProfileFilterSettings, ResourceProfileSettings } from "./settings-manager.ts";
|
|
10
10
|
import { SettingsManager } from "./settings-manager.ts";
|
|
11
11
|
import { createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createReadOnlyTools, createReadTool, createWriteTool, withFileMutationQueue } from "./tools/index.ts";
|
|
@@ -67,7 +67,7 @@ export interface CreateAgentSessionOptions {
|
|
|
67
67
|
customTools?: ToolDefinition[];
|
|
68
68
|
/** Resource loader. When omitted, DefaultResourceLoader is used. */
|
|
69
69
|
resourceLoader?: ResourceLoader;
|
|
70
|
-
/** Session manager. Default: SessionManager.create(cwd) */
|
|
70
|
+
/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */
|
|
71
71
|
sessionManager?: SessionManager;
|
|
72
72
|
/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */
|
|
73
73
|
settingsManager?: SettingsManager;
|
package/dist/core/sdk.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAoC,KAAK,KAAK,EAAgB,MAAM,mBAAmB,CAAC;AAG/F,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEtH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,KAAK,EAAE,6BAA6B,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AACpG,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAAyB;IACzC,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb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EAAE,eAAe,CAAC;IAClC,kEAAkE;IAClE,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACtC;AAED,qCAAqC;AACrC,MAAM,WAAW,wBAAwB;IACxC,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,mEAAmE;IACnE,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,wEAAwE;IACxE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AA8CF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CA6QnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport type { ResourceProfileFilterSettings, ResourceProfileSettings } from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write, context_audit)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot profile definitions. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles && options.resourceProfiles.length > 0) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\"read\", \"bash\", \"edit\", \"write\", \"context_audit\"];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAA0C,KAAK,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAwB,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAoC,KAAK,KAAK,EAAgB,MAAM,mBAAmB,CAAC;AAG/F,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,KAAK,EAAE,6BAA6B,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AACpG,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAAyB;IACzC,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,oFAAoF;IACpF,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,uFAAuF;IAC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wB;IACxC,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,mEAAmE;IACnE,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,wEAAwE;IACxE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AA8CF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CA8QnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type { ResourceProfileFilterSettings, ResourceProfileSettings } from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write, context_audit)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot profile definitions. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles && options.resourceProfiles.length > 0) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\"read\", \"bash\", \"edit\", \"write\", \"context_audit\"];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
package/dist/core/sdk.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
-
import { Agent } from "@caupulican/pi-agent-core";
|
|
2
|
+
import { Agent, convertToLlm } from "@caupulican/pi-agent-core";
|
|
3
|
+
import { getDefaultSessionDir, SessionManager } from "@caupulican/pi-agent-core/node";
|
|
3
4
|
import { clampThinkingLevel, streamSimple } from "@caupulican/pi-ai";
|
|
4
5
|
import { getAgentDir } from "../config.js";
|
|
5
6
|
import { resolvePath } from "../utils/paths.js";
|
|
@@ -7,12 +8,10 @@ import { AgentSession } from "./agent-session.js";
|
|
|
7
8
|
import { formatNoModelsAvailableMessage } from "./auth-guidance.js";
|
|
8
9
|
import { AuthStorage } from "./auth-storage.js";
|
|
9
10
|
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
|
|
10
|
-
import { convertToLlm } from "./messages.js";
|
|
11
11
|
import { ModelRegistry } from "./model-registry.js";
|
|
12
12
|
import { findInitialModel, resolveProfileModelSettings } from "./model-resolver.js";
|
|
13
13
|
import { DefaultResourceLoader } from "./resource-loader.js";
|
|
14
14
|
import { parseResourceProfileInput } from "./resource-profile-blocks.js";
|
|
15
|
-
import { getDefaultSessionDir, SessionManager } from "./session-manager.js";
|
|
16
15
|
import { SettingsManager } from "./settings-manager.js";
|
|
17
16
|
import { isInstallTelemetryEnabled } from "./telemetry.js";
|
|
18
17
|
import { time } from "./timings.js";
|
|
@@ -110,7 +109,7 @@ export async function createAgentSession(options = {}) {
|
|
|
110
109
|
if (options.resourceProfiles && options.resourceProfiles.length > 0) {
|
|
111
110
|
settingsManager.setRuntimeResourceProfiles(options.resourceProfiles);
|
|
112
111
|
}
|
|
113
|
-
const sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));
|
|
112
|
+
const sessionManager = options.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));
|
|
114
113
|
if (!resourceLoader) {
|
|
115
114
|
resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });
|
|
116
115
|
await resourceLoader.reload();
|
package/dist/core/sdk.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAyC,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAEpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAA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aAAa;KAClE,CAAC,CAAC;IAEH,gDAAgD;IAChD,IAAI,kBAAkB,EAAE,CAAC;QACxB,KAAK,CAAC,KAAK,CAAC,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC;QAChD,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACvB,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;QACzD,CAAC;IACF,CAAC;SAAM,CAAC;QACP,2FAA2F;QAC3F,IAAI,KAAK,EAAE,CAAC;YACX,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5D,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAChC,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,QAAQ;QACR,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB;QACjB,kBAAkB;QAClB,iBAAiB;QACjB,eAAe,EAAE,OAAO,CAAC,eAAe,IAAI,OAAO,CAAC,KAAK,IAAI,IAAI;QACjE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,IAAI,OAAO,CAAC,aAAa,KAAK,SAAS;QACrF,cAAc,EAAE,OAAO,CAAC,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB,KAAK,GAAG;QAC9E,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport type { ResourceProfileFilterSettings, ResourceProfileSettings } from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write, context_audit)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot profile definitions. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles && options.resourceProfiles.length > 0) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\"read\", \"bash\", \"edit\", \"write\", \"context_audit\"];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAqB,YAAY,EAAsB,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAA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C,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type { ResourceProfileFilterSettings, ResourceProfileSettings } from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write, context_audit)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot profile definitions. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles && options.resourceProfiles.length > 0) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\"read\", \"bash\", \"edit\", \"write\", \"context_audit\"];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session usage / cost / stats accounting, context-window usage, and session export.
|
|
3
|
+
*
|
|
4
|
+
* Extracted verbatim from agent-session.ts (god-file decomposition). Read-only over the session
|
|
5
|
+
* except for its two owned memo caches (`_spawnedUsageCache`, `_dailyUsageCache`) — it never mutates
|
|
6
|
+
* agent or session state. Single source of truth for "how much did this session and its spawned
|
|
7
|
+
* subtree spend" (footer roll-up, print-mode child reporting), the daily cross-session totals, the
|
|
8
|
+
* /context window estimate, and HTML/JSONL export of the current branch.
|
|
9
|
+
*/
|
|
10
|
+
import type { AgentMessage, AgentState } from "@caupulican/pi-agent-core";
|
|
11
|
+
import { type SessionManager } from "@caupulican/pi-agent-core/node";
|
|
12
|
+
import type { Model, Usage } from "@caupulican/pi-ai";
|
|
13
|
+
import { type SessionStats, type SpawnedUsageTotals } from "./agent-session.ts";
|
|
14
|
+
import { type DailyUsageTotals } from "./cost/daily-usage.ts";
|
|
15
|
+
import type { ContextUsage, ToolDefinition } from "./extensions/index.ts";
|
|
16
|
+
import type { SettingsManager } from "./settings-manager.ts";
|
|
17
|
+
export interface SessionAnalyticsDeps {
|
|
18
|
+
/** Live agent state — assistant-message usage and message counts are read from here. */
|
|
19
|
+
getState(): AgentState;
|
|
20
|
+
/** All messages (agent state view) — used for context-window estimation and last-assistant text. */
|
|
21
|
+
getMessages(): AgentMessage[];
|
|
22
|
+
/** Current session model — its context window bounds the /context estimate. */
|
|
23
|
+
getModel(): Model<any> | undefined;
|
|
24
|
+
/** Session log — entries feed spawned-usage roll-up, daily totals, branch export. */
|
|
25
|
+
getSessionManager(): SessionManager;
|
|
26
|
+
/** Settings — the export theme is read here. */
|
|
27
|
+
getSettingsManager(): SettingsManager;
|
|
28
|
+
/** Resolve a tool definition for the HTML export's custom-tool renderer. */
|
|
29
|
+
getToolDefinition(name: string): ToolDefinition | undefined;
|
|
30
|
+
}
|
|
31
|
+
export declare class SessionAnalytics {
|
|
32
|
+
/** Memoized spawned-usage totals, keyed by session entry count (Bug #22: O(1) between turns). */
|
|
33
|
+
private _spawnedUsageCache?;
|
|
34
|
+
/** Memoized daily usage totals with a short TTL, keyed by the resolved scope dir. */
|
|
35
|
+
private _dailyUsageCache?;
|
|
36
|
+
private readonly deps;
|
|
37
|
+
constructor(deps: SessionAnalyticsDeps);
|
|
38
|
+
getSessionStats(): SessionStats;
|
|
39
|
+
/**
|
|
40
|
+
* Cumulative usage (full breakdown) for this session's entire spawn subtree: its own
|
|
41
|
+
* assistant messages PLUS every `spawned_usage` report it has rolled up. Single source of
|
|
42
|
+
* truth for "how much did this session and everything it spawned spend" — used by print-mode
|
|
43
|
+
* to emit a child's total so a spawner can roll it up via {@link addSpawnedUsage}.
|
|
44
|
+
*
|
|
45
|
+
* Including the `spawned_usage` reports is what keeps the single-hop invariant intact: a child
|
|
46
|
+
* that itself spawned grandchildren must report own + sub-usage in one number, or the parent
|
|
47
|
+
* silently under-counts the grandchildren.
|
|
48
|
+
*/
|
|
49
|
+
getCumulativeUsage(): Usage;
|
|
50
|
+
/**
|
|
51
|
+
* Record usage spent by a spawned/subagent session so the footer can roll it into the
|
|
52
|
+
* displayed cost. Persisted as a `CustomEntry` (`customType: "spawned_usage"`, Model A) so
|
|
53
|
+
* it survives reload and is reconstructed exactly like main usage; a new/forked session
|
|
54
|
+
* starts fresh because it owns a new log file.
|
|
55
|
+
*
|
|
56
|
+
* Idempotent on `opts.reportId`: a re-report (retry, duplicate `agent_end`) with a
|
|
57
|
+
* previously-seen id is ignored, so cost cannot be double-counted. Honors the single-hop
|
|
58
|
+
* invariant documented on {@link SpawnedUsageReport}.
|
|
59
|
+
*
|
|
60
|
+
* @returns the id of the appended entry, or `undefined` if the report was a duplicate.
|
|
61
|
+
*/
|
|
62
|
+
addSpawnedUsage(usage: Usage, opts?: {
|
|
63
|
+
label?: string;
|
|
64
|
+
sourceSessionId?: string;
|
|
65
|
+
reportId?: string;
|
|
66
|
+
}): string | undefined;
|
|
67
|
+
/**
|
|
68
|
+
* Aggregate all recorded spawned-usage reports (see {@link addSpawnedUsage}). Cached by the session
|
|
69
|
+
* entry count so the interactive footer (which calls this every render frame) is O(1) between turns
|
|
70
|
+
* instead of an O(N) scan on every keystroke (Bug #22). Recomputes only when entries change.
|
|
71
|
+
*/
|
|
72
|
+
getSpawnedUsage(): SpawnedUsageTotals;
|
|
73
|
+
getDailyUsageTotals(now?: Date): DailyUsageTotals;
|
|
74
|
+
getDailyUsageBreakdown(formatLabel?: (label: string) => string, now?: Date): string;
|
|
75
|
+
getContextUsage(): ContextUsage | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Export session to HTML.
|
|
78
|
+
* @param outputPath Optional output path (defaults to session directory)
|
|
79
|
+
* @returns Path to exported file
|
|
80
|
+
*/
|
|
81
|
+
exportToHtml(outputPath?: string): Promise<string>;
|
|
82
|
+
/**
|
|
83
|
+
* Export the current session branch to a JSONL file.
|
|
84
|
+
* Writes the session header followed by all entries on the current branch path.
|
|
85
|
+
* @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
|
|
86
|
+
* @returns The resolved output file path.
|
|
87
|
+
*/
|
|
88
|
+
exportToJsonl(outputPath?: string): string;
|
|
89
|
+
/**
|
|
90
|
+
* Get text content of last assistant message.
|
|
91
|
+
* Useful for /copy command.
|
|
92
|
+
* @returns Text content, or undefined if no assistant message exists
|
|
93
|
+
*/
|
|
94
|
+
getLastAssistantText(): string | undefined;
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=session-analytics.d.ts.map
|