@bastani/atomic 0.9.28-alpha.1 → 0.9.28-alpha.3
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 +60 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/native-client-licenses/NOTICE +2 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +34 -0
- package/dist/builtin/workflows/builtin/{chunk-wz8v67bn.js → chunk-aqv8ny38.js} +257 -259
- package/dist/builtin/workflows/builtin/{chunk-f61w0hpm.js → chunk-br4ac9a3.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-tecnpe8j.js → chunk-p3xmajmj.js} +438 -39
- package/dist/builtin/workflows/builtin/chunk-p6jagvyf.js +8 -0
- package/dist/builtin/workflows/builtin/goal.js +2 -2
- package/dist/builtin/workflows/builtin/index.js +4 -4
- package/dist/builtin/workflows/builtin/ralph.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/authoring.d.ts +14 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +111102 -110218
- package/dist/builtin/workflows/src/index.js +42284 -41141
- package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +16 -11
- package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +16 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +8 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/credential-print.d.ts +1 -1
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +2 -56
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/config.d.ts +2 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -2
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-accessors.d.ts.map +1 -1
- package/dist/core/agent-session-accessors.js +6 -1
- package/dist/core/agent-session-accessors.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +20 -3
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +2 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts +6 -0
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +90 -9
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +3 -1
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +14 -1
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
- package/dist/core/agent-session-tool-registry.js +1 -0
- package/dist/core/agent-session-tool-registry.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +2 -0
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +6 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +22 -4
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/child-session-options.d.ts.map +1 -1
- package/dist/core/child-session-options.js +17 -2
- package/dist/core/child-session-options.js.map +1 -1
- package/dist/core/compaction/classifier-compaction.d.ts +13 -0
- package/dist/core/compaction/classifier-compaction.d.ts.map +1 -0
- package/dist/core/compaction/classifier-compaction.js +110 -0
- package/dist/core/compaction/classifier-compaction.js.map +1 -0
- package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
- package/dist/core/compaction/compaction-boundary.js +2 -6
- package/dist/core/compaction/compaction-boundary.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts +16 -1
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js +97 -12
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +18 -1
- package/dist/core/compaction/compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/compaction-types.js +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/compaction/fallback-planner.d.ts +1 -0
- package/dist/core/compaction/fallback-planner.d.ts.map +1 -1
- package/dist/core/compaction/fallback-planner.js +2 -0
- package/dist/core/compaction/fallback-planner.js.map +1 -1
- package/dist/core/compaction/index.d.ts +3 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +3 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/model-resolver.d.ts +16 -0
- package/dist/core/compaction/model-resolver.d.ts.map +1 -0
- package/dist/core/compaction/model-resolver.js +18 -0
- package/dist/core/compaction/model-resolver.js.map +1 -0
- package/dist/core/compaction/morph-compaction.d.ts +14 -0
- package/dist/core/compaction/morph-compaction.d.ts.map +1 -0
- package/dist/core/compaction/morph-compaction.js +99 -0
- package/dist/core/compaction/morph-compaction.js.map +1 -0
- package/dist/core/compaction/pi-summary-fallback.d.ts +34 -0
- package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -0
- package/dist/core/compaction/pi-summary-fallback.js +357 -0
- package/dist/core/compaction/pi-summary-fallback.js.map +1 -0
- package/dist/core/compaction/planner-outcome.d.ts +10 -6
- package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
- package/dist/core/compaction/planner-outcome.js +11 -4
- package/dist/core/compaction/planner-outcome.js.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.d.ts +3 -1
- package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.js +11 -0
- package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
- package/dist/core/compaction/range-planner.d.ts +3 -3
- package/dist/core/compaction/range-planner.d.ts.map +1 -1
- package/dist/core/compaction/range-planner.js +59 -28
- package/dist/core/compaction/range-planner.js.map +1 -1
- package/dist/core/compaction/region-trimming.d.ts.map +1 -1
- package/dist/core/compaction/region-trimming.js +7 -0
- package/dist/core/compaction/region-trimming.js.map +1 -1
- package/dist/core/compaction/structured-compaction-input.d.ts +19 -0
- package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -0
- package/dist/core/compaction/structured-compaction-input.js +70 -0
- package/dist/core/compaction/structured-compaction-input.js.map +1 -0
- package/dist/core/compaction/transcript-serialization.d.ts +1 -0
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
- package/dist/core/compaction/transcript-serialization.js +26 -0
- package/dist/core/compaction/transcript-serialization.js.map +1 -1
- package/dist/core/extensions/api-types.d.ts +2 -2
- package/dist/core/extensions/api-types.d.ts.map +1 -1
- package/dist/core/extensions/api-types.js.map +1 -1
- package/dist/core/extensions/context-types.d.ts +1 -0
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/loader-api.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts +3 -4
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +14 -9
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts +10 -4
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js +47 -3
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +10 -3
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +31 -7
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/tool-events.d.ts +1 -1
- package/dist/core/extensions/tool-events.js.map +1 -1
- package/dist/core/extensions/ts-source-specifiers.d.ts +18 -0
- package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -0
- package/dist/core/extensions/ts-source-specifiers.js +142 -0
- package/dist/core/extensions/ts-source-specifiers.js.map +1 -0
- package/dist/core/extensions/workflow-events.d.ts +49 -0
- package/dist/core/extensions/workflow-events.d.ts.map +1 -1
- package/dist/core/extensions/workflow-events.js.map +1 -1
- package/dist/core/extensions/workflow-run-control-hub.d.ts +16 -4
- package/dist/core/extensions/workflow-run-control-hub.d.ts.map +1 -1
- package/dist/core/extensions/workflow-run-control-hub.js +72 -1
- package/dist/core/extensions/workflow-run-control-hub.js.map +1 -1
- package/dist/core/extensions/workflow-run-control.d.ts +11 -3
- package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
- package/dist/core/extensions/workflow-run-control.js.map +1 -1
- package/dist/core/messages.d.ts +1 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +5 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +3 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/sdk-exports.d.ts +2 -2
- package/dist/core/sdk-exports.js.map +1 -1
- package/dist/core/sdk-types.d.ts +3 -0
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +17 -8
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-history.js +4 -2
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +29 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-manager-core.js.map +1 -1
- package/dist/core/settings-merge.d.ts +3 -0
- package/dist/core/settings-merge.d.ts.map +1 -1
- package/dist/core/settings-merge.js +18 -4
- package/dist/core/settings-merge.js.map +1 -1
- package/dist/core/settings-storage.js.map +1 -1
- package/dist/core/settings-types.d.ts +1 -0
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/core/transcript.d.ts +58 -0
- package/dist/core/transcript.d.ts.map +1 -0
- package/dist/core/transcript.js +185 -0
- package/dist/core/transcript.js.map +1 -0
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +14 -1
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.js +2 -2
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/herdr/index.d.ts.map +1 -1
- package/dist/extensions/herdr/index.js +15 -10
- package/dist/extensions/herdr/index.js.map +1 -1
- package/dist/extensions/herdr/pane-owner.d.ts +6 -2
- package/dist/extensions/herdr/pane-owner.d.ts.map +1 -1
- package/dist/extensions/herdr/pane-owner.js +19 -4
- package/dist/extensions/herdr/pane-owner.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +19 -8
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/extensions/mcp/cli.js +18 -24
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/client/auth-provider.d.ts +4 -0
- package/dist/extensions/mcp/client/auth-provider.d.ts.map +1 -1
- package/dist/extensions/mcp/client/auth-provider.js.map +1 -1
- package/dist/extensions/mcp/client/oauth/discovery.d.ts +3 -0
- package/dist/extensions/mcp/client/oauth/discovery.d.ts.map +1 -1
- package/dist/extensions/mcp/client/oauth/discovery.js +8 -5
- package/dist/extensions/mcp/client/oauth/discovery.js.map +1 -1
- package/dist/extensions/mcp/client/oauth/flow.d.ts +4 -0
- package/dist/extensions/mcp/client/oauth/flow.d.ts.map +1 -1
- package/dist/extensions/mcp/client/oauth/flow.js +12 -2
- package/dist/extensions/mcp/client/oauth/flow.js.map +1 -1
- package/dist/extensions/mcp/client/transports/streamable-http.d.ts +3 -0
- package/dist/extensions/mcp/client/transports/streamable-http.d.ts.map +1 -1
- package/dist/extensions/mcp/client/transports/streamable-http.js +17 -14
- package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +150 -72
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +5 -3
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +36 -10
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts +3 -3
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +10 -2
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/main-deferred-startup.d.ts +1 -0
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-deferred-startup.js +9 -21
- package/dist/main-deferred-startup.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +8 -6
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js +15 -3
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-items.js +43 -0
- package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-types.d.ts +6 -0
- package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +1 -47
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +0 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +0 -1
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +0 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-prompt-restore.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-prompt-restore.js +0 -5
- package/dist/modes/interactive/interactive-prompt-restore.js.map +1 -1
- package/dist/modes/interactive/interactive-prompt-turn.js +6 -4
- package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +13 -6
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/modes/interactive/interactive-selectors.js +8 -0
- package/dist/modes/interactive/interactive-selectors.js.map +1 -1
- package/dist/modes/interactive/interactive-session-runtime.js +2 -0
- package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +1 -1
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/rpc/rpc-client-process.d.ts +7 -0
- package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-process.js +20 -3
- package/dist/modes/rpc/rpc-client-process.js.map +1 -1
- package/dist/modes/rpc/rpc-command-timeouts.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-timeouts.js +1 -0
- package/dist/modes/rpc/rpc-command-timeouts.js.map +1 -1
- package/dist/utils/ansi.d.ts +8 -0
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +29 -10
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +13 -3
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/credential-redaction.d.ts +2 -0
- package/dist/utils/credential-redaction.d.ts.map +1 -0
- package/dist/utils/credential-redaction.js +20 -0
- package/dist/utils/credential-redaction.js.map +1 -0
- package/dist/utils/image-resize-core.d.ts +8 -0
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +1 -0
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/image-resize-worker.js +3 -2
- package/dist/utils/image-resize-worker.js.map +1 -1
- package/dist/utils/image-resize.d.ts +2 -2
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +7 -10
- package/dist/utils/image-resize.js.map +1 -1
- package/docs/codemode.md +21 -1
- package/docs/compaction/reference.md +10 -4
- package/docs/compaction.md +40 -8
- package/docs/docs.json +1 -0
- package/docs/extensions/api-reference.md +4 -0
- package/docs/extensions/events.md +2 -2
- package/docs/llama-cpp.md +9 -2
- package/docs/mcp-servers.md +3 -3
- package/docs/models.md +10 -0
- package/docs/providers.md +39 -5
- package/docs/reference/cli.md +2 -2
- package/docs/sdk/reference.md +19 -4
- package/docs/sdk/web-server.md +325 -0
- package/docs/sdk.md +83 -1
- package/docs/security.md +1 -1
- package/docs/settings.md +2 -2
- package/docs/tools.md +1 -1
- package/docs/workflows/api-reference.md +71 -3
- package/docs/workflows/builtins.md +4 -0
- package/docs/workflows/operations.md +13 -5
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-types.js","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,CAAU,CAAC","sourcesContent":["export const CACHE_WARMING_MODES = [\"off\", \"streaming\", \"idle\"] as const;\nexport type CacheWarmingMode = (typeof CACHE_WARMING_MODES)[number];\n\nimport type { Transport } from \"@bastani/pi-ai/compat\";\nimport type { ScrollViewScrollbar, WheelScrollLines } from \"@earendil-works/pi-tui\";\n\nexport interface CompactionModelOverride {\n\treserveTokens?: number;\n\tpreserve_recent?: number;\n}\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tcompression_ratio?: number; // default: 0.5 (fraction of compactable context to keep)\n\tpreserve_recent?: number; // default: 2 (recent context-eligible messages to keep)\n\tquery?: string; // default: auto-detected from session context\n\tmodelOverrides?: Record<string, CompactionModelOverride>; // exact \"provider/modelId\" keys\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface SessionSummarySettings {\n\tenabled?: boolean; // default: true - generate a one-line resume-picker summary once the agent goes idle\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tmaxAgentDelayMs?: number; // default: 60000\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n\thyperlinks?: boolean | \"auto\";\n\timages?: \"kitty\" | \"iterm2\" | \"auto\" | false;\n\ttrueColor?: boolean | \"auto\";\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface SearchSettings {\n\tcontextBefore?: number;\n\tcontextAfter?: number;\n}\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport type MermaidRenderingMode = \"off\" | \"final\" | \"streaming\";\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n\tmermaid?: MermaidRenderingMode; // default: \"streaming\"\n\tlatex?: boolean; // default: true\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport type DefaultProjectTrust = \"ask\" | \"always\" | \"never\";\nexport type QuietStartup = boolean | \"header\";\n\nexport type TransportSetting = Transport;\n\n/** What the terminal keeps when Atomic's fullscreen session exits. */\nexport type FullscreenExitOutput = \"transcript\" | \"resume-hint\";\n\nexport type CodemodeMode = \"on\" | \"only\";\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n * - autoload=false: start empty and apply only explicit resource patterns\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\tautoload?: boolean;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t\t\tworkflows?: string[];\n\t\t\tmcpServers?: string[];\n\t };\n\nexport interface BashInterceptorSettings {\n\tenabled?: boolean; // default: false\n}\n\n/** Provider filters for the candidates `model: \"auto\"` may route to. Does not affect `routerModel`. */\nexport interface ModelRoutingSettings {\n\t/** When nonempty, only these provider IDs are routing candidates. */\n\tallowedProviders?: string[];\n\t/** Provider IDs that are never routing candidates; applied after `allowedProviders`. */\n\texcludedProviders?: string[];\n}\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tfirstRunOnboardingStartedVersion?: string;\n\tonboardedVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\trouterModel?: string; // default: \"\"; workflow-stage/subagent auto-model router inference only, never \"auto\"\n\tmodelRouting?: ModelRoutingSettings;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\tmodelThinkingLevels?: Record<string, \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\">;\n\tfallbackModels?: string[]; // Ordered main-chat fallback models, optionally suffixed with :thinkingLevel\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tenableAnalytics?: boolean; // storage only; no analytics transmission is performed\n\ttrackingId?: string; // stable UUID generated on first analytics opt-in\n\tdeviceId?: string; // global installation ID, created only when a login needs it\n\tshowCacheMissNotices?: boolean; // default: false - show cache costs and provider recovery diagnostics\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tsessionSummary?: SessionSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\texternalEditor?: string; // Command for Ctrl+G external editor; takes precedence over VISUAL/EDITOR\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: QuietStartup; // default: false; true hides all startup output, \"header\" keeps only the startup header\n\tdefaultProjectTrust?: DefaultProjectTrust; // default: \"ask\"; global setting only\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tbashInterceptor?: BashInterceptorSettings; // default: disabled; when enabled, user_bash handlers can intercept bash tool execution\n\tsearch?: SearchSettings; // Context lines for search results; defaults: before=1, after=3\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - version-adoption ping on first interactive launch with fresh settings or after an update with changelog entries\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tworkflows?:\n\t\t| string[]\n\t\t| {\n\t\t\t\tpaths?: string[];\n\t\t\t\tdurability?: { systemDatabaseUrl?: string; systemDatabaseUrlFile?: string };\n\t\t };\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\therdr?: { enabled?: boolean }; // default: true, only inside an interactive Herdr pane\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdefaultTools?: string[]; // Initial tool selection; +name/-name modify inherited selection\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\toutputPad?: 0 | 1; // Horizontal padding for chat message output (default: 1)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tfullscreenScrollbar?: ScrollViewScrollbar; // default: \"auto\"\n\tfullscreenExitOutput?: FullscreenExitOutput; // default: \"transcript\"\n\tfullscreenCopyOnSelect?: boolean; // default: true\n\tfullscreenWheelScrollLines?: WheelScrollLines; // default: \"auto\", numeric values 1-100\n\tcodemode?: { mode?: CodemodeMode; inlineBudget?: number };\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpProxy?: string; // Proxy URL applied as HTTP_PROXY and HTTPS_PROXY; global setting only\n\thttpIdleTimeoutMs?: number | string; // HTTP idle timeout; 0 or \"disabled\" disables it\n\tcacheWarming?: CacheWarmingMode; // Global only; each refresh costs money. Default: streaming.\n\twebsocketConnectTimeoutMs?: number | string; // WebSocket connect timeout; 0 or \"disabled\" disables it\n\tstreamDeadlineMs?: number | string; // Max idle gap between provider stream events; 0 or \"disabled\" disables it\n}\n\nexport type SettingsScope = \"global\" | \"project\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport type SettingsFieldOrigin = \"primary\" | \"legacy\";\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n\t/**\n\t * Optional write-specific lock whose callback receives the current primary\n\t * document rather than a layered effective view. Storage implementations\n\t * without a distinct primary document can omit this method; layered storage\n\t * implementations must provide it to keep fallback fields out of the primary\n\t * document.\n\t */\n\twithPrimaryWriteLock?(scope: SettingsScope, fn: (currentPrimary: string | undefined) => string | undefined): void;\n\tgetFieldOrigin?(scope: SettingsScope, field: keyof Settings): SettingsFieldOrigin | undefined;\n}\n\nexport interface SettingsError {\n\tscope: SettingsScope;\n\tpath?: string;\n\terror: Error;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"settings-types.js","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,CAAU,CAAC","sourcesContent":["export const CACHE_WARMING_MODES = [\"off\", \"streaming\", \"idle\"] as const;\nexport type CacheWarmingMode = (typeof CACHE_WARMING_MODES)[number];\n\nimport type { Transport } from \"@bastani/pi-ai/compat\";\nimport type { ScrollViewScrollbar, WheelScrollLines } from \"@earendil-works/pi-tui\";\n\nexport interface CompactionModelOverride {\n\treserveTokens?: number;\n\tpreserve_recent?: number;\n}\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tcompression_ratio?: number; // default: 0.5 (fraction of compactable context to keep)\n\tpreserve_recent?: number; // default: 2 (recent context-eligible messages to keep)\n\tquery?: string; // default: auto-detected from session context\n\tmodelOverrides?: Record<string, CompactionModelOverride>; // exact \"provider/modelId\" keys\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface SessionSummarySettings {\n\tenabled?: boolean; // default: true - generate a one-line resume-picker summary once the agent goes idle\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tmaxAgentDelayMs?: number; // default: 60000\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n\thyperlinks?: boolean | \"auto\";\n\timages?: \"kitty\" | \"iterm2\" | \"auto\" | false;\n\ttrueColor?: boolean | \"auto\";\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface SearchSettings {\n\tcontextBefore?: number;\n\tcontextAfter?: number;\n}\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport type MermaidRenderingMode = \"off\" | \"final\" | \"streaming\";\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n\tmermaid?: MermaidRenderingMode; // default: \"streaming\"\n\tlatex?: boolean; // default: true\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport type DefaultProjectTrust = \"ask\" | \"always\" | \"never\";\nexport type QuietStartup = boolean | \"header\";\n\nexport type TransportSetting = Transport;\n\n/** What the terminal keeps when Atomic's fullscreen session exits. */\nexport type FullscreenExitOutput = \"transcript\" | \"resume-hint\";\n\nexport type CodemodeMode = \"on\" | \"only\";\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n * - autoload=false: start empty and apply only explicit resource patterns\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\tautoload?: boolean;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t\t\tworkflows?: string[];\n\t\t\tmcpServers?: string[];\n\t };\n\nexport interface BashInterceptorSettings {\n\tenabled?: boolean; // default: false\n}\n\n/** Provider filters for the candidates `model: \"auto\"` may route to. Does not affect `routerModel`. */\nexport interface ModelRoutingSettings {\n\t/** When nonempty, only these provider IDs are routing candidates. */\n\tallowedProviders?: string[];\n\t/** Provider IDs that are never routing candidates; applied after `allowedProviders`. */\n\texcludedProviders?: string[];\n}\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tfirstRunOnboardingStartedVersion?: string;\n\tonboardedVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\trouterModel?: string; // default: \"\"; workflow-stage/subagent auto-model router inference only, never \"auto\"\n\tcompactionModel?: string;\n\tmodelRouting?: ModelRoutingSettings;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\tmodelThinkingLevels?: Record<string, \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\">;\n\tfallbackModels?: string[]; // Ordered main-chat fallback models, optionally suffixed with :thinkingLevel\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tenableAnalytics?: boolean; // storage only; no analytics transmission is performed\n\ttrackingId?: string; // stable UUID generated on first analytics opt-in\n\tdeviceId?: string; // global installation ID, created only when a login needs it\n\tshowCacheMissNotices?: boolean; // default: false - show cache costs and provider recovery diagnostics\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tsessionSummary?: SessionSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\texternalEditor?: string; // Command for Ctrl+G external editor; takes precedence over VISUAL/EDITOR\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: QuietStartup; // default: false; true hides all startup output, \"header\" keeps only the startup header\n\tdefaultProjectTrust?: DefaultProjectTrust; // default: \"ask\"; global setting only\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tbashInterceptor?: BashInterceptorSettings; // default: disabled; when enabled, user_bash handlers can intercept bash tool execution\n\tsearch?: SearchSettings; // Context lines for search results; defaults: before=1, after=3\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - version-adoption ping on first interactive launch with fresh settings or after an update with changelog entries\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tworkflows?:\n\t\t| string[]\n\t\t| {\n\t\t\t\tpaths?: string[];\n\t\t\t\tdurability?: { systemDatabaseUrl?: string; systemDatabaseUrlFile?: string };\n\t\t };\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\therdr?: { enabled?: boolean }; // default: true, only inside an interactive Herdr pane\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdefaultTools?: string[]; // Initial tool selection; +name/-name modify inherited selection\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\toutputPad?: 0 | 1; // Horizontal padding for chat message output (default: 1)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tfullscreenScrollbar?: ScrollViewScrollbar; // default: \"auto\"\n\tfullscreenExitOutput?: FullscreenExitOutput; // default: \"transcript\"\n\tfullscreenCopyOnSelect?: boolean; // default: true\n\tfullscreenWheelScrollLines?: WheelScrollLines; // default: \"auto\", numeric values 1-100\n\tcodemode?: { mode?: CodemodeMode; inlineBudget?: number };\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpProxy?: string; // Proxy URL applied as HTTP_PROXY and HTTPS_PROXY; global setting only\n\thttpIdleTimeoutMs?: number | string; // HTTP idle timeout; 0 or \"disabled\" disables it\n\tcacheWarming?: CacheWarmingMode; // Global only; each refresh costs money. Default: streaming.\n\twebsocketConnectTimeoutMs?: number | string; // WebSocket connect timeout; 0 or \"disabled\" disables it\n\tstreamDeadlineMs?: number | string; // Max idle gap between provider stream events; 0 or \"disabled\" disables it\n}\n\nexport type SettingsScope = \"global\" | \"project\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport type SettingsFieldOrigin = \"primary\" | \"legacy\";\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n\t/**\n\t * Optional write-specific lock whose callback receives the current primary\n\t * document rather than a layered effective view. Storage implementations\n\t * without a distinct primary document can omit this method; layered storage\n\t * implementations must provide it to keep fallback fields out of the primary\n\t * document.\n\t */\n\twithPrimaryWriteLock?(scope: SettingsScope, fn: (currentPrimary: string | undefined) => string | undefined): void;\n\tgetFieldOrigin?(scope: SettingsScope, field: keyof Settings): SettingsFieldOrigin | undefined;\n}\n\nexport interface SettingsError {\n\tscope: SettingsScope;\n\tpath?: string;\n\terror: Error;\n}\n"]}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { JsonObject, JsonValue } from "@bastani/pi-ai";
|
|
2
|
+
import type { AgentSessionEvent } from "./agent-session-types.js";
|
|
3
|
+
/** Assistant prose. */
|
|
4
|
+
export interface TranscriptTextPart {
|
|
5
|
+
type: "text";
|
|
6
|
+
text: string;
|
|
7
|
+
}
|
|
8
|
+
/** Visible assistant reasoning. Redacted thinking blocks are never reported. */
|
|
9
|
+
export interface TranscriptThinkingPart {
|
|
10
|
+
type: "thinking";
|
|
11
|
+
thinking: string;
|
|
12
|
+
}
|
|
13
|
+
/** The latest result reported for a tool call. */
|
|
14
|
+
export interface TranscriptToolResult {
|
|
15
|
+
/** Text content of the result, joined with newlines. Set when the tool reports `"content"`. */
|
|
16
|
+
content?: string;
|
|
17
|
+
/**
|
|
18
|
+
* The result's `details`, or `null` when it had none. Set when the tool reports `"details"`.
|
|
19
|
+
* A failed call without details also carries its error text in `content`.
|
|
20
|
+
*/
|
|
21
|
+
details?: JsonValue;
|
|
22
|
+
isError: boolean;
|
|
23
|
+
/** True while the result comes from `tool_execution_update` and the tool is still running. */
|
|
24
|
+
isPartial: boolean;
|
|
25
|
+
}
|
|
26
|
+
/** A tool call from assistant content, joined by id with its execution result. */
|
|
27
|
+
export interface TranscriptToolCallPart {
|
|
28
|
+
type: "toolCall";
|
|
29
|
+
id: string;
|
|
30
|
+
name: string;
|
|
31
|
+
arguments: JsonObject;
|
|
32
|
+
/** Absent until the tool reports an update or finishes. */
|
|
33
|
+
result?: TranscriptToolResult;
|
|
34
|
+
}
|
|
35
|
+
export type TranscriptPart = TranscriptTextPart | TranscriptThinkingPart | TranscriptToolCallPart;
|
|
36
|
+
/** Which field of a tool result to report: its text content (the default) or its `details`. */
|
|
37
|
+
export type TranscriptToolResultFormat = "content" | "details";
|
|
38
|
+
export interface TranscriptOptions {
|
|
39
|
+
/** Choose per tool whether `result.content` or `result.details` is reported. Defaults to `"content"`. */
|
|
40
|
+
toolResult?: (toolName: string) => TranscriptToolResultFormat;
|
|
41
|
+
}
|
|
42
|
+
export interface Transcript {
|
|
43
|
+
/** Feed one session event. Events from nested tool calls (`parentToolCallId`) are ignored. */
|
|
44
|
+
apply(event: AgentSessionEvent): void;
|
|
45
|
+
/** Ordered parts of every assistant message seen so far, including the one still streaming. */
|
|
46
|
+
parts(): TranscriptPart[];
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Reduce session events into the assistant's output as plain JSON parts.
|
|
50
|
+
*
|
|
51
|
+
* ```ts
|
|
52
|
+
* const transcript = createTranscript();
|
|
53
|
+
* session.subscribe((event) => transcript.apply(event));
|
|
54
|
+
* transcript.parts();
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export declare function createTranscript(options?: TranscriptOptions): Transcript;
|
|
58
|
+
//# sourceMappingURL=transcript.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version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K,IAAI,cAAc,EAAE,CAAC;CAC1B;AA+BD;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,iBAAsB,GAAG,UAAU,CAuJ5E"}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { applyAssistantMessageDelta, beginStreamingAssistantMessage, } from "../modes/interactive/streaming-assistant-message.js";
|
|
2
|
+
/** A detached, JSON-shaped copy, so callers cannot mutate transcript state and parts always serialize. */
|
|
3
|
+
function toJson(value) {
|
|
4
|
+
try {
|
|
5
|
+
const text = JSON.stringify(value);
|
|
6
|
+
return text === undefined ? null : JSON.parse(text);
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function hasToolCall(message, id) {
|
|
13
|
+
return message.content.some((block) => block.type === "toolCall" && block.id === id);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Reduce session events into the assistant's output as plain JSON parts.
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* const transcript = createTranscript();
|
|
20
|
+
* session.subscribe((event) => transcript.apply(event));
|
|
21
|
+
* transcript.parts();
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export function createTranscript(options = {}) {
|
|
25
|
+
const entries = [];
|
|
26
|
+
/** Results that arrived before any assistant message held their tool call. */
|
|
27
|
+
const unbound = new Map();
|
|
28
|
+
let streaming;
|
|
29
|
+
/** Bind to the most recent call with this id that has no final result, so reused ids keep separate results. */
|
|
30
|
+
const record = (id, raw) => {
|
|
31
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
32
|
+
const entry = entries[i];
|
|
33
|
+
if (!hasToolCall(entry.message, id) || entry.results.get(id)?.isPartial === false)
|
|
34
|
+
continue;
|
|
35
|
+
entry.results.set(id, raw);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (raw.isPartial && unbound.get(id)?.isPartial === false)
|
|
39
|
+
return;
|
|
40
|
+
unbound.set(id, raw);
|
|
41
|
+
};
|
|
42
|
+
const adopt = (entry) => {
|
|
43
|
+
for (const block of entry.message.content) {
|
|
44
|
+
if (block.type !== "toolCall" || entry.results.has(block.id))
|
|
45
|
+
continue;
|
|
46
|
+
const raw = unbound.get(block.id);
|
|
47
|
+
if (!raw)
|
|
48
|
+
continue;
|
|
49
|
+
entry.results.set(block.id, raw);
|
|
50
|
+
unbound.delete(block.id);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
const settle = (entry) => {
|
|
54
|
+
const message = entry.message;
|
|
55
|
+
if (message.stopReason !== "aborted" && message.stopReason !== "error")
|
|
56
|
+
return;
|
|
57
|
+
const text = message.errorMessage || (message.stopReason === "aborted" ? "Operation aborted" : "Unknown error");
|
|
58
|
+
for (const block of message.content) {
|
|
59
|
+
if (block.type !== "toolCall" || entry.results.get(block.id)?.isPartial === false)
|
|
60
|
+
continue;
|
|
61
|
+
entry.results.set(block.id, {
|
|
62
|
+
result: { content: [{ type: "text", text }] },
|
|
63
|
+
isError: true,
|
|
64
|
+
isPartial: false,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const toolResult = (toolName, raw) => {
|
|
69
|
+
const value = raw.result;
|
|
70
|
+
let content = typeof value === "string" ? value : "";
|
|
71
|
+
if (typeof value === "object" && value !== null && Array.isArray(value.content)) {
|
|
72
|
+
content = value.content
|
|
73
|
+
.filter((item) => item?.type === "text")
|
|
74
|
+
.map((item) => item.text)
|
|
75
|
+
.join("\n");
|
|
76
|
+
}
|
|
77
|
+
if ((options.toolResult?.(toolName) ?? "content") === "details") {
|
|
78
|
+
const details = toJson(typeof value === "object" && value !== null ? value.details : undefined);
|
|
79
|
+
const errorText = raw.isError && details === null && content !== "" ? { content } : {};
|
|
80
|
+
return { details, ...errorText, isError: raw.isError, isPartial: raw.isPartial };
|
|
81
|
+
}
|
|
82
|
+
return { content, isError: raw.isError, isPartial: raw.isPartial };
|
|
83
|
+
};
|
|
84
|
+
return {
|
|
85
|
+
apply(event) {
|
|
86
|
+
if ("parentToolCallId" in event && typeof event.parentToolCallId === "string")
|
|
87
|
+
return;
|
|
88
|
+
switch (event.type) {
|
|
89
|
+
case "message_start":
|
|
90
|
+
if (event.message.role !== "assistant")
|
|
91
|
+
return;
|
|
92
|
+
streaming = { message: beginStreamingAssistantMessage(event.message), results: new Map() };
|
|
93
|
+
entries.push(streaming);
|
|
94
|
+
return;
|
|
95
|
+
case "message_update": {
|
|
96
|
+
if (!streaming) {
|
|
97
|
+
streaming = {
|
|
98
|
+
message: {
|
|
99
|
+
role: "assistant",
|
|
100
|
+
content: [],
|
|
101
|
+
api: "",
|
|
102
|
+
provider: "",
|
|
103
|
+
model: "",
|
|
104
|
+
usage: {
|
|
105
|
+
input: 0,
|
|
106
|
+
output: 0,
|
|
107
|
+
cacheRead: 0,
|
|
108
|
+
cacheWrite: 0,
|
|
109
|
+
totalTokens: 0,
|
|
110
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
111
|
+
},
|
|
112
|
+
stopReason: "stop",
|
|
113
|
+
timestamp: Date.now(),
|
|
114
|
+
},
|
|
115
|
+
results: new Map(),
|
|
116
|
+
};
|
|
117
|
+
entries.push(streaming);
|
|
118
|
+
}
|
|
119
|
+
const delta = event.assistantMessageEvent;
|
|
120
|
+
applyAssistantMessageDelta(streaming.message, delta);
|
|
121
|
+
if (delta.type === "thinking_start" ||
|
|
122
|
+
delta.type === "thinking_delta" ||
|
|
123
|
+
delta.type === "thinking_end") {
|
|
124
|
+
// Deltas do not carry the redaction flag; the provider's partial does.
|
|
125
|
+
const source = delta.partial?.content[delta.contentIndex];
|
|
126
|
+
const block = streaming.message.content[delta.contentIndex];
|
|
127
|
+
if (source?.type === "thinking" && source.redacted && block?.type === "thinking")
|
|
128
|
+
block.redacted = true;
|
|
129
|
+
}
|
|
130
|
+
adopt(streaming);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
case "message_end": {
|
|
134
|
+
if (event.message.role !== "assistant")
|
|
135
|
+
return;
|
|
136
|
+
const message = beginStreamingAssistantMessage(event.message);
|
|
137
|
+
const entry = streaming ?? { message, results: new Map() };
|
|
138
|
+
if (streaming)
|
|
139
|
+
entry.message = message;
|
|
140
|
+
else
|
|
141
|
+
entries.push(entry);
|
|
142
|
+
streaming = undefined;
|
|
143
|
+
adopt(entry);
|
|
144
|
+
settle(entry);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
case "tool_execution_update":
|
|
148
|
+
record(event.toolCallId, { result: event.partialResult, isError: false, isPartial: true });
|
|
149
|
+
return;
|
|
150
|
+
case "tool_execution_end":
|
|
151
|
+
record(event.toolCallId, { result: event.result, isError: event.isError, isPartial: false });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
parts() {
|
|
156
|
+
const parts = [];
|
|
157
|
+
for (const { message, results } of entries) {
|
|
158
|
+
for (const block of message.content) {
|
|
159
|
+
if (block.type === "text") {
|
|
160
|
+
if (block.text)
|
|
161
|
+
parts.push({ type: "text", text: block.text });
|
|
162
|
+
}
|
|
163
|
+
else if (block.type === "thinking") {
|
|
164
|
+
if (!block.redacted && block.thinking)
|
|
165
|
+
parts.push({ type: "thinking", thinking: block.thinking });
|
|
166
|
+
}
|
|
167
|
+
else if (block.type === "toolCall") {
|
|
168
|
+
const raw = results.get(block.id);
|
|
169
|
+
const part = {
|
|
170
|
+
type: "toolCall",
|
|
171
|
+
id: block.id,
|
|
172
|
+
name: block.name,
|
|
173
|
+
arguments: toJson(block.arguments),
|
|
174
|
+
};
|
|
175
|
+
if (raw)
|
|
176
|
+
part.result = toolResult(block.name, raw);
|
|
177
|
+
parts.push(part);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return parts;
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
//# sourceMappingURL=transcript.js.map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BACtC,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,QAAQ;4BAAE,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;oBACnG,CAAC;yBAAM,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;wBACtC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;wBAClC,MAAM,IAAI,GAA2B;4BACpC,IAAI,EAAE,UAAU;4BAChB,EAAE,EAAE,KAAK,CAAC,EAAE;4BACZ,IAAI,EAAE,KAAK,CAAC,IAAI;4BAChB,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,SAAS,CAAe;yBAChD,CAAC;wBACF,IAAI,GAAG;4BAAE,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;wBACnD,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;oBAClB,CAAC;gBACF,CAAC;YACF,CAAC;YACD,OAAO,KAAK,CAAC;QACd,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { JsonObject, JsonValue } from \"@bastani/pi-ai\";\nimport type { AssistantMessage, TextContent } from \"@bastani/pi-ai/compat\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport {\n\tapplyAssistantMessageDelta,\n\tbeginStreamingAssistantMessage,\n} from \"../modes/interactive/streaming-assistant-message.ts\";\nimport type { AgentSessionEvent } from \"./agent-session-types.js\";\n\n/** Assistant prose. */\nexport interface TranscriptTextPart {\n\ttype: \"text\";\n\ttext: string;\n}\n\n/** Visible assistant reasoning. Redacted thinking blocks are never reported. */\nexport interface TranscriptThinkingPart {\n\ttype: \"thinking\";\n\tthinking: string;\n}\n\n/** The latest result reported for a tool call. */\nexport interface TranscriptToolResult {\n\t/** Text content of the result, joined with newlines. Set when the tool reports `\"content\"`. */\n\tcontent?: string;\n\t/**\n\t * The result's `details`, or `null` when it had none. Set when the tool reports `\"details\"`.\n\t * A failed call without details also carries its error text in `content`.\n\t */\n\tdetails?: JsonValue;\n\tisError: boolean;\n\t/** True while the result comes from `tool_execution_update` and the tool is still running. */\n\tisPartial: boolean;\n}\n\n/** A tool call from assistant content, joined by id with its execution result. */\nexport interface TranscriptToolCallPart {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: JsonObject;\n\t/** Absent until the tool reports an update or finishes. */\n\tresult?: TranscriptToolResult;\n}\n\nexport type TranscriptPart = TranscriptTextPart | TranscriptThinkingPart | TranscriptToolCallPart;\n\n/** Which field of a tool result to report: its text content (the default) or its `details`. */\nexport type TranscriptToolResultFormat = \"content\" | \"details\";\n\nexport interface TranscriptOptions {\n\t/** Choose per tool whether `result.content` or `result.details` is reported. Defaults to `\"content\"`. */\n\ttoolResult?: (toolName: string) => TranscriptToolResultFormat;\n}\n\nexport interface Transcript {\n\t/** Feed one session event. Events from nested tool calls (`parentToolCallId`) are ignored. */\n\tapply(event: AgentSessionEvent): void;\n\t/** Ordered parts of every assistant message seen so far, including the one still streaming. */\n\tparts(): TranscriptPart[];\n}\n\n/** What a tool reports as its result; anything else reports empty content and no details. */\ntype ToolResultValue = Partial<AgentToolResult> | string | null | undefined;\n\ninterface RawToolResult {\n\tresult: ToolResultValue;\n\tisError: boolean;\n\tisPartial: boolean;\n}\n\n/** One assistant message and the results bound to its tool calls, keyed by call id. */\ninterface MessageEntry {\n\tmessage: AssistantMessage;\n\tresults: Map<string, RawToolResult>;\n}\n\n/** A detached, JSON-shaped copy, so callers cannot mutate transcript state and parts always serialize. */\nfunction toJson(value: JsonValue | undefined): JsonValue {\n\ttry {\n\t\tconst text = JSON.stringify(value);\n\t\treturn text === undefined ? null : (JSON.parse(text) as JsonValue);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction hasToolCall(message: AssistantMessage, id: string): boolean {\n\treturn message.content.some((block) => block.type === \"toolCall\" && block.id === id);\n}\n\n/**\n * Reduce session events into the assistant's output as plain JSON parts.\n *\n * ```ts\n * const transcript = createTranscript();\n * session.subscribe((event) => transcript.apply(event));\n * transcript.parts();\n * ```\n */\nexport function createTranscript(options: TranscriptOptions = {}): Transcript {\n\tconst entries: MessageEntry[] = [];\n\t/** Results that arrived before any assistant message held their tool call. */\n\tconst unbound = new Map<string, RawToolResult>();\n\tlet streaming: MessageEntry | undefined;\n\n\t/** Bind to the most recent call with this id that has no final result, so reused ids keep separate results. */\n\tconst record = (id: string, raw: RawToolResult): void => {\n\t\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\t\tconst entry = entries[i];\n\t\t\tif (!hasToolCall(entry.message, id) || entry.results.get(id)?.isPartial === false) continue;\n\t\t\tentry.results.set(id, raw);\n\t\t\treturn;\n\t\t}\n\t\tif (raw.isPartial && unbound.get(id)?.isPartial === false) return;\n\t\tunbound.set(id, raw);\n\t};\n\n\tconst adopt = (entry: MessageEntry): void => {\n\t\tfor (const block of entry.message.content) {\n\t\t\tif (block.type !== \"toolCall\" || entry.results.has(block.id)) continue;\n\t\t\tconst raw = unbound.get(block.id);\n\t\t\tif (!raw) continue;\n\t\t\tentry.results.set(block.id, raw);\n\t\t\tunbound.delete(block.id);\n\t\t}\n\t};\n\n\tconst settle = (entry: MessageEntry): void => {\n\t\tconst message = entry.message;\n\t\tif (message.stopReason !== \"aborted\" && message.stopReason !== \"error\") return;\n\t\tconst text = message.errorMessage || (message.stopReason === \"aborted\" ? \"Operation aborted\" : \"Unknown error\");\n\t\tfor (const block of message.content) {\n\t\t\tif (block.type !== \"toolCall\" || entry.results.get(block.id)?.isPartial === false) continue;\n\t\t\tentry.results.set(block.id, {\n\t\t\t\tresult: { content: [{ type: \"text\", text }] },\n\t\t\t\tisError: true,\n\t\t\t\tisPartial: false,\n\t\t\t});\n\t\t}\n\t};\n\n\tconst toolResult = (toolName: string, raw: RawToolResult): TranscriptToolResult => {\n\t\tconst value = raw.result;\n\t\tlet content = typeof value === \"string\" ? value : \"\";\n\t\tif (typeof value === \"object\" && value !== null && Array.isArray(value.content)) {\n\t\t\tcontent = value.content\n\t\t\t\t.filter((item): item is TextContent => item?.type === \"text\")\n\t\t\t\t.map((item) => item.text)\n\t\t\t\t.join(\"\\n\");\n\t\t}\n\t\tif ((options.toolResult?.(toolName) ?? \"content\") === \"details\") {\n\t\t\tconst details = toJson(typeof value === \"object\" && value !== null ? value.details : undefined);\n\t\t\tconst errorText = raw.isError && details === null && content !== \"\" ? { content } : {};\n\t\t\treturn { details, ...errorText, isError: raw.isError, isPartial: raw.isPartial };\n\t\t}\n\t\treturn { content, isError: raw.isError, isPartial: raw.isPartial };\n\t};\n\n\treturn {\n\t\tapply(event) {\n\t\t\tif (\"parentToolCallId\" in event && typeof event.parentToolCallId === \"string\") return;\n\t\t\tswitch (event.type) {\n\t\t\t\tcase \"message_start\":\n\t\t\t\t\tif (event.message.role !== \"assistant\") return;\n\t\t\t\t\tstreaming = { message: beginStreamingAssistantMessage(event.message), results: new Map() };\n\t\t\t\t\tentries.push(streaming);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"message_update\": {\n\t\t\t\t\tif (!streaming) {\n\t\t\t\t\t\tstreaming = {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\t\tcontent: [],\n\t\t\t\t\t\t\t\tapi: \"\",\n\t\t\t\t\t\t\t\tprovider: \"\",\n\t\t\t\t\t\t\t\tmodel: \"\",\n\t\t\t\t\t\t\t\tusage: {\n\t\t\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstopReason: \"stop\",\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\tresults: new Map(),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tentries.push(streaming);\n\t\t\t\t\t}\n\t\t\t\t\tconst delta = event.assistantMessageEvent;\n\t\t\t\t\tapplyAssistantMessageDelta(streaming.message, delta);\n\t\t\t\t\tif (\n\t\t\t\t\t\tdelta.type === \"thinking_start\" ||\n\t\t\t\t\t\tdelta.type === \"thinking_delta\" ||\n\t\t\t\t\t\tdelta.type === \"thinking_end\"\n\t\t\t\t\t) {\n\t\t\t\t\t\t// Deltas do not carry the redaction flag; the provider's partial does.\n\t\t\t\t\t\tconst source = delta.partial?.content[delta.contentIndex];\n\t\t\t\t\t\tconst block = streaming.message.content[delta.contentIndex];\n\t\t\t\t\t\tif (source?.type === \"thinking\" && source.redacted && block?.type === \"thinking\")\n\t\t\t\t\t\t\tblock.redacted = true;\n\t\t\t\t\t}\n\t\t\t\t\tadopt(streaming);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase \"message_end\": {\n\t\t\t\t\tif (event.message.role !== \"assistant\") return;\n\t\t\t\t\tconst message = beginStreamingAssistantMessage(event.message);\n\t\t\t\t\tconst entry = streaming ?? { message, results: new Map<string, RawToolResult>() };\n\t\t\t\t\tif (streaming) entry.message = message;\n\t\t\t\t\telse entries.push(entry);\n\t\t\t\t\tstreaming = undefined;\n\t\t\t\t\tadopt(entry);\n\t\t\t\t\tsettle(entry);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase \"tool_execution_update\":\n\t\t\t\t\trecord(event.toolCallId, { result: event.partialResult, isError: false, isPartial: true });\n\t\t\t\t\treturn;\n\t\t\t\tcase \"tool_execution_end\":\n\t\t\t\t\trecord(event.toolCallId, { result: event.result, isError: event.isError, isPartial: false });\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t},\n\t\tparts() {\n\t\t\tconst parts: TranscriptPart[] = [];\n\t\t\tfor (const { message, results } of entries) {\n\t\t\t\tfor (const block of message.content) {\n\t\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\t\tif (block.text) parts.push({ type: \"text\", text: block.text });\n\t\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t\tif (!block.redacted && block.thinking) parts.push({ type: \"thinking\", thinking: block.thinking });\n\t\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\t\tconst raw = results.get(block.id);\n\t\t\t\t\t\tconst part: TranscriptToolCallPart = {\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: block.id,\n\t\t\t\t\t\t\tname: block.name,\n\t\t\t\t\t\t\targuments: toJson(block.arguments) as JsonObject,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (raw) part.result = toolResult(block.name, raw);\n\t\t\t\t\t\tparts.push(part);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn parts;\n\t\t},\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,QAAQ,EAQR,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAa,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAWhF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAEnF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAKlE,OAAO,EAIN,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAGxB,MAAM,WAAW,CAAC;AAqCnB,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAsB1F;AAOD,kHAAkH;AAClH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAa5E;
|
|
1
|
+
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,QAAQ,EAQR,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAa,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAWhF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAEnF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAKlE,OAAO,EAIN,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAGxB,MAAM,WAAW,CAAC;AAqCnB,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAsB1F;AAOD,kHAAkH;AAClH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAa5E;AAgTD,wBAAsB,eAAe,CACpC,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,iBAAiB,EACxB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,eAAe,CAAC,mBAAmB,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,EAC5E,GAAG,EAAE,oBAAoB,GAAG,SAAS,EACrC,OAAO,GAAE,mBAAwB,GAC/B,OAAO,CAAC,eAAe,CAAC,mBAAmB,CAAC,CAAC,CAqI/C"}
|
|
@@ -106,13 +106,26 @@ function describeValue(value) {
|
|
|
106
106
|
}
|
|
107
107
|
return typeof value === "string" ? "a string" : `a ${typeof value}`;
|
|
108
108
|
}
|
|
109
|
-
const CLASSIFIER_CONTEXT_SHAPE = '{ state: { ... }, questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';
|
|
109
|
+
const CLASSIFIER_CONTEXT_SHAPE = '{ state: { ... }, images?: [{ type: "image", data: <base64>, mimeType }], questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';
|
|
110
110
|
function checkClassifierContext(context) {
|
|
111
111
|
const fail = (problem) => new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`);
|
|
112
112
|
if (!isRecord(context))
|
|
113
113
|
throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
|
|
114
114
|
if (!isRecord(context.state))
|
|
115
115
|
throw fail(`context.state must be an object, got ${describeValue(context.state)}`);
|
|
116
|
+
const { images } = context;
|
|
117
|
+
if (images !== undefined) {
|
|
118
|
+
if (!Array.isArray(images))
|
|
119
|
+
throw fail(`context.images must be an array, got ${describeValue(images)}`);
|
|
120
|
+
images.forEach((image, index) => {
|
|
121
|
+
if (!isRecord(image) ||
|
|
122
|
+
image.type !== "image" ||
|
|
123
|
+
typeof image.data !== "string" ||
|
|
124
|
+
typeof image.mimeType !== "string") {
|
|
125
|
+
throw fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
116
129
|
const { questions } = context;
|
|
117
130
|
if (!isRecord(questions) || Object.keys(questions).length === 0)
|
|
118
131
|
throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":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AAE,CAAC;QAC3B,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;KACvC,CAAC;AACH,CAAC","sourcesContent":["import type {\n\tAnyModel,\n\tClassifierContext,\n\tImageContent,\n\tImagesContext,\n\tModelType,\n\tModelTypeMap,\n\tTextContent,\n\tUsage,\n} from \"@bastani/pi-ai\";\nimport type { AgentTool, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerUrl, getQuickJSWasmPath } from \"../../config.js\";\nimport type { ExtensionToolContext } from \"../../core/extensions/context-types.ts\";\nimport type { ToolNamespace } from \"../../core/extensions/tool-types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { formatSize } from \"../../core/tools/truncate.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.js\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.js\";\nimport {\n\tCODEMODE_DOCS_PATH,\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeNestedCall,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.js\";\n\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n\t\"image/png\": \".png\",\n\t\"image/jpeg\": \".jpg\",\n\t\"image/gif\": \".gif\",\n\t\"image/webp\": \".webp\",\n};\n\nasync function saveImages(items: (TextContent | ImageContent)[]): Promise<(TextContent | ImageContent)[]> {\n\tconst labels = new Map<string, Promise<string>>();\n\tconst label = async ({ data, mimeType }: ImageContent): Promise<string> => {\n\t\tconst bytes = Buffer.from(data, \"base64\");\n\t\tconst kind = `${mimeType}, ${formatSize(bytes.length)}`;\n\t\tconst extension = IMAGE_EXTENSIONS[mimeType];\n\t\tif (!extension) throw new Error(`No file extension for image type ${mimeType}`);\n\t\ttry {\n\t\t\tconst path = await writeOutputFile(\"atomic-codemode\", extension, bytes);\n\t\t\treturn `[Image saved to ${path} (${kind})]`;\n\t\t} catch (error) {\n\t\t\treturn `[Image (${kind}) could not be saved: ${error instanceof Error ? error.message : String(error)}]`;\n\t\t}\n\t};\n\tconst result = await Promise.all(\n\t\titems.map(async (item): Promise<(TextContent | ImageContent)[]> => {\n\t\t\tif (item.type !== \"image\") return [item];\n\t\t\tlet pending = labels.get(item.data);\n\t\t\tif (!pending) {\n\t\t\t\tpending = label(item);\n\t\t\t\tlabels.set(item.data, pending);\n\t\t\t}\n\t\t\treturn [{ type: \"text\", text: await pending }, item];\n\t\t}),\n\t);\n\treturn result.flat();\n}\n\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (\n\t\t\tentry.type !== \"custom\" ||\n\t\t\tentry.customType !== CODEMODE_STORE_ENTRY_TYPE ||\n\t\t\ttypeof entry.data !== \"object\" ||\n\t\t\tentry.data === null\n\t\t)\n\t\t\tcontinue;\n\t\tconst data = entry.data as { set?: Record<string, unknown>; delete?: string[] };\n\t\tif (\n\t\t\t!data.set ||\n\t\t\ttypeof data.set !== \"object\" ||\n\t\t\t!Array.isArray(data.delete) ||\n\t\t\t!data.delete.every((key) => typeof key === \"string\")\n\t\t)\n\t\t\tcontinue;\n\t\tfor (const key of data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn result.content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n/** Explicit public catalog fields. Provider configuration and credential-bearing URLs never cross into the VM. */\nexport function toCodemodeModelInfo(model: AnyModel): Record<string, unknown> {\n\treturn {\n\t\ttype: model.type,\n\t\tprovider: model.provider,\n\t\tid: model.id,\n\t\tname: model.name,\n\t\tapi: model.api,\n\t\tinput: model.input,\n\t\t...(\"reasoning\" in model ? { reasoning: model.reasoning } : {}),\n\t\t...(\"contextWindow\" in model ? { contextWindow: model.contextWindow } : {}),\n\t\t...(\"maxTokens\" in model ? { maxTokens: model.maxTokens } : {}),\n\t\tcost: model.cost,\n\t};\n}\nconst MODEL_TYPES = [\"chat\", \"image\", \"classifier\"] as const;\nfunction modelType(value: unknown): ModelType {\n\tif (value === \"chat\" || value === \"image\" || value === \"classifier\") return value;\n\tthrow new Error('Model type must be \"chat\", \"image\", or \"classifier\"');\n}\nfunction withArticle(word: string): string {\n\treturn `${/^[aeiou]/.test(word) ? \"an\" : \"a\"} ${word}`;\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction describeValue(value: unknown): string {\n\tif (value === undefined || value === null) return String(value);\n\tif (Array.isArray(value)) return value.length === 0 ? \"an empty array\" : \"an array\";\n\tif (typeof value === \"object\") {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{ ${keys.slice(0, 6).join(\", \")}${keys.length > 6 ? \", ...\" : \"\"} }`;\n\t}\n\treturn typeof value === \"string\" ? \"a string\" : `a ${typeof value}`;\n}\nconst CLASSIFIER_CONTEXT_SHAPE =\n\t'{ state: { ... }, questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';\nfunction checkClassifierContext(context: unknown): ClassifierContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See \"Classify\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tif (!isRecord(context.state)) throw fail(`context.state must be an object, got ${describeValue(context.state)}`);\n\tconst { questions } = context;\n\tif (!isRecord(questions) || Object.keys(questions).length === 0)\n\t\tthrow fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);\n\tconst isStrings = (values: unknown[]) => values.length > 0 && values.every((value) => typeof value === \"string\");\n\tfor (const [questionId, question] of Object.entries(questions)) {\n\t\tconst at = `context.questions.${questionId}`;\n\t\tif (!isRecord(question)) throw fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\tif (typeof question.instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tconst { criteria } = question;\n\t\tif (question.type === \"choice\") {\n\t\t\tif (!isRecord(criteria) || !isStrings(Object.values(criteria)))\n\t\t\t\tthrow fail(`${at} is a \"choice\" question, so criteria must map each label to its meaning`);\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (!Array.isArray(criteria) || !isStrings(criteria))\n\t\t\t\tthrow fail(`${at} is a \"score\" question, so criteria must list the levels as strings, lowest first`);\n\t\t} else if (question.type === \"bool\") {\n\t\t\tif (!isRecord(criteria) || typeof criteria.true !== \"string\" || typeof criteria.false !== \"string\")\n\t\t\t\tthrow fail(`${at} is a \"bool\" question, so criteria must be { true: string, false: string }`);\n\t\t} else {\n\t\t\tthrow fail(`${at}.type must be \"choice\", \"score\", or \"bool\", got ${JSON.stringify(question.type)}`);\n\t\t}\n\t}\n\treturn context as unknown as ClassifierContext;\n}\nfunction checkImagesContext(context: unknown): ImagesContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.generateImages() ${problem}. Expected context: { input: [{ type: \"text\", text: <prompt> }, ...optional { type: \"image\", data: <base64>, mimeType } references] }. See \"Generate images\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tconst { input } = context;\n\tif (!Array.isArray(input) || input.length === 0)\n\t\tthrow fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);\n\tinput.forEach((block: unknown, index) => {\n\t\tif (isRecord(block) && block.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (\n\t\t\tisRecord(block) &&\n\t\t\tblock.type === \"image\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t)\n\t\t\treturn;\n\t\tthrow fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);\n\t});\n\treturn context as unknown as ImagesContext;\n}\nfunction provider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value === \"string\") return value;\n\tthrow new Error(\"provider must be a string\");\n}\nfunction preview(args: unknown): string {\n\ttry {\n\t\treturn (JSON.stringify(args) ?? \"\").slice(0, 200);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\ninterface ModelCallResult {\n\tstopReason: \"stop\" | \"error\" | \"aborted\";\n\terrorMessage?: string;\n\tusage?: Usage;\n}\nfunction createLimiter(limit: number) {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async <T>(run: () => Promise<T>): Promise<T> => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\nfunction discoveryGlobals(\n\ttools: readonly AgentTool[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, config] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = config?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0)\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\tif (config?.namespace !== undefined && typeof config.namespace !== \"string\")\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\tconst docs = tools.flatMap((tool) => {\n\t\t\t\t\tconst namespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\treturn config?.namespace && namespace?.name !== config.namespace\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: [createToolSearchDocument(tool, namespace)];\n\t\t\t\t});\n\t\t\t\treturn new Bm25Ranker().rank(query, docs, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find((tool) => tool.name === name || toCodemodeIdentifier(tool.name) === name);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (toolNamespace?.name !== name) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\nfunction modelGlobals(\n\tctx: ExtensionToolContext,\n\tid: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n\taddGeneratedImages: (count: number) => void,\n): CodemodeTool[] {\n\tconst models = ctx.modelRegistry;\n\tconst limit = createLimiter(4);\n\tlet count = 0;\n\tconst runModelCall = async <TType extends \"classifier\" | \"image\", TContext, TResult extends ModelCallResult>(\n\t\tname: string,\n\t\ttype: TType,\n\t\t[ref, context]: unknown[],\n\t\tcheckContext: (context: unknown) => TContext,\n\t\trun: (model: ModelTypeMap[TType], context: TContext) => Promise<TResult>,\n\t): Promise<TResult> => {\n\t\tconst listHint = `List the ${type} models you can use with models.getAvailableOfType(\"${type}\").`;\n\t\tif (!isRecord(ref) || typeof ref.provider !== \"string\" || typeof ref.id !== \"string\") {\n\t\t\tconst undefinedHint =\n\t\t\t\tref === undefined || ref === null\n\t\t\t\t\t? \" models.getModelOfType() returns undefined for an unknown provider or id.\"\n\t\t\t\t\t: \"\";\n\t\t\tthrow new Error(\n\t\t\t\t`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(ref)}.${undefinedHint} ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst { provider: providerId, id: modelId } = ref;\n\t\tconst model = models.getModelOfType(type, providerId, modelId);\n\t\tif (!model) {\n\t\t\tconst actualType = MODEL_TYPES.find(\n\t\t\t\t(other) => other !== type && models.getModelOfType(other, providerId, modelId) !== undefined,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\tactualType\n\t\t\t\t\t? `\"${providerId}/${modelId}\" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`\n\t\t\t\t\t: `Unknown ${type} model \"${providerId}/${modelId}\". ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst checked = checkContext(context);\n\t\tconst record: CodemodeNestedCall = {\n\t\t\tid: `${id}/${name}/${++count}`,\n\t\t\tname,\n\t\t\targs: `${model.provider}/${model.id}`,\n\t\t\tstatus: \"running\",\n\t\t};\n\t\tcalls.push(record);\n\t\tpublish();\n\t\tconst start = performance.now();\n\t\tconst result = await limit(() => run(model, checked));\n\t\trecord.durationMs = performance.now() - start;\n\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\tif (result.errorMessage) record.error = result.errorMessage.slice(0, 500);\n\t\tif (result.usage) {\n\t\t\trecord.cost = result.usage.cost.total;\n\t\t\taddUsage(result.usage);\n\t\t}\n\t\tpublish();\n\t\treturn result;\n\t};\n\treturn [\n\t\t{\n\t\t\tname: \"models.getModelsOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn models.getModelsOfType(modelType(type), provider(source)).map(toCodemodeModelInfo);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getAvailableOfType\",\n\t\t\tspread: true,\n\t\t\texecute: async (args, { signal }) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn (await models.getAvailableOfType(modelType(type), provider(source), { signal })).map(\n\t\t\t\t\ttoCodemodeModelInfo,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getModelOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source, modelId] = args as unknown[];\n\t\t\t\tif (typeof source !== \"string\" || typeof modelId !== \"string\")\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`models.getModelOfType(type, provider, id) expects three strings, got (${(args as unknown[]).map(describeValue).join(\", \")}). The provider and the id are separate arguments, for example models.getModelOfType(\"classifier\", \"typesafe\", \"jev-latest\").`,\n\t\t\t\t\t);\n\t\t\t\tconst model = models.getModelOfType(modelType(type), source, modelId);\n\t\t\t\treturn model ? toCodemodeModelInfo(model) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.classify\",\n\t\t\tspread: true,\n\t\t\texecute: (args, { signal }) =>\n\t\t\t\trunModelCall(\"models.classify\", \"classifier\", args as unknown[], checkClassifierContext, (model, context) =>\n\t\t\t\t\tmodels.classify(model, context, { signal }),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"models.generateImages\",\n\t\t\tspread: true,\n\t\t\texecute: (args, { signal }) =>\n\t\t\t\trunModelCall(\n\t\t\t\t\t\"models.generateImages\",\n\t\t\t\t\t\"image\",\n\t\t\t\t\targs as unknown[],\n\t\t\t\t\tcheckImagesContext,\n\t\t\t\t\tasync (model, context) => {\n\t\t\t\t\t\tconst result = await models.generateImages(model, context, { signal });\n\t\t\t\t\t\taddGeneratedImages(result.output.filter((block) => block.type === \"image\").length);\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t];\n}\n\nexport async function executeCodemode(\n\tid: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tupdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst start = performance.now();\n\tconst { code, options: source } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\tlet usage: Usage | undefined;\n\tlet generatedImages = 0;\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => update?.({ content: [], details: snapshot() });\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\tconst guidelines = options.getToolGuidelines?.();\n\tconst samples = new Map(\n\t\tcallable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool, guidelines?.get(tool.name)))]),\n\t);\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: callable.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: samples.get(tool.name),\n\t\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\t\tid: `${id}/?`,\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\targs: preview(args),\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t};\n\t\t\t\tcalls.push(record);\n\t\t\t\tpublish();\n\t\t\t\tconst started = performance.now();\n\t\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\t\trecord.id = outcome.toolCall.id;\n\t\t\t\trecord.durationMs = performance.now() - started;\n\t\t\t\trecord.status = outcome.isError ? (callSignal.aborted ? \"cancelled\" : \"error\") : \"ok\";\n\t\t\t\tconst text = textOf(outcome.result);\n\t\t\t\tif (outcome.isError) record.error = (text || `Tool ${tool.name} failed`).slice(0, 500);\n\t\t\t\tpublish();\n\t\t\t\tif (tool.outputSchema && outcome.result.structuredContent !== undefined)\n\t\t\t\t\treturn outcome.result.structuredContent;\n\t\t\t\tif (outcome.isError) throw new Error(text || `Tool ${tool.name} failed`);\n\t\t\t\treturn text;\n\t\t\t},\n\t\t})),\n\t\tglobals: [\n\t\t\t...discoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? modelGlobals(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tcalls,\n\t\t\t\t\t\tpublish,\n\t\t\t\t\t\t(extra) => {\n\t\t\t\t\t\t\tusage = usage ? combineUsage(usage, extra) : extra;\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(count) => {\n\t\t\t\t\t\t\tgeneratedImages += count;\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: source.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: 256 * 1024 * 1024,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerUrl(),\n\t});\n\tlet result: CodemodeResult;\n\ttry {\n\t\tresult = await sandbox.execute(code, {\n\t\t\tsignal,\n\t\t\tstore: ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {},\n\t\t});\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\tfor (const call of calls) if (call.status === \"running\") call.status = \"cancelled\";\n\tlet content: (TextContent | ImageContent)[] = [...result.output];\n\tif (result.ok) {\n\t\tif (Object.keys(result.storeWrites.set).length || result.storeWrites.delete.length)\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, result.storeWrites);\n\t\tif (result.value !== undefined)\n\t\t\tcontent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\ttypeof result.value === \"string\" ? result.value : (JSON.stringify(result.value) ?? String(result.value)),\n\t\t\t});\n\t} else\n\t\tcontent.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Script error:\\n${result.error.stack ?? result.error.message}\\n\\nTool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \") || \"none\"}`,\n\t\t});\n\tif (generatedImages > 0 && !content.some((block) => block.type === \"image\"))\n\t\tcontent.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? \"\" : \"s\"} that the script did not show. Show each image block of result.output with image(block).`,\n\t\t});\n\tconst text = content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tconst budget = (source.maxOutputTokens ?? 10_000) * 4;\n\tconst details = snapshot();\n\tif (text.length > budget) {\n\t\tlet path: string;\n\t\tlet notice: string;\n\t\ttry {\n\t\t\tpath = await writeOutputFile(\"atomic-codemode\", \".txt\", text);\n\t\t\tdetails.fullOutputPath = path;\n\t\t\tnotice = `Full output: ${path}`;\n\t\t} catch (error) {\n\t\t\tnotice = `Could not save full output: ${error instanceof Error ? error.message : String(error)}`;\n\t\t}\n\t\tconst head = Math.floor(budget / 2);\n\t\tconst tail = budget - head;\n\t\tcontent = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Warning: truncated output (original token count: ${Math.ceil(text.length / 4)})\\n${text.slice(0, head)}\\n... output truncated ...\\n${tail ? text.slice(-tail) : \"\"}\\n${notice}`,\n\t\t\t},\n\t\t\t...content.filter((block) => block.type === \"image\"),\n\t\t];\n\t}\n\t// Save after truncation so labels cannot be cut or separated from their images.\n\tcontent = await saveImages(content);\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${((performance.now() - start) / 1000).toFixed(1)} seconds\\nOutput:\\n`,\n\t\t\t},\n\t\t\t...content,\n\t\t],\n\t\tdetails,\n\t\t...(usage ? { usage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAWA,OAAO,EAEN,eAAe,EAEf,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAI3E,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,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Z,IAAI,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,eAAe,eAAe,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,qBAAqB;aAC5I;YACD,GAAG,OAAO;SACV;QACD,OAAO;QACP,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3B,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;KACvC,CAAC;AACH,CAAC","sourcesContent":["import type {\n\tAnyModel,\n\tClassifierContext,\n\tImageContent,\n\tImagesContext,\n\tModelType,\n\tModelTypeMap,\n\tTextContent,\n\tUsage,\n} from \"@bastani/pi-ai\";\nimport type { AgentTool, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerUrl, getQuickJSWasmPath } from \"../../config.js\";\nimport type { ExtensionToolContext } from \"../../core/extensions/context-types.ts\";\nimport type { ToolNamespace } from \"../../core/extensions/tool-types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { formatSize } from \"../../core/tools/truncate.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.js\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.js\";\nimport {\n\tCODEMODE_DOCS_PATH,\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeNestedCall,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.js\";\n\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n\t\"image/png\": \".png\",\n\t\"image/jpeg\": \".jpg\",\n\t\"image/gif\": \".gif\",\n\t\"image/webp\": \".webp\",\n};\n\nasync function saveImages(items: (TextContent | ImageContent)[]): Promise<(TextContent | ImageContent)[]> {\n\tconst labels = new Map<string, Promise<string>>();\n\tconst label = async ({ data, mimeType }: ImageContent): Promise<string> => {\n\t\tconst bytes = Buffer.from(data, \"base64\");\n\t\tconst kind = `${mimeType}, ${formatSize(bytes.length)}`;\n\t\tconst extension = IMAGE_EXTENSIONS[mimeType];\n\t\tif (!extension) throw new Error(`No file extension for image type ${mimeType}`);\n\t\ttry {\n\t\t\tconst path = await writeOutputFile(\"atomic-codemode\", extension, bytes);\n\t\t\treturn `[Image saved to ${path} (${kind})]`;\n\t\t} catch (error) {\n\t\t\treturn `[Image (${kind}) could not be saved: ${error instanceof Error ? error.message : String(error)}]`;\n\t\t}\n\t};\n\tconst result = await Promise.all(\n\t\titems.map(async (item): Promise<(TextContent | ImageContent)[]> => {\n\t\t\tif (item.type !== \"image\") return [item];\n\t\t\tlet pending = labels.get(item.data);\n\t\t\tif (!pending) {\n\t\t\t\tpending = label(item);\n\t\t\t\tlabels.set(item.data, pending);\n\t\t\t}\n\t\t\treturn [{ type: \"text\", text: await pending }, item];\n\t\t}),\n\t);\n\treturn result.flat();\n}\n\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (\n\t\t\tentry.type !== \"custom\" ||\n\t\t\tentry.customType !== CODEMODE_STORE_ENTRY_TYPE ||\n\t\t\ttypeof entry.data !== \"object\" ||\n\t\t\tentry.data === null\n\t\t)\n\t\t\tcontinue;\n\t\tconst data = entry.data as { set?: Record<string, unknown>; delete?: string[] };\n\t\tif (\n\t\t\t!data.set ||\n\t\t\ttypeof data.set !== \"object\" ||\n\t\t\t!Array.isArray(data.delete) ||\n\t\t\t!data.delete.every((key) => typeof key === \"string\")\n\t\t)\n\t\t\tcontinue;\n\t\tfor (const key of data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn result.content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n/** Explicit public catalog fields. Provider configuration and credential-bearing URLs never cross into the VM. */\nexport function toCodemodeModelInfo(model: AnyModel): Record<string, unknown> {\n\treturn {\n\t\ttype: model.type,\n\t\tprovider: model.provider,\n\t\tid: model.id,\n\t\tname: model.name,\n\t\tapi: model.api,\n\t\tinput: model.input,\n\t\t...(\"reasoning\" in model ? { reasoning: model.reasoning } : {}),\n\t\t...(\"contextWindow\" in model ? { contextWindow: model.contextWindow } : {}),\n\t\t...(\"maxTokens\" in model ? { maxTokens: model.maxTokens } : {}),\n\t\tcost: model.cost,\n\t};\n}\nconst MODEL_TYPES = [\"chat\", \"image\", \"classifier\"] as const;\nfunction modelType(value: unknown): ModelType {\n\tif (value === \"chat\" || value === \"image\" || value === \"classifier\") return value;\n\tthrow new Error('Model type must be \"chat\", \"image\", or \"classifier\"');\n}\nfunction withArticle(word: string): string {\n\treturn `${/^[aeiou]/.test(word) ? \"an\" : \"a\"} ${word}`;\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction describeValue(value: unknown): string {\n\tif (value === undefined || value === null) return String(value);\n\tif (Array.isArray(value)) return value.length === 0 ? \"an empty array\" : \"an array\";\n\tif (typeof value === \"object\") {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{ ${keys.slice(0, 6).join(\", \")}${keys.length > 6 ? \", ...\" : \"\"} }`;\n\t}\n\treturn typeof value === \"string\" ? \"a string\" : `a ${typeof value}`;\n}\nconst CLASSIFIER_CONTEXT_SHAPE =\n\t'{ state: { ... }, images?: [{ type: \"image\", data: <base64>, mimeType }], questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';\nfunction checkClassifierContext(context: unknown): ClassifierContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See \"Classify\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tif (!isRecord(context.state)) throw fail(`context.state must be an object, got ${describeValue(context.state)}`);\n\tconst { images } = context;\n\tif (images !== undefined) {\n\t\tif (!Array.isArray(images)) throw fail(`context.images must be an array, got ${describeValue(images)}`);\n\t\timages.forEach((image, index) => {\n\t\t\tif (\n\t\t\t\t!isRecord(image) ||\n\t\t\t\timage.type !== \"image\" ||\n\t\t\t\ttypeof image.data !== \"string\" ||\n\t\t\t\ttypeof image.mimeType !== \"string\"\n\t\t\t) {\n\t\t\t\tthrow fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);\n\t\t\t}\n\t\t});\n\t}\n\tconst { questions } = context;\n\tif (!isRecord(questions) || Object.keys(questions).length === 0)\n\t\tthrow fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);\n\tconst isStrings = (values: unknown[]) => values.length > 0 && values.every((value) => typeof value === \"string\");\n\tfor (const [questionId, question] of Object.entries(questions)) {\n\t\tconst at = `context.questions.${questionId}`;\n\t\tif (!isRecord(question)) throw fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\tif (typeof question.instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tconst { criteria } = question;\n\t\tif (question.type === \"choice\") {\n\t\t\tif (!isRecord(criteria) || !isStrings(Object.values(criteria)))\n\t\t\t\tthrow fail(`${at} is a \"choice\" question, so criteria must map each label to its meaning`);\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (!Array.isArray(criteria) || !isStrings(criteria))\n\t\t\t\tthrow fail(`${at} is a \"score\" question, so criteria must list the levels as strings, lowest first`);\n\t\t} else if (question.type === \"bool\") {\n\t\t\tif (!isRecord(criteria) || typeof criteria.true !== \"string\" || typeof criteria.false !== \"string\")\n\t\t\t\tthrow fail(`${at} is a \"bool\" question, so criteria must be { true: string, false: string }`);\n\t\t} else {\n\t\t\tthrow fail(`${at}.type must be \"choice\", \"score\", or \"bool\", got ${JSON.stringify(question.type)}`);\n\t\t}\n\t}\n\treturn context as unknown as ClassifierContext;\n}\nfunction checkImagesContext(context: unknown): ImagesContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.generateImages() ${problem}. Expected context: { input: [{ type: \"text\", text: <prompt> }, ...optional { type: \"image\", data: <base64>, mimeType } references] }. See \"Generate images\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tconst { input } = context;\n\tif (!Array.isArray(input) || input.length === 0)\n\t\tthrow fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);\n\tinput.forEach((block: unknown, index) => {\n\t\tif (isRecord(block) && block.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (\n\t\t\tisRecord(block) &&\n\t\t\tblock.type === \"image\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t)\n\t\t\treturn;\n\t\tthrow fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);\n\t});\n\treturn context as unknown as ImagesContext;\n}\nfunction provider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value === \"string\") return value;\n\tthrow new Error(\"provider must be a string\");\n}\nfunction preview(args: unknown): string {\n\ttry {\n\t\treturn (JSON.stringify(args) ?? \"\").slice(0, 200);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\ninterface ModelCallResult {\n\tstopReason: \"stop\" | \"error\" | \"aborted\";\n\terrorMessage?: string;\n\tusage?: Usage;\n}\nfunction createLimiter(limit: number) {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async <T>(run: () => Promise<T>): Promise<T> => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\nfunction discoveryGlobals(\n\ttools: readonly AgentTool[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, config] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = config?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0)\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\tif (config?.namespace !== undefined && typeof config.namespace !== \"string\")\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\tconst docs = tools.flatMap((tool) => {\n\t\t\t\t\tconst namespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\treturn config?.namespace && namespace?.name !== config.namespace\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: [createToolSearchDocument(tool, namespace)];\n\t\t\t\t});\n\t\t\t\treturn new Bm25Ranker().rank(query, docs, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find((tool) => tool.name === name || toCodemodeIdentifier(tool.name) === name);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (toolNamespace?.name !== name) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\nfunction modelGlobals(\n\tctx: ExtensionToolContext,\n\tid: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n\taddGeneratedImages: (count: number) => void,\n): CodemodeTool[] {\n\tconst models = ctx.modelRegistry;\n\tconst limit = createLimiter(4);\n\tlet count = 0;\n\tconst runModelCall = async <TType extends \"classifier\" | \"image\", TContext, TResult extends ModelCallResult>(\n\t\tname: string,\n\t\ttype: TType,\n\t\t[ref, context]: unknown[],\n\t\tcheckContext: (context: unknown) => TContext,\n\t\trun: (model: ModelTypeMap[TType], context: TContext) => Promise<TResult>,\n\t): Promise<TResult> => {\n\t\tconst listHint = `List the ${type} models you can use with models.getAvailableOfType(\"${type}\").`;\n\t\tif (!isRecord(ref) || typeof ref.provider !== \"string\" || typeof ref.id !== \"string\") {\n\t\t\tconst undefinedHint =\n\t\t\t\tref === undefined || ref === null\n\t\t\t\t\t? \" models.getModelOfType() returns undefined for an unknown provider or id.\"\n\t\t\t\t\t: \"\";\n\t\t\tthrow new Error(\n\t\t\t\t`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(ref)}.${undefinedHint} ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst { provider: providerId, id: modelId } = ref;\n\t\tconst model = models.getModelOfType(type, providerId, modelId);\n\t\tif (!model) {\n\t\t\tconst actualType = MODEL_TYPES.find(\n\t\t\t\t(other) => other !== type && models.getModelOfType(other, providerId, modelId) !== undefined,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\tactualType\n\t\t\t\t\t? `\"${providerId}/${modelId}\" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`\n\t\t\t\t\t: `Unknown ${type} model \"${providerId}/${modelId}\". ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst checked = checkContext(context);\n\t\tconst record: CodemodeNestedCall = {\n\t\t\tid: `${id}/${name}/${++count}`,\n\t\t\tname,\n\t\t\targs: `${model.provider}/${model.id}`,\n\t\t\tstatus: \"running\",\n\t\t};\n\t\tcalls.push(record);\n\t\tpublish();\n\t\tconst start = performance.now();\n\t\tconst result = await limit(() => run(model, checked));\n\t\trecord.durationMs = performance.now() - start;\n\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\tif (result.errorMessage) record.error = result.errorMessage.slice(0, 500);\n\t\tif (result.usage) {\n\t\t\trecord.cost = result.usage.cost.total;\n\t\t\taddUsage(result.usage);\n\t\t}\n\t\tpublish();\n\t\treturn result;\n\t};\n\treturn [\n\t\t{\n\t\t\tname: \"models.getModelsOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn models.getModelsOfType(modelType(type), provider(source)).map(toCodemodeModelInfo);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getAvailableOfType\",\n\t\t\tspread: true,\n\t\t\texecute: async (args, { signal }) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn (await models.getAvailableOfType(modelType(type), provider(source), { signal })).map(\n\t\t\t\t\ttoCodemodeModelInfo,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getModelOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source, modelId] = args as unknown[];\n\t\t\t\tif (typeof source !== \"string\" || typeof modelId !== \"string\")\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`models.getModelOfType(type, provider, id) expects three strings, got (${(args as unknown[]).map(describeValue).join(\", \")}). The provider and the id are separate arguments, for example models.getModelOfType(\"classifier\", \"typesafe\", \"jev-latest\").`,\n\t\t\t\t\t);\n\t\t\t\tconst model = models.getModelOfType(modelType(type), source, modelId);\n\t\t\t\treturn model ? toCodemodeModelInfo(model) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.classify\",\n\t\t\tspread: true,\n\t\t\texecute: (args, { signal }) =>\n\t\t\t\trunModelCall(\"models.classify\", \"classifier\", args as unknown[], checkClassifierContext, (model, context) =>\n\t\t\t\t\tmodels.classify(model, context, { signal }),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"models.generateImages\",\n\t\t\tspread: true,\n\t\t\texecute: (args, { signal }) =>\n\t\t\t\trunModelCall(\n\t\t\t\t\t\"models.generateImages\",\n\t\t\t\t\t\"image\",\n\t\t\t\t\targs as unknown[],\n\t\t\t\t\tcheckImagesContext,\n\t\t\t\t\tasync (model, context) => {\n\t\t\t\t\t\tconst result = await models.generateImages(model, context, { signal });\n\t\t\t\t\t\taddGeneratedImages(result.output.filter((block) => block.type === \"image\").length);\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t];\n}\n\nexport async function executeCodemode(\n\tid: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tupdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst start = performance.now();\n\tconst { code, options: source } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\tlet usage: Usage | undefined;\n\tlet generatedImages = 0;\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => update?.({ content: [], details: snapshot() });\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\tconst guidelines = options.getToolGuidelines?.();\n\tconst samples = new Map(\n\t\tcallable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool, guidelines?.get(tool.name)))]),\n\t);\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: callable.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: samples.get(tool.name),\n\t\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\t\tid: `${id}/?`,\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\targs: preview(args),\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t};\n\t\t\t\tcalls.push(record);\n\t\t\t\tpublish();\n\t\t\t\tconst started = performance.now();\n\t\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\t\trecord.id = outcome.toolCall.id;\n\t\t\t\trecord.durationMs = performance.now() - started;\n\t\t\t\trecord.status = outcome.isError ? (callSignal.aborted ? \"cancelled\" : \"error\") : \"ok\";\n\t\t\t\tconst text = textOf(outcome.result);\n\t\t\t\tif (outcome.isError) record.error = (text || `Tool ${tool.name} failed`).slice(0, 500);\n\t\t\t\tpublish();\n\t\t\t\tif (tool.outputSchema && outcome.result.structuredContent !== undefined)\n\t\t\t\t\treturn outcome.result.structuredContent;\n\t\t\t\tif (outcome.isError) throw new Error(text || `Tool ${tool.name} failed`);\n\t\t\t\treturn text;\n\t\t\t},\n\t\t})),\n\t\tglobals: [\n\t\t\t...discoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? modelGlobals(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tcalls,\n\t\t\t\t\t\tpublish,\n\t\t\t\t\t\t(extra) => {\n\t\t\t\t\t\t\tusage = usage ? combineUsage(usage, extra) : extra;\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(count) => {\n\t\t\t\t\t\t\tgeneratedImages += count;\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: source.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: 256 * 1024 * 1024,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerUrl(),\n\t});\n\tlet result: CodemodeResult;\n\ttry {\n\t\tresult = await sandbox.execute(code, {\n\t\t\tsignal,\n\t\t\tstore: ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {},\n\t\t});\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\tfor (const call of calls) if (call.status === \"running\") call.status = \"cancelled\";\n\tlet content: (TextContent | ImageContent)[] = [...result.output];\n\tif (result.ok) {\n\t\tif (Object.keys(result.storeWrites.set).length || result.storeWrites.delete.length)\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, result.storeWrites);\n\t\tif (result.value !== undefined)\n\t\t\tcontent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\ttypeof result.value === \"string\" ? result.value : (JSON.stringify(result.value) ?? String(result.value)),\n\t\t\t});\n\t} else\n\t\tcontent.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Script error:\\n${result.error.stack ?? result.error.message}\\n\\nTool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \") || \"none\"}`,\n\t\t});\n\tif (generatedImages > 0 && !content.some((block) => block.type === \"image\"))\n\t\tcontent.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? \"\" : \"s\"} that the script did not show. Show each image block of result.output with image(block).`,\n\t\t});\n\tconst text = content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tconst budget = (source.maxOutputTokens ?? 10_000) * 4;\n\tconst details = snapshot();\n\tif (text.length > budget) {\n\t\tlet path: string;\n\t\tlet notice: string;\n\t\ttry {\n\t\t\tpath = await writeOutputFile(\"atomic-codemode\", \".txt\", text);\n\t\t\tdetails.fullOutputPath = path;\n\t\t\tnotice = `Full output: ${path}`;\n\t\t} catch (error) {\n\t\t\tnotice = `Could not save full output: ${error instanceof Error ? error.message : String(error)}`;\n\t\t}\n\t\tconst head = Math.floor(budget / 2);\n\t\tconst tail = budget - head;\n\t\tcontent = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Warning: truncated output (original token count: ${Math.ceil(text.length / 4)})\\n${text.slice(0, head)}\\n... output truncated ...\\n${tail ? text.slice(-tail) : \"\"}\\n${notice}`,\n\t\t\t},\n\t\t\t...content.filter((block) => block.type === \"image\"),\n\t\t];\n\t}\n\t// Save after truncation so labels cannot be cut or separated from their images.\n\tcontent = await saveImages(content);\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${((performance.now() - start) / 1000).toFixed(1)} seconds\\nOutput:\\n`,\n\t\t\t},\n\t\t\t...content,\n\t\t],\n\t\tdetails,\n\t\t...(usage ? { usage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n"]}
|