@myagentroam/agent 0.11.33 → 0.11.34
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/dist/cli/catalog-file.d.ts +78 -0
- package/dist/cli/catalog-file.js +102 -0
- package/dist/cli/codex-auth-file.d.ts +1 -1
- package/dist/cli/codex-auth-file.js +9 -10
- package/dist/cli/main.js +44 -54
- package/dist/error.d.ts +15 -0
- package/dist/error.js +74 -0
- package/dist/extensions/agents.d.ts +100 -0
- package/dist/extensions/agents.js +121 -0
- package/dist/extensions/capabilities.d.ts +4 -0
- package/dist/extensions/commands.d.ts +23 -0
- package/dist/extensions/commands.js +45 -0
- package/dist/extensions/compaction.d.ts +36 -0
- package/dist/extensions/contracts.d.ts +147 -0
- package/dist/extensions/data.d.ts +81 -0
- package/dist/extensions/data.js +78 -0
- package/dist/extensions/environment.d.ts +39 -0
- package/dist/extensions/environment.js +52 -0
- package/dist/extensions/files.d.ts +68 -0
- package/dist/extensions/files.js +26 -0
- package/dist/extensions/hooks.d.ts +32 -0
- package/dist/extensions/host-ports.d.ts +24 -0
- package/dist/extensions/manager.d.ts +42 -0
- package/dist/extensions/manager.js +457 -0
- package/dist/extensions/mcp.d.ts +116 -0
- package/dist/extensions/mcp.js +434 -0
- package/dist/extensions/model-request.d.ts +65 -0
- package/dist/extensions/model-request.js +197 -0
- package/dist/extensions/model-stream.d.ts +18 -0
- package/dist/extensions/model-stream.js +108 -0
- package/dist/extensions/models.d.ts +46 -0
- package/dist/extensions/models.js +7 -0
- package/dist/extensions/network.d.ts +40 -0
- package/dist/extensions/network.js +97 -0
- package/dist/extensions/operation.d.ts +32 -0
- package/dist/extensions/processes.d.ts +64 -0
- package/dist/extensions/processes.js +284 -0
- package/dist/extensions/prompt-composition.d.ts +38 -0
- package/dist/extensions/prompt-composition.js +100 -0
- package/dist/extensions/prompt-input.d.ts +30 -0
- package/dist/extensions/prompt-input.js +48 -0
- package/dist/extensions/prompts.d.ts +31 -0
- package/dist/extensions/prompts.js +88 -0
- package/dist/extensions/resources.d.ts +26 -0
- package/dist/extensions/resources.js +221 -0
- package/dist/extensions/services.d.ts +31 -0
- package/dist/extensions/services.js +61 -0
- package/dist/extensions/session-api.d.ts +6 -0
- package/dist/extensions/session-api.js +52 -0
- package/dist/extensions/session-input.d.ts +184 -0
- package/dist/extensions/session-input.js +422 -0
- package/dist/extensions/session-messages.d.ts +41 -0
- package/dist/extensions/session-messages.js +76 -0
- package/dist/extensions/session-tools.d.ts +32 -0
- package/dist/extensions/session-tools.js +208 -0
- package/dist/extensions/session.d.ts +60 -0
- package/dist/extensions/session.js +265 -0
- package/dist/extensions/settings.d.ts +76 -0
- package/dist/extensions/settings.js +115 -0
- package/dist/extensions/store.d.ts +10 -0
- package/dist/extensions/store.js +131 -0
- package/dist/extensions/tool-runtime.d.ts +16 -0
- package/dist/extensions/tools.d.ts +80 -0
- package/dist/extensions/tools.js +270 -0
- package/dist/extensions.d.ts +22 -0
- package/dist/host/contracts.d.ts +58 -0
- package/dist/host/contracts.js +18 -0
- package/dist/host/description.d.ts +19 -0
- package/dist/host/local-agent-host.d.ts +96 -0
- package/dist/host/local-agent-host.js +429 -0
- package/dist/host/local-exec-tool.d.ts +26 -0
- package/dist/host/local-exec-tool.js +686 -0
- package/dist/host/local-file-access.d.ts +30 -0
- package/dist/host/local-file-access.js +107 -0
- package/dist/host/local-network-access.d.ts +6 -0
- package/dist/host/local-network-access.js +101 -0
- package/dist/host/local-process-executor.d.ts +5 -0
- package/dist/host/local-process-executor.js +17 -0
- package/dist/host/local-session-environment.d.ts +18 -0
- package/dist/host/local-shell.d.ts +3 -0
- package/dist/host/local-tool-registry.d.ts +34 -0
- package/dist/host/local-tool-registry.js +134 -0
- package/dist/host/network.d.ts +5 -0
- package/dist/host/network.js +42 -0
- package/dist/host/process-control.d.ts +2 -0
- package/dist/host/process-control.js +26 -0
- package/dist/host/skill-contract.d.ts +6 -0
- package/dist/host.d.ts +17 -0
- package/dist/host.js +3 -0
- package/dist/index.d.ts +26 -51
- package/dist/index.js +9 -12
- package/dist/model/anthropic-messages.d.ts +10 -0
- package/dist/model/anthropic-messages.js +692 -0
- package/dist/model/anthropic-thinking.js +33 -0
- package/dist/model/configuration.d.ts +111 -0
- package/dist/model/configuration.js +201 -0
- package/dist/model/contracts.d.ts +229 -0
- package/dist/model/http.d.ts +13 -0
- package/dist/model/http.js +119 -0
- package/dist/model/image-contract.d.ts +10 -0
- package/dist/model/image.d.ts +9 -0
- package/dist/model/inline-media-budget.d.ts +7 -0
- package/dist/model/inline-media-budget.js +36 -0
- package/dist/model/input-images.d.ts +3 -0
- package/dist/model/input-images.js +16 -0
- package/dist/model/openai-responses.d.ts +59 -0
- package/dist/model/openai-responses.js +1586 -0
- package/dist/model/recovery.js +80 -0
- package/dist/model/request-configuration.d.ts +17 -0
- package/dist/model/request-configuration.js +47 -0
- package/dist/model/responses-event-projection.d.ts +24 -0
- package/dist/model/responses-event-projection.js +194 -0
- package/dist/model/responses-request.d.ts +5 -0
- package/dist/model/responses-request.js +363 -0
- package/dist/model/responses-session-cache.d.ts +33 -0
- package/dist/model/responses-session-cache.js +64 -0
- package/dist/model/runtime-credential.d.ts +1 -0
- package/dist/model/runtime-credential.js +1 -0
- package/dist/model/sse.js +281 -0
- package/dist/model/text-blocks.js +40 -0
- package/dist/model/tool-declarations.d.ts +4 -0
- package/dist/model/tool-definition-projection.d.ts +6 -0
- package/dist/model/tool-definition-projection.js +11 -0
- package/dist/model/tool-schema.d.ts +2 -0
- package/dist/model/tool-schema.js +17 -0
- package/dist/model/transport-test.d.ts +10 -0
- package/dist/model/transport-test.js +27 -0
- package/dist/model/usage-observer.d.ts +5 -0
- package/dist/model/usage.d.ts +40 -0
- package/dist/network/credential-runtime.d.ts +8 -0
- package/dist/network/credential-runtime.js +72 -0
- package/dist/network/credentials.d.ts +20 -0
- package/dist/network/credentials.js +18 -0
- package/dist/network/http.d.ts +20 -0
- package/dist/network/http.js +421 -0
- package/dist/network/product-user-agent.d.ts +5 -0
- package/dist/network/product-user-agent.js +22 -0
- package/dist/network/transport-error.d.ts +5 -0
- package/dist/network/transport-error.js +31 -0
- package/dist/process/contracts.d.ts +26 -0
- package/dist/prompts/index.d.ts +20 -0
- package/dist/prompts/index.js +49 -0
- package/dist/prompts/prompt-sections.d.ts +6 -0
- package/dist/prompts/prompt-sections.js +6 -0
- package/dist/prompts/read-context.js +152 -0
- package/dist/runtime/compaction/contracts.d.ts +23 -0
- package/dist/runtime/compaction/coordinator.js +88 -0
- package/dist/runtime/compaction/generate.d.ts +31 -0
- package/dist/runtime/compaction/generate.js +84 -0
- package/dist/runtime/compaction/history.d.ts +16 -0
- package/dist/runtime/compaction/operation.d.ts +30 -0
- package/dist/runtime/compaction/operation.js +131 -0
- package/dist/runtime/compaction/requests.d.ts +16 -0
- package/dist/runtime/compaction/requests.js +114 -0
- package/dist/runtime/compaction/retained-context.d.ts +6 -0
- package/dist/runtime/compaction/retained-context.js +48 -0
- package/dist/runtime/compaction/smart.d.ts +14 -0
- package/dist/runtime/compaction/smart.js +59 -0
- package/dist/runtime/context/contextual-blocks.d.ts +31 -0
- package/dist/runtime/context/contextual-blocks.js +158 -0
- package/dist/runtime/context/environment.d.ts +5 -0
- package/dist/runtime/context/gc-candidates-code.d.ts +6 -0
- package/dist/runtime/context/gc-candidates-code.js +102 -0
- package/dist/runtime/context/gc-candidates-exec.d.ts +6 -0
- package/dist/runtime/context/gc-candidates-exec.js +131 -0
- package/dist/runtime/context/gc-candidates-read-patch.d.ts +7 -0
- package/dist/runtime/context/gc-candidates-read-patch.js +118 -0
- package/dist/runtime/context/gc-candidates-subagent.d.ts +6 -0
- package/dist/runtime/context/gc-candidates-subagent.js +100 -0
- package/dist/runtime/context/gc-candidates-web.d.ts +6 -0
- package/dist/runtime/context/gc-candidates-web.js +58 -0
- package/dist/runtime/context/gc-candidates.d.ts +12 -0
- package/dist/runtime/context/gc-candidates.js +192 -0
- package/dist/runtime/context/gc-contracts.d.ts +57 -0
- package/dist/runtime/context/gc-economics.d.ts +48 -0
- package/dist/runtime/context/gc-economics.js +161 -0
- package/dist/runtime/context/gc-runtime.d.ts +43 -0
- package/dist/runtime/context/gc-tokens.d.ts +26 -0
- package/dist/runtime/context/gc-tokens.js +106 -0
- package/dist/runtime/context/gc.d.ts +7 -0
- package/dist/runtime/context/gc.js +552 -0
- package/dist/runtime/context/instructions.d.ts +37 -0
- package/dist/runtime/context/instructions.js +297 -0
- package/dist/runtime/context/normalize.d.ts +5 -0
- package/dist/runtime/context/projection.d.ts +23 -0
- package/dist/runtime/context/projection.js +284 -0
- package/dist/runtime/context/request-budget.d.ts +5 -0
- package/dist/runtime/context/request-budget.js +25 -0
- package/dist/runtime/context/restore.d.ts +27 -0
- package/dist/runtime/context/restore.js +186 -0
- package/dist/runtime/context/usage.d.ts +17 -0
- package/dist/runtime/context/usage.js +124 -0
- package/dist/runtime/context/world-state.d.ts +34 -0
- package/dist/runtime/context/world-state.js +232 -0
- package/dist/runtime/contracts.d.ts +29 -0
- package/dist/runtime/event-projection.d.ts +14 -0
- package/dist/runtime/event-projection.js +87 -0
- package/dist/runtime/events.d.ts +195 -0
- package/dist/runtime/execution-handle.d.ts +12 -0
- package/dist/runtime/execution-handle.js +1 -0
- package/dist/runtime/execution.d.ts +55 -0
- package/dist/runtime/execution.js +444 -0
- package/dist/runtime/model-progress.js +85 -0
- package/dist/runtime/resource-publication.d.ts +27 -0
- package/dist/runtime/resource-publication.js +60 -0
- package/dist/runtime/tool-round-contract.d.ts +19 -0
- package/dist/runtime/tool-round-contract.js +1 -0
- package/dist/runtime/wait.js +82 -0
- package/dist/sandbox/linux/bubblewrap-sandbox-executor.d.ts +1 -1
- package/dist/sandbox/linux/bubblewrap-sandbox-executor.js +8 -8
- package/dist/sdk/agent.d.ts +7 -0
- package/dist/sdk/agent.js +321 -0
- package/dist/sdk/execution-code-mode.d.ts +18 -0
- package/dist/sdk/execution-code-mode.js +51 -0
- package/dist/sdk/execution-compact-commit.d.ts +23 -0
- package/dist/sdk/execution-compact-commit.js +41 -0
- package/dist/sdk/execution-compact-extension.d.ts +12 -0
- package/dist/sdk/execution-compact-extension.js +46 -0
- package/dist/sdk/execution-compact-generation.d.ts +17 -0
- package/dist/sdk/execution-compact-generation.js +30 -0
- package/dist/sdk/execution-compaction-flight.d.ts +31 -0
- package/dist/sdk/execution-compaction-flight.js +50 -0
- package/dist/sdk/execution-compaction.d.ts +47 -0
- package/dist/sdk/execution-compaction.js +121 -0
- package/dist/sdk/execution-context-coordinator.d.ts +56 -0
- package/dist/sdk/execution-context-coordinator.js +102 -0
- package/dist/sdk/execution-input.d.ts +58 -0
- package/dist/sdk/execution-input.js +266 -0
- package/dist/sdk/execution-model-context.d.ts +52 -0
- package/dist/sdk/execution-model-context.js +156 -0
- package/dist/sdk/execution-model-lifecycle.d.ts +39 -0
- package/dist/sdk/execution-model-lifecycle.js +73 -0
- package/dist/sdk/execution-model-request.d.ts +40 -0
- package/dist/sdk/execution-model-request.js +45 -0
- package/dist/sdk/execution-round-preparation.d.ts +11 -0
- package/dist/sdk/execution-round-preparation.js +18 -0
- package/dist/sdk/execution-round-request.d.ts +30 -0
- package/dist/sdk/execution-round-request.js +31 -0
- package/dist/sdk/execution-tool-catalog.d.ts +46 -0
- package/dist/sdk/execution-tool-catalog.js +103 -0
- package/dist/sdk/execution-tool-scope.d.ts +67 -0
- package/dist/sdk/execution-tool-scope.js +147 -0
- package/dist/sdk/extension-agent-controller.d.ts +3 -0
- package/dist/sdk/extension-agent-controller.js +69 -0
- package/dist/sdk/extension-agents.d.ts +9 -0
- package/dist/sdk/extension-agents.js +58 -0
- package/dist/sdk/extension-models.d.ts +17 -0
- package/dist/sdk/extension-models.js +142 -0
- package/dist/sdk/extension-session-launch.d.ts +18 -0
- package/dist/sdk/extension-session-launch.js +73 -0
- package/dist/sdk/extension-session.d.ts +30 -0
- package/dist/sdk/extension-session.js +107 -0
- package/dist/sdk/extension-tool-runtime.d.ts +2 -0
- package/dist/sdk/extension-tool-runtime.js +14 -0
- package/dist/sdk/extension-tools.d.ts +16 -0
- package/dist/sdk/extension-tools.js +126 -0
- package/dist/sdk/model-input-projection.d.ts +4 -0
- package/dist/sdk/model-input-projection.js +27 -0
- package/dist/sdk/model-runtime.d.ts +21 -0
- package/dist/sdk/model-runtime.js +91 -0
- package/dist/sdk/native-steer.d.ts +20 -0
- package/dist/sdk/native-steer.js +84 -0
- package/dist/sdk/request-preparation.d.ts +9 -0
- package/dist/sdk/resource-input.d.ts +33 -0
- package/dist/sdk/resource-input.js +402 -0
- package/dist/sdk/session-catalog.d.ts +2 -0
- package/dist/sdk/session-catalog.js +12 -0
- package/dist/sdk/session-composition.d.ts +54 -0
- package/dist/sdk/session-composition.js +1 -0
- package/dist/sdk/session-execution-factory.d.ts +43 -0
- package/dist/sdk/session-execution-factory.js +937 -0
- package/dist/sdk/session-execution.d.ts +163 -0
- package/dist/sdk/session-execution.js +388 -0
- package/dist/sdk/session-extension-messages.d.ts +16 -0
- package/dist/sdk/session-extension-messages.js +64 -0
- package/dist/sdk/session-extension-prompt.d.ts +35 -0
- package/dist/sdk/session-extension-prompt.js +62 -0
- package/dist/sdk/session-maintenance.d.ts +25 -0
- package/dist/sdk/session-maintenance.js +205 -0
- package/dist/sdk/session-model-adapters.d.ts +28 -0
- package/dist/sdk/session-model-adapters.js +96 -0
- package/dist/sdk/session-open.d.ts +22 -0
- package/dist/sdk/session-open.js +44 -0
- package/dist/sdk/session-registry.d.ts +17 -0
- package/dist/sdk/session-registry.js +83 -0
- package/dist/sdk/session-runtime.d.ts +72 -0
- package/dist/sdk/session-runtime.js +205 -0
- package/dist/sdk/session.d.ts +3 -0
- package/dist/sdk/session.js +313 -0
- package/dist/sdk/subagent-backend.d.ts +3 -0
- package/dist/sdk/subagent-backend.js +49 -0
- package/dist/sdk/types.d.ts +80 -0
- package/dist/sdk/types.js +1 -0
- package/dist/session/catalog.d.ts +70 -0
- package/dist/session/catalog.js +194 -0
- package/dist/session/code-observation-contract.d.ts +40 -0
- package/dist/session/code-observation-contract.js +1 -0
- package/dist/session/code-observation-projection.d.ts +54 -0
- package/dist/session/code-observation-projection.js +165 -0
- package/dist/session/code-state.d.ts +27 -0
- package/dist/session/code-state.js +89 -0
- package/dist/session/context-gc-checkpoint.d.ts +26 -0
- package/dist/session/context-gc-checkpoint.js +935 -0
- package/dist/session/context-gc-contract.d.ts +141 -0
- package/dist/session/context-gc-contract.js +1 -0
- package/dist/session/context-gc-observations.d.ts +58 -0
- package/dist/session/context-gc-observations.js +187 -0
- package/dist/session/context-gc-replacements.d.ts +63 -0
- package/dist/session/context-gc-subagent.d.ts +54 -0
- package/dist/session/deferred-input.d.ts +5 -0
- package/dist/session/deferred-input.js +74 -0
- package/dist/session/extension-checkpoint.d.ts +8 -0
- package/dist/session/extension-checkpoint.js +30 -0
- package/dist/session/history-input-limits.d.ts +4 -0
- package/dist/session/history-input-limits.js +4 -0
- package/dist/session/inline-media-contract.d.ts +16 -0
- package/dist/session/inline-media-contract.js +1 -0
- package/dist/session/inline-media.d.ts +26 -0
- package/dist/session/inline-media.js +138 -0
- package/dist/session/model-request.d.ts +14 -0
- package/dist/session/model-request.js +1 -0
- package/dist/session/record-contract.d.ts +19 -0
- package/dist/session/record-contract.js +1 -0
- package/dist/session/record-projection.d.ts +6 -0
- package/dist/session/record-projection.js +80 -0
- package/dist/session/resource-contract.d.ts +9 -0
- package/dist/session/resource-contract.js +1 -0
- package/dist/session/rollback.d.ts +13 -0
- package/dist/session/rollback.js +46 -0
- package/dist/session/store/contracts.d.ts +160 -0
- package/dist/session/store/contracts.js +1 -0
- package/dist/session/store/current-state.d.ts +17 -0
- package/dist/session/store/current-state.js +53 -0
- package/dist/session/store/execution-state.d.ts +13 -0
- package/dist/session/store/execution-state.js +103 -0
- package/dist/session/store/index.d.ts +4 -0
- package/dist/session/store/index.js +2 -0
- package/dist/session/store/jsonl/directory-index.d.ts +26 -0
- package/dist/session/store/jsonl/directory-index.js +283 -0
- package/dist/session/store/jsonl/fs-durability.d.ts +3 -0
- package/dist/session/store/jsonl/fs-durability.js +17 -0
- package/dist/session/store/jsonl/history-replacement.d.ts +48 -0
- package/dist/session/store/jsonl/history-replacement.js +147 -0
- package/dist/session/store/jsonl/history.d.ts +25 -0
- package/dist/session/store/jsonl/history.js +181 -0
- package/dist/session/store/jsonl/images.d.ts +19 -0
- package/dist/session/store/jsonl/images.js +122 -0
- package/dist/session/store/jsonl/index-transaction.d.ts +13 -0
- package/dist/session/store/jsonl/index-transaction.js +87 -0
- package/dist/session/store/jsonl/jsonl-admission.d.ts +10 -0
- package/dist/session/store/jsonl/jsonl-admission.js +205 -0
- package/dist/session/store/jsonl/jsonl-codec.d.ts +11 -0
- package/dist/session/store/jsonl/jsonl-codec.js +138 -0
- package/dist/session/store/jsonl/jsonl-migration.d.ts +12 -0
- package/dist/session/store/jsonl/jsonl-migration.js +105 -0
- package/dist/session/store/jsonl/jsonl-store.d.ts +171 -0
- package/dist/session/store/jsonl/jsonl-store.js +2482 -0
- package/dist/session/store/jsonl/open-recovery.d.ts +13 -0
- package/dist/session/store/jsonl/open-recovery.js +131 -0
- package/dist/session/store/jsonl/read-pins.d.ts +4 -0
- package/dist/session/store/jsonl/read-pins.js +131 -0
- package/dist/session/store/jsonl/record-append.d.ts +16 -0
- package/dist/session/store/jsonl/record-append.js +49 -0
- package/dist/session/store/jsonl/records.d.ts +30 -0
- package/dist/session/store/jsonl/records.js +313 -0
- package/dist/session/store/jsonl/resources.d.ts +19 -0
- package/dist/session/store/jsonl/resources.js +209 -0
- package/dist/session/store/jsonl/store-pool.d.ts +12 -0
- package/dist/session/store/jsonl/store-pool.js +55 -0
- package/dist/session/store/jsonl/transaction-recovery.d.ts +48 -0
- package/dist/session/store/jsonl/transaction-recovery.js +374 -0
- package/dist/session/store/jsonl/tree-maintenance.d.ts +12 -0
- package/dist/session/store/jsonl/tree-maintenance.js +59 -0
- package/dist/session/store/types.d.ts +69 -0
- package/dist/session/store/types.js +1 -0
- package/dist/session/summary.d.ts +18 -0
- package/dist/session/summary.js +1 -0
- package/dist/session/todo.d.ts +11 -0
- package/dist/session/todo.js +30 -0
- package/dist/session/tool-result-resources.d.ts +27 -0
- package/dist/session/tool-result-resources.js +255 -0
- package/dist/session/types.js +1 -0
- package/dist/session/user-history.d.ts +17 -0
- package/dist/session/user-history.js +1 -0
- package/dist/session-store.d.ts +2 -0
- package/dist/session-store.js +1 -0
- package/dist/shared/auto-title.d.ts +3 -3
- package/dist/shared/auto-title.js +6 -6
- package/dist/shared/model-text.d.ts +8 -8
- package/dist/shared/model-text.js +8 -7
- package/dist/storage/file-lock.js +83 -0
- package/dist/subagent/contracts.d.ts +107 -0
- package/dist/subagent/contracts.js +1 -0
- package/dist/subagent/limits.d.ts +17 -0
- package/dist/subagent/limits.js +17 -0
- package/dist/subagent/model-update.js +81 -0
- package/dist/subagent/session-controller.d.ts +148 -0
- package/dist/subagent/session-controller.js +1761 -0
- package/dist/subagent/wait-targets.d.ts +10 -0
- package/dist/subagent/wait-targets.js +26 -0
- package/dist/subagent/wait.d.ts +26 -0
- package/dist/subagent/wait.js +73 -0
- package/dist/tools/agent/agent-cancel.d.ts +7 -0
- package/dist/tools/agent/agent-cancel.js +29 -0
- package/dist/tools/agent/agent-message.d.ts +7 -0
- package/dist/tools/agent/agent-message.js +57 -0
- package/dist/tools/agent/agent-start.d.ts +12 -0
- package/dist/tools/agent/agent-start.js +106 -0
- package/dist/tools/agent/agent-wait.d.ts +7 -0
- package/dist/tools/agent/agent-wait.js +91 -0
- package/dist/tools/agent/question.d.ts +7 -0
- package/dist/tools/agent/question.js +125 -0
- package/dist/tools/agent/skill.d.ts +11 -0
- package/dist/tools/agent/skill.js +38 -0
- package/dist/tools/agent/sleep.d.ts +9 -0
- package/dist/tools/agent/sleep.js +54 -0
- package/dist/tools/agent/smart-compact.d.ts +9 -0
- package/dist/tools/agent/smart-compact.js +23 -0
- package/dist/tools/agent/todo-read.d.ts +14 -0
- package/dist/tools/agent/todo-write.d.ts +14 -0
- package/dist/tools/agent/todo-write.js +66 -0
- package/dist/tools/agent/todo.d.ts +25 -0
- package/dist/tools/agent/todo.js +32 -0
- package/dist/tools/callers.d.ts +7 -0
- package/dist/tools/callers.js +39 -0
- package/dist/tools/code-mode/cells.d.ts +29 -0
- package/dist/tools/code-mode/cells.js +338 -0
- package/dist/tools/code-mode/dispatch.d.ts +20 -0
- package/dist/tools/code-mode/dispatch.js +80 -0
- package/dist/tools/code-mode/engine.d.ts +60 -0
- package/dist/tools/code-mode/engine.js +1 -0
- package/dist/tools/code-mode/index.d.ts +31 -0
- package/dist/tools/code-mode/index.js +751 -0
- package/dist/tools/code-mode/observations.d.ts +8 -0
- package/dist/tools/code-mode/observations.js +64 -0
- package/dist/tools/code-mode/worker.d.ts +1 -0
- package/dist/tools/contracts.d.ts +193 -0
- package/dist/tools/contracts.js +1 -0
- package/dist/tools/definition-projection.d.ts +1 -0
- package/dist/tools/definition-projection.js +1 -0
- package/dist/tools/execution-limits.d.ts +69 -0
- package/dist/tools/execution-limits.js +58 -0
- package/dist/tools/execution.d.ts +30 -0
- package/dist/tools/execution.js +191 -0
- package/dist/tools/local/apply-patch-parser.js +177 -0
- package/dist/tools/local/apply-patch.d.ts +19 -0
- package/dist/tools/local/apply-patch.js +489 -0
- package/dist/tools/local/exec.d.ts +28 -0
- package/dist/tools/local/exec.js +194 -0
- package/dist/tools/local/image-processing.js +146 -0
- package/dist/tools/local/read.d.ts +43 -0
- package/dist/tools/local/read.js +470 -0
- package/dist/tools/local/view-image.d.ts +15 -0
- package/dist/tools/local/view-image.js +317 -0
- package/dist/tools/mcp/catalog.js +220 -0
- package/dist/tools/mcp/history.d.ts +4 -0
- package/dist/tools/mcp/tool-search.d.ts +45 -0
- package/dist/tools/mcp/tool-search.js +294 -0
- package/dist/tools/output-projection.d.ts +18 -0
- package/dist/tools/output-projection.js +341 -0
- package/dist/tools/permission-contract.d.ts +25 -0
- package/dist/tools/permission-contract.js +1 -0
- package/dist/tools/permissions.d.ts +61 -0
- package/dist/tools/permissions.js +237 -0
- package/dist/tools/registry.d.ts +7 -0
- package/dist/tools/result-extension-contract.d.ts +37 -0
- package/dist/tools/result-extension-contract.js +32 -0
- package/dist/tools/result-extensions.d.ts +12 -0
- package/dist/tools/result-extensions.js +104 -0
- package/dist/tools/runtime-context.d.ts +89 -0
- package/dist/tools/runtime-context.js +1 -0
- package/dist/tools/runtime-resource-handles.js +28 -0
- package/dist/tools/runtime.js +77 -0
- package/dist/tools/scheduler.d.ts +12 -0
- package/dist/tools/shared/path-resolver.js +133 -0
- package/dist/tools/wait.d.ts +1 -0
- package/dist/tools/wait.js +1 -0
- package/package.json +15 -3
- package/dist/agent-core/error.d.ts +0 -15
- package/dist/agent-core/error.js +0 -74
- package/dist/agent-core/extensions/agents.d.ts +0 -79
- package/dist/agent-core/extensions/agents.js +0 -186
- package/dist/agent-core/extensions/compaction.d.ts +0 -48
- package/dist/agent-core/extensions/contracts.d.ts +0 -265
- package/dist/agent-core/extensions/data.d.ts +0 -84
- package/dist/agent-core/extensions/data.js +0 -83
- package/dist/agent-core/extensions/environment.d.ts +0 -27
- package/dist/agent-core/extensions/environment.js +0 -52
- package/dist/agent-core/extensions/files.d.ts +0 -64
- package/dist/agent-core/extensions/files.js +0 -26
- package/dist/agent-core/extensions/hooks.d.ts +0 -32
- package/dist/agent-core/extensions/manager.d.ts +0 -39
- package/dist/agent-core/extensions/manager.js +0 -458
- package/dist/agent-core/extensions/mcp.d.ts +0 -99
- package/dist/agent-core/extensions/mcp.js +0 -433
- package/dist/agent-core/extensions/model-request.d.ts +0 -56
- package/dist/agent-core/extensions/model-request.js +0 -197
- package/dist/agent-core/extensions/model-stream.d.ts +0 -9
- package/dist/agent-core/extensions/model-stream.js +0 -108
- package/dist/agent-core/extensions/models.d.ts +0 -43
- package/dist/agent-core/extensions/network.d.ts +0 -32
- package/dist/agent-core/extensions/network.js +0 -97
- package/dist/agent-core/extensions/operation.d.ts +0 -30
- package/dist/agent-core/extensions/processes.d.ts +0 -52
- package/dist/agent-core/extensions/processes.js +0 -284
- package/dist/agent-core/extensions/prompt-composition.d.ts +0 -24
- package/dist/agent-core/extensions/prompt-composition.js +0 -106
- package/dist/agent-core/extensions/prompt-input.d.ts +0 -23
- package/dist/agent-core/extensions/prompt-input.js +0 -48
- package/dist/agent-core/extensions/resources.d.ts +0 -27
- package/dist/agent-core/extensions/resources.js +0 -221
- package/dist/agent-core/extensions/services.d.ts +0 -31
- package/dist/agent-core/extensions/services.js +0 -61
- package/dist/agent-core/extensions/session-input.d.ts +0 -163
- package/dist/agent-core/extensions/session-input.js +0 -411
- package/dist/agent-core/extensions/session-messages.d.ts +0 -41
- package/dist/agent-core/extensions/session-messages.js +0 -76
- package/dist/agent-core/extensions/session.d.ts +0 -69
- package/dist/agent-core/extensions/session.js +0 -607
- package/dist/agent-core/extensions/settings.d.ts +0 -59
- package/dist/agent-core/extensions/settings.js +0 -115
- package/dist/agent-core/extensions/store.d.ts +0 -10
- package/dist/agent-core/extensions/store.js +0 -131
- package/dist/agent-core/extensions/tools.d.ts +0 -61
- package/dist/agent-core/extensions/tools.js +0 -269
- package/dist/agent-core/host/contracts.d.ts +0 -100
- package/dist/agent-core/host/contracts.js +0 -18
- package/dist/agent-core/host/local-agent-host.d.ts +0 -96
- package/dist/agent-core/host/local-agent-host.js +0 -425
- package/dist/agent-core/host/local-file-access.d.ts +0 -30
- package/dist/agent-core/host/local-file-access.js +0 -107
- package/dist/agent-core/host/local-network-access.d.ts +0 -6
- package/dist/agent-core/host/local-network-access.js +0 -101
- package/dist/agent-core/host/local-process-executor.d.ts +0 -29
- package/dist/agent-core/host/local-process-executor.js +0 -41
- package/dist/agent-core/host/local-session-environment.d.ts +0 -18
- package/dist/agent-core/host/local-shell.d.ts +0 -3
- package/dist/agent-core/host/network.d.ts +0 -4
- package/dist/agent-core/host/network.js +0 -6
- package/dist/agent-core/model/anthropic-messages.d.ts +0 -10
- package/dist/agent-core/model/anthropic-messages.js +0 -707
- package/dist/agent-core/model/anthropic-thinking.js +0 -33
- package/dist/agent-core/model/catalog-file.d.ts +0 -80
- package/dist/agent-core/model/catalog-file.js +0 -103
- package/dist/agent-core/model/configuration.d.ts +0 -127
- package/dist/agent-core/model/configuration.js +0 -168
- package/dist/agent-core/model/contracts.d.ts +0 -229
- package/dist/agent-core/model/http.d.ts +0 -27
- package/dist/agent-core/model/http.js +0 -534
- package/dist/agent-core/model/image.d.ts +0 -17
- package/dist/agent-core/model/openai-responses.d.ts +0 -77
- package/dist/agent-core/model/openai-responses.js +0 -2123
- package/dist/agent-core/model/product-user-agent.d.ts +0 -5
- package/dist/agent-core/model/product-user-agent.js +0 -22
- package/dist/agent-core/model/recovery.js +0 -80
- package/dist/agent-core/model/request-configuration.d.ts +0 -17
- package/dist/agent-core/model/request-configuration.js +0 -47
- package/dist/agent-core/model/runtime-credential.d.ts +0 -8
- package/dist/agent-core/model/runtime-credential.js +0 -72
- package/dist/agent-core/model/sse.js +0 -281
- package/dist/agent-core/model/text-blocks.js +0 -40
- package/dist/agent-core/model/tool-declarations.d.ts +0 -4
- package/dist/agent-core/model/transport-test.d.ts +0 -3
- package/dist/agent-core/model/transport-test.js +0 -23
- package/dist/agent-core/model/usage-observer.d.ts +0 -31
- package/dist/agent-core/prompts/index.d.ts +0 -20
- package/dist/agent-core/prompts/index.js +0 -49
- package/dist/agent-core/runtime/compaction/coordinator.js +0 -88
- package/dist/agent-core/runtime/compaction/generate.d.ts +0 -28
- package/dist/agent-core/runtime/compaction/generate.js +0 -84
- package/dist/agent-core/runtime/compaction/history.d.ts +0 -16
- package/dist/agent-core/runtime/compaction/operation.d.ts +0 -29
- package/dist/agent-core/runtime/compaction/operation.js +0 -131
- package/dist/agent-core/runtime/compaction/requests.d.ts +0 -16
- package/dist/agent-core/runtime/compaction/requests.js +0 -114
- package/dist/agent-core/runtime/compaction/retained-context.d.ts +0 -6
- package/dist/agent-core/runtime/compaction/retained-context.js +0 -47
- package/dist/agent-core/runtime/compaction/smart.d.ts +0 -14
- package/dist/agent-core/runtime/compaction/smart.js +0 -59
- package/dist/agent-core/runtime/context/contextual-blocks.d.ts +0 -30
- package/dist/agent-core/runtime/context/contextual-blocks.js +0 -146
- package/dist/agent-core/runtime/context/environment.d.ts +0 -5
- package/dist/agent-core/runtime/context/gc-runtime.d.ts +0 -38
- package/dist/agent-core/runtime/context/gc-tokens.d.ts +0 -25
- package/dist/agent-core/runtime/context/gc-tokens.js +0 -103
- package/dist/agent-core/runtime/context/gc.d.ts +0 -75
- package/dist/agent-core/runtime/context/gc.js +0 -1386
- package/dist/agent-core/runtime/context/instructions.d.ts +0 -37
- package/dist/agent-core/runtime/context/instructions.js +0 -297
- package/dist/agent-core/runtime/context/normalize.d.ts +0 -5
- package/dist/agent-core/runtime/context/projection.d.ts +0 -23
- package/dist/agent-core/runtime/context/projection.js +0 -284
- package/dist/agent-core/runtime/context/request-budget.d.ts +0 -4
- package/dist/agent-core/runtime/context/request-budget.js +0 -25
- package/dist/agent-core/runtime/context/restore.d.ts +0 -25
- package/dist/agent-core/runtime/context/restore.js +0 -186
- package/dist/agent-core/runtime/context/usage.d.ts +0 -17
- package/dist/agent-core/runtime/context/usage.js +0 -124
- package/dist/agent-core/runtime/context/world-state.d.ts +0 -33
- package/dist/agent-core/runtime/context/world-state.js +0 -232
- package/dist/agent-core/runtime/contracts.d.ts +0 -41
- package/dist/agent-core/runtime/event-projection.d.ts +0 -14
- package/dist/agent-core/runtime/event-projection.js +0 -87
- package/dist/agent-core/runtime/events.d.ts +0 -197
- package/dist/agent-core/runtime/execution-handle.d.ts +0 -12
- package/dist/agent-core/runtime/execution.d.ts +0 -50
- package/dist/agent-core/runtime/execution.js +0 -445
- package/dist/agent-core/runtime/model-progress.js +0 -85
- package/dist/agent-core/runtime/resource-publication.d.ts +0 -8
- package/dist/agent-core/runtime/resource-publication.js +0 -60
- package/dist/agent-core/sdk/agent.d.ts +0 -11
- package/dist/agent-core/sdk/agent.js +0 -474
- package/dist/agent-core/sdk/extension-agents.d.ts +0 -9
- package/dist/agent-core/sdk/extension-agents.js +0 -58
- package/dist/agent-core/sdk/extension-models.d.ts +0 -13
- package/dist/agent-core/sdk/extension-models.js +0 -137
- package/dist/agent-core/sdk/extension-session.d.ts +0 -30
- package/dist/agent-core/sdk/extension-session.js +0 -105
- package/dist/agent-core/sdk/extension-tools.d.ts +0 -16
- package/dist/agent-core/sdk/extension-tools.js +0 -126
- package/dist/agent-core/sdk/model-runtime.d.ts +0 -18
- package/dist/agent-core/sdk/model-runtime.js +0 -93
- package/dist/agent-core/sdk/native-steer.d.ts +0 -20
- package/dist/agent-core/sdk/native-steer.js +0 -84
- package/dist/agent-core/sdk/request-preparation.d.ts +0 -7
- package/dist/agent-core/sdk/resource-input.d.ts +0 -32
- package/dist/agent-core/sdk/resource-input.js +0 -403
- package/dist/agent-core/sdk/session.d.ts +0 -94
- package/dist/agent-core/sdk/session.js +0 -2377
- package/dist/agent-core/sdk/subagent-backend.d.ts +0 -3
- package/dist/agent-core/sdk/subagent-backend.js +0 -49
- package/dist/agent-core/sdk/types.d.ts +0 -81
- package/dist/agent-core/session/catalog.d.ts +0 -99
- package/dist/agent-core/session/catalog.js +0 -200
- package/dist/agent-core/session/context-gc-checkpoint.d.ts +0 -165
- package/dist/agent-core/session/context-gc-checkpoint.js +0 -935
- package/dist/agent-core/session/context-gc-observations.d.ts +0 -60
- package/dist/agent-core/session/context-gc-observations.js +0 -187
- package/dist/agent-core/session/context-gc-replacements.d.ts +0 -62
- package/dist/agent-core/session/context-gc-subagent.d.ts +0 -53
- package/dist/agent-core/session/deferred-input.d.ts +0 -5
- package/dist/agent-core/session/deferred-input.js +0 -74
- package/dist/agent-core/session/inline-media.d.ts +0 -45
- package/dist/agent-core/session/inline-media.js +0 -163
- package/dist/agent-core/session/rollback.d.ts +0 -13
- package/dist/agent-core/session/rollback.js +0 -46
- package/dist/agent-core/session/store/contracts.d.ts +0 -158
- package/dist/agent-core/session/store/current-state.d.ts +0 -17
- package/dist/agent-core/session/store/current-state.js +0 -53
- package/dist/agent-core/session/store/directory-index.d.ts +0 -18
- package/dist/agent-core/session/store/directory-index.js +0 -169
- package/dist/agent-core/session/store/execution-state.d.ts +0 -18
- package/dist/agent-core/session/store/execution-state.js +0 -175
- package/dist/agent-core/session/store/history.d.ts +0 -25
- package/dist/agent-core/session/store/history.js +0 -181
- package/dist/agent-core/session/store/images.d.ts +0 -19
- package/dist/agent-core/session/store/images.js +0 -110
- package/dist/agent-core/session/store/index.d.ts +0 -4
- package/dist/agent-core/session/store/index.js +0 -2
- package/dist/agent-core/session/store/jsonl-store.d.ts +0 -171
- package/dist/agent-core/session/store/jsonl-store.js +0 -2078
- package/dist/agent-core/session/store/records.d.ts +0 -23
- package/dist/agent-core/session/store/records.js +0 -261
- package/dist/agent-core/session/store/resources.d.ts +0 -26
- package/dist/agent-core/session/store/resources.js +0 -197
- package/dist/agent-core/session/store/types.d.ts +0 -82
- package/dist/agent-core/session/tool-result-resources.d.ts +0 -26
- package/dist/agent-core/session/tool-result-resources.js +0 -256
- package/dist/agent-core/session/transaction-recovery.d.ts +0 -16
- package/dist/agent-core/session/transaction-recovery.js +0 -135
- package/dist/agent-core/storage/file-lock.js +0 -83
- package/dist/agent-core/subagent/contracts.d.ts +0 -117
- package/dist/agent-core/subagent/model-update.js +0 -81
- package/dist/agent-core/subagent/scheduler.d.ts +0 -135
- package/dist/agent-core/subagent/scheduler.js +0 -369
- package/dist/agent-core/subagent/session-controller.d.ts +0 -138
- package/dist/agent-core/subagent/session-controller.js +0 -1594
- package/dist/agent-core/subagent/wait.d.ts +0 -14
- package/dist/agent-core/subagent/wait.js +0 -32
- package/dist/agent-core/tools/agent/agent-cancel.d.ts +0 -7
- package/dist/agent-core/tools/agent/agent-cancel.js +0 -29
- package/dist/agent-core/tools/agent/agent-message.d.ts +0 -7
- package/dist/agent-core/tools/agent/agent-message.js +0 -57
- package/dist/agent-core/tools/agent/agent-start.d.ts +0 -12
- package/dist/agent-core/tools/agent/agent-start.js +0 -106
- package/dist/agent-core/tools/agent/agent-wait.d.ts +0 -7
- package/dist/agent-core/tools/agent/agent-wait.js +0 -91
- package/dist/agent-core/tools/agent/question.d.ts +0 -7
- package/dist/agent-core/tools/agent/question.js +0 -125
- package/dist/agent-core/tools/agent/skill.d.ts +0 -11
- package/dist/agent-core/tools/agent/skill.js +0 -38
- package/dist/agent-core/tools/agent/sleep.d.ts +0 -12
- package/dist/agent-core/tools/agent/sleep.js +0 -54
- package/dist/agent-core/tools/agent/smart-compact.d.ts +0 -9
- package/dist/agent-core/tools/agent/smart-compact.js +0 -23
- package/dist/agent-core/tools/agent/todo-read.d.ts +0 -14
- package/dist/agent-core/tools/agent/todo-write.d.ts +0 -14
- package/dist/agent-core/tools/agent/todo-write.js +0 -66
- package/dist/agent-core/tools/agent/todo.d.ts +0 -26
- package/dist/agent-core/tools/agent/todo.js +0 -60
- package/dist/agent-core/tools/callers.d.ts +0 -6
- package/dist/agent-core/tools/callers.js +0 -39
- package/dist/agent-core/tools/code-mode/cells.d.ts +0 -29
- package/dist/agent-core/tools/code-mode/cells.js +0 -337
- package/dist/agent-core/tools/code-mode/dispatch.d.ts +0 -20
- package/dist/agent-core/tools/code-mode/dispatch.js +0 -80
- package/dist/agent-core/tools/code-mode/engine.d.ts +0 -60
- package/dist/agent-core/tools/code-mode/index.d.ts +0 -29
- package/dist/agent-core/tools/code-mode/index.js +0 -749
- package/dist/agent-core/tools/code-mode/observations.d.ts +0 -98
- package/dist/agent-core/tools/code-mode/observations.js +0 -228
- package/dist/agent-core/tools/code-mode/state.d.ts +0 -9
- package/dist/agent-core/tools/code-mode/state.js +0 -82
- package/dist/agent-core/tools/contracts.d.ts +0 -211
- package/dist/agent-core/tools/definition-projection.d.ts +0 -7
- package/dist/agent-core/tools/definition-projection.js +0 -26
- package/dist/agent-core/tools/execution-limits.d.ts +0 -69
- package/dist/agent-core/tools/execution-limits.js +0 -69
- package/dist/agent-core/tools/execution.d.ts +0 -46
- package/dist/agent-core/tools/execution.js +0 -191
- package/dist/agent-core/tools/local/apply-patch-parser.js +0 -177
- package/dist/agent-core/tools/local/apply-patch.d.ts +0 -19
- package/dist/agent-core/tools/local/apply-patch.js +0 -489
- package/dist/agent-core/tools/local/exec.d.ts +0 -53
- package/dist/agent-core/tools/local/exec.js +0 -877
- package/dist/agent-core/tools/local/image-processing.js +0 -146
- package/dist/agent-core/tools/local/read-context.js +0 -152
- package/dist/agent-core/tools/local/read.d.ts +0 -43
- package/dist/agent-core/tools/local/read.js +0 -470
- package/dist/agent-core/tools/local/registry.d.ts +0 -34
- package/dist/agent-core/tools/local/registry.js +0 -132
- package/dist/agent-core/tools/local/view-image.d.ts +0 -15
- package/dist/agent-core/tools/local/view-image.js +0 -317
- package/dist/agent-core/tools/local/workspace-tools.d.ts +0 -12
- package/dist/agent-core/tools/local/workspace-tools.js +0 -28
- package/dist/agent-core/tools/mcp/catalog.js +0 -220
- package/dist/agent-core/tools/mcp/history.d.ts +0 -4
- package/dist/agent-core/tools/mcp/tool-search.d.ts +0 -45
- package/dist/agent-core/tools/mcp/tool-search.js +0 -294
- package/dist/agent-core/tools/output-projection.d.ts +0 -18
- package/dist/agent-core/tools/output-projection.js +0 -341
- package/dist/agent-core/tools/permissions.d.ts +0 -85
- package/dist/agent-core/tools/permissions.js +0 -237
- package/dist/agent-core/tools/registry.d.ts +0 -7
- package/dist/agent-core/tools/result-extensions.d.ts +0 -46
- package/dist/agent-core/tools/result-extensions.js +0 -134
- package/dist/agent-core/tools/runtime-context.d.ts +0 -74
- package/dist/agent-core/tools/runtime-resource-handles.js +0 -28
- package/dist/agent-core/tools/runtime.js +0 -77
- package/dist/agent-core/tools/scheduler.d.ts +0 -12
- package/dist/agent-core/tools/shared/path-resolver.js +0 -133
- package/dist/agent-core/tools/wait.js +0 -82
- /package/dist/{agent-core/extensions/models.js → extensions/capabilities.js} +0 -0
- /package/dist/{agent-core/extensions → extensions}/compaction.js +0 -0
- /package/dist/{agent-core/model → extensions}/contracts.js +0 -0
- /package/dist/{agent-core/extensions → extensions}/hooks.js +0 -0
- /package/dist/{agent-core/runtime/context/contracts.js → extensions/host-ports.js} +0 -0
- /package/dist/{agent-core/extensions → extensions}/operation.js +0 -0
- /package/dist/{agent-core/runtime/contracts.js → extensions/tool-runtime.js} +0 -0
- /package/dist/{agent-core/extensions/contracts.js → extensions.js} +0 -0
- /package/dist/{agent-core/runtime/events.js → host/description.js} +0 -0
- /package/dist/{agent-core/host → host}/local-session-environment.js +0 -0
- /package/dist/{agent-core/host → host}/local-shell.js +0 -0
- /package/dist/{agent-core/runtime/execution-handle.js → host/skill-contract.js} +0 -0
- /package/dist/{agent-core/model → model}/anthropic-thinking.d.ts +0 -0
- /package/dist/{agent-core/model → model}/attempt-diagnostics.d.ts +0 -0
- /package/dist/{agent-core/model → model}/attempt-diagnostics.js +0 -0
- /package/dist/{agent-core/session/store → model}/contracts.js +0 -0
- /package/dist/{agent-core/sdk/types.js → model/image-contract.js} +0 -0
- /package/dist/{agent-core/model → model}/image.js +0 -0
- /package/dist/{agent-core/model → model}/native-context.d.ts +0 -0
- /package/dist/{agent-core/model → model}/native-context.js +0 -0
- /package/dist/{agent-core/model → model}/recovery.d.ts +0 -0
- /package/dist/{agent-core/model → model}/sse.d.ts +0 -0
- /package/dist/{agent-core/model → model}/text-blocks.d.ts +0 -0
- /package/dist/{agent-core/model → model}/tool-declarations.js +0 -0
- /package/dist/{agent-core/model → model}/tool-input.d.ts +0 -0
- /package/dist/{agent-core/model → model}/tool-input.js +0 -0
- /package/dist/{agent-core/model → model}/usage-observer.js +0 -0
- /package/dist/{agent-core/session/store/types.js → model/usage.js} +0 -0
- /package/dist/{agent-core/subagent → process}/contracts.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/compact.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/compact.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/core.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/core.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/markup.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/markup.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/modes.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/modes.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/output.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/output.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/permissions.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/permissions.js +0 -0
- /package/dist/{agent-core/tools/local → prompts}/read-context.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/resources.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/resources.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/subagent.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/subagent.js +0 -0
- /package/dist/{agent-core/prompts → prompts}/workflow.d.ts +0 -0
- /package/dist/{agent-core/prompts → prompts}/workflow.js +0 -0
- /package/dist/{agent-core/runtime → runtime}/async-queue.d.ts +0 -0
- /package/dist/{agent-core/runtime → runtime}/async-queue.js +0 -0
- /package/dist/{agent-core/tools → runtime/compaction}/contracts.js +0 -0
- /package/dist/{agent-core/runtime → runtime}/compaction/coordinator.d.ts +0 -0
- /package/dist/{agent-core/runtime → runtime}/compaction/history.js +0 -0
- /package/dist/{agent-core/runtime → runtime}/context/contracts.d.ts +0 -0
- /package/dist/{agent-core/session/types.js → runtime/context/contracts.js} +0 -0
- /package/dist/{agent-core/runtime → runtime}/context/environment.js +0 -0
- /package/dist/{agent-core/tools/code-mode/engine.js → runtime/context/gc-contracts.js} +0 -0
- /package/dist/{agent-core/runtime → runtime}/context/gc-runtime.js +0 -0
- /package/dist/{agent-core/runtime → runtime}/context/normalize.js +0 -0
- /package/dist/{agent-core/tools/code-mode/worker.d.ts → runtime/contracts.js} +0 -0
- /package/dist/{agent-core/tools/runtime-context.js → runtime/events.js} +0 -0
- /package/dist/{agent-core/runtime → runtime}/execution-policy.d.ts +0 -0
- /package/dist/{agent-core/runtime → runtime}/execution-policy.js +0 -0
- /package/dist/{agent-core/runtime → runtime}/model-generation-timing.d.ts +0 -0
- /package/dist/{agent-core/runtime → runtime}/model-generation-timing.js +0 -0
- /package/dist/{agent-core/runtime → runtime}/model-progress.d.ts +0 -0
- /package/dist/{agent-core/runtime → runtime}/plan-output.d.ts +0 -0
- /package/dist/{agent-core/runtime → runtime}/plan-output.js +0 -0
- /package/dist/{agent-core/tools/public-metadata.d.ts → runtime/public-tool-metadata.d.ts} +0 -0
- /package/dist/{agent-core/tools/public-metadata.js → runtime/public-tool-metadata.js} +0 -0
- /package/dist/{agent-core/runtime → runtime}/token-budget.d.ts +0 -0
- /package/dist/{agent-core/runtime → runtime}/token-budget.js +0 -0
- /package/dist/{agent-core/tools → runtime}/wait.d.ts +0 -0
- /package/dist/{agent-core/sdk → sdk}/request-preparation.js +0 -0
- /package/dist/{agent-core/session → session}/context-gc-markup.d.ts +0 -0
- /package/dist/{agent-core/session → session}/context-gc-markup.js +0 -0
- /package/dist/{agent-core/session → session}/context-gc-replacements.js +0 -0
- /package/dist/{agent-core/session → session}/context-gc-subagent.js +0 -0
- /package/dist/{agent-core/session → session}/types.d.ts +0 -0
- /package/dist/{agent-core/storage → storage}/file-lock.d.ts +0 -0
- /package/dist/{agent-core/subagent → subagent}/model-update.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/agent/todo-read.js +0 -0
- /package/dist/{agent-core/tools → tools}/code-mode/quickjs-engine.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/code-mode/quickjs-engine.js +0 -0
- /package/dist/{agent-core/tools → tools}/code-mode/text-output.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/code-mode/text-output.js +0 -0
- /package/dist/{agent-core/tools → tools}/code-mode/worker.js +0 -0
- /package/dist/{agent-core/tools → tools}/file-change-diff.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/file-change-diff.js +0 -0
- /package/dist/{agent-core/tools → tools}/input-diagnostics/source-preview.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/input-diagnostics/source-preview.js +0 -0
- /package/dist/{agent-core/tools → tools}/input.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/input.js +0 -0
- /package/dist/{agent-core/tools → tools}/local/apply-patch-parser.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/local/image-processing.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/mcp/catalog.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/mcp/history.js +0 -0
- /package/dist/{agent-core/tools → tools}/registry.js +0 -0
- /package/dist/{agent-core/tools → tools}/runtime-resource-handles.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/runtime.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/scheduler.js +0 -0
- /package/dist/{agent-core/tools → tools}/shared/patch-result.d.ts +0 -0
- /package/dist/{agent-core/tools → tools}/shared/patch-result.js +0 -0
- /package/dist/{agent-core/tools → tools}/shared/path-resolver.d.ts +0 -0
|
@@ -1,2377 +0,0 @@
|
|
|
1
|
-
import { readResourceImages, restoreMessages } from '../runtime/context/restore.js';
|
|
2
|
-
import { createNativeSteer } from './native-steer.js';
|
|
3
|
-
import { latestModelUsage, reasoningEffortBaseline } from '../runtime/context/usage.js';
|
|
4
|
-
import { splitContextualPrompt } from '../runtime/context/contextual-blocks.js';
|
|
5
|
-
import { contextualInstructionInsertIndex, latestContextualWorldStateGeneration, parsePersistedContextualWorldState, persistContextualWorldState, resetContextualWorldState, updateContextualWorldState, updatePromptWorldState } from '../runtime/context/world-state.js';
|
|
6
|
-
import { eventForPersistence, publicModelUsage } from '../runtime/event-projection.js';
|
|
7
|
-
import { ExecutionLoop } from '../runtime/execution.js';
|
|
8
|
-
import { publishModelResources } from '../runtime/resource-publication.js';
|
|
9
|
-
import { ResourceInputProjection } from './resource-input.js';
|
|
10
|
-
import { closeModelAdapters, createExecutionModelResources, createModelTurnSession } from './model-runtime.js';
|
|
11
|
-
import { prepareSessionModelRequest, projectSessionRequestMessages } from './request-preparation.js';
|
|
12
|
-
import { createSubagentBackend } from './subagent-backend.js';
|
|
13
|
-
import { ExecutionToolPermissions, projectPermissionTool, resolvePermissionMode, withToolPermissions } from '../tools/permissions.js';
|
|
14
|
-
import { createToolWaitInterrupt } from '../tools/wait.js';
|
|
15
|
-
import { discoveredMcpToolNames, rebindMcpToolSearchOutputs } from '../tools/mcp/history.js';
|
|
16
|
-
import { currentExecutionImages } from '../tools/output-projection.js';
|
|
17
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
18
|
-
import { ExecutionToolSources } from './extension-tools.js';
|
|
19
|
-
import { compactExtensionMessages, compactExtensionResult, compactExtensionDiagnostic } from '../extensions/compaction.js';
|
|
20
|
-
import { ExtensionRequestBridge, ExtensionRequestSnapshots } from '../extensions/model-request.js';
|
|
21
|
-
import { normalizeSessionMessagesInput, sessionMessagesPage } from '../extensions/session-messages.js';
|
|
22
|
-
import { transformCoreModelStream } from '../extensions/model-stream.js';
|
|
23
|
-
import { SessionInputCoordinator, recordSessionInputCommit } from '../extensions/session-input.js';
|
|
24
|
-
import { createExtensionSessionBackend } from './extension-session.js';
|
|
25
|
-
import { invokeCorePromptSubmission } from '../extensions/prompt-input.js';
|
|
26
|
-
import { createExtensionAgentsBackend } from './extension-agents.js';
|
|
27
|
-
import { coreMcpCatalog } from '../extensions/mcp.js';
|
|
28
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
29
|
-
import { MarAgentError, describeMarAgentError } from '../error.js';
|
|
30
|
-
import { prepareModelConfiguration } from '../model/request-configuration.js';
|
|
31
|
-
import { autoPermissionPrompt } from '../prompts/permissions.js';
|
|
32
|
-
import { MAR_AGENT_PROMPT_VERSION, buildSystemPromptSections } from '../prompts/index.js';
|
|
33
|
-
import { renderPromptSections } from '../extensions/prompt-composition.js';
|
|
34
|
-
import { retainedSessionResourcesSnapshot } from '../prompts/resources.js';
|
|
35
|
-
import { childSubagentInstruction } from '../prompts/subagent.js';
|
|
36
|
-
import { renderSubagentUpdate } from '../subagent/model-update.js';
|
|
37
|
-
import { AsyncQueue } from '../runtime/async-queue.js';
|
|
38
|
-
import { CompactionOperation } from '../runtime/compaction/operation.js';
|
|
39
|
-
import { generateCompactionCandidate } from '../runtime/compaction/generate.js';
|
|
40
|
-
import { CompactCoordinator } from '../runtime/compaction/coordinator.js';
|
|
41
|
-
import { CompactRequests } from '../runtime/compaction/requests.js';
|
|
42
|
-
import { compactSnapshotAnchor } from '../runtime/compaction/retained-context.js';
|
|
43
|
-
import { DEFAULT_COMPACTION_FOCUS, buildCompactedHistory, buildCompactionMessages, compactedHistoryMessages } from '../runtime/compaction/history.js';
|
|
44
|
-
import { currentLocalTimeContext, environmentContextUpdate, restoreEnvironmentState } from '../runtime/context/environment.js';
|
|
45
|
-
import { ContextGcRuntime } from '../runtime/context/gc-runtime.js';
|
|
46
|
-
import { AGENT_EXECUTION_POLICY } from '../runtime/execution-policy.js';
|
|
47
|
-
import { loadAgentInstructions, renderAgentInstructions } from '../runtime/context/instructions.js';
|
|
48
|
-
import { normalizeMessagesForModel } from '../runtime/context/normalize.js';
|
|
49
|
-
import { latestSmartContextTokens, requestSmartCompaction } from '../runtime/compaction/smart.js';
|
|
50
|
-
import { compactSummaryFromCheckpoint, inputMetadataFromRecord } from '../session/store/execution-state.js';
|
|
51
|
-
import { SubagentSessionController } from '../subagent/session-controller.js';
|
|
52
|
-
import { agentStartToolDefinitionWithModels } from '../tools/agent/agent-start.js';
|
|
53
|
-
import { allowsDirectTool, allowsToolCaller, toolCallers } from '../tools/callers.js';
|
|
54
|
-
import { assertMcpToolCatalog } from '../tools/mcp/catalog.js';
|
|
55
|
-
import { BUILTIN_TOOL_DEFINITIONS } from '../tools/registry.js';
|
|
56
|
-
import { createSessionToolScheduler } from '../tools/scheduler.js';
|
|
57
|
-
import { TodoStore } from '../tools/agent/todo.js';
|
|
58
|
-
import { DeferredMcpRegistry } from '../tools/mcp/tool-search.js';
|
|
59
|
-
/** SDK Session orchestration owns warm resources; Runtime owns only the model/tool loop. */
|
|
60
|
-
export function createSessionOpener(services) {
|
|
61
|
-
const { host, description, settings, store, createAdapter, activeAdaptersExcept } = services;
|
|
62
|
-
const { active, activeExecutionAdapters, executionResults, sessionRuntimes, sessionWriterOwner } = services.registry;
|
|
63
|
-
const openSession = async (sessionId, workspace) => {
|
|
64
|
-
services.assertSessionAdmission();
|
|
65
|
-
const storedSession = await store.getSession(sessionId);
|
|
66
|
-
services.assertSessionAdmission();
|
|
67
|
-
const storedWorkspace = storedSession.workspace;
|
|
68
|
-
const sessionSource = storedSession.source;
|
|
69
|
-
const logicalWorkspace = settings.workspaceMapping?.logicalPath ?? workspace ?? storedWorkspace ?? '';
|
|
70
|
-
const instructionWorkspace = settings.workspaceMapping?.physicalPath ?? workspace ?? storedWorkspace ?? '';
|
|
71
|
-
const currentEnvironment = {
|
|
72
|
-
platform: description.platform,
|
|
73
|
-
...(description.architecture ? { architecture: description.architecture } : {}),
|
|
74
|
-
...(description.shell ? { shell: description.shell } : {}),
|
|
75
|
-
...(description.guaranteedCommands
|
|
76
|
-
? { guaranteedCommands: description.guaranteedCommands }
|
|
77
|
-
: {}),
|
|
78
|
-
workspace: logicalWorkspace
|
|
79
|
-
};
|
|
80
|
-
if (!restoreEnvironmentState({ version: 1, state: currentEnvironment }))
|
|
81
|
-
throw new MarAgentError('MAR_AGENT_HOST_INCOMPATIBLE', 'Host environment facts are invalid or exceed the context limit.');
|
|
82
|
-
let sessionRuntime = sessionRuntimes.get(sessionId);
|
|
83
|
-
if (sessionRuntime === undefined) {
|
|
84
|
-
sessionRuntime = {
|
|
85
|
-
sourceType: sessionSource.type,
|
|
86
|
-
scheduleTool: createSessionToolScheduler(),
|
|
87
|
-
adapterGeneration: services.modelState().generation,
|
|
88
|
-
adapters: new Map()
|
|
89
|
-
};
|
|
90
|
-
sessionRuntimes.set(sessionId, sessionRuntime);
|
|
91
|
-
}
|
|
92
|
-
if (sessionSource.type === 'user' && sessionRuntime.subagents === undefined) {
|
|
93
|
-
sessionRuntime.subagentsOpening ??= SubagentSessionController.open({
|
|
94
|
-
parentSessionId: sessionId,
|
|
95
|
-
rootSessionId: sessionId,
|
|
96
|
-
backend: createSubagentBackend(store, storedWorkspace)
|
|
97
|
-
});
|
|
98
|
-
try {
|
|
99
|
-
sessionRuntime.subagents = await sessionRuntime.subagentsOpening;
|
|
100
|
-
}
|
|
101
|
-
finally {
|
|
102
|
-
delete sessionRuntime.subagentsOpening;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
const buildSessionPromptSections = (availableTools, promptMode, selectedModel, executionSystemInstruction, skillCatalog) => buildSystemPromptSections({
|
|
106
|
-
mode: promptMode,
|
|
107
|
-
platform: description.platform,
|
|
108
|
-
...(description.architecture ? { architecture: description.architecture } : {}),
|
|
109
|
-
...(description.shell ? { shell: description.shell } : {}),
|
|
110
|
-
...(description.guaranteedCommands
|
|
111
|
-
? { guaranteedCommands: description.guaranteedCommands }
|
|
112
|
-
: {}),
|
|
113
|
-
workspace: logicalWorkspace,
|
|
114
|
-
tools: availableTools
|
|
115
|
-
.filter((tool) => !tool.name.startsWith('mcp__'))
|
|
116
|
-
.map((tool) => tool.name),
|
|
117
|
-
directTools: availableTools
|
|
118
|
-
.filter((tool) => !tool.name.startsWith('mcp__') &&
|
|
119
|
-
allowsDirectTool(tool, availableTools.some((candidate) => candidate.name === 'code_exec')))
|
|
120
|
-
.map((tool) => tool.name),
|
|
121
|
-
extension: executionSystemInstruction
|
|
122
|
-
}).concat([
|
|
123
|
-
{ id: 'core:skill-catalog', text: skillCatalog || null },
|
|
124
|
-
{
|
|
125
|
-
id: 'core:child-instructions',
|
|
126
|
-
text: sessionSource.type === 'subagent' ? childSubagentInstruction || null : null
|
|
127
|
-
}
|
|
128
|
-
]);
|
|
129
|
-
const sessionAdapter = (modelId, configuredModels) => {
|
|
130
|
-
let selected = sessionRuntime.adapters.get(modelId);
|
|
131
|
-
if (selected === undefined) {
|
|
132
|
-
selected = createAdapter(modelId, configuredModels);
|
|
133
|
-
if (!services.hasCustomAdapters || selected.createTurnSession !== undefined)
|
|
134
|
-
sessionRuntime.adapters.set(modelId, selected);
|
|
135
|
-
}
|
|
136
|
-
return selected;
|
|
137
|
-
};
|
|
138
|
-
const refreshSessionAdapters = async (generation) => {
|
|
139
|
-
if (sessionRuntime.adapterGeneration === generation)
|
|
140
|
-
return;
|
|
141
|
-
const retainedByActiveSessions = activeAdaptersExcept(sessionId);
|
|
142
|
-
await closeModelAdapters([...sessionRuntime.adapters.values()].filter((adapter) => !retainedByActiveSessions.has(adapter)));
|
|
143
|
-
sessionRuntime.adapters.clear();
|
|
144
|
-
sessionRuntime.adapterGeneration = generation;
|
|
145
|
-
};
|
|
146
|
-
const sessionInputs = () => (sessionRuntime.inputs ??= new SessionInputCoordinator((receipt) => services.extensions.session(sessionId)?.diagnose({
|
|
147
|
-
code: receipt.errorCode ?? 'MAR_AGENT_SESSION_INPUT_FAILED',
|
|
148
|
-
operationId: receipt.operationId,
|
|
149
|
-
sessionId
|
|
150
|
-
})));
|
|
151
|
-
// Only physical record commits and projection replacement enter this lane, never Hooks.
|
|
152
|
-
const withRecordProjection = async (action) => {
|
|
153
|
-
const pending = (sessionRuntime.recordProjection ?? Promise.resolve())
|
|
154
|
-
.catch(() => undefined)
|
|
155
|
-
.then(action);
|
|
156
|
-
sessionRuntime.recordProjection = pending;
|
|
157
|
-
try {
|
|
158
|
-
return await pending;
|
|
159
|
-
}
|
|
160
|
-
finally {
|
|
161
|
-
if (sessionRuntime.recordProjection === pending)
|
|
162
|
-
delete sessionRuntime.recordProjection;
|
|
163
|
-
}
|
|
164
|
-
};
|
|
165
|
-
const appendExtensionMessage = async (entry, request, call) => {
|
|
166
|
-
call.signal.throwIfAborted();
|
|
167
|
-
const release = await store.acquireSessionWriteLease(sessionId, sessionWriterOwner);
|
|
168
|
-
try {
|
|
169
|
-
return await withRecordProjection(async () => {
|
|
170
|
-
call.signal.throwIfAborted();
|
|
171
|
-
const message = projectAppendedModelMessage(request.input);
|
|
172
|
-
const record = await store.append(sessionId, {
|
|
173
|
-
type: message ? 'model.context' : 'session.notice',
|
|
174
|
-
payload: {
|
|
175
|
-
...(message ?? {
|
|
176
|
-
content: request.input.content,
|
|
177
|
-
textBlocks: request.input.textBlocks
|
|
178
|
-
}),
|
|
179
|
-
source: extensionInputSource(call, request.input.attribution)
|
|
180
|
-
},
|
|
181
|
-
...(call.executionId ? { executionId: call.executionId } : {}),
|
|
182
|
-
...(call.turnId ? { turnId: call.turnId } : {})
|
|
183
|
-
}, { signal: call.signal });
|
|
184
|
-
const result = {
|
|
185
|
-
changed: true,
|
|
186
|
-
modelChanged: !!message,
|
|
187
|
-
recordId: record.recordId,
|
|
188
|
-
...(call.executionId ? { executionId: call.executionId } : {})
|
|
189
|
-
};
|
|
190
|
-
recordSessionInputCommit(entry, result);
|
|
191
|
-
if (message)
|
|
192
|
-
sessionRuntime.execution?.appendedMessages?.append(record.recordId, message);
|
|
193
|
-
return result;
|
|
194
|
-
});
|
|
195
|
-
}
|
|
196
|
-
finally {
|
|
197
|
-
await release();
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
const execution = (mode, input, internal = {}) => {
|
|
201
|
-
services.assertCanStart(sessionId);
|
|
202
|
-
if ([...active.keys()].some((key) => key.startsWith(`${sessionId}:`)))
|
|
203
|
-
throw new MarAgentError('MAR_AGENT_EXECUTION_ACTIVE', 'Session already has an active execution.');
|
|
204
|
-
const { models: executionModels, defaultModelId: executionDefaultModelId, generation: executionModelGeneration } = services.modelState();
|
|
205
|
-
if (mode !== 'compact' &&
|
|
206
|
-
executionModels.get(input.modelId ?? executionDefaultModelId)?.conversationModel === false)
|
|
207
|
-
throw new MarAgentError('MAR_AGENT_MODEL_DISABLED', 'The selected model is not a conversation model.');
|
|
208
|
-
const executionId = randomUUID(), turnId = internal.turnId ?? randomUUID(), queue = new AsyncQueue(), controller = new AbortController();
|
|
209
|
-
const compactCoordinator = new CompactCoordinator();
|
|
210
|
-
const messageSources = new WeakMap();
|
|
211
|
-
let liveModelMessages = [];
|
|
212
|
-
const compactRequests = new CompactRequests(executionId, () => compactCoordinator.assertNotReentrant());
|
|
213
|
-
const permissionPolicy = new ExecutionToolPermissions(mode === 'compact' ? 'full-access' : resolvePermissionMode(input.permissionMode), { sessionId, executionId }, host.requestToolApproval
|
|
214
|
-
? {
|
|
215
|
-
request: (request, signal) => host.requestToolApproval(request, signal),
|
|
216
|
-
signal: controller.signal
|
|
217
|
-
}
|
|
218
|
-
: undefined);
|
|
219
|
-
const projectTools = (tools) => permissionPolicy.mode === 'auto' ? tools.map(projectPermissionTool) : tools;
|
|
220
|
-
const abortSource = () => controller.abort(internal.signal?.reason);
|
|
221
|
-
internal.signal?.addEventListener('abort', abortSource, { once: true });
|
|
222
|
-
if (internal.signal?.aborted)
|
|
223
|
-
abortSource();
|
|
224
|
-
let executionEnvironment = {
|
|
225
|
-
...currentEnvironment,
|
|
226
|
-
...currentLocalTimeContext()
|
|
227
|
-
};
|
|
228
|
-
const executionSystemInstruction = settings.systemInstruction;
|
|
229
|
-
const executionContext = {
|
|
230
|
-
executionId,
|
|
231
|
-
modelId: input.modelId ?? executionDefaultModelId,
|
|
232
|
-
mode: mode === 'compact' ? 'run' : mode,
|
|
233
|
-
models: executionModels,
|
|
234
|
-
instruction: executionSystemInstruction,
|
|
235
|
-
compactRequests
|
|
236
|
-
};
|
|
237
|
-
sessionRuntime.execution = executionContext;
|
|
238
|
-
const manualCompactionId = mode === 'compact' ? randomUUID() : undefined;
|
|
239
|
-
active.set(`${sessionId}:${executionId}`, controller);
|
|
240
|
-
const inputs = sessionInputs();
|
|
241
|
-
const acceptParent = (message) => {
|
|
242
|
-
const origin = message.delivery?.origin;
|
|
243
|
-
const signal = AbortSignal.any([
|
|
244
|
-
controller.signal,
|
|
245
|
-
...(message.delivery?.signal === undefined ? [] : [message.delivery.signal])
|
|
246
|
-
]);
|
|
247
|
-
if (signal.aborted) {
|
|
248
|
-
message.delivery?.settled?.('cancelled');
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
const accept = (call) => {
|
|
252
|
-
const entry = inputs.accept({ kind: 'submit', input: { text: message.text } }, call, (request, call, leaf) => leaf(request, call), 'accepted', message);
|
|
253
|
-
void entry.terminal.then(() => {
|
|
254
|
-
if (entry.receipt.status === 'cancelled' || entry.receipt.status === 'failed')
|
|
255
|
-
message.delivery?.settled?.(entry.receipt.status);
|
|
256
|
-
});
|
|
257
|
-
};
|
|
258
|
-
if (origin) {
|
|
259
|
-
accept(Object.freeze({
|
|
260
|
-
...origin,
|
|
261
|
-
sessionId,
|
|
262
|
-
sessionEpoch: services.extensions.session(sessionId)?.epoch ?? 0,
|
|
263
|
-
signal,
|
|
264
|
-
executionId,
|
|
265
|
-
turnId
|
|
266
|
-
}));
|
|
267
|
-
return;
|
|
268
|
-
}
|
|
269
|
-
services.extensions.operations.enter({
|
|
270
|
-
sessionId,
|
|
271
|
-
sessionEpoch: services.extensions.session(sessionId)?.epoch ?? 0,
|
|
272
|
-
actor: 'sdk',
|
|
273
|
-
entry: 'native-api',
|
|
274
|
-
signal,
|
|
275
|
-
executionId,
|
|
276
|
-
turnId
|
|
277
|
-
}, accept);
|
|
278
|
-
};
|
|
279
|
-
for (const message of internal.initialMailbox ?? [])
|
|
280
|
-
acceptParent(message);
|
|
281
|
-
let acceptsMailbox = sessionSource.type === 'subagent' && mode !== 'compact';
|
|
282
|
-
let acceptsSteer = false;
|
|
283
|
-
let sequence = 0;
|
|
284
|
-
let emitTail = Promise.resolve();
|
|
285
|
-
let releaseSession;
|
|
286
|
-
let failedExecution = false;
|
|
287
|
-
let exhaustedModelAttempt;
|
|
288
|
-
// Serialize durable events before either the local stream or Host observes them.
|
|
289
|
-
let persistedTerminal = false;
|
|
290
|
-
const emit = (event, assertLive) => {
|
|
291
|
-
assertLive?.();
|
|
292
|
-
const full = {
|
|
293
|
-
...event,
|
|
294
|
-
eventId: randomUUID(),
|
|
295
|
-
sequence: ++sequence,
|
|
296
|
-
timestamp: new Date().toISOString(),
|
|
297
|
-
sessionId,
|
|
298
|
-
executionId,
|
|
299
|
-
turnId
|
|
300
|
-
};
|
|
301
|
-
const operation = emitTail.then(async () => {
|
|
302
|
-
assertLive?.();
|
|
303
|
-
const persistent = eventForPersistence(full);
|
|
304
|
-
let committedTerminal = false;
|
|
305
|
-
if (persistent !== undefined && releaseSession !== undefined) {
|
|
306
|
-
const stored = await store.append(sessionId, {
|
|
307
|
-
type: full.type,
|
|
308
|
-
payload: persistent,
|
|
309
|
-
executionId,
|
|
310
|
-
turnId
|
|
311
|
-
});
|
|
312
|
-
if (full.type === 'execution.completed' ||
|
|
313
|
-
full.type === 'execution.failed' ||
|
|
314
|
-
full.type === 'execution.cancelled')
|
|
315
|
-
committedTerminal = persistedTerminal = true;
|
|
316
|
-
if (full.type === 'message.completed') {
|
|
317
|
-
const message = liveModelMessages.findLast((item) => item.role === 'assistant' && item.content === full.text);
|
|
318
|
-
if (message)
|
|
319
|
-
messageSources.set(message, stored);
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
if (full.type === 'tool.output')
|
|
323
|
-
queue.pushIfWaiting(full);
|
|
324
|
-
else
|
|
325
|
-
queue.push(full);
|
|
326
|
-
compactRequests.publish(full);
|
|
327
|
-
if (internal.publishHostEvents !== false) {
|
|
328
|
-
try {
|
|
329
|
-
await host.emit(full);
|
|
330
|
-
}
|
|
331
|
-
catch (error) {
|
|
332
|
-
if (!committedTerminal)
|
|
333
|
-
throw error;
|
|
334
|
-
// Host observation cannot rewrite a terminal already committed to the Store.
|
|
335
|
-
try {
|
|
336
|
-
// Host errors may contain private data; publish only SDK-owned facts.
|
|
337
|
-
process.emitWarning(new MarAgentError('MAR_AGENT_HOST_EVENT_PUBLICATION_FAILED', `Host publication of ${full.type} failed for Execution ${executionId}.`, {
|
|
338
|
-
details: {
|
|
339
|
-
sessionId,
|
|
340
|
-
executionId,
|
|
341
|
-
eventId: full.eventId,
|
|
342
|
-
eventType: full.type
|
|
343
|
-
}
|
|
344
|
-
}));
|
|
345
|
-
}
|
|
346
|
-
catch {
|
|
347
|
-
// A diagnostic sink must not change the committed outcome either.
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
});
|
|
352
|
-
// Best-effort previews follow prior durable events without delaying later results.
|
|
353
|
-
if (full.type !== 'tool.output')
|
|
354
|
-
emitTail = operation.catch(() => undefined);
|
|
355
|
-
return operation;
|
|
356
|
-
};
|
|
357
|
-
const recordModelAttempt = (purpose) => (diagnostic) => {
|
|
358
|
-
if (purpose === 'EXECUTION' || purpose === 'COMPACTION') {
|
|
359
|
-
if ((diagnostic.state === 'STARTED' && diagnostic.attempt === 1) ||
|
|
360
|
-
diagnostic.state === 'SUCCEEDED')
|
|
361
|
-
exhaustedModelAttempt = undefined;
|
|
362
|
-
else if (diagnostic.state === 'FAILED' &&
|
|
363
|
-
diagnostic.willRetry === false &&
|
|
364
|
-
diagnostic.attempt > 1)
|
|
365
|
-
exhaustedModelAttempt = {
|
|
366
|
-
attempts: diagnostic.attempt,
|
|
367
|
-
retries: diagnostic.attempt - 1
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
const operation = emitTail.then(async () => {
|
|
371
|
-
await store.append(sessionId, {
|
|
372
|
-
type: 'model.attempt',
|
|
373
|
-
payload: { purpose, ...diagnostic },
|
|
374
|
-
executionId,
|
|
375
|
-
turnId
|
|
376
|
-
});
|
|
377
|
-
});
|
|
378
|
-
emitTail = operation.catch(() => undefined);
|
|
379
|
-
return operation;
|
|
380
|
-
};
|
|
381
|
-
const createCompactionOperation = (compactionId, signal = controller.signal) => new CompactionOperation(signal, (progress) => {
|
|
382
|
-
const operation = emitTail.then(async () => {
|
|
383
|
-
await store.append(sessionId, {
|
|
384
|
-
type: 'compact.progress',
|
|
385
|
-
payload: { compactionId, ...progress },
|
|
386
|
-
executionId,
|
|
387
|
-
turnId
|
|
388
|
-
});
|
|
389
|
-
});
|
|
390
|
-
emitTail = operation.catch(() => undefined);
|
|
391
|
-
return operation;
|
|
392
|
-
});
|
|
393
|
-
const result = withToolPermissions(permissionPolicy, async () => {
|
|
394
|
-
let finalAnswer = '';
|
|
395
|
-
let executionLoop;
|
|
396
|
-
let executionToolSources;
|
|
397
|
-
let releaseImageBytes;
|
|
398
|
-
const contextGc = new ContextGcRuntime();
|
|
399
|
-
let selectedAdapter;
|
|
400
|
-
const modelResources = createExecutionModelResources(activeExecutionAdapters);
|
|
401
|
-
const subagents = sessionSource.type === 'user' ? sessionRuntime.subagents : undefined;
|
|
402
|
-
try {
|
|
403
|
-
controller.signal.throwIfAborted();
|
|
404
|
-
releaseSession = await store.acquireSessionLease(sessionId, sessionWriterOwner);
|
|
405
|
-
if (!inputs.executing)
|
|
406
|
-
await inputs.idle();
|
|
407
|
-
let immediateTarget;
|
|
408
|
-
const pendingAppends = [];
|
|
409
|
-
executionContext.appendedMessages = {
|
|
410
|
-
append(recordId, message) {
|
|
411
|
-
pendingAppends.push({
|
|
412
|
-
recordId,
|
|
413
|
-
message
|
|
414
|
-
});
|
|
415
|
-
if (immediateTarget)
|
|
416
|
-
immediateTarget.push(message);
|
|
417
|
-
}
|
|
418
|
-
};
|
|
419
|
-
await refreshSessionAdapters(executionModelGeneration);
|
|
420
|
-
const sessionState = await store.readExecutionState(sessionId);
|
|
421
|
-
if (!store.hasRetainedSessionLease(sessionId, sessionWriterOwner))
|
|
422
|
-
sessionRuntime.todo = TodoStore.restore(sessionState.todo);
|
|
423
|
-
const todo = (sessionRuntime.todo ??= TodoStore.restore(sessionState.todo));
|
|
424
|
-
const contextRecords = sessionState.contextRecords;
|
|
425
|
-
const contextualWorldStateGeneration = latestContextualWorldStateGeneration(contextRecords);
|
|
426
|
-
const restoredContextualWorldState = sessionRuntime.contextualWorldState;
|
|
427
|
-
const persistedContextualWorldState = parsePersistedContextualWorldState(await store.readContextualWorldState(sessionId));
|
|
428
|
-
const initialContextualWorldState = restoredContextualWorldState !== undefined &&
|
|
429
|
-
restoredContextualWorldState.generation === contextualWorldStateGeneration
|
|
430
|
-
? restoredContextualWorldState
|
|
431
|
-
: persistedContextualWorldState !== undefined &&
|
|
432
|
-
persistedContextualWorldState.generation === contextualWorldStateGeneration
|
|
433
|
-
? persistedContextualWorldState
|
|
434
|
-
: {
|
|
435
|
-
generation: contextualWorldStateGeneration,
|
|
436
|
-
initialized: false,
|
|
437
|
-
instructionSnapshot: undefined,
|
|
438
|
-
resourceSnapshot: undefined,
|
|
439
|
-
entries: []
|
|
440
|
-
};
|
|
441
|
-
sessionRuntime.contextualWorldState = initialContextualWorldState;
|
|
442
|
-
const compactMayContainAgentInstructions = contextRecords.some((record) => compactSummaryFromCheckpoint(record) !== undefined);
|
|
443
|
-
const restored = await restoreMessages(store, sessionId, contextRecords, {
|
|
444
|
-
messageSources,
|
|
445
|
-
includeImages: mode !== 'compact'
|
|
446
|
-
});
|
|
447
|
-
// This execution owns checkpoint adoption, not another copy of the live context.
|
|
448
|
-
const modelContext = (() => {
|
|
449
|
-
const messages = restored.messages;
|
|
450
|
-
let userMessages = [...restored.userMessages];
|
|
451
|
-
let recordedEnvironment = restored.environmentState;
|
|
452
|
-
let instructionInsertIndex = 0;
|
|
453
|
-
let worldState = initialContextualWorldState;
|
|
454
|
-
const commitWorldState = async (next) => {
|
|
455
|
-
await persistContextualWorldState(store, sessionId, next);
|
|
456
|
-
worldState = next;
|
|
457
|
-
sessionRuntime.contextualWorldState = next;
|
|
458
|
-
};
|
|
459
|
-
const resetCompactWorldState = async (generation, committed) => {
|
|
460
|
-
instructionInsertIndex = contextualInstructionInsertIndex(messages);
|
|
461
|
-
const next = resetContextualWorldState(generation, instructionInsertIndex, {
|
|
462
|
-
instructionSnapshot: currentInstructionSnapshot,
|
|
463
|
-
instructionContent: renderAgentInstructions(instructionEntries, true),
|
|
464
|
-
resourceSnapshot: committed
|
|
465
|
-
? committed.resources
|
|
466
|
-
: retainedSessionResourcesSnapshot(await loadRetainedSessionResources())
|
|
467
|
-
});
|
|
468
|
-
if (!committed)
|
|
469
|
-
await commitWorldState(next);
|
|
470
|
-
else {
|
|
471
|
-
// The checkpoint is authoritative; its sidecar is recoverable on restart.
|
|
472
|
-
worldState = next;
|
|
473
|
-
sessionRuntime.contextualWorldState = next;
|
|
474
|
-
try {
|
|
475
|
-
await persistContextualWorldState(store, sessionId, next);
|
|
476
|
-
}
|
|
477
|
-
catch {
|
|
478
|
-
coreExtensions.diagnose({
|
|
479
|
-
code: 'MAR_AGENT_COMPACT_SIDECAR_PERSIST_FAILED',
|
|
480
|
-
sessionId
|
|
481
|
-
});
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
};
|
|
485
|
-
const recordEnvironment = async () => {
|
|
486
|
-
const message = environmentContextUpdate(executionEnvironment, recordedEnvironment);
|
|
487
|
-
if (!message)
|
|
488
|
-
return;
|
|
489
|
-
await store.append(sessionId, {
|
|
490
|
-
type: 'context.environment',
|
|
491
|
-
payload: { version: 1, state: executionEnvironment },
|
|
492
|
-
executionId,
|
|
493
|
-
turnId
|
|
494
|
-
});
|
|
495
|
-
messages.push(message);
|
|
496
|
-
recordedEnvironment = executionEnvironment;
|
|
497
|
-
};
|
|
498
|
-
const syncMcpWorldState = async (index = instructionInsertIndex) => {
|
|
499
|
-
const snapshot = mcpRegistry.navigation();
|
|
500
|
-
if (worldState.mcpSnapshot === snapshot)
|
|
501
|
-
return;
|
|
502
|
-
const next = {
|
|
503
|
-
...worldState,
|
|
504
|
-
mcpSnapshot: snapshot,
|
|
505
|
-
entries: [
|
|
506
|
-
...worldState.entries,
|
|
507
|
-
{
|
|
508
|
-
index,
|
|
509
|
-
kind: 'mcp',
|
|
510
|
-
content: snapshot ?? '<mcp_catalog>No deferred MCP tools remain.</mcp_catalog>'
|
|
511
|
-
}
|
|
512
|
-
]
|
|
513
|
-
};
|
|
514
|
-
await commitWorldState(next);
|
|
515
|
-
};
|
|
516
|
-
return {
|
|
517
|
-
messages,
|
|
518
|
-
get worldState() {
|
|
519
|
-
return worldState;
|
|
520
|
-
},
|
|
521
|
-
commitWorldState,
|
|
522
|
-
recordEnvironment,
|
|
523
|
-
syncMcpWorldState,
|
|
524
|
-
rememberInput(input) {
|
|
525
|
-
userMessages.push(input);
|
|
526
|
-
},
|
|
527
|
-
compactInputs(prefix) {
|
|
528
|
-
return userMessages.filter((entry) => prefix.some((message) => message.role === 'user' &&
|
|
529
|
-
message.contextKind === undefined &&
|
|
530
|
-
(entry.metadata?.recordId
|
|
531
|
-
? message.metadata?.recordId === entry.metadata.recordId
|
|
532
|
-
: message.content === entry.content)));
|
|
533
|
-
},
|
|
534
|
-
async initializeWorldState() {
|
|
535
|
-
instructionInsertIndex =
|
|
536
|
-
mode === 'compact' ? contextualInstructionInsertIndex(messages) : messages.length;
|
|
537
|
-
// Only the latest Compact may rebuild missing sidecar resources, never a GC boundary.
|
|
538
|
-
if (!worldState.initialized &&
|
|
539
|
-
contextRecords.some((record) => record.recordId === contextualWorldStateGeneration &&
|
|
540
|
-
compactSummaryFromCheckpoint(record) !== undefined))
|
|
541
|
-
await resetCompactWorldState(contextualWorldStateGeneration);
|
|
542
|
-
const nextInstructionWorldState = updateContextualWorldState(worldState, instructionInsertIndex, {
|
|
543
|
-
instructionSnapshot: currentInstructionSnapshot,
|
|
544
|
-
instructionContent: renderAgentInstructions(instructionEntries, compactMayContainAgentInstructions ||
|
|
545
|
-
worldState.instructionSnapshot !== undefined)
|
|
546
|
-
});
|
|
547
|
-
if (!isDeepStrictEqual(worldState, nextInstructionWorldState))
|
|
548
|
-
await commitWorldState(nextInstructionWorldState);
|
|
549
|
-
},
|
|
550
|
-
// Must run inside the existing writer/projection commit window.
|
|
551
|
-
replaceCompactMessages(replacementHistory, retainedModelContext) {
|
|
552
|
-
messages.splice(0, messages.length, environmentContextUpdate(executionEnvironment), ...compactedHistoryMessages(replacementHistory), ...retainedModelContext);
|
|
553
|
-
pendingAppends.length = 0;
|
|
554
|
-
resourceInput.replace(messages);
|
|
555
|
-
selected.resetContinuation?.();
|
|
556
|
-
},
|
|
557
|
-
// Derived state follows the committed splice, never delays it past the writer window.
|
|
558
|
-
async adoptCompactCheckpoint(recordId, replacementHistory, retainedModelContext, resources) {
|
|
559
|
-
contextGc.reset();
|
|
560
|
-
restoreMcpDiscovery();
|
|
561
|
-
recordedEnvironment = executionEnvironment;
|
|
562
|
-
userMessages = replacementHistory
|
|
563
|
-
.filter((message) => message.kind !== 'summary')
|
|
564
|
-
.map((message) => ({
|
|
565
|
-
content: message.content,
|
|
566
|
-
...(message.metadata ? { metadata: { ...message.metadata } } : {})
|
|
567
|
-
}));
|
|
568
|
-
userMessages.push(...retainedModelContext
|
|
569
|
-
.filter((message) => message.role === 'user' && message.contextKind === undefined)
|
|
570
|
-
.map((message) => ({
|
|
571
|
-
content: message.content,
|
|
572
|
-
...(message.metadata ? { metadata: message.metadata } : {})
|
|
573
|
-
})));
|
|
574
|
-
await resetCompactWorldState(recordId, { resources });
|
|
575
|
-
},
|
|
576
|
-
async adoptGcCheckpoint(committed, appendBoundary) {
|
|
577
|
-
smartContextTokens = undefined;
|
|
578
|
-
selected.resetContinuation?.();
|
|
579
|
-
const refreshed = await restoreMessages(store, sessionId, committed.records, {
|
|
580
|
-
includeImages: true,
|
|
581
|
-
currentTurnId: turnId,
|
|
582
|
-
messageSources,
|
|
583
|
-
projection: committed.projection
|
|
584
|
-
});
|
|
585
|
-
const restoredIds = new Set(committed.records.map((record) => record.recordId));
|
|
586
|
-
const lateMessages = pendingAppends
|
|
587
|
-
.slice(appendBoundary)
|
|
588
|
-
.filter((entry) => !restoredIds.has(entry.recordId))
|
|
589
|
-
.map((entry) => entry.message);
|
|
590
|
-
messages.splice(0, messages.length, ...refreshed.messages, ...lateMessages);
|
|
591
|
-
resourceInput.replace(messages);
|
|
592
|
-
resourceInput.adoptGc(committed.projection.checkpoint?.inlineMedia?.state);
|
|
593
|
-
restoreMcpDiscovery();
|
|
594
|
-
recordedEnvironment = refreshed.environmentState;
|
|
595
|
-
userMessages = [...refreshed.userMessages];
|
|
596
|
-
instructionInsertIndex = contextualInstructionInsertIndex(messages);
|
|
597
|
-
const next = resetContextualWorldState(latestContextualWorldStateGeneration(committed.records), instructionInsertIndex, {
|
|
598
|
-
instructionSnapshot: currentInstructionSnapshot,
|
|
599
|
-
instructionContent: renderAgentInstructions(instructionEntries, committed.records.some((record) => compactSummaryFromCheckpoint(record) !== undefined))
|
|
600
|
-
});
|
|
601
|
-
await commitWorldState(next);
|
|
602
|
-
}
|
|
603
|
-
};
|
|
604
|
-
})();
|
|
605
|
-
const messages = modelContext.messages;
|
|
606
|
-
const pendingInputs = restored.pendingInputs;
|
|
607
|
-
const waitInterrupt = createToolWaitInterrupt(() => pendingInputs.size > 0);
|
|
608
|
-
liveModelMessages = messages;
|
|
609
|
-
const restoredRecordIds = new Set(contextRecords.map((record) => record.recordId));
|
|
610
|
-
for (const pending of pendingAppends)
|
|
611
|
-
if (!restoredRecordIds.has(pending.recordId))
|
|
612
|
-
messages.push(pending.message);
|
|
613
|
-
pendingAppends.length = 0;
|
|
614
|
-
immediateTarget = messages;
|
|
615
|
-
let smartInput;
|
|
616
|
-
let compactContext;
|
|
617
|
-
let startCompact;
|
|
618
|
-
const writeInputRecord = async (content, type, metadata, call, committed) => {
|
|
619
|
-
call.signal.throwIfAborted();
|
|
620
|
-
if (content.images?.length && !selectedModel.inputCapabilities.includes('IMAGE'))
|
|
621
|
-
throw new MarAgentError('MAR_AGENT_INPUT_CAPABILITY_UNSUPPORTED', 'Selected model does not support image input.');
|
|
622
|
-
await withRecordProjection(async () => {
|
|
623
|
-
call.signal.throwIfAborted();
|
|
624
|
-
const smartPercent = smartContextTokens === undefined
|
|
625
|
-
? undefined
|
|
626
|
-
: (smartContextTokens * 100) / selectedModel.contextWindowTokens;
|
|
627
|
-
const smartCompaction = mode !== 'compact' &&
|
|
628
|
-
sessionSource.type === 'user' &&
|
|
629
|
-
type === 'turn.user' &&
|
|
630
|
-
metadata.inputSource === undefined &&
|
|
631
|
-
smartPercent !== undefined &&
|
|
632
|
-
smartPercent >= AGENT_EXECUTION_POLICY.smartCompactionPercent &&
|
|
633
|
-
smartPercent < AGENT_EXECUTION_POLICY.automaticCompactionPercent;
|
|
634
|
-
const modelImages = await publishModelResources(host, content.images, {
|
|
635
|
-
sessionId,
|
|
636
|
-
executionId
|
|
637
|
-
}, store);
|
|
638
|
-
const actualContent = modelImages === content.images
|
|
639
|
-
? content
|
|
640
|
-
: {
|
|
641
|
-
...content,
|
|
642
|
-
...(modelImages === undefined ? {} : { images: modelImages })
|
|
643
|
-
};
|
|
644
|
-
const images = modelImages?.length
|
|
645
|
-
? await store.persistInputImages(sessionId, modelImages)
|
|
646
|
-
: [];
|
|
647
|
-
const record = await store.append(sessionId, {
|
|
648
|
-
type,
|
|
649
|
-
payload: {
|
|
650
|
-
...metadata,
|
|
651
|
-
prompt: content.text,
|
|
652
|
-
...(smartCompaction ? { smartCompaction: true } : {}),
|
|
653
|
-
...(content.modelText === undefined ? {} : { modelText: content.modelText }),
|
|
654
|
-
...(content.context === undefined ? {} : { context: content.context }),
|
|
655
|
-
...(content.modelContext === undefined
|
|
656
|
-
? {}
|
|
657
|
-
: { modelContext: content.modelContext }),
|
|
658
|
-
...(images.length ? { images } : {})
|
|
659
|
-
},
|
|
660
|
-
executionId,
|
|
661
|
-
turnId
|
|
662
|
-
}, { signal: call.signal });
|
|
663
|
-
const inputMetadata = inputMetadataFromRecord(record);
|
|
664
|
-
smartInput = {
|
|
665
|
-
recordId: record.recordId,
|
|
666
|
-
eligible: smartCompaction,
|
|
667
|
-
requested: false
|
|
668
|
-
};
|
|
669
|
-
modelContext.rememberInput({
|
|
670
|
-
content: content.modelText ?? content.text,
|
|
671
|
-
metadata: inputMetadata
|
|
672
|
-
});
|
|
673
|
-
committed(actualContent, record.recordId, inputMetadata);
|
|
674
|
-
for (const text of content.modelContext ?? content.context ?? [])
|
|
675
|
-
messages.push({ role: 'user', content: text, contextKind: 'contextual' });
|
|
676
|
-
});
|
|
677
|
-
};
|
|
678
|
-
const appendMailboxMessages = async (restoring = false) => inputs.drain(async (entry, request, call) => {
|
|
679
|
-
call.signal.throwIfAborted();
|
|
680
|
-
if (request.kind === 'compact') {
|
|
681
|
-
if (request.input.async) {
|
|
682
|
-
const flight = startCompact(request.input);
|
|
683
|
-
entry.start();
|
|
684
|
-
return { changed: await flight.result, executionId };
|
|
685
|
-
}
|
|
686
|
-
return { changed: await compactContext(request.input), executionId };
|
|
687
|
-
}
|
|
688
|
-
if (request.kind === 'append') {
|
|
689
|
-
const result = await appendExtensionMessage(entry, request, call);
|
|
690
|
-
return { ...result, executionId };
|
|
691
|
-
}
|
|
692
|
-
if (entry.nativeSteer?.recordId) {
|
|
693
|
-
const received = pendingInputs.get(entry.nativeSteer.recordId);
|
|
694
|
-
if (!received)
|
|
695
|
-
return { changed: false, modelChanged: false };
|
|
696
|
-
return withRecordProjection(async () => {
|
|
697
|
-
call.signal.throwIfAborted();
|
|
698
|
-
const payload = received.payload;
|
|
699
|
-
const images = await store.readInputImages(sessionId, payload.images);
|
|
700
|
-
if (images.length && !selectedModel.inputCapabilities.includes('IMAGE'))
|
|
701
|
-
throw new MarAgentError('MAR_AGENT_INPUT_CAPABILITY_UNSUPPORTED', 'Selected model does not support image input.');
|
|
702
|
-
const percent = smartContextTokens === undefined
|
|
703
|
-
? undefined
|
|
704
|
-
: (smartContextTokens * 100) / selectedModel.contextWindowTokens;
|
|
705
|
-
const eligible = sessionSource.type === 'user' &&
|
|
706
|
-
percent !== undefined &&
|
|
707
|
-
percent >= AGENT_EXECUTION_POLICY.smartCompactionPercent &&
|
|
708
|
-
percent < AGENT_EXECUTION_POLICY.automaticCompactionPercent;
|
|
709
|
-
const actual = {
|
|
710
|
-
...payload,
|
|
711
|
-
...(eligible ? { smartCompaction: true } : {})
|
|
712
|
-
};
|
|
713
|
-
const content = (actual.modelText ?? actual.prompt);
|
|
714
|
-
const applied = await store.append(sessionId, {
|
|
715
|
-
type: 'model.context',
|
|
716
|
-
payload: {
|
|
717
|
-
role: 'user',
|
|
718
|
-
content,
|
|
719
|
-
inputRef: received.recordId,
|
|
720
|
-
input: actual
|
|
721
|
-
},
|
|
722
|
-
executionId,
|
|
723
|
-
turnId
|
|
724
|
-
}, { signal: call.signal });
|
|
725
|
-
const outcome = {
|
|
726
|
-
changed: true,
|
|
727
|
-
modelChanged: true,
|
|
728
|
-
executionId,
|
|
729
|
-
recordId: received.recordId
|
|
730
|
-
};
|
|
731
|
-
recordSessionInputCommit(entry, outcome);
|
|
732
|
-
pendingInputs.delete(received.recordId);
|
|
733
|
-
const metadata = inputMetadataFromRecord({ ...received, payload: actual });
|
|
734
|
-
const message = {
|
|
735
|
-
role: 'user',
|
|
736
|
-
content,
|
|
737
|
-
metadata,
|
|
738
|
-
...(images.length ? { images } : {})
|
|
739
|
-
};
|
|
740
|
-
messages.push(message);
|
|
741
|
-
messageSources.set(message, applied);
|
|
742
|
-
modelContext.rememberInput({ content, metadata });
|
|
743
|
-
smartInput = { recordId: received.recordId, eligible, requested: false };
|
|
744
|
-
for (const text of (payload.modelContext ?? payload.context ?? []))
|
|
745
|
-
messages.push({ role: 'user', content: text, contextKind: 'contextual' });
|
|
746
|
-
return outcome;
|
|
747
|
-
});
|
|
748
|
-
}
|
|
749
|
-
const parent = entry.parentMessage;
|
|
750
|
-
let outcome;
|
|
751
|
-
const content = {
|
|
752
|
-
text: request.input.text,
|
|
753
|
-
...(request.input.modelText === undefined
|
|
754
|
-
? {}
|
|
755
|
-
: { modelText: request.input.modelText }),
|
|
756
|
-
...(request.input.context === undefined
|
|
757
|
-
? {}
|
|
758
|
-
: { context: request.input.context }),
|
|
759
|
-
...(request.input.modelContext === undefined
|
|
760
|
-
? {}
|
|
761
|
-
: { modelContext: request.input.modelContext }),
|
|
762
|
-
...(request.input.images === undefined ? {} : { images: request.input.images })
|
|
763
|
-
};
|
|
764
|
-
await writeInputRecord(content, parent && !parent.delivery?.origin ? 'turn.user' : 'extension.input', parent && !parent.delivery?.origin
|
|
765
|
-
? {
|
|
766
|
-
inputSource: 'parent_agent',
|
|
767
|
-
...(parent.delivery ? { messageId: parent.delivery.messageId } : {})
|
|
768
|
-
}
|
|
769
|
-
: {
|
|
770
|
-
source: extensionInputSource(call, request.input.provenance, request.input.modelAttribution),
|
|
771
|
-
...(parent?.delivery ? { messageId: parent.delivery.messageId } : {})
|
|
772
|
-
}, call, (actual, recordId, metadata) => {
|
|
773
|
-
outcome = { changed: true, executionId, recordId };
|
|
774
|
-
recordSessionInputCommit(entry, outcome);
|
|
775
|
-
messages.push({
|
|
776
|
-
role: 'user',
|
|
777
|
-
content: actual.modelText ?? actual.text,
|
|
778
|
-
metadata,
|
|
779
|
-
...(actual.images?.length
|
|
780
|
-
? {
|
|
781
|
-
images: actual.images.map((image) => ({ ...image }))
|
|
782
|
-
}
|
|
783
|
-
: {})
|
|
784
|
-
});
|
|
785
|
-
parent?.delivery?.applied();
|
|
786
|
-
});
|
|
787
|
-
return outcome;
|
|
788
|
-
}, {
|
|
789
|
-
executionId,
|
|
790
|
-
turnId,
|
|
791
|
-
signal: controller.signal,
|
|
792
|
-
...(restoring ? { restoring: true } : {})
|
|
793
|
-
}, inputs.boundarySize);
|
|
794
|
-
const hasRestoredUserImages = messages.some((message) => message.role === 'user' && Boolean(message.images?.length));
|
|
795
|
-
let modelInputImages;
|
|
796
|
-
const inputImageBytes = new Map();
|
|
797
|
-
const currentExecutionToolImages = [];
|
|
798
|
-
let currentExecutionUserIndex;
|
|
799
|
-
await emit({ type: 'execution.started', mode, permissionMode: permissionPolicy.mode });
|
|
800
|
-
if (restored.ignoredImages > 0)
|
|
801
|
-
await store.append(sessionId, {
|
|
802
|
-
type: 'context.warning',
|
|
803
|
-
payload: {
|
|
804
|
-
code: 'MAR_AGENT_INPUT_IMAGE_IGNORED',
|
|
805
|
-
message: 'One or more corrupt historical input images were ignored.',
|
|
806
|
-
ignoredImages: restored.ignoredImages
|
|
807
|
-
},
|
|
808
|
-
executionId,
|
|
809
|
-
turnId
|
|
810
|
-
});
|
|
811
|
-
selectedAdapter = sessionAdapter(input.modelId ?? executionDefaultModelId, executionModels);
|
|
812
|
-
const selectedModel = executionModels.get(input.modelId ?? executionDefaultModelId);
|
|
813
|
-
const restoredMessageCount = messages.length;
|
|
814
|
-
const resourceInput = new ResourceInputProjection(selectedModel.useResourceUrl === true, store, sessionId, messages, {
|
|
815
|
-
records: contextRecords,
|
|
816
|
-
persist: async (state) => {
|
|
817
|
-
await withRecordProjection(() => store.append(sessionId, {
|
|
818
|
-
type: 'resource.window',
|
|
819
|
-
payload: state,
|
|
820
|
-
executionId,
|
|
821
|
-
turnId
|
|
822
|
-
}));
|
|
823
|
-
}
|
|
824
|
-
});
|
|
825
|
-
releaseImageBytes = () => resourceInput.releaseBytes();
|
|
826
|
-
const selected = modelResources.openTurn(selectedAdapter, services.hasCustomAdapters && selectedAdapter.createTurnSession === undefined);
|
|
827
|
-
let lastServerUsage = latestModelUsage(contextRecords, selectedModel.id);
|
|
828
|
-
let smartContextTokens = latestSmartContextTokens(contextRecords, selectedModel.id, selectedModel.contextWindowTokens);
|
|
829
|
-
const compactUserTokenLimit = Math.min(20_000, Math.floor(selectedModel.contextWindowTokens / 8));
|
|
830
|
-
const reasoningEffort = input.reasoningEffort ?? selectedModel.defaultReasoningEffort;
|
|
831
|
-
if (mode !== 'compact' && subagents)
|
|
832
|
-
await subagents.beginParentExecution({
|
|
833
|
-
executionId,
|
|
834
|
-
modelId: selectedModel.id,
|
|
835
|
-
reasoningEffort,
|
|
836
|
-
models: executionModels,
|
|
837
|
-
emitTerminal: async (task) => emit({
|
|
838
|
-
type: 'subagent.completed',
|
|
839
|
-
agentId: task.agentId,
|
|
840
|
-
description: task.description,
|
|
841
|
-
status: task.status,
|
|
842
|
-
...(task.permissionStop === undefined
|
|
843
|
-
? {}
|
|
844
|
-
: { permissionStop: task.permissionStop }),
|
|
845
|
-
...(task.modelId === undefined ? {} : { modelId: task.modelId }),
|
|
846
|
-
...(task.modelName === undefined ? {} : { modelName: task.modelName }),
|
|
847
|
-
...(task.reasoningEffort === undefined
|
|
848
|
-
? {}
|
|
849
|
-
: { reasoningEffort: task.reasoningEffort }),
|
|
850
|
-
...(task.latestMessage === undefined
|
|
851
|
-
? {}
|
|
852
|
-
: { latestMessage: task.latestMessage }),
|
|
853
|
-
...(task.latestActivity === undefined
|
|
854
|
-
? {}
|
|
855
|
-
: { latestActivity: task.latestActivity }),
|
|
856
|
-
...(task.errorCode === undefined ? {} : { errorCode: task.errorCode }),
|
|
857
|
-
...(task.errorMessage === undefined ? {} : { errorMessage: task.errorMessage })
|
|
858
|
-
}),
|
|
859
|
-
startTurn: async (turn) => {
|
|
860
|
-
const child = await openSession(turn.sessionId);
|
|
861
|
-
return child.startSubagentTurn({
|
|
862
|
-
permissionMode: permissionPolicy.mode,
|
|
863
|
-
prompt: turn.prompt,
|
|
864
|
-
modelId: turn.modelId,
|
|
865
|
-
reasoningEffort: turn.reasoningEffort,
|
|
866
|
-
role: turn.role,
|
|
867
|
-
initialMailbox: turn.initialMailbox,
|
|
868
|
-
turnId: turn.turnId,
|
|
869
|
-
...(turn.origin === undefined ? {} : { origin: turn.origin }),
|
|
870
|
-
mcpExecutionScopeId: executionId,
|
|
871
|
-
...(turn.delivery ? { delivery: turn.delivery } : {})
|
|
872
|
-
});
|
|
873
|
-
}
|
|
874
|
-
});
|
|
875
|
-
const catalogContext = {
|
|
876
|
-
sessionId,
|
|
877
|
-
executionId,
|
|
878
|
-
modelId: selectedModel.id,
|
|
879
|
-
...(sessionSource.type === 'subagent'
|
|
880
|
-
? internal.mcpExecutionScopeId === undefined
|
|
881
|
-
? {}
|
|
882
|
-
: { executionScopeId: internal.mcpExecutionScopeId }
|
|
883
|
-
: { claimExecutionScope: true })
|
|
884
|
-
};
|
|
885
|
-
const readMcpCatalog = async () => {
|
|
886
|
-
if (host.listMcpToolCatalog) {
|
|
887
|
-
const catalog = await host.listMcpToolCatalog(catalogContext);
|
|
888
|
-
assertMcpToolCatalog(catalog);
|
|
889
|
-
return catalog;
|
|
890
|
-
}
|
|
891
|
-
const definitions = (await host.listMcpTools?.(catalogContext)) ?? [];
|
|
892
|
-
return {
|
|
893
|
-
revision: createHash('sha256').update(JSON.stringify(definitions)).digest('hex'),
|
|
894
|
-
servers: [{ id: 'legacy', name: 'External MCP' }],
|
|
895
|
-
tools: definitions.map((definition) => ({
|
|
896
|
-
definition,
|
|
897
|
-
serverId: 'legacy',
|
|
898
|
-
rawName: definition.name,
|
|
899
|
-
sourceIdentity: `legacy:${executionId}`,
|
|
900
|
-
definitionRevision: createHash('sha256')
|
|
901
|
-
.update(JSON.stringify(definition))
|
|
902
|
-
.digest('hex'),
|
|
903
|
-
lifetime: 'execution',
|
|
904
|
-
exposure: 'deferred'
|
|
905
|
-
}))
|
|
906
|
-
};
|
|
907
|
-
};
|
|
908
|
-
const mcpCatalog = await readMcpCatalog();
|
|
909
|
-
const mcpRegistry = new DeferredMcpRegistry(discoveredMcpToolNames(messages));
|
|
910
|
-
const mcpTools = mcpCatalog.tools.map((tool) => tool.definition);
|
|
911
|
-
const extensions = (await host.listExecutionExtensions?.(catalogContext)) ?? {};
|
|
912
|
-
if (extensions.tools?.some((tool) => tool.name.startsWith('mcp__')))
|
|
913
|
-
throw new MarAgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Host tools cannot use the MCP namespace.');
|
|
914
|
-
const selectedModelForTools = executionModels.get(input.modelId ?? executionDefaultModelId);
|
|
915
|
-
const builtinTools = BUILTIN_TOOL_DEFINITIONS.map((tool) => tool.name === 'agent_start'
|
|
916
|
-
? agentStartToolDefinitionWithModels([...executionModels.values()]
|
|
917
|
-
.filter((configuration) => configuration.conversationModel !== false)
|
|
918
|
-
.map((configuration) => ({
|
|
919
|
-
id: configuration.id,
|
|
920
|
-
name: configuration.name,
|
|
921
|
-
reasoningEfforts: configuration.reasoningEfforts
|
|
922
|
-
})))
|
|
923
|
-
: tool);
|
|
924
|
-
const combinedTools = [...builtinTools, ...(extensions.tools ?? []), ...mcpTools];
|
|
925
|
-
if (new Set(combinedTools.map((tool) => tool.name)).size !== combinedTools.length)
|
|
926
|
-
throw new MarAgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Tool names conflict.');
|
|
927
|
-
const executionSourceNames = new Set(combinedTools.map((tool) => tool.name));
|
|
928
|
-
const supplementalBindings = services.extensions.options
|
|
929
|
-
.baseTools?.(sessionId, { executionId })
|
|
930
|
-
?.filter((binding) => !executionSourceNames.has(binding.definition.name)) ?? [];
|
|
931
|
-
const sources = (executionToolSources = new ExecutionToolSources(executionId, sessionId, combinedTools, builtinTools, mcpCatalog, supplementalBindings));
|
|
932
|
-
const sourceBindings = sources.bindings;
|
|
933
|
-
const coreExtensions = await services.extensions.prepare(sessionId, controller.signal, sourceBindings, sessionSource.type === 'user' && !internal.automaticInput);
|
|
934
|
-
executionContext.toolSources = sources;
|
|
935
|
-
const operation = (run) => services.extensions.operations.run({
|
|
936
|
-
sessionId,
|
|
937
|
-
sessionEpoch: coreExtensions.epoch,
|
|
938
|
-
executionId,
|
|
939
|
-
turnId,
|
|
940
|
-
actor: 'sdk',
|
|
941
|
-
entry: 'native-api',
|
|
942
|
-
signal: controller.signal
|
|
943
|
-
}, run);
|
|
944
|
-
if (mode !== 'compact') {
|
|
945
|
-
// Missing entries prepend in reverse order; warm entries retain their FIFO position.
|
|
946
|
-
for (const record of [...pendingInputs.values()].reverse()) {
|
|
947
|
-
operation((call) => inputs.restoreSteer(record.recordId, record.payload.prompt, call));
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
await operation((call) => coreExtensions.ready(call));
|
|
951
|
-
const captureTools = () => operation((call) => {
|
|
952
|
-
return coreExtensions.capture(call, false, sourceBindings.filter((binding) => !supplementalBindings.includes(binding) || binding.available?.(call) !== false));
|
|
953
|
-
});
|
|
954
|
-
const streamModel = (start, signal = controller.signal) => transformCoreModelStream(start, signal, (event, signal) => operation((call) => coreExtensions.modelEvent(event, Object.freeze({ ...call, signal }))), () => coreExtensions.diagnose({
|
|
955
|
-
code: 'MAR_AGENT_MODEL_STREAM_CLEANUP_FAILED',
|
|
956
|
-
sessionId
|
|
957
|
-
}));
|
|
958
|
-
const transformModelRequest = async (candidate, bindings = captureTools(), modelId = selectedModel.id, purpose = mode === 'compact' ? 'compact' : 'conversation') => {
|
|
959
|
-
let lowered = candidate;
|
|
960
|
-
if (coreExtensions.hooks.hasInterceptors('model.request')) {
|
|
961
|
-
const bridge = new ExtensionRequestBridge(modelId, candidate, undefined, selected.continuationInputCount?.() ?? 0);
|
|
962
|
-
const request = await operation((call) => coreExtensions.hooks.invoke('model.request', bridge.view, call, async (view) => view));
|
|
963
|
-
lowered = bridge.lower(request);
|
|
964
|
-
if (bridge.rewroteCommittedInput)
|
|
965
|
-
selected.resetContinuation?.();
|
|
966
|
-
}
|
|
967
|
-
for (const definition of lowered.tools) {
|
|
968
|
-
const binding = bindings.get(definition.name);
|
|
969
|
-
const { description: _description, ...contract } = definition;
|
|
970
|
-
const { description: _capturedDescription, ...capturedContract } = binding
|
|
971
|
-
? permissionPolicy.mode === 'auto'
|
|
972
|
-
? projectPermissionTool(binding.definition)
|
|
973
|
-
: binding.definition
|
|
974
|
-
: {};
|
|
975
|
-
if (!binding || !isDeepStrictEqual(contract, capturedContract))
|
|
976
|
-
throw new MarAgentError('MAR_AGENT_EXTENSION_MODEL_REQUEST_INVALID', 'Request tools do not match captured sources.');
|
|
977
|
-
}
|
|
978
|
-
return {
|
|
979
|
-
...lowered,
|
|
980
|
-
usageRequestId: randomUUID(),
|
|
981
|
-
...(host.modelUsage === undefined
|
|
982
|
-
? {}
|
|
983
|
-
: {
|
|
984
|
-
onModelUsage: (usage) => host.modelUsage({
|
|
985
|
-
...usage,
|
|
986
|
-
sessionId,
|
|
987
|
-
executionId,
|
|
988
|
-
purpose,
|
|
989
|
-
agentRole: sessionSource.type === 'subagent' ? 'subagent' : 'root'
|
|
990
|
-
}),
|
|
991
|
-
onModelUsageFailure: () => coreExtensions.diagnose({
|
|
992
|
-
code: 'MAR_AGENT_MODEL_USAGE_FAILED',
|
|
993
|
-
sessionId
|
|
994
|
-
})
|
|
995
|
-
})
|
|
996
|
-
};
|
|
997
|
-
};
|
|
998
|
-
const toolEligible = (tool) => {
|
|
999
|
-
toolCallers(tool);
|
|
1000
|
-
if (sessionSource.type === 'subagent' && tool.agentScope === 'ROOT_ONLY')
|
|
1001
|
-
return false;
|
|
1002
|
-
if (sessionSource.type === 'subagent' &&
|
|
1003
|
-
(tool.name.startsWith('agent_') || tool.name === 'question'))
|
|
1004
|
-
return false;
|
|
1005
|
-
if (tool.name === 'tool_search')
|
|
1006
|
-
return mcpRegistry.hasDeferred;
|
|
1007
|
-
return tool.name === 'code_exec' || tool.name === 'code_exec_wait'
|
|
1008
|
-
? selectedModelForTools.codeMode && description.capabilities.includes('code.execute')
|
|
1009
|
-
: tool.name === 'question'
|
|
1010
|
-
? mode === 'plan'
|
|
1011
|
-
: tool.name !== 'view_image' ||
|
|
1012
|
-
selectedModelForTools.inputCapabilities.includes('IMAGE');
|
|
1013
|
-
};
|
|
1014
|
-
const updateMcpRegistry = () => mcpRegistry.update(coreMcpCatalog([...mcpCatalog.servers, ...coreExtensions.mcp.servers()], captureTools()), (tool) => toolEligible(tool.definition), { nativeToolNames: true });
|
|
1015
|
-
updateMcpRegistry();
|
|
1016
|
-
rebindMcpToolSearchOutputs(messages, mcpRegistry);
|
|
1017
|
-
const availableTools = [...captureTools().values()]
|
|
1018
|
-
.map((binding) => binding.definition)
|
|
1019
|
-
.filter(toolEligible);
|
|
1020
|
-
const instructionContext = await loadAgentInstructions({
|
|
1021
|
-
home: description.homeDirectory,
|
|
1022
|
-
workspace: instructionWorkspace,
|
|
1023
|
-
availableTools: new Set(availableTools.map((tool) => tool.name)),
|
|
1024
|
-
hostSkills: extensions.skills ?? [],
|
|
1025
|
-
...(settings.workspaceMapping === undefined
|
|
1026
|
-
? {}
|
|
1027
|
-
: { workspaceDisplayPath: logicalWorkspace })
|
|
1028
|
-
});
|
|
1029
|
-
const instructionEntries = instructionContext?.entries ?? [];
|
|
1030
|
-
const currentInstructionSnapshot = renderAgentInstructions(instructionEntries, false);
|
|
1031
|
-
const baseTools = () => [...captureTools().values()]
|
|
1032
|
-
.filter((binding) => binding.mcp === undefined)
|
|
1033
|
-
.map((binding) => binding.definition)
|
|
1034
|
-
.filter((tool) => toolEligible(tool) &&
|
|
1035
|
-
(tool.name !== 'skill' || (instructionContext?.skills.size ?? 0) > 0));
|
|
1036
|
-
let executionTools = mcpRegistry.project(baseTools());
|
|
1037
|
-
const restoreMcpDiscovery = () => {
|
|
1038
|
-
mcpRegistry.restore(discoveredMcpToolNames(messages));
|
|
1039
|
-
rebindMcpToolSearchOutputs(messages, mcpRegistry);
|
|
1040
|
-
executionTools = mcpRegistry.project(baseTools());
|
|
1041
|
-
};
|
|
1042
|
-
const loadRetainedSessionResources = async () => {
|
|
1043
|
-
await subagents?.prepareSessionResources(controller.signal);
|
|
1044
|
-
const hostResources = (await host.listSessionResources?.(sessionId)) ?? {
|
|
1045
|
-
processes: []
|
|
1046
|
-
};
|
|
1047
|
-
return {
|
|
1048
|
-
...(hostResources.idleTtlMs === undefined
|
|
1049
|
-
? {}
|
|
1050
|
-
: { idleTtlMs: hostResources.idleTtlMs }),
|
|
1051
|
-
processes: hostResources.processes,
|
|
1052
|
-
...(hostResources.codeCells ? { codeCells: hostResources.codeCells } : {}),
|
|
1053
|
-
subagents: subagents?.listSessionResources() ?? []
|
|
1054
|
-
};
|
|
1055
|
-
};
|
|
1056
|
-
await modelContext.initializeWorldState();
|
|
1057
|
-
const buildExecutionPromptSections = (availableTools = executionTools, promptMode = mode) => buildSessionPromptSections(availableTools, promptMode, selectedModel, executionSystemInstruction, instructionContext?.skillCatalog);
|
|
1058
|
-
const buildExecutionSystemPrompt = (availableTools = executionTools, promptMode = mode) => renderPromptSections(buildExecutionPromptSections(availableTools, promptMode));
|
|
1059
|
-
const promptComposition = (availableTools, promptMode) => ({
|
|
1060
|
-
sections: buildExecutionPromptSections(availableTools, promptMode),
|
|
1061
|
-
facts: {
|
|
1062
|
-
modelId: selectedModel.id,
|
|
1063
|
-
mode: promptMode,
|
|
1064
|
-
tools: availableTools.map((tool) => tool.name)
|
|
1065
|
-
}
|
|
1066
|
-
});
|
|
1067
|
-
if (mode !== 'compact')
|
|
1068
|
-
await modelContext.syncMcpWorldState();
|
|
1069
|
-
const writeCompactionRecord = async (summary, _automatic, signal, write) => withRecordProjection(async () => {
|
|
1070
|
-
signal.throwIfAborted();
|
|
1071
|
-
const stored = await write(summary, { signal });
|
|
1072
|
-
inputs.recordCompactCommit({ changed: true, recordId: stored.recordId, executionId });
|
|
1073
|
-
return stored;
|
|
1074
|
-
});
|
|
1075
|
-
const performCompact = (input, leaf) => operation((call) => inputs.performCompact(input, call, (commit) => coreExtensions.hooks.invoke('session.compact', input, call, async (input, effective) => {
|
|
1076
|
-
effective.signal.throwIfAborted();
|
|
1077
|
-
if (input.focus !== undefined && typeof input.focus !== 'string')
|
|
1078
|
-
throw new MarAgentError('MAR_AGENT_SESSION_INPUT_INVALID', 'Compaction focus is invalid.');
|
|
1079
|
-
const outcome = await leaf(input, effective);
|
|
1080
|
-
commit(outcome);
|
|
1081
|
-
return outcome;
|
|
1082
|
-
})));
|
|
1083
|
-
const captureRoundToolScope = () => {
|
|
1084
|
-
const roundTools = projectTools(executionTools);
|
|
1085
|
-
const availableBindings = captureTools();
|
|
1086
|
-
const roundBindings = new Map(roundTools.map((tool) => [tool.name, availableBindings.get(tool.name)]));
|
|
1087
|
-
const defaultComposition = promptComposition(roundTools, mode === 'compact' ? 'run' : mode);
|
|
1088
|
-
if (permissionPolicy.mode === 'auto')
|
|
1089
|
-
defaultComposition.sections = [
|
|
1090
|
-
...defaultComposition.sections,
|
|
1091
|
-
{ id: 'core:auto-permission', text: autoPermissionPrompt }
|
|
1092
|
-
];
|
|
1093
|
-
const defaultSystemPrompt = renderPromptSections(defaultComposition.sections);
|
|
1094
|
-
let systemPrompt = defaultSystemPrompt;
|
|
1095
|
-
const roundMcpExpectations = new Map(roundTools
|
|
1096
|
-
.filter((tool) => roundBindings.get(tool.name)?.mcp !== undefined)
|
|
1097
|
-
.map((tool) => [tool.name, mcpRegistry.expectedTool(tool.name)]));
|
|
1098
|
-
const parentFrame = subagents === undefined || mode === 'compact'
|
|
1099
|
-
? undefined
|
|
1100
|
-
: subagents.captureParentFrame(executionId);
|
|
1101
|
-
const roundSmartInput = smartInput;
|
|
1102
|
-
const toolContext = {
|
|
1103
|
-
imageStore: store,
|
|
1104
|
-
host: host,
|
|
1105
|
-
requestSmartCompact: () => {
|
|
1106
|
-
controller.signal.throwIfAborted();
|
|
1107
|
-
requestSmartCompaction(roundSmartInput === smartInput ? roundSmartInput : undefined, () => {
|
|
1108
|
-
// The Session owns this background operation, not the short-lived tool callback.
|
|
1109
|
-
services.extensions.operations.enter({
|
|
1110
|
-
sessionId,
|
|
1111
|
-
sessionEpoch: coreExtensions.epoch,
|
|
1112
|
-
executionId,
|
|
1113
|
-
turnId,
|
|
1114
|
-
actor: 'sdk',
|
|
1115
|
-
entry: 'native-api',
|
|
1116
|
-
signal: controller.signal
|
|
1117
|
-
}, () => startCompact({ async: true }));
|
|
1118
|
-
});
|
|
1119
|
-
},
|
|
1120
|
-
permissionPolicy,
|
|
1121
|
-
writeToolResultResource: (text) => store.writeToolResultResource(sessionId, text),
|
|
1122
|
-
todo,
|
|
1123
|
-
...(subagents === undefined || mode === 'compact'
|
|
1124
|
-
? {}
|
|
1125
|
-
: {
|
|
1126
|
-
subagents: coreExtensions.bindAgents(subagents.captureExecution(executionId)),
|
|
1127
|
-
subagentMessages: subagents.modelMessages
|
|
1128
|
-
}),
|
|
1129
|
-
mode,
|
|
1130
|
-
sessionId,
|
|
1131
|
-
executionId,
|
|
1132
|
-
modelId: selectedModel.id,
|
|
1133
|
-
signal: controller.signal,
|
|
1134
|
-
waitInterrupt,
|
|
1135
|
-
emit,
|
|
1136
|
-
skills: instructionContext?.skills ?? new Map(),
|
|
1137
|
-
invokeTool: (call, context, caller) => {
|
|
1138
|
-
const invoke = () => coreExtensions.withTools(roundBindings, sessionRuntime.scheduleTool, () => withToolPermissions(permissionPolicy, () => services.extensions.operations.enter({
|
|
1139
|
-
sessionId,
|
|
1140
|
-
sessionEpoch: coreExtensions.epoch,
|
|
1141
|
-
executionId,
|
|
1142
|
-
turnId,
|
|
1143
|
-
actor: caller === 'programmatic' ? 'code-mode' : 'model',
|
|
1144
|
-
entry: caller,
|
|
1145
|
-
...(context.parentCallId === undefined
|
|
1146
|
-
? {}
|
|
1147
|
-
: { parentToolCallId: context.parentCallId }),
|
|
1148
|
-
signal: context.signal
|
|
1149
|
-
}, (operation) => coreExtensions.invoke(call, operation, roundBindings))));
|
|
1150
|
-
return sources.withFrame(context, () => parentFrame === undefined ? invoke() : parentFrame(invoke));
|
|
1151
|
-
}
|
|
1152
|
-
};
|
|
1153
|
-
const recentImages = async () => {
|
|
1154
|
-
const inputImages = await Promise.all((modelInputImages ?? []).map(async (image) => {
|
|
1155
|
-
if (image.dataBase64 !== undefined || image.resourceId === undefined)
|
|
1156
|
-
return image;
|
|
1157
|
-
const cached = inputImageBytes.get(image.resourceId);
|
|
1158
|
-
if (cached !== undefined)
|
|
1159
|
-
return cached;
|
|
1160
|
-
const source = await store.readResource(sessionId, image.resourceId);
|
|
1161
|
-
const restored = { ...image, ...source };
|
|
1162
|
-
inputImageBytes.set(image.resourceId, restored);
|
|
1163
|
-
return restored;
|
|
1164
|
-
}));
|
|
1165
|
-
return currentExecutionImages(inputImages, currentExecutionToolImages);
|
|
1166
|
-
};
|
|
1167
|
-
const toolScope = {
|
|
1168
|
-
context: toolContext,
|
|
1169
|
-
tools: roundTools,
|
|
1170
|
-
expectations: roundMcpExpectations,
|
|
1171
|
-
extensionToolNames: new Set([...roundBindings.values()]
|
|
1172
|
-
.filter((binding) => binding.source.kind === 'host' || binding.source.kind === 'extension')
|
|
1173
|
-
.map((binding) => binding.definition.name)),
|
|
1174
|
-
schedule: sessionRuntime.scheduleTool,
|
|
1175
|
-
assertLive: () => coreExtensions.assertLive(),
|
|
1176
|
-
assertExecutionLive: () => sources.assertActive(),
|
|
1177
|
-
emit: (event, assertLive) => emit(event, () => {
|
|
1178
|
-
coreExtensions.assertLive();
|
|
1179
|
-
assertLive?.();
|
|
1180
|
-
}),
|
|
1181
|
-
searchMcpTools: (arguments_, searchSignal) => mcpRegistry.expose(arguments_, {
|
|
1182
|
-
signal: searchSignal,
|
|
1183
|
-
base: projectTools(baseTools()),
|
|
1184
|
-
window: selectedModel.contextWindowTokens,
|
|
1185
|
-
system: systemPrompt
|
|
1186
|
-
}),
|
|
1187
|
-
recentImages,
|
|
1188
|
-
captureCodeContext: () => ({
|
|
1189
|
-
...toolContext,
|
|
1190
|
-
waitInterrupt: undefined
|
|
1191
|
-
}),
|
|
1192
|
-
codeModeContext: async (call) => {
|
|
1193
|
-
const stateSnapshot = call.name === 'code_exec' ? await store.readCodeModeState(sessionId) : [];
|
|
1194
|
-
return {
|
|
1195
|
-
retainSession: async () => {
|
|
1196
|
-
coreExtensions.assertLive();
|
|
1197
|
-
const release = await store.retainSessionLease(sessionId, sessionWriterOwner);
|
|
1198
|
-
let unpin;
|
|
1199
|
-
try {
|
|
1200
|
-
unpin = coreExtensions.pin();
|
|
1201
|
-
}
|
|
1202
|
-
catch (error) {
|
|
1203
|
-
try {
|
|
1204
|
-
await release();
|
|
1205
|
-
}
|
|
1206
|
-
catch {
|
|
1207
|
-
coreExtensions.diagnose({
|
|
1208
|
-
code: 'MAR_AGENT_EXTENSION_CLEANUP_FAILED',
|
|
1209
|
-
sessionId
|
|
1210
|
-
});
|
|
1211
|
-
}
|
|
1212
|
-
throw error;
|
|
1213
|
-
}
|
|
1214
|
-
return async () => {
|
|
1215
|
-
try {
|
|
1216
|
-
await release();
|
|
1217
|
-
}
|
|
1218
|
-
finally {
|
|
1219
|
-
unpin();
|
|
1220
|
-
}
|
|
1221
|
-
};
|
|
1222
|
-
},
|
|
1223
|
-
onSettled: async (result) => {
|
|
1224
|
-
await store.append(sessionId, {
|
|
1225
|
-
type: 'code.cell.completed',
|
|
1226
|
-
payload: { ...result, callId: call.callId },
|
|
1227
|
-
executionId,
|
|
1228
|
-
turnId
|
|
1229
|
-
});
|
|
1230
|
-
},
|
|
1231
|
-
supportsImages: selectedModel.inputCapabilities.includes('IMAGE'),
|
|
1232
|
-
permissionStop: () => permissionPolicy.stop?.source.parentCallId === call.callId
|
|
1233
|
-
? permissionPolicy.stop
|
|
1234
|
-
: undefined,
|
|
1235
|
-
tools: roundTools.filter((tool) => allowsToolCaller(tool, 'programmatic')),
|
|
1236
|
-
state: stateSnapshot,
|
|
1237
|
-
commitState: (mutations) => store.commitCodeModeState(sessionId, mutations, {
|
|
1238
|
-
executionId,
|
|
1239
|
-
turnId,
|
|
1240
|
-
expectedState: stateSnapshot
|
|
1241
|
-
})
|
|
1242
|
-
};
|
|
1243
|
-
}
|
|
1244
|
-
};
|
|
1245
|
-
return {
|
|
1246
|
-
roundTools,
|
|
1247
|
-
roundBindings,
|
|
1248
|
-
toolScope,
|
|
1249
|
-
async composeSystemPrompt() {
|
|
1250
|
-
const composed = preparedCompactPrompt ??
|
|
1251
|
-
(await operation((call) => coreExtensions.composeModelSystem(defaultComposition, call)));
|
|
1252
|
-
preparedCompactPrompt = undefined;
|
|
1253
|
-
systemPrompt = composed.text;
|
|
1254
|
-
return composed;
|
|
1255
|
-
}
|
|
1256
|
-
};
|
|
1257
|
-
};
|
|
1258
|
-
let preparedCompactPrompt;
|
|
1259
|
-
sources.bind(captureRoundToolScope().toolScope);
|
|
1260
|
-
let preparingRequestMessages;
|
|
1261
|
-
let preparingRequestBaseLength = 0;
|
|
1262
|
-
let dispatchedInputCount = 0;
|
|
1263
|
-
const completedMediaRequests = new WeakSet();
|
|
1264
|
-
let dispatchedLocalCount = 0;
|
|
1265
|
-
executionContext.requestMessages = {
|
|
1266
|
-
read: () => preparingRequestMessages !== undefined
|
|
1267
|
-
? normalizeMessagesForModel([...preparingRequestMessages, ...messages.slice(preparingRequestBaseLength)], { supportsImages: selectedModel.inputCapabilities.includes('IMAGE') })
|
|
1268
|
-
: projectSessionRequestMessages(messages.map((message, index) => index === currentExecutionUserIndex && modelInputImages?.length
|
|
1269
|
-
? { ...message, images: modelInputImages }
|
|
1270
|
-
: message), mode === 'compact' ? [] : modelContext.worldState.entries, mode !== 'compact' && selectedModel.inputCapabilities.includes('IMAGE'), baseTools().some((tool) => tool.name === 'code_exec'), permissionPolicy.mode === 'auto')
|
|
1271
|
-
};
|
|
1272
|
-
if (mode !== 'compact') {
|
|
1273
|
-
if (pendingInputs.size)
|
|
1274
|
-
await appendMailboxMessages(true);
|
|
1275
|
-
let entered = false;
|
|
1276
|
-
const writeInput = async (content, call) => {
|
|
1277
|
-
call.signal.throwIfAborted();
|
|
1278
|
-
if ((content.images?.length || hasRestoredUserImages) &&
|
|
1279
|
-
!selectedModel.inputCapabilities.includes('IMAGE'))
|
|
1280
|
-
throw new MarAgentError('MAR_AGENT_INPUT_CAPABILITY_UNSUPPORTED', 'Selected model does not support image input.');
|
|
1281
|
-
if (entered) {
|
|
1282
|
-
await sessionRuntime.sessionBackend.enqueue({ kind: 'submit', input: { ...content, delivery: 'idle' } }, call, (request, effective, next) => next(request, effective));
|
|
1283
|
-
return {};
|
|
1284
|
-
}
|
|
1285
|
-
await modelContext.recordEnvironment();
|
|
1286
|
-
call.signal.throwIfAborted();
|
|
1287
|
-
await writeInputRecord(content, internal.inputSource === 'extension' ? 'extension.input' : 'turn.user', {
|
|
1288
|
-
...(internal.extensionSource ? { source: internal.extensionSource } : {}),
|
|
1289
|
-
...(internal.delivery ? { messageId: internal.delivery.messageId } : {}),
|
|
1290
|
-
...(internal.inputSource === undefined
|
|
1291
|
-
? {}
|
|
1292
|
-
: { inputSource: internal.inputSource }),
|
|
1293
|
-
...(input.clientMessageId ? { clientMessageId: input.clientMessageId } : {})
|
|
1294
|
-
}, call, (actual, recordId, metadata) => {
|
|
1295
|
-
entered = true;
|
|
1296
|
-
modelInputImages = actual.images?.map((image) => ({ ...image }));
|
|
1297
|
-
messages.push({
|
|
1298
|
-
role: 'user',
|
|
1299
|
-
content: actual.modelText ?? actual.text,
|
|
1300
|
-
metadata,
|
|
1301
|
-
...(modelInputImages?.length ? { images: modelInputImages } : {})
|
|
1302
|
-
});
|
|
1303
|
-
currentExecutionUserIndex = messages.length - 1;
|
|
1304
|
-
internal.inputCommitted?.(recordId);
|
|
1305
|
-
internal.delivery?.applied();
|
|
1306
|
-
});
|
|
1307
|
-
return {};
|
|
1308
|
-
};
|
|
1309
|
-
const content = {
|
|
1310
|
-
text: input.prompt,
|
|
1311
|
-
...(internal.modelText === undefined ? {} : { modelText: internal.modelText }),
|
|
1312
|
-
...(internal.inputContext === undefined ? {} : { context: internal.inputContext }),
|
|
1313
|
-
...(internal.modelContext === undefined
|
|
1314
|
-
? {}
|
|
1315
|
-
: { modelContext: internal.modelContext }),
|
|
1316
|
-
...(input.images === undefined ? {} : { images: input.images })
|
|
1317
|
-
};
|
|
1318
|
-
await operation((call) => internal.promptAdmitted
|
|
1319
|
-
? writeInput(content, call)
|
|
1320
|
-
: invokeCorePromptSubmission(coreExtensions.hooks, content, call, writeInput));
|
|
1321
|
-
if (!entered) {
|
|
1322
|
-
await emit({ type: 'execution.completed' });
|
|
1323
|
-
return { executionId, status: 'completed', finalAnswer: '', inputHandled: true };
|
|
1324
|
-
}
|
|
1325
|
-
acceptsSteer = true;
|
|
1326
|
-
executionContext.steer = createNativeSteer({
|
|
1327
|
-
executionId,
|
|
1328
|
-
inputs,
|
|
1329
|
-
signal: controller.signal,
|
|
1330
|
-
isOpen: () => acceptsSteer,
|
|
1331
|
-
operation,
|
|
1332
|
-
admit: (content, call, write) => invokeCorePromptSubmission(coreExtensions.hooks, content, call, write),
|
|
1333
|
-
receive: (content, clientMessageId, call) => withRecordProjection(async () => {
|
|
1334
|
-
call.signal.throwIfAborted();
|
|
1335
|
-
if (content.images?.length && !selectedModel.inputCapabilities.includes('IMAGE'))
|
|
1336
|
-
throw new MarAgentError('MAR_AGENT_INPUT_CAPABILITY_UNSUPPORTED', 'Selected model does not support image input.');
|
|
1337
|
-
const modelImages = await publishModelResources(host, content.images, {
|
|
1338
|
-
sessionId,
|
|
1339
|
-
executionId
|
|
1340
|
-
}, store);
|
|
1341
|
-
const images = modelImages?.length
|
|
1342
|
-
? await store.persistInputImages(sessionId, modelImages)
|
|
1343
|
-
: [];
|
|
1344
|
-
const record = await store.append(sessionId, {
|
|
1345
|
-
type: 'turn.user',
|
|
1346
|
-
payload: {
|
|
1347
|
-
deferred: true,
|
|
1348
|
-
prompt: content.text,
|
|
1349
|
-
...(content.modelText === undefined
|
|
1350
|
-
? {}
|
|
1351
|
-
: { modelText: content.modelText }),
|
|
1352
|
-
...(content.context === undefined ? {} : { context: content.context }),
|
|
1353
|
-
...(content.modelContext === undefined
|
|
1354
|
-
? {}
|
|
1355
|
-
: { modelContext: content.modelContext }),
|
|
1356
|
-
clientMessageId,
|
|
1357
|
-
...(images.length ? { images } : {})
|
|
1358
|
-
},
|
|
1359
|
-
executionId,
|
|
1360
|
-
turnId
|
|
1361
|
-
}, { signal: call.signal });
|
|
1362
|
-
pendingInputs.set(record.recordId, record);
|
|
1363
|
-
return record;
|
|
1364
|
-
}),
|
|
1365
|
-
notify: (entry) => emit({ type: 'input.received', entry }),
|
|
1366
|
-
wake: () => waitInterrupt.notify(),
|
|
1367
|
-
diagnose: () => coreExtensions.diagnose({ code: 'MAR_AGENT_STEER_POST_COMMIT_FAILED', sessionId })
|
|
1368
|
-
});
|
|
1369
|
-
}
|
|
1370
|
-
const modelConfiguration = prepareModelConfiguration(selectedModel, reasoningEffort, {
|
|
1371
|
-
baselineEffort: reasoningEffortBaseline(contextRecords, selectedModel.id),
|
|
1372
|
-
messages
|
|
1373
|
-
});
|
|
1374
|
-
let requestReasoningEffort = modelConfiguration.requestReasoningEffort;
|
|
1375
|
-
if (mode !== 'compact')
|
|
1376
|
-
for (const update of modelConfiguration.updates) {
|
|
1377
|
-
messages.push(update);
|
|
1378
|
-
await store.append(sessionId, {
|
|
1379
|
-
type: 'model.context',
|
|
1380
|
-
payload: update,
|
|
1381
|
-
executionId,
|
|
1382
|
-
turnId
|
|
1383
|
-
});
|
|
1384
|
-
}
|
|
1385
|
-
const runPreparedExecution = async (compactFocus = input.prompt, compactSignal = controller.signal) => {
|
|
1386
|
-
const initialSystemPrompt = mode === 'compact'
|
|
1387
|
-
? buildExecutionSystemPrompt(executionTools, 'run')
|
|
1388
|
-
: buildExecutionSystemPrompt();
|
|
1389
|
-
const generateCompactExtension = async (history, reason, focus, compaction) => {
|
|
1390
|
-
if (!coreExtensions.hooks.hasInterceptors('compact.generate'))
|
|
1391
|
-
return undefined;
|
|
1392
|
-
const summaryTokenBudget = Math.min(10_000, selectedModel.maxOutputTokens, Math.max(1, Math.floor(selectedModel.contextWindowTokens / 4)));
|
|
1393
|
-
let diagnosticReports = 0;
|
|
1394
|
-
let acceptsDiagnostics = true;
|
|
1395
|
-
try {
|
|
1396
|
-
const result = await compaction.generate((signal) => operation((call) => coreExtensions.hooks.invoke('compact.generate', Object.freeze({
|
|
1397
|
-
operationId: call.operationId,
|
|
1398
|
-
reason,
|
|
1399
|
-
messages: compactExtensionMessages(history),
|
|
1400
|
-
...(focus === undefined ? {} : { focus }),
|
|
1401
|
-
summaryTokenBudget,
|
|
1402
|
-
getPrompt: () => buildCompactionMessages('')[1].content,
|
|
1403
|
-
reportModelUsage: host.modelUsage === undefined
|
|
1404
|
-
? undefined
|
|
1405
|
-
: (usage) => host.modelUsage({
|
|
1406
|
-
...usage,
|
|
1407
|
-
sessionId,
|
|
1408
|
-
executionId,
|
|
1409
|
-
purpose: 'compact',
|
|
1410
|
-
agentRole: sessionSource.type === 'subagent' ? 'subagent' : 'root'
|
|
1411
|
-
}),
|
|
1412
|
-
reportDiagnostic: async (value) => {
|
|
1413
|
-
if (!acceptsDiagnostics || ++diagnosticReports > 8)
|
|
1414
|
-
return;
|
|
1415
|
-
try {
|
|
1416
|
-
const diagnostic = compactExtensionDiagnostic(value);
|
|
1417
|
-
if (diagnostic)
|
|
1418
|
-
await compaction.observeExtension(diagnostic);
|
|
1419
|
-
}
|
|
1420
|
-
catch {
|
|
1421
|
-
// Diagnostic failures must not change compaction or fallback.
|
|
1422
|
-
}
|
|
1423
|
-
}
|
|
1424
|
-
}), Object.freeze({ ...call, signal }), async () => undefined)));
|
|
1425
|
-
compaction.signal.throwIfAborted();
|
|
1426
|
-
const handled = compactExtensionResult(result, summaryTokenBudget);
|
|
1427
|
-
await compaction.finishExtension(handled ? 'HANDLED' : result === undefined ? 'DECLINED' : 'INVALID_RESULT');
|
|
1428
|
-
return handled;
|
|
1429
|
-
}
|
|
1430
|
-
catch {
|
|
1431
|
-
await compaction.finishExtension('FAILED');
|
|
1432
|
-
compaction.signal.throwIfAborted();
|
|
1433
|
-
return undefined;
|
|
1434
|
-
}
|
|
1435
|
-
finally {
|
|
1436
|
-
acceptsDiagnostics = false;
|
|
1437
|
-
}
|
|
1438
|
-
};
|
|
1439
|
-
await store.append(sessionId, {
|
|
1440
|
-
type: 'execution.header',
|
|
1441
|
-
payload: {
|
|
1442
|
-
promptVersion: MAR_AGENT_PROMPT_VERSION,
|
|
1443
|
-
promptHash: createHash('sha256').update(initialSystemPrompt).digest('hex'),
|
|
1444
|
-
modelId: selectedModel.id,
|
|
1445
|
-
modelName: selectedModel.name,
|
|
1446
|
-
reasoningEffort,
|
|
1447
|
-
contextWindowTokens: selectedModel.contextWindowTokens,
|
|
1448
|
-
mode
|
|
1449
|
-
},
|
|
1450
|
-
executionId,
|
|
1451
|
-
turnId
|
|
1452
|
-
});
|
|
1453
|
-
let lastServerContextTokens = lastServerUsage?.contextInputTokens;
|
|
1454
|
-
let compactBoundary = restoredMessageCount;
|
|
1455
|
-
const advanceCompactBoundary = () => {
|
|
1456
|
-
// Keep a new image with its complete tool round until a model accepts it.
|
|
1457
|
-
if (!resourceInput.hasPendingImages(messages.slice(compactBoundary)))
|
|
1458
|
-
compactBoundary = messages.length;
|
|
1459
|
-
};
|
|
1460
|
-
const invalidateCompactUsage = () => {
|
|
1461
|
-
lastServerContextTokens = undefined;
|
|
1462
|
-
lastServerUsage = undefined;
|
|
1463
|
-
smartContextTokens = undefined;
|
|
1464
|
-
requestReasoningEffort = prepareModelConfiguration(selectedModel, reasoningEffort, {
|
|
1465
|
-
checkpointAdopted: true
|
|
1466
|
-
}).requestReasoningEffort;
|
|
1467
|
-
};
|
|
1468
|
-
const compactLeaf = async (input, signal, prepare, compactionId) => {
|
|
1469
|
-
if (messages.length < 2)
|
|
1470
|
-
return false;
|
|
1471
|
-
const cutoff = Math.min(compactBoundary, messages.length);
|
|
1472
|
-
const current = messages[cutoff - 1];
|
|
1473
|
-
const retainCurrent = mode !== 'compact' && current.role === 'user' && current.contextKind === undefined;
|
|
1474
|
-
const prefix = messages.slice(0, cutoff - (retainCurrent ? 1 : 0));
|
|
1475
|
-
if (!prefix.some((message) => message.role !== 'user' ||
|
|
1476
|
-
message.contextKind === undefined ||
|
|
1477
|
-
message.contextKind === 'summary'))
|
|
1478
|
-
return false;
|
|
1479
|
-
const compactHistory = structuredClone(prefix).map(({ images: _images, ...message }) => message);
|
|
1480
|
-
const prefixInputs = modelContext.compactInputs(prefix);
|
|
1481
|
-
const snapshotTools = structuredClone(projectTools(executionTools));
|
|
1482
|
-
const generation = modelContext.worldState.generation;
|
|
1483
|
-
const snapshotUsage = lastServerUsage;
|
|
1484
|
-
const snapshotEffort = requestReasoningEffort ?? reasoningEffort;
|
|
1485
|
-
const anchorRecordId = prefix
|
|
1486
|
-
.map((message) => messageSources.get(message)?.recordId ?? message.metadata?.recordId)
|
|
1487
|
-
.findLast((id) => id !== undefined);
|
|
1488
|
-
const visibleAnchor = compactSnapshotAnchor(prefix, messageSources);
|
|
1489
|
-
const anchor = {
|
|
1490
|
-
...(anchorRecordId ? { anchorRecordId } : {}),
|
|
1491
|
-
...(visibleAnchor ? { anchor: visibleAnchor } : {})
|
|
1492
|
-
};
|
|
1493
|
-
const compactComposition = splitContextualPrompt(await operation((call) => coreExtensions.composeModelSystem(promptComposition(snapshotTools, 'run'), call)));
|
|
1494
|
-
await emit({
|
|
1495
|
-
type: 'context.compacting',
|
|
1496
|
-
compactionId,
|
|
1497
|
-
async: input.async === true,
|
|
1498
|
-
stage: 'GENERATING',
|
|
1499
|
-
...anchor
|
|
1500
|
-
});
|
|
1501
|
-
let latestUsage;
|
|
1502
|
-
let compactSummary;
|
|
1503
|
-
const compaction = createCompactionOperation(compactionId, signal);
|
|
1504
|
-
const compactTurn = createModelTurnSession(selectedAdapter);
|
|
1505
|
-
try {
|
|
1506
|
-
const candidate = await generateCompactionCandidate({
|
|
1507
|
-
history: compactHistory,
|
|
1508
|
-
system: compactComposition.system,
|
|
1509
|
-
...(compactComposition.systemBlocks === undefined
|
|
1510
|
-
? {}
|
|
1511
|
-
: { systemBlocks: compactComposition.systemBlocks }),
|
|
1512
|
-
tools: snapshotTools,
|
|
1513
|
-
contextWindowTokens: selectedModel.contextWindowTokens,
|
|
1514
|
-
latestUsage: snapshotUsage,
|
|
1515
|
-
reasoningEffort: snapshotEffort,
|
|
1516
|
-
...(input.focus === undefined ? {} : { focus: input.focus }),
|
|
1517
|
-
reason: mode === 'compact' ? 'manual' : 'automatic',
|
|
1518
|
-
promptCacheKey: sessionId
|
|
1519
|
-
}, {
|
|
1520
|
-
operation: compaction,
|
|
1521
|
-
turn: compactTurn,
|
|
1522
|
-
generateExtension: generateCompactExtension,
|
|
1523
|
-
transformRequest: (request) => transformModelRequest(request, undefined, selectedModel.id, 'compact'),
|
|
1524
|
-
stream: streamModel,
|
|
1525
|
-
observeUsage: (usage) => emit({
|
|
1526
|
-
type: 'usage.updated',
|
|
1527
|
-
purpose: 'compact',
|
|
1528
|
-
...publicModelUsage(usage)
|
|
1529
|
-
}),
|
|
1530
|
-
onAttemptDiagnostic: recordModelAttempt('COMPACTION')
|
|
1531
|
-
});
|
|
1532
|
-
compactSummary = candidate.summary;
|
|
1533
|
-
latestUsage = candidate.usage;
|
|
1534
|
-
}
|
|
1535
|
-
finally {
|
|
1536
|
-
await compaction.dispose();
|
|
1537
|
-
await compactTurn.close();
|
|
1538
|
-
}
|
|
1539
|
-
await emit({
|
|
1540
|
-
type: 'context.compacting',
|
|
1541
|
-
compactionId,
|
|
1542
|
-
async: !compactCoordinator.waiting && input.async === true,
|
|
1543
|
-
stage: compactCoordinator.waiting ? 'WAITING' : 'READY',
|
|
1544
|
-
...anchor
|
|
1545
|
-
});
|
|
1546
|
-
await prepare();
|
|
1547
|
-
signal.throwIfAborted();
|
|
1548
|
-
const compactResources = retainedSessionResourcesSnapshot(await loadRetainedSessionResources());
|
|
1549
|
-
const replacementHistory = buildCompactedHistory(compactSummary, prefixInputs, compactUserTokenLimit);
|
|
1550
|
-
let retainedModelContext = [];
|
|
1551
|
-
const compactRecord = await writeCompactionRecord(compactSummary, true, signal, async (actual, options) => {
|
|
1552
|
-
if (modelContext.worldState.generation !== generation ||
|
|
1553
|
-
prefix.some((message, index) => messages[index] !== message))
|
|
1554
|
-
throw new MarAgentError('MAR_AGENT_COMPACT_STALE', 'The compaction prefix has changed.');
|
|
1555
|
-
retainedModelContext = messages
|
|
1556
|
-
.slice(prefix.length)
|
|
1557
|
-
.filter((message) => message.contextKind !== 'private' || message.role === 'provider');
|
|
1558
|
-
const record = await store.compact(sessionId, {
|
|
1559
|
-
summary: actual,
|
|
1560
|
-
replacementHistory,
|
|
1561
|
-
inlineMediaState: resourceInput.checkpoint(retainedModelContext),
|
|
1562
|
-
retainedModelContext: retainedModelContext.map((message) => {
|
|
1563
|
-
const source = messageSources.get(message);
|
|
1564
|
-
const saved = source?.type === 'model.context' &&
|
|
1565
|
-
source.payload.inputRef
|
|
1566
|
-
? source.payload
|
|
1567
|
-
: source?.type === 'compact.completed'
|
|
1568
|
-
? (source.payload.retainedModelContext ?? []).find((item) => item.inputRef === message.metadata?.recordId)
|
|
1569
|
-
: undefined;
|
|
1570
|
-
return saved
|
|
1571
|
-
? {
|
|
1572
|
-
...saved,
|
|
1573
|
-
...(message.metadata ? { metadata: message.metadata } : {})
|
|
1574
|
-
}
|
|
1575
|
-
: {
|
|
1576
|
-
...message,
|
|
1577
|
-
...(message.images?.length
|
|
1578
|
-
? {
|
|
1579
|
-
images: message.images.map(({ dataBase64: _bytes, ...image }) => image)
|
|
1580
|
-
}
|
|
1581
|
-
: {})
|
|
1582
|
-
};
|
|
1583
|
-
}),
|
|
1584
|
-
pendingInputs: [...pendingInputs.values()],
|
|
1585
|
-
snapshotMessageCount: prefix.length,
|
|
1586
|
-
...(anchorRecordId ? { snapshotRecordId: anchorRecordId } : {}),
|
|
1587
|
-
automatic: mode !== 'compact',
|
|
1588
|
-
environment: executionEnvironment,
|
|
1589
|
-
modelId: selectedModel.id,
|
|
1590
|
-
contextWindowTokens: selectedModel.contextWindowTokens,
|
|
1591
|
-
...(latestUsage === undefined ? {} : { usage: latestUsage }),
|
|
1592
|
-
executionId,
|
|
1593
|
-
turnId
|
|
1594
|
-
}, options);
|
|
1595
|
-
modelContext.replaceCompactMessages(replacementHistory, retainedModelContext);
|
|
1596
|
-
compactBoundary = messages.length - retainedModelContext.length;
|
|
1597
|
-
return record;
|
|
1598
|
-
});
|
|
1599
|
-
await modelContext.adoptCompactCheckpoint(compactRecord.recordId, replacementHistory, retainedModelContext, compactResources);
|
|
1600
|
-
invalidateCompactUsage();
|
|
1601
|
-
await emit({
|
|
1602
|
-
type: 'context.compacted',
|
|
1603
|
-
compactionId,
|
|
1604
|
-
async: input.async === true,
|
|
1605
|
-
retainedContext: retainedModelContext.length > 0,
|
|
1606
|
-
...anchor
|
|
1607
|
-
});
|
|
1608
|
-
return true;
|
|
1609
|
-
};
|
|
1610
|
-
startCompact = (input = {}) => {
|
|
1611
|
-
const id = manualCompactionId ?? randomUUID();
|
|
1612
|
-
const flight = compactCoordinator.start(id, input.focus, async (prepare, signal) => {
|
|
1613
|
-
const linked = AbortSignal.any([signal, controller.signal, compactSignal]);
|
|
1614
|
-
try {
|
|
1615
|
-
if (mode === 'compact' && inputs.currentCompact())
|
|
1616
|
-
return await compactLeaf(input, linked, prepare, id);
|
|
1617
|
-
return (await performCompact(input, async (effective, call) => ({
|
|
1618
|
-
changed: await compactLeaf({ ...effective, async: input.async === true }, AbortSignal.any([linked, call.signal]), prepare, id),
|
|
1619
|
-
executionId
|
|
1620
|
-
}))).changed;
|
|
1621
|
-
}
|
|
1622
|
-
catch (error) {
|
|
1623
|
-
const diagnostic = describeMarAgentError(error, 'MAR_AGENT_COMPACT_FAILED');
|
|
1624
|
-
await emit({
|
|
1625
|
-
type: 'context.compact_failed',
|
|
1626
|
-
compactionId: id,
|
|
1627
|
-
code: diagnostic.code,
|
|
1628
|
-
async: input.async === true,
|
|
1629
|
-
cancelled: linked.aborted
|
|
1630
|
-
});
|
|
1631
|
-
throw error;
|
|
1632
|
-
}
|
|
1633
|
-
});
|
|
1634
|
-
if (smartInput)
|
|
1635
|
-
smartInput.requested = true;
|
|
1636
|
-
return flight;
|
|
1637
|
-
};
|
|
1638
|
-
compactContext = async (input = {}) => {
|
|
1639
|
-
const flight = startCompact(input);
|
|
1640
|
-
if (input.async)
|
|
1641
|
-
return false;
|
|
1642
|
-
await emit({
|
|
1643
|
-
type: 'context.compacting',
|
|
1644
|
-
compactionId: flight.id,
|
|
1645
|
-
stage: 'WAITING',
|
|
1646
|
-
async: false
|
|
1647
|
-
});
|
|
1648
|
-
return (await compactCoordinator.checkpoint(true)) ?? false;
|
|
1649
|
-
};
|
|
1650
|
-
compactRequests.bind((input) => compactCoordinator.pending
|
|
1651
|
-
? startCompact({
|
|
1652
|
-
...(input.prompt === undefined ? {} : { focus: input.prompt }),
|
|
1653
|
-
async: input.async === true
|
|
1654
|
-
})
|
|
1655
|
-
: undefined);
|
|
1656
|
-
if (mode === 'compact') {
|
|
1657
|
-
startCompact({ focus: compactFocus });
|
|
1658
|
-
compactRequests.drain((input) => startCompact({
|
|
1659
|
-
...(input.prompt === undefined ? {} : { focus: input.prompt }),
|
|
1660
|
-
async: input.async === true
|
|
1661
|
-
}));
|
|
1662
|
-
await compactCoordinator.checkpoint(true);
|
|
1663
|
-
compactRequests.seal();
|
|
1664
|
-
compactRequests.drain((input) => startCompact({
|
|
1665
|
-
...(input.prompt === undefined ? {} : { focus: input.prompt }),
|
|
1666
|
-
async: input.async === true
|
|
1667
|
-
}));
|
|
1668
|
-
await compactCoordinator.checkpoint(true);
|
|
1669
|
-
return;
|
|
1670
|
-
}
|
|
1671
|
-
const ensureContextBudget = async () => {
|
|
1672
|
-
const percent = lastServerContextTokens === undefined
|
|
1673
|
-
? undefined
|
|
1674
|
-
: (lastServerContextTokens * 100) / selectedModel.contextWindowTokens;
|
|
1675
|
-
if (percent !== undefined &&
|
|
1676
|
-
percent >= AGENT_EXECUTION_POLICY.automaticCompactionPercent) {
|
|
1677
|
-
const hadPending = compactCoordinator.pending;
|
|
1678
|
-
let compacted;
|
|
1679
|
-
try {
|
|
1680
|
-
compacted = await compactContext();
|
|
1681
|
-
}
|
|
1682
|
-
catch (error) {
|
|
1683
|
-
controller.signal.throwIfAborted();
|
|
1684
|
-
if (!hadPending)
|
|
1685
|
-
throw error;
|
|
1686
|
-
advanceCompactBoundary();
|
|
1687
|
-
compacted = await compactContext();
|
|
1688
|
-
}
|
|
1689
|
-
if (!compacted)
|
|
1690
|
-
throw new MarAgentError('MAR_AGENT_CONTEXT_LIMIT', 'Provider usage reached the compaction threshold but no history can be compacted.');
|
|
1691
|
-
}
|
|
1692
|
-
else {
|
|
1693
|
-
const adopted = await compactCoordinator.checkpoint(false).catch(() => {
|
|
1694
|
-
controller.signal.throwIfAborted();
|
|
1695
|
-
});
|
|
1696
|
-
if (!adopted &&
|
|
1697
|
-
percent !== undefined &&
|
|
1698
|
-
percent >= AGENT_EXECUTION_POLICY.backgroundCompactionPercent &&
|
|
1699
|
-
!compactCoordinator.pending)
|
|
1700
|
-
startCompact({ async: true });
|
|
1701
|
-
}
|
|
1702
|
-
};
|
|
1703
|
-
executionLoop = new ExecutionLoop({
|
|
1704
|
-
mode,
|
|
1705
|
-
sourceType: sessionSource.type,
|
|
1706
|
-
permissionStop: () => permissionPolicy.stop,
|
|
1707
|
-
signal: controller.signal,
|
|
1708
|
-
model: selectedModel,
|
|
1709
|
-
messages,
|
|
1710
|
-
toolImages: currentExecutionToolImages,
|
|
1711
|
-
publish: emit,
|
|
1712
|
-
appendContext: (message) => withRecordProjection(async () => {
|
|
1713
|
-
const stored = await store.append(sessionId, {
|
|
1714
|
-
type: 'model.context',
|
|
1715
|
-
payload: message,
|
|
1716
|
-
executionId,
|
|
1717
|
-
turnId
|
|
1718
|
-
});
|
|
1719
|
-
messageSources.set(message, stored);
|
|
1720
|
-
}),
|
|
1721
|
-
prepareRound: async function prepareRound(pendingOutputContinuation, subagentUpdatesCollected = false) {
|
|
1722
|
-
await appendMailboxMessages();
|
|
1723
|
-
if (!subagentUpdatesCollected && subagents)
|
|
1724
|
-
await withRecordProjection(async () => {
|
|
1725
|
-
controller.signal.throwIfAborted();
|
|
1726
|
-
for (const update of subagents.collectModelUpdates()) {
|
|
1727
|
-
controller.signal.throwIfAborted();
|
|
1728
|
-
const message = {
|
|
1729
|
-
role: 'user',
|
|
1730
|
-
content: renderSubagentUpdate(update.snapshot, update.truncated),
|
|
1731
|
-
contextKind: 'contextual'
|
|
1732
|
-
};
|
|
1733
|
-
const stored = await store.append(sessionId, {
|
|
1734
|
-
type: 'model.context',
|
|
1735
|
-
payload: message,
|
|
1736
|
-
executionId,
|
|
1737
|
-
turnId
|
|
1738
|
-
}, { signal: controller.signal });
|
|
1739
|
-
messages.push(message);
|
|
1740
|
-
messageSources.set(message, stored);
|
|
1741
|
-
update.acknowledge();
|
|
1742
|
-
}
|
|
1743
|
-
});
|
|
1744
|
-
updateMcpRegistry();
|
|
1745
|
-
executionTools = mcpRegistry.project(baseTools());
|
|
1746
|
-
await modelContext.syncMcpWorldState(messages.length);
|
|
1747
|
-
advanceCompactBoundary();
|
|
1748
|
-
const blocking = compactRequests.drain((input) => startCompact({
|
|
1749
|
-
...(input.prompt === undefined ? {} : { focus: input.prompt }),
|
|
1750
|
-
async: input.async === true
|
|
1751
|
-
}));
|
|
1752
|
-
if (blocking)
|
|
1753
|
-
await compactCoordinator.checkpoint(true);
|
|
1754
|
-
await ensureContextBudget();
|
|
1755
|
-
await modelContext.syncMcpWorldState(messages.length);
|
|
1756
|
-
executionEnvironment = { ...currentEnvironment, ...currentLocalTimeContext() };
|
|
1757
|
-
await modelContext.recordEnvironment();
|
|
1758
|
-
const { roundTools, roundBindings, toolScope, composeSystemPrompt } = captureRoundToolScope();
|
|
1759
|
-
const residentTools = projectTools(mcpRegistry.projectDirect(baseTools()));
|
|
1760
|
-
const requestContextMessages = pendingOutputContinuation === undefined
|
|
1761
|
-
? messages
|
|
1762
|
-
: [...messages, pendingOutputContinuation];
|
|
1763
|
-
sources.bind(toolScope);
|
|
1764
|
-
const composedSystem = splitContextualPrompt(await composeSystemPrompt());
|
|
1765
|
-
const candidateWorld = updatePromptWorldState(modelContext.worldState, messages.length, composedSystem.parts);
|
|
1766
|
-
const candidateRequest = prepareSessionModelRequest({
|
|
1767
|
-
system: composedSystem.system,
|
|
1768
|
-
...(composedSystem.systemBlocks
|
|
1769
|
-
? { systemBlocks: composedSystem.systemBlocks }
|
|
1770
|
-
: {}),
|
|
1771
|
-
messages: requestContextMessages,
|
|
1772
|
-
tools: roundTools,
|
|
1773
|
-
promptCacheKey: sessionId,
|
|
1774
|
-
reasoningEffort,
|
|
1775
|
-
...(requestReasoningEffort === undefined ? {} : { requestReasoningEffort }),
|
|
1776
|
-
...(modelInputImages?.length ? { images: modelInputImages } : {}),
|
|
1777
|
-
onAttemptDiagnostic: recordModelAttempt('EXECUTION')
|
|
1778
|
-
}, selectedModel, candidateWorld.entries, residentTools, permissionPolicy.mode === 'auto');
|
|
1779
|
-
preparingRequestMessages = candidateRequest.messages;
|
|
1780
|
-
preparingRequestBaseLength = messages.length;
|
|
1781
|
-
let request;
|
|
1782
|
-
try {
|
|
1783
|
-
request = await transformModelRequest(candidateRequest, roundBindings);
|
|
1784
|
-
}
|
|
1785
|
-
finally {
|
|
1786
|
-
preparingRequestMessages = undefined;
|
|
1787
|
-
}
|
|
1788
|
-
controller.signal.throwIfAborted();
|
|
1789
|
-
if (candidateWorld !== modelContext.worldState) {
|
|
1790
|
-
// Commit only after request middleware accepts the entire candidate.
|
|
1791
|
-
await modelContext.commitWorldState(candidateWorld);
|
|
1792
|
-
}
|
|
1793
|
-
const lateCoreChange = inputs.hasBoundaryCompactPending && (await appendMailboxMessages());
|
|
1794
|
-
const lateBlocking = compactRequests.drain((input) => startCompact({
|
|
1795
|
-
...(input.prompt === undefined ? {} : { focus: input.prompt }),
|
|
1796
|
-
async: input.async === true
|
|
1797
|
-
}));
|
|
1798
|
-
const lateAdopted = lateBlocking && (await compactCoordinator.checkpoint(true));
|
|
1799
|
-
if (lateCoreChange || lateAdopted) {
|
|
1800
|
-
// Middleware may admit a blocking join after the initial checkpoint.
|
|
1801
|
-
// Never sample the candidate assembled against the replaced context.
|
|
1802
|
-
return prepareRound(pendingOutputContinuation, true);
|
|
1803
|
-
}
|
|
1804
|
-
resourceInput.observe(candidateRequest.messages);
|
|
1805
|
-
const media = sessionSource.type === 'subagent'
|
|
1806
|
-
? undefined
|
|
1807
|
-
: await resourceInput.gcCandidate(request, candidateRequest.images);
|
|
1808
|
-
if (media?.reason === 'HARD_LIMIT') {
|
|
1809
|
-
const appendBoundary = pendingAppends.length;
|
|
1810
|
-
const committed = await contextGc.run({
|
|
1811
|
-
inlineMedia: media,
|
|
1812
|
-
mediaView: (messages) => resourceInput.historyView(messages),
|
|
1813
|
-
store,
|
|
1814
|
-
sessionId,
|
|
1815
|
-
system: request.system,
|
|
1816
|
-
tools: toolScope.tools,
|
|
1817
|
-
modelId: selectedModel.id,
|
|
1818
|
-
contextWindowTokens: selectedModel.contextWindowTokens,
|
|
1819
|
-
usage: lastServerUsage ?? {},
|
|
1820
|
-
...modelConfiguration.contextProjection,
|
|
1821
|
-
workspace: logicalWorkspace,
|
|
1822
|
-
platform: description.platform
|
|
1823
|
-
});
|
|
1824
|
-
if (committed) {
|
|
1825
|
-
await modelContext.adoptGcCheckpoint(committed, appendBoundary);
|
|
1826
|
-
return prepareRound(pendingOutputContinuation, true);
|
|
1827
|
-
}
|
|
1828
|
-
}
|
|
1829
|
-
return {
|
|
1830
|
-
request: await resourceInput.prepare(request, candidateRequest.images, candidateRequest.messages),
|
|
1831
|
-
toolScope
|
|
1832
|
-
};
|
|
1833
|
-
},
|
|
1834
|
-
startModel: async function* (request) {
|
|
1835
|
-
const snapshots = (sessionRuntime.requestSnapshots ??=
|
|
1836
|
-
new ExtensionRequestSnapshots());
|
|
1837
|
-
const snapshot = snapshots.record(selectedModel.id, request);
|
|
1838
|
-
dispatchedInputCount = request.messages.length;
|
|
1839
|
-
dispatchedLocalCount = messages.length;
|
|
1840
|
-
yield* streamModel(async function* (nativeSignal) {
|
|
1841
|
-
for await (const event of selected.start(request, nativeSignal)) {
|
|
1842
|
-
if (event.type === 'completed' && event.reason !== 'cancelled') {
|
|
1843
|
-
completedMediaRequests.add(request.messages);
|
|
1844
|
-
if (snapshot)
|
|
1845
|
-
snapshots.complete(snapshot);
|
|
1846
|
-
}
|
|
1847
|
-
yield event;
|
|
1848
|
-
}
|
|
1849
|
-
}, controller.signal);
|
|
1850
|
-
},
|
|
1851
|
-
recoverySignal: () => controller.signal,
|
|
1852
|
-
compactContext,
|
|
1853
|
-
afterModel: async (closedPrefixLength, acceptedRequest) => {
|
|
1854
|
-
selected.commitContinuationInput?.(dispatchedInputCount + messages.length - dispatchedLocalCount);
|
|
1855
|
-
if (acceptedRequest && completedMediaRequests.has(acceptedRequest.messages)) {
|
|
1856
|
-
await resourceInput.complete(acceptedRequest);
|
|
1857
|
-
compactBoundary = closedPrefixLength;
|
|
1858
|
-
}
|
|
1859
|
-
if (lastServerContextTokens !== undefined &&
|
|
1860
|
-
(lastServerContextTokens * 100) / selectedModel.contextWindowTokens >=
|
|
1861
|
-
AGENT_EXECUTION_POLICY.backgroundCompactionPercent &&
|
|
1862
|
-
!compactCoordinator.pending)
|
|
1863
|
-
startCompact({ async: true });
|
|
1864
|
-
},
|
|
1865
|
-
observeContextTokens: (tokens) => {
|
|
1866
|
-
lastServerContextTokens = tokens;
|
|
1867
|
-
smartContextTokens = tokens;
|
|
1868
|
-
},
|
|
1869
|
-
observeUsage: (usage) => {
|
|
1870
|
-
if (usage !== undefined) {
|
|
1871
|
-
lastServerContextTokens = usage.contextInputTokens;
|
|
1872
|
-
smartContextTokens = usage.contextInputTokens;
|
|
1873
|
-
lastServerUsage = { ...usage, historyMessages: [...messages] };
|
|
1874
|
-
}
|
|
1875
|
-
},
|
|
1876
|
-
checkpoint: async (round, latestUsage) => {
|
|
1877
|
-
advanceCompactBoundary();
|
|
1878
|
-
const blocking = compactRequests.drain((input) => startCompact({
|
|
1879
|
-
...(input.prompt === undefined ? {} : { focus: input.prompt }),
|
|
1880
|
-
async: input.async === true
|
|
1881
|
-
}));
|
|
1882
|
-
if (blocking)
|
|
1883
|
-
await compactCoordinator.checkpoint(true);
|
|
1884
|
-
else
|
|
1885
|
-
await compactCoordinator.checkpoint(false).catch(() => {
|
|
1886
|
-
controller.signal.throwIfAborted();
|
|
1887
|
-
});
|
|
1888
|
-
if (!compactCoordinator.pending && sessionSource.type !== 'subagent') {
|
|
1889
|
-
// Only a committed GC checkpoint may replace active context and invalidate continuation.
|
|
1890
|
-
const appendBoundary = pendingAppends.length;
|
|
1891
|
-
const committed = await contextGc.run({
|
|
1892
|
-
inlineMedia: await resourceInput.gcCandidate(),
|
|
1893
|
-
mediaView: (messages) => resourceInput.historyView(messages),
|
|
1894
|
-
store,
|
|
1895
|
-
sessionId,
|
|
1896
|
-
system: round.request.system,
|
|
1897
|
-
tools: round.toolScope.tools,
|
|
1898
|
-
modelId: selectedModel.id,
|
|
1899
|
-
contextWindowTokens: selectedModel.contextWindowTokens,
|
|
1900
|
-
usage: latestUsage ?? {},
|
|
1901
|
-
...modelConfiguration.contextProjection,
|
|
1902
|
-
workspace: logicalWorkspace,
|
|
1903
|
-
platform: description.platform,
|
|
1904
|
-
getActiveProcessIds: async () => {
|
|
1905
|
-
const resources = await host
|
|
1906
|
-
.listSessionResources?.(sessionId)
|
|
1907
|
-
.catch(() => undefined);
|
|
1908
|
-
return new Set((resources?.processes ?? [])
|
|
1909
|
-
.filter((process) => process.status === 'running')
|
|
1910
|
-
.map((process) => process.processId));
|
|
1911
|
-
}
|
|
1912
|
-
});
|
|
1913
|
-
if (committed) {
|
|
1914
|
-
await modelContext.adoptGcCheckpoint(committed, appendBoundary);
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
},
|
|
1918
|
-
mailbox: {
|
|
1919
|
-
hasPending: () => inputs.hasBoundaryPending && !inputs.executing,
|
|
1920
|
-
append: appendMailboxMessages,
|
|
1921
|
-
close: () => {
|
|
1922
|
-
acceptsMailbox = false;
|
|
1923
|
-
acceptsSteer = false;
|
|
1924
|
-
}
|
|
1925
|
-
}
|
|
1926
|
-
});
|
|
1927
|
-
const completed = await executionLoop.run();
|
|
1928
|
-
compactRequests.seal();
|
|
1929
|
-
compactRequests.drain((input) => startCompact({
|
|
1930
|
-
...(input.prompt === undefined ? {} : { focus: input.prompt }),
|
|
1931
|
-
async: input.async === true
|
|
1932
|
-
}));
|
|
1933
|
-
await compactCoordinator.checkpoint(true).catch(() => {
|
|
1934
|
-
controller.signal.throwIfAborted();
|
|
1935
|
-
});
|
|
1936
|
-
finalAnswer = completed.finalAnswer;
|
|
1937
|
-
};
|
|
1938
|
-
if (mode === 'compact')
|
|
1939
|
-
await performCompact({ focus: input.prompt }, async (effective, call) => {
|
|
1940
|
-
await runPreparedExecution(effective.focus ?? DEFAULT_COMPACTION_FOCUS, call.signal);
|
|
1941
|
-
return { changed: true, executionId };
|
|
1942
|
-
});
|
|
1943
|
-
else
|
|
1944
|
-
await runPreparedExecution();
|
|
1945
|
-
subagents?.endParentExecution(executionId);
|
|
1946
|
-
await emit({
|
|
1947
|
-
type: 'execution.completed',
|
|
1948
|
-
...(permissionPolicy.stop ? { permissionStop: permissionPolicy.stop } : {})
|
|
1949
|
-
});
|
|
1950
|
-
return {
|
|
1951
|
-
executionId,
|
|
1952
|
-
status: 'completed',
|
|
1953
|
-
...(permissionPolicy.stop ? { permissionStop: permissionPolicy.stop } : {}),
|
|
1954
|
-
finalAnswer: mode === 'compact' || permissionPolicy.stop ? '' : finalAnswer
|
|
1955
|
-
};
|
|
1956
|
-
}
|
|
1957
|
-
catch (error) {
|
|
1958
|
-
failedExecution = true;
|
|
1959
|
-
finalAnswer = executionLoop?.finalAnswer ?? finalAnswer;
|
|
1960
|
-
acceptsMailbox = false;
|
|
1961
|
-
acceptsSteer = false;
|
|
1962
|
-
delete executionContext.steer;
|
|
1963
|
-
await sessionRuntime.recordProjection?.catch(() => undefined);
|
|
1964
|
-
await compactCoordinator.close(error);
|
|
1965
|
-
compactRequests.close(new MarAgentError('MAR_AGENT_CANCELLED', 'Execution ended.'));
|
|
1966
|
-
if (executionContext.compactRequests === compactRequests)
|
|
1967
|
-
delete executionContext.compactRequests;
|
|
1968
|
-
if (controller.signal.aborted) {
|
|
1969
|
-
subagents?.endParentExecution(executionId);
|
|
1970
|
-
// A faulted Store must not prevent result settlement or lease release.
|
|
1971
|
-
await emit({ type: 'execution.cancelled' }).catch(() => undefined);
|
|
1972
|
-
return {
|
|
1973
|
-
executionId,
|
|
1974
|
-
status: 'cancelled',
|
|
1975
|
-
finalAnswer: mode === 'compact' ? '' : finalAnswer
|
|
1976
|
-
};
|
|
1977
|
-
}
|
|
1978
|
-
const diagnostic = modelAttemptFailureDiagnostic(describeMarAgentError(error, 'MAR_AGENT_EXECUTION_FAILED'), exhaustedModelAttempt);
|
|
1979
|
-
subagents?.endParentExecution(executionId);
|
|
1980
|
-
// Keep the original diagnostic if persisting the failure terminal also fails.
|
|
1981
|
-
await emit({ type: 'execution.failed', ...diagnostic }).catch(() => undefined);
|
|
1982
|
-
return {
|
|
1983
|
-
executionId,
|
|
1984
|
-
status: 'failed',
|
|
1985
|
-
finalAnswer: mode === 'compact' ? '' : finalAnswer,
|
|
1986
|
-
errorCode: diagnostic.code,
|
|
1987
|
-
errorMessage: diagnostic.message
|
|
1988
|
-
};
|
|
1989
|
-
}
|
|
1990
|
-
finally {
|
|
1991
|
-
releaseImageBytes?.();
|
|
1992
|
-
// Revoke this Execution's request and input bindings, not Session warm resources.
|
|
1993
|
-
delete executionContext.requestMessages;
|
|
1994
|
-
compactRequests.close(new MarAgentError('MAR_AGENT_CANCELLED', 'Execution ended.'));
|
|
1995
|
-
if (executionContext.compactRequests === compactRequests)
|
|
1996
|
-
delete executionContext.compactRequests;
|
|
1997
|
-
delete executionContext.appendedMessages;
|
|
1998
|
-
delete executionContext.steer;
|
|
1999
|
-
acceptsMailbox = false;
|
|
2000
|
-
executionToolSources?.close();
|
|
2001
|
-
if (executionContext.toolSources === executionToolSources)
|
|
2002
|
-
delete executionContext.toolSources;
|
|
2003
|
-
internal.signal?.removeEventListener('abort', abortSource);
|
|
2004
|
-
// Compact retains its existing owner, waiting and error propagation.
|
|
2005
|
-
await compactCoordinator.close(controller.signal.reason ?? new MarAgentError('MAR_AGENT_CANCELLED', 'Execution ended.'));
|
|
2006
|
-
await modelResources.close();
|
|
2007
|
-
// Ending the parent Execution does not destroy Session-owned child tasks.
|
|
2008
|
-
subagents?.endParentExecution(executionId);
|
|
2009
|
-
try {
|
|
2010
|
-
await releaseSession?.();
|
|
2011
|
-
}
|
|
2012
|
-
catch (error) {
|
|
2013
|
-
// Preserve the first failure/cancellation; successful executions still report release errors.
|
|
2014
|
-
// eslint-disable-next-line no-unsafe-finally -- Successful results must not hide writer lease release failures.
|
|
2015
|
-
if (!failedExecution)
|
|
2016
|
-
throw error;
|
|
2017
|
-
}
|
|
2018
|
-
finally {
|
|
2019
|
-
// Writer release cannot skip owner-safe deactivation; the event stream closes last.
|
|
2020
|
-
if (sessionRuntime.execution === executionContext)
|
|
2021
|
-
delete sessionRuntime.execution;
|
|
2022
|
-
active.delete(`${sessionId}:${executionId}`);
|
|
2023
|
-
sessionRuntime.sessionBackend?.kick();
|
|
2024
|
-
queue.close();
|
|
2025
|
-
}
|
|
2026
|
-
}
|
|
2027
|
-
});
|
|
2028
|
-
const executionKey = `${sessionId}:${executionId}`;
|
|
2029
|
-
executionResults.set(executionKey, result);
|
|
2030
|
-
void result.then((outcome) => {
|
|
2031
|
-
inputs.settleExecution(executionId, outcome.status);
|
|
2032
|
-
executionResults.delete(executionKey);
|
|
2033
|
-
}, () => {
|
|
2034
|
-
inputs.settleExecution(executionId, 'failed');
|
|
2035
|
-
executionResults.delete(executionKey);
|
|
2036
|
-
});
|
|
2037
|
-
return {
|
|
2038
|
-
get persistedEvents() {
|
|
2039
|
-
return persistedTerminal;
|
|
2040
|
-
},
|
|
2041
|
-
executionId,
|
|
2042
|
-
turnId,
|
|
2043
|
-
[Symbol.asyncIterator]: () => queue[Symbol.asyncIterator](),
|
|
2044
|
-
result: () => {
|
|
2045
|
-
queue.discardIfUnobserved();
|
|
2046
|
-
return result;
|
|
2047
|
-
},
|
|
2048
|
-
cancel: () => controller.abort(new MarAgentError('MAR_AGENT_CANCELLED', 'Execution was cancelled.')),
|
|
2049
|
-
enqueueMessage: (message, delivery) => {
|
|
2050
|
-
if (!acceptsMailbox || controller.signal.aborted)
|
|
2051
|
-
return false;
|
|
2052
|
-
acceptParent({ text: message, ...(delivery ? { delivery } : {}) });
|
|
2053
|
-
return true;
|
|
2054
|
-
}
|
|
2055
|
-
};
|
|
2056
|
-
};
|
|
2057
|
-
sessionRuntime.sessionBackend ??= createExtensionSessionBackend({
|
|
2058
|
-
describe: async (call) => {
|
|
2059
|
-
call.signal.throwIfAborted();
|
|
2060
|
-
const defaults = sessionRuntime.execution;
|
|
2061
|
-
const state = defaults ?? services.modelState();
|
|
2062
|
-
const modelId = defaults?.modelId ?? services.modelState().defaultModelId;
|
|
2063
|
-
const current = await store.getSession(sessionId);
|
|
2064
|
-
const userTurns = await store.userTurnCount(sessionId);
|
|
2065
|
-
call.signal.throwIfAborted();
|
|
2066
|
-
const model = state.models.get(modelId);
|
|
2067
|
-
if (!model)
|
|
2068
|
-
throw new MarAgentError('MAR_AGENT_MODEL_DISABLED', 'Selected model is unavailable.');
|
|
2069
|
-
return {
|
|
2070
|
-
sessionId,
|
|
2071
|
-
...(logicalWorkspace ? { cwd: logicalWorkspace, root: logicalWorkspace } : {}),
|
|
2072
|
-
modelId,
|
|
2073
|
-
modelName: model.name,
|
|
2074
|
-
startedAt: Date.parse(current.createdAt),
|
|
2075
|
-
source: structuredClone(sessionSource),
|
|
2076
|
-
userTurns
|
|
2077
|
-
};
|
|
2078
|
-
},
|
|
2079
|
-
composePrompt: async (facts, call) => {
|
|
2080
|
-
call.signal.throwIfAborted();
|
|
2081
|
-
const defaults = sessionRuntime.execution;
|
|
2082
|
-
const state = defaults ?? services.modelState();
|
|
2083
|
-
const modelId = facts.modelId ?? defaults?.modelId ?? services.modelState().defaultModelId;
|
|
2084
|
-
const instruction = defaults ? defaults.instruction : settings.systemInstruction;
|
|
2085
|
-
const model = state.models.get(modelId);
|
|
2086
|
-
if (!model)
|
|
2087
|
-
throw new MarAgentError('MAR_AGENT_MODEL_DISABLED', 'Selected model is unavailable.');
|
|
2088
|
-
const mode = facts.mode ?? defaults?.mode ?? 'run';
|
|
2089
|
-
const bindings = services.extensions.session(sessionId)?.capture(call);
|
|
2090
|
-
if (!bindings)
|
|
2091
|
-
throw new MarAgentError('MAR_AGENT_EXTENSION_PROMPT_UNAVAILABLE', 'Session prompt tool sources are unavailable.');
|
|
2092
|
-
const definitions = [...bindings.values()]
|
|
2093
|
-
.filter((binding) => binding.available?.(call) !== false)
|
|
2094
|
-
.map((binding) => binding.definition)
|
|
2095
|
-
.filter((tool) => !(sessionSource.type === 'subagent' &&
|
|
2096
|
-
(tool.agentScope === 'ROOT_ONLY' ||
|
|
2097
|
-
tool.name.startsWith('agent_') ||
|
|
2098
|
-
tool.name === 'question')) &&
|
|
2099
|
-
!(tool.name === 'question' && mode !== 'plan') &&
|
|
2100
|
-
!(tool.name === 'view_image' && !model.inputCapabilities.includes('IMAGE')) &&
|
|
2101
|
-
!(['code_exec', 'code_exec_wait'].includes(tool.name) &&
|
|
2102
|
-
(!model.codeMode || !description.capabilities.includes('code.execute'))));
|
|
2103
|
-
const byName = new Map(definitions.map((tool) => [tool.name, tool]));
|
|
2104
|
-
const tools = facts.tools === undefined
|
|
2105
|
-
? definitions
|
|
2106
|
-
: facts.tools.flatMap((name) => {
|
|
2107
|
-
const tool = byName.get(name);
|
|
2108
|
-
return tool ? [tool] : [];
|
|
2109
|
-
});
|
|
2110
|
-
const executionId = call.executionId ?? defaults?.executionId;
|
|
2111
|
-
if (executionId === undefined && host.listExecutionExtensions && !host.listSessionSkills)
|
|
2112
|
-
throw new MarAgentError('MAR_AGENT_EXTENSION_PROMPT_UNAVAILABLE', 'The Host does not provide an idle Session Skill catalog.');
|
|
2113
|
-
const hostSkills = executionId !== undefined
|
|
2114
|
-
? ((await host.listExecutionExtensions?.({ sessionId, modelId, executionId }))
|
|
2115
|
-
?.skills ?? [])
|
|
2116
|
-
: ((await host.listSessionSkills?.({ sessionId, modelId })) ?? []);
|
|
2117
|
-
call.signal.throwIfAborted();
|
|
2118
|
-
const instructions = await loadAgentInstructions({
|
|
2119
|
-
home: description.homeDirectory,
|
|
2120
|
-
workspace: instructionWorkspace,
|
|
2121
|
-
availableTools: new Set(tools.map((tool) => tool.name)),
|
|
2122
|
-
hostSkills,
|
|
2123
|
-
...(settings.workspaceMapping === undefined
|
|
2124
|
-
? {}
|
|
2125
|
-
: { workspaceDisplayPath: logicalWorkspace })
|
|
2126
|
-
});
|
|
2127
|
-
call.signal.throwIfAborted();
|
|
2128
|
-
return {
|
|
2129
|
-
sections: buildSessionPromptSections(tools, mode, model, instruction, instructions?.skillCatalog),
|
|
2130
|
-
facts: { modelId, mode, tools: tools.map((tool) => tool.name) }
|
|
2131
|
-
};
|
|
2132
|
-
},
|
|
2133
|
-
captureRequest: async (call, input) => {
|
|
2134
|
-
call.signal.throwIfAborted();
|
|
2135
|
-
return sessionRuntime.requestSnapshots?.capture(input);
|
|
2136
|
-
},
|
|
2137
|
-
sessionId,
|
|
2138
|
-
coordinator: sessionInputs,
|
|
2139
|
-
activeExecutionId: () => [...active.keys()]
|
|
2140
|
-
.find((key) => key.startsWith(`${sessionId}:`))
|
|
2141
|
-
?.slice(sessionId.length + 1),
|
|
2142
|
-
append: appendExtensionMessage,
|
|
2143
|
-
messages: async (input, call) => {
|
|
2144
|
-
const selection = normalizeSessionMessagesInput(input);
|
|
2145
|
-
call.signal.throwIfAborted();
|
|
2146
|
-
let target = sessionId;
|
|
2147
|
-
let targetModelId;
|
|
2148
|
-
if (selection.agentId !== undefined) {
|
|
2149
|
-
if (!sessionRuntime.agentsBackend)
|
|
2150
|
-
throw new MarAgentError('MAR_AGENT_SESSION_INPUT_UNAVAILABLE', 'Session child message access is unavailable.');
|
|
2151
|
-
const child = await sessionRuntime.agentsBackend.inspect({ agentId: selection.agentId }, call);
|
|
2152
|
-
target = child.agentId;
|
|
2153
|
-
targetModelId = child.modelId;
|
|
2154
|
-
}
|
|
2155
|
-
call.signal.throwIfAborted();
|
|
2156
|
-
const targetRuntime = sessionRuntimes.get(target);
|
|
2157
|
-
const requestMessages = targetRuntime?.execution?.requestMessages;
|
|
2158
|
-
if (selection.view === 'request' && requestMessages) {
|
|
2159
|
-
const messages = requestMessages.read();
|
|
2160
|
-
const restored = selection.includeImages
|
|
2161
|
-
? await Promise.all(messages.map(async (message) => message.images?.length
|
|
2162
|
-
? {
|
|
2163
|
-
...message,
|
|
2164
|
-
images: await readResourceImages(store, target, message.images)
|
|
2165
|
-
}
|
|
2166
|
-
: message))
|
|
2167
|
-
: messages;
|
|
2168
|
-
call.signal.throwIfAborted();
|
|
2169
|
-
return sessionMessagesPage(restored, selection);
|
|
2170
|
-
}
|
|
2171
|
-
const modelState = services.modelState();
|
|
2172
|
-
const requestModel = selection.view === 'request'
|
|
2173
|
-
? modelState.models.get(targetModelId ?? modelState.defaultModelId)
|
|
2174
|
-
: undefined;
|
|
2175
|
-
if (selection.view === 'request' && !requestModel)
|
|
2176
|
-
throw new MarAgentError('MAR_AGENT_MODEL_DISABLED', 'Selected model is unavailable.');
|
|
2177
|
-
const includeImages = selection.includeImages &&
|
|
2178
|
-
(requestModel === undefined || requestModel.inputCapabilities.includes('IMAGE'));
|
|
2179
|
-
const state = await store.readExecutionState(target);
|
|
2180
|
-
call.signal.throwIfAborted();
|
|
2181
|
-
const restored = await restoreMessages(store, target, state.contextRecords, {
|
|
2182
|
-
includeImages,
|
|
2183
|
-
strictImages: includeImages
|
|
2184
|
-
});
|
|
2185
|
-
call.signal.throwIfAborted();
|
|
2186
|
-
if (requestModel) {
|
|
2187
|
-
const generation = latestContextualWorldStateGeneration(state.contextRecords);
|
|
2188
|
-
const cachedWorld = targetRuntime?.contextualWorldState;
|
|
2189
|
-
const world = cachedWorld?.generation === generation
|
|
2190
|
-
? cachedWorld
|
|
2191
|
-
: parsePersistedContextualWorldState(await store.readContextualWorldState(target));
|
|
2192
|
-
call.signal.throwIfAborted();
|
|
2193
|
-
return sessionMessagesPage(projectSessionRequestMessages(restored.messages, world?.generation === generation ? (world?.entries ?? []) : [], requestModel.inputCapabilities.includes('IMAGE'), requestModel.codeMode), selection);
|
|
2194
|
-
}
|
|
2195
|
-
return sessionMessagesPage(restored.messages, selection, restored.toolOutcomes);
|
|
2196
|
-
},
|
|
2197
|
-
launch: async (entry, request, call) => {
|
|
2198
|
-
if (sessionSource.type !== 'user')
|
|
2199
|
-
throw new MarAgentError('MAR_AGENT_SESSION_INPUT_UNAVAILABLE', 'Idle subagent input must use its task controller.');
|
|
2200
|
-
let resolveInput;
|
|
2201
|
-
let rejectInput;
|
|
2202
|
-
const inputCommitted = new Promise((resolve, reject) => {
|
|
2203
|
-
resolveInput = resolve;
|
|
2204
|
-
rejectInput = reject;
|
|
2205
|
-
});
|
|
2206
|
-
void inputCommitted.catch(() => undefined);
|
|
2207
|
-
const handle = execution(request.kind === 'compact' ? 'compact' : 'run', {
|
|
2208
|
-
prompt: request.kind === 'compact'
|
|
2209
|
-
? (request.input.focus ?? DEFAULT_COMPACTION_FOCUS)
|
|
2210
|
-
: request.input.text,
|
|
2211
|
-
...(request.kind === 'submit' && request.input.images !== undefined
|
|
2212
|
-
? { images: request.input.images }
|
|
2213
|
-
: {})
|
|
2214
|
-
}, {
|
|
2215
|
-
automaticInput: true,
|
|
2216
|
-
inputCommitted: (recordId) => {
|
|
2217
|
-
const outcome = { changed: true, recordId, executionId: handle.executionId };
|
|
2218
|
-
recordSessionInputCommit(entry, outcome);
|
|
2219
|
-
resolveInput(outcome);
|
|
2220
|
-
},
|
|
2221
|
-
...(request.kind === 'submit' ? { promptAdmitted: true } : {}),
|
|
2222
|
-
...(call.actor === 'sdk' && call.extensionId === undefined
|
|
2223
|
-
? {}
|
|
2224
|
-
: { inputSource: 'extension' }),
|
|
2225
|
-
...(request.kind === 'submit' && request.input.modelText !== undefined
|
|
2226
|
-
? { modelText: request.input.modelText }
|
|
2227
|
-
: {}),
|
|
2228
|
-
...(request.kind === 'submit' && request.input.context !== undefined
|
|
2229
|
-
? { inputContext: request.input.context }
|
|
2230
|
-
: {}),
|
|
2231
|
-
...(request.kind === 'submit' && request.input.modelContext !== undefined
|
|
2232
|
-
? { modelContext: request.input.modelContext }
|
|
2233
|
-
: {}),
|
|
2234
|
-
...(call.actor === 'sdk' && call.extensionId === undefined
|
|
2235
|
-
? {}
|
|
2236
|
-
: {
|
|
2237
|
-
extensionSource: extensionInputSource(call, request.kind === 'submit' ? request.input.provenance : undefined, request.kind === 'submit' ? request.input.modelAttribution : undefined)
|
|
2238
|
-
})
|
|
2239
|
-
});
|
|
2240
|
-
void handle.result().then((result) => {
|
|
2241
|
-
if (request.kind === 'compact')
|
|
2242
|
-
resolveInput({
|
|
2243
|
-
changed: result.status === 'completed',
|
|
2244
|
-
executionId: handle.executionId
|
|
2245
|
-
});
|
|
2246
|
-
else
|
|
2247
|
-
rejectInput(new MarAgentError(result.errorCode ??
|
|
2248
|
-
(result.status === 'cancelled'
|
|
2249
|
-
? 'MAR_AGENT_EXECUTION_CANCELLED'
|
|
2250
|
-
: 'MAR_AGENT_SESSION_INPUT_FAILED'), 'Execution ended before its input record was committed.'));
|
|
2251
|
-
}, rejectInput);
|
|
2252
|
-
return Object.assign(handle, { inputCommitted });
|
|
2253
|
-
},
|
|
2254
|
-
diagnose: (code, operationId) => services.extensions.session(sessionId)?.diagnose({ code, operationId, sessionId })
|
|
2255
|
-
});
|
|
2256
|
-
if (sessionSource.type === 'user')
|
|
2257
|
-
sessionRuntime.agentsBackend ??= createExtensionAgentsBackend({
|
|
2258
|
-
existingController: () => sessionRuntime.subagents,
|
|
2259
|
-
controller: async () => {
|
|
2260
|
-
// Access to managed children is not a new Execution admission for their parent.
|
|
2261
|
-
services.assertCanStart();
|
|
2262
|
-
if (sessionRuntime.subagents === undefined)
|
|
2263
|
-
await openSession(sessionId);
|
|
2264
|
-
if (!sessionRuntime.subagents)
|
|
2265
|
-
throw new MarAgentError('MAR_AGENT_SUBAGENT_FAILED', 'Session task controller is unavailable.');
|
|
2266
|
-
return sessionRuntime.subagents;
|
|
2267
|
-
},
|
|
2268
|
-
parent: (controller, call) => {
|
|
2269
|
-
const current = call.executionId === undefined
|
|
2270
|
-
? undefined
|
|
2271
|
-
: controller.parentExecution(call.executionId);
|
|
2272
|
-
if (call.executionId !== undefined && !current)
|
|
2273
|
-
throw new MarAgentError('MAR_AGENT_SUBAGENT_FAILED', 'Parent Execution source is unavailable.');
|
|
2274
|
-
const state = services.modelState();
|
|
2275
|
-
const selected = state.models.get(state.defaultModelId);
|
|
2276
|
-
return {
|
|
2277
|
-
...(current ?? {
|
|
2278
|
-
modelId: selected.id,
|
|
2279
|
-
reasoningEffort: selected.defaultReasoningEffort,
|
|
2280
|
-
models: state.models,
|
|
2281
|
-
emitTerminal: async () => { },
|
|
2282
|
-
startTurn: async (turn) => {
|
|
2283
|
-
const child = await openSession(turn.sessionId);
|
|
2284
|
-
return child.startSubagentTurn({
|
|
2285
|
-
prompt: turn.prompt,
|
|
2286
|
-
modelId: turn.modelId,
|
|
2287
|
-
reasoningEffort: turn.reasoningEffort,
|
|
2288
|
-
role: turn.role,
|
|
2289
|
-
initialMailbox: turn.initialMailbox,
|
|
2290
|
-
turnId: turn.turnId,
|
|
2291
|
-
...(turn.origin === undefined ? {} : { origin: turn.origin }),
|
|
2292
|
-
...(turn.delivery === undefined ? {} : { delivery: turn.delivery })
|
|
2293
|
-
});
|
|
2294
|
-
}
|
|
2295
|
-
}),
|
|
2296
|
-
operationId: call.operationId,
|
|
2297
|
-
origin: call,
|
|
2298
|
-
signal: call.signal,
|
|
2299
|
-
...(call.ownerInstanceId === undefined
|
|
2300
|
-
? {}
|
|
2301
|
-
: { ownerInstanceId: call.ownerInstanceId }),
|
|
2302
|
-
...(call.extensionId === undefined ? {} : { extensionId: call.extensionId })
|
|
2303
|
-
};
|
|
2304
|
-
}
|
|
2305
|
-
});
|
|
2306
|
-
return {
|
|
2307
|
-
id: sessionId,
|
|
2308
|
-
run: (input) => execution('run', input),
|
|
2309
|
-
plan: (input) => execution('plan', input),
|
|
2310
|
-
steer: (input) => sessionRuntime.execution?.steer?.(input) ?? Promise.resolve({ status: 'notAccepted' }),
|
|
2311
|
-
compact: (input = {}) => {
|
|
2312
|
-
const requests = sessionRuntime.execution?.compactRequests;
|
|
2313
|
-
if (requests) {
|
|
2314
|
-
services.assertSessionAdmission(sessionId);
|
|
2315
|
-
return requests.request(input);
|
|
2316
|
-
}
|
|
2317
|
-
return execution('compact', {
|
|
2318
|
-
prompt: input.prompt ?? DEFAULT_COMPACTION_FOCUS,
|
|
2319
|
-
...input
|
|
2320
|
-
});
|
|
2321
|
-
},
|
|
2322
|
-
cancel: async (executionId) => active.get(`${sessionId}:${executionId}`)?.abort(),
|
|
2323
|
-
startSubagentTurn: (turn) => execution(turn.role === 'explore' ? 'plan' : 'run', {
|
|
2324
|
-
prompt: turn.prompt,
|
|
2325
|
-
modelId: turn.modelId,
|
|
2326
|
-
reasoningEffort: turn.reasoningEffort,
|
|
2327
|
-
...(turn.permissionMode === undefined ? {} : { permissionMode: turn.permissionMode })
|
|
2328
|
-
}, {
|
|
2329
|
-
publishHostEvents: false,
|
|
2330
|
-
...(turn.origin === undefined ? {} : { signal: turn.origin.signal }),
|
|
2331
|
-
inputSource: turn.origin === undefined ? 'parent_agent' : 'extension',
|
|
2332
|
-
...(turn.origin === undefined
|
|
2333
|
-
? {}
|
|
2334
|
-
: { extensionSource: extensionInputSource(turn.origin) }),
|
|
2335
|
-
initialMailbox: turn.initialMailbox,
|
|
2336
|
-
turnId: turn.turnId,
|
|
2337
|
-
...(turn.mcpExecutionScopeId === undefined
|
|
2338
|
-
? {}
|
|
2339
|
-
: { mcpExecutionScopeId: turn.mcpExecutionScopeId }),
|
|
2340
|
-
...(turn.delivery ? { delivery: turn.delivery } : {})
|
|
2341
|
-
})
|
|
2342
|
-
};
|
|
2343
|
-
};
|
|
2344
|
-
return openSession;
|
|
2345
|
-
}
|
|
2346
|
-
function extensionInputSource(call, provenance, modelAttribution) {
|
|
2347
|
-
return {
|
|
2348
|
-
operationId: call.operationId,
|
|
2349
|
-
actor: call.actor,
|
|
2350
|
-
...(call.extensionId ? { extensionId: call.extensionId } : {}),
|
|
2351
|
-
...(call.ownerInstanceId ? { ownerInstanceId: call.ownerInstanceId } : {}),
|
|
2352
|
-
...(provenance !== undefined ? { provenance } : {}),
|
|
2353
|
-
...(modelAttribution === undefined ? {} : { modelAttribution })
|
|
2354
|
-
};
|
|
2355
|
-
}
|
|
2356
|
-
function modelAttemptFailureDiagnostic(diagnostic, summary) {
|
|
2357
|
-
if (summary === undefined)
|
|
2358
|
-
return diagnostic;
|
|
2359
|
-
const prefix = `Model request failed after ${summary.attempts} attempts (${summary.retries} retries). `;
|
|
2360
|
-
const availableCharacters = Math.max(0, 1_000 - [...prefix].length);
|
|
2361
|
-
return {
|
|
2362
|
-
code: diagnostic.code,
|
|
2363
|
-
message: `${prefix}${[...diagnostic.message].slice(0, availableCharacters).join('')}`
|
|
2364
|
-
};
|
|
2365
|
-
}
|
|
2366
|
-
function projectAppendedModelMessage(input) {
|
|
2367
|
-
if (input.visibility === 'transcript')
|
|
2368
|
-
return undefined;
|
|
2369
|
-
return {
|
|
2370
|
-
role: 'user',
|
|
2371
|
-
contextKind: 'contextual',
|
|
2372
|
-
content: input.content,
|
|
2373
|
-
...(input.textBlocks === undefined
|
|
2374
|
-
? {}
|
|
2375
|
-
: { textBlocks: input.textBlocks.map((block) => ({ text: block.text })) })
|
|
2376
|
-
};
|
|
2377
|
-
}
|