@cuylabs/agent-core 4.8.1 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -12
- package/dist/agent/chat-loop/commit-batch.d.ts +10 -0
- package/dist/agent/chat-loop/commit-batch.d.ts.map +1 -0
- package/dist/agent/chat-loop/context-recovery.d.ts +29 -0
- package/dist/agent/chat-loop/context-recovery.d.ts.map +1 -0
- package/dist/agent/chat-loop/finalize-turn.d.ts +19 -0
- package/dist/agent/chat-loop/finalize-turn.d.ts.map +1 -0
- package/dist/agent/chat-loop/index.d.ts +7 -0
- package/dist/agent/chat-loop/index.d.ts.map +1 -0
- package/dist/agent/chat-loop/loop.d.ts +8 -0
- package/dist/agent/chat-loop/loop.d.ts.map +1 -0
- package/dist/agent/chat-loop/model-step-runner.d.ts +26 -0
- package/dist/agent/chat-loop/model-step-runner.d.ts.map +1 -0
- package/dist/agent/chat-loop/model-step-snapshot.d.ts +49 -0
- package/dist/agent/chat-loop/model-step-snapshot.d.ts.map +1 -0
- package/dist/agent/chat-loop/turn-tools.d.ts +19 -0
- package/dist/agent/chat-loop/turn-tools.d.ts.map +1 -0
- package/dist/agent/chat-loop/types.d.ts +60 -0
- package/dist/agent/chat-loop/types.d.ts.map +1 -0
- package/dist/agent/defaults.d.ts +69 -0
- package/dist/agent/defaults.d.ts.map +1 -0
- package/dist/agent/event-printer.d.ts +94 -0
- package/dist/agent/event-printer.d.ts.map +1 -0
- package/dist/agent/fork.d.ts +59 -0
- package/dist/agent/fork.d.ts.map +1 -0
- package/dist/agent/index.d.ts +17 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/instance/context-management.d.ts +29 -0
- package/dist/agent/instance/context-management.d.ts.map +1 -0
- package/dist/agent/instance/forking.d.ts +26 -0
- package/dist/agent/instance/forking.d.ts.map +1 -0
- package/dist/agent/instance/index.d.ts +170 -0
- package/dist/agent/instance/index.d.ts.map +1 -0
- package/dist/agent/instance/interventions.d.ts +10 -0
- package/dist/agent/instance/interventions.d.ts.map +1 -0
- package/dist/agent/instance/mcp.d.ts +21 -0
- package/dist/agent/instance/mcp.d.ts.map +1 -0
- package/dist/agent/instance/sessions.d.ts +8 -0
- package/dist/agent/instance/sessions.d.ts.map +1 -0
- package/dist/agent/instance/tools.d.ts +16 -0
- package/dist/agent/instance/tools.d.ts.map +1 -0
- package/dist/agent/instance/turn-lifecycle.d.ts +61 -0
- package/dist/agent/instance/turn-lifecycle.d.ts.map +1 -0
- package/dist/agent/session.d.ts +16 -0
- package/dist/agent/session.d.ts.map +1 -0
- package/dist/agent/setup/config.d.ts +8 -0
- package/dist/agent/setup/config.d.ts.map +1 -0
- package/dist/agent/setup/context-window.d.ts +4 -0
- package/dist/agent/setup/context-window.d.ts.map +1 -0
- package/dist/agent/setup/environment.d.ts +5 -0
- package/dist/agent/setup/environment.d.ts.map +1 -0
- package/dist/agent/setup/middleware.d.ts +9 -0
- package/dist/agent/setup/middleware.d.ts.map +1 -0
- package/dist/agent/setup/runtime-config.d.ts +9 -0
- package/dist/agent/setup/runtime-config.d.ts.map +1 -0
- package/dist/agent/setup/state.d.ts +4 -0
- package/dist/agent/setup/state.d.ts.map +1 -0
- package/dist/agent/setup/tools.d.ts +8 -0
- package/dist/agent/setup/tools.d.ts.map +1 -0
- package/dist/agent/setup.d.ts +47 -0
- package/dist/agent/setup.d.ts.map +1 -0
- package/dist/agent/stream-provider.d.ts +27 -0
- package/dist/agent/stream-provider.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/agent-context.d.ts +53 -0
- package/dist/agent/turn-context/compaction/agent-context.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/budget.d.ts +4 -0
- package/dist/agent/turn-context/compaction/budget.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/check.d.ts +39 -0
- package/dist/agent/turn-context/compaction/check.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/fragments.d.ts +4 -0
- package/dist/agent/turn-context/compaction/fragments.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/index.d.ts +5 -0
- package/dist/agent/turn-context/compaction/index.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/memory.d.ts +17 -0
- package/dist/agent/turn-context/compaction/memory.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/results.d.ts +19 -0
- package/dist/agent/turn-context/compaction/results.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/summary.d.ts +3 -0
- package/dist/agent/turn-context/compaction/summary.d.ts.map +1 -0
- package/dist/agent/turn-context/compaction/types.d.ts +24 -0
- package/dist/agent/turn-context/compaction/types.d.ts.map +1 -0
- package/dist/agent/turn-context/fit-model-context.d.ts +29 -0
- package/dist/agent/turn-context/fit-model-context.d.ts.map +1 -0
- package/dist/agent/turn-context/index.d.ts +5 -0
- package/dist/agent/turn-context/index.d.ts.map +1 -0
- package/dist/agent/turn-context/system-prompts.d.ts +12 -0
- package/dist/agent/turn-context/system-prompts.d.ts.map +1 -0
- package/dist/agent/types/config.d.ts +199 -0
- package/dist/agent/types/config.d.ts.map +1 -0
- package/dist/agent/types/index.d.ts +11 -0
- package/dist/agent/types/index.d.ts.map +1 -0
- package/dist/agent/types/state.d.ts +16 -0
- package/dist/agent/types/state.d.ts.map +1 -0
- package/dist/agent/types/tracing.d.ts +12 -0
- package/dist/agent/types/tracing.d.ts.map +1 -0
- package/dist/{chunk-KYLPMBHD.js → chunk-336EDIBL.js} +1 -1
- package/dist/chunk-AAGKWUXR.js +539 -0
- package/dist/chunk-AHDCR7SX.js +83 -0
- package/dist/{chunk-CSR75JVC.js → chunk-ASXF5AC6.js} +1 -1
- package/dist/{chunk-2TTOLHBT.js → chunk-CFBSQLP5.js} +1 -1
- package/dist/{chunk-GJFP5L2V.js → chunk-CNM6OROH.js} +15 -3
- package/dist/chunk-E66PKKDL.js +772 -0
- package/dist/{chunk-HSUPTXNV.js → chunk-EBVSPHXA.js} +13 -10
- package/dist/chunk-EEAGM5MS.js +257 -0
- package/dist/chunk-IQA64CAO.js +84 -0
- package/dist/chunk-JFH6HBUG.js +227 -0
- package/dist/{chunk-MWPU2EVV.js → chunk-JUIL2NJC.js} +4 -81
- package/dist/{chunk-NS7D7JJU.js → chunk-K453AFTL.js} +35 -16
- package/dist/chunk-LX4AHGI3.js +960 -0
- package/dist/chunk-MJRZ2ZRI.js +498 -0
- package/dist/chunk-NMJNN6LS.js +1155 -0
- package/dist/{chunk-UMIVJDEJ.js → chunk-SAWRDGBE.js} +30 -7
- package/dist/{chunk-GEBFHREI.js → chunk-TU5KDFWI.js} +30 -5
- package/dist/{chunk-QJV5XPPS.js → chunk-UEEHZ4QH.js} +1 -1
- package/dist/chunk-UG5PVNZV.js +53 -0
- package/dist/{chunk-BGG2HVIR.js → chunk-V4MIDL5B.js} +9 -0
- package/dist/{chunk-BJC46FIF.js → chunk-V4YQ6MBK.js} +2 -2
- package/dist/{chunk-H3GRHFFG.js → chunk-VMGZKIFT.js} +30 -9
- package/dist/chunk-W6LWIMIX.js +8 -0
- package/dist/context/assembly/index.d.ts +3 -0
- package/dist/context/assembly/index.d.ts.map +1 -0
- package/dist/context/assembly/prepare.d.ts +11 -0
- package/dist/context/assembly/prepare.d.ts.map +1 -0
- package/dist/context/assembly/types.d.ts +60 -0
- package/dist/context/assembly/types.d.ts.map +1 -0
- package/dist/context/config.d.ts +11 -0
- package/dist/context/config.d.ts.map +1 -0
- package/dist/context/fragments/index.d.ts +4 -0
- package/dist/context/fragments/index.d.ts.map +1 -0
- package/dist/context/fragments/messages.d.ts +10 -0
- package/dist/context/fragments/messages.d.ts.map +1 -0
- package/dist/context/fragments/render.d.ts +16 -0
- package/dist/context/fragments/render.d.ts.map +1 -0
- package/dist/context/fragments/types.d.ts +87 -0
- package/dist/context/fragments/types.d.ts.map +1 -0
- package/dist/context/index.d.ts +13 -0
- package/dist/context/index.d.ts.map +1 -0
- package/dist/context/index.js +90 -0
- package/dist/context/text/truncation.d.ts +13 -0
- package/dist/context/text/truncation.d.ts.map +1 -0
- package/dist/context/window/budget.d.ts +108 -0
- package/dist/context/window/budget.d.ts.map +1 -0
- package/dist/context/window/compactor.d.ts +74 -0
- package/dist/context/window/compactor.d.ts.map +1 -0
- package/dist/context/window/cut-planner.d.ts +64 -0
- package/dist/context/window/cut-planner.d.ts.map +1 -0
- package/dist/context/window/decision.d.ts +41 -0
- package/dist/context/window/decision.d.ts.map +1 -0
- package/dist/context/window/estimation.d.ts +45 -0
- package/dist/context/window/estimation.d.ts.map +1 -0
- package/dist/context/window/index.d.ts +26 -0
- package/dist/context/window/index.d.ts.map +1 -0
- package/dist/context/window/manager.d.ts +80 -0
- package/dist/context/window/manager.d.ts.map +1 -0
- package/dist/context/window/summary-policy.d.ts +50 -0
- package/dist/context/window/summary-policy.d.ts.map +1 -0
- package/dist/context/window/summary.d.ts +56 -0
- package/dist/context/window/summary.d.ts.map +1 -0
- package/dist/context/window/tool-pruning.d.ts +62 -0
- package/dist/context/window/tool-pruning.d.ts.map +1 -0
- package/dist/dispatch/executor.d.ts +56 -0
- package/dist/dispatch/executor.d.ts.map +1 -0
- package/dist/dispatch/index.d.ts +7 -95
- package/dist/dispatch/index.d.ts.map +1 -0
- package/dist/dispatch/index.js +4 -3
- package/dist/dispatch/results.d.ts +9 -0
- package/dist/dispatch/results.d.ts.map +1 -0
- package/dist/dispatch/runtime.d.ts +19 -0
- package/dist/dispatch/runtime.d.ts.map +1 -0
- package/dist/dispatch/tool-factories.d.ts +8 -0
- package/dist/dispatch/tool-factories.d.ts.map +1 -0
- package/dist/dispatch/tools.d.ts +10 -0
- package/dist/dispatch/tools.d.ts.map +1 -0
- package/dist/dispatch/types.d.ts +131 -0
- package/dist/dispatch/types.d.ts.map +1 -0
- package/dist/events/event-bus/index.d.ts +13 -0
- package/dist/events/event-bus/index.d.ts.map +1 -0
- package/dist/events/event-bus/index.js +6 -0
- package/dist/events/event-bus/local.d.ts +14 -0
- package/dist/events/event-bus/local.d.ts.map +1 -0
- package/dist/events/event-bus/types.d.ts +78 -0
- package/dist/events/event-bus/types.d.ts.map +1 -0
- package/dist/events/index.d.ts +10 -89
- package/dist/events/index.d.ts.map +1 -0
- package/dist/events/index.js +6 -1
- package/dist/events/signal/index.d.ts +18 -0
- package/dist/events/signal/index.d.ts.map +1 -0
- package/dist/events/signal/index.js +6 -0
- package/dist/events/signal/local.d.ts +22 -0
- package/dist/events/signal/local.d.ts.map +1 -0
- package/dist/events/signal/types.d.ts +69 -0
- package/dist/events/signal/types.d.ts.map +1 -0
- package/dist/execution/index.d.ts +33 -481
- package/dist/execution/index.d.ts.map +1 -0
- package/dist/execution/index.js +45 -19
- package/dist/execution/scope/index.d.ts +10 -0
- package/dist/execution/scope/index.d.ts.map +1 -0
- package/dist/execution/scope/index.js +12 -0
- package/dist/execution/scope/run.d.ts +8 -0
- package/dist/execution/scope/run.d.ts.map +1 -0
- package/dist/execution/scope/store.d.ts +6 -0
- package/dist/execution/scope/store.d.ts.map +1 -0
- package/dist/execution/scope/types.d.ts +28 -0
- package/dist/execution/scope/types.d.ts.map +1 -0
- package/dist/execution/shared/usage.d.ts +9 -0
- package/dist/execution/shared/usage.d.ts.map +1 -0
- package/dist/execution/task/index.d.ts +6 -0
- package/dist/execution/task/index.d.ts.map +1 -0
- package/dist/execution/task/observer.d.ts +80 -0
- package/dist/execution/task/observer.d.ts.map +1 -0
- package/dist/execution/task/runner.d.ts +39 -0
- package/dist/execution/task/runner.d.ts.map +1 -0
- package/dist/execution/task/types.d.ts +85 -0
- package/dist/execution/task/types.d.ts.map +1 -0
- package/dist/execution/turn/engine/commit-batch.d.ts +16 -0
- package/dist/execution/turn/engine/commit-batch.d.ts.map +1 -0
- package/dist/execution/turn/engine/engine.d.ts +32 -0
- package/dist/execution/turn/engine/engine.d.ts.map +1 -0
- package/dist/execution/turn/engine/index.d.ts +12 -0
- package/dist/execution/turn/engine/index.d.ts.map +1 -0
- package/dist/execution/turn/engine/types.d.ts +67 -0
- package/dist/execution/turn/engine/types.d.ts.map +1 -0
- package/dist/execution/turn/index.d.ts +18 -0
- package/dist/execution/turn/index.d.ts.map +1 -0
- package/dist/execution/turn/index.js +52 -0
- package/dist/execution/turn/runner/commit.d.ts +11 -0
- package/dist/execution/turn/runner/commit.d.ts.map +1 -0
- package/dist/execution/turn/runner/index.d.ts +16 -0
- package/dist/execution/turn/runner/index.d.ts.map +1 -0
- package/dist/execution/turn/runner/prepare.d.ts +6 -0
- package/dist/execution/turn/runner/prepare.d.ts.map +1 -0
- package/dist/execution/turn/runner/stream-step.d.ts +8 -0
- package/dist/execution/turn/runner/stream-step.d.ts.map +1 -0
- package/dist/execution/turn/runner/tool-batch.d.ts +13 -0
- package/dist/execution/turn/runner/tool-batch.d.ts.map +1 -0
- package/dist/execution/turn/runner/types.d.ts +111 -0
- package/dist/execution/turn/runner/types.d.ts.map +1 -0
- package/dist/execution/turn/state.d.ts +110 -0
- package/dist/execution/turn/state.d.ts.map +1 -0
- package/dist/execution/turn/step-ledger.d.ts +89 -0
- package/dist/execution/turn/step-ledger.d.ts.map +1 -0
- package/dist/execution/turn/step-processing/doom-loop.d.ts +28 -0
- package/dist/execution/turn/step-processing/doom-loop.d.ts.map +1 -0
- package/dist/execution/turn/step-processing/index.d.ts +14 -0
- package/dist/execution/turn/step-processing/index.d.ts.map +1 -0
- package/dist/execution/turn/step-processing/overflow.d.ts +17 -0
- package/dist/execution/turn/step-processing/overflow.d.ts.map +1 -0
- package/dist/execution/turn/step-processing/process.d.ts +7 -0
- package/dist/execution/turn/step-processing/process.d.ts.map +1 -0
- package/dist/execution/turn/step-processing/types.d.ts +65 -0
- package/dist/execution/turn/step-processing/types.d.ts.map +1 -0
- package/dist/execution/workflow/index.d.ts +12 -0
- package/dist/execution/workflow/index.d.ts.map +1 -0
- package/dist/execution/workflow/index.js +39 -0
- package/dist/execution/workflow/planner/apply.d.ts +30 -0
- package/dist/execution/workflow/planner/apply.d.ts.map +1 -0
- package/dist/execution/workflow/planner/helpers.d.ts +6 -0
- package/dist/execution/workflow/planner/helpers.d.ts.map +1 -0
- package/dist/execution/workflow/planner/index.d.ts +13 -0
- package/dist/execution/workflow/planner/index.d.ts.map +1 -0
- package/dist/execution/workflow/planner/plan.d.ts +7 -0
- package/dist/execution/workflow/planner/plan.d.ts.map +1 -0
- package/dist/execution/workflow/planner/types.d.ts +49 -0
- package/dist/execution/workflow/planner/types.d.ts.map +1 -0
- package/dist/execution/workflow/snapshot.d.ts +11 -0
- package/dist/execution/workflow/snapshot.d.ts.map +1 -0
- package/dist/execution/workflow/state.d.ts +161 -0
- package/dist/execution/workflow/state.d.ts.map +1 -0
- package/dist/human/controller.d.ts +24 -0
- package/dist/human/controller.d.ts.map +1 -0
- package/dist/human/handler.d.ts +15 -0
- package/dist/human/handler.d.ts.map +1 -0
- package/dist/human/index.d.ts +5 -0
- package/dist/human/index.d.ts.map +1 -0
- package/dist/human/tool.d.ts +17 -0
- package/dist/human/tool.d.ts.map +1 -0
- package/dist/human/types.d.ts +62 -0
- package/dist/human/types.d.ts.map +1 -0
- package/dist/index.d.ts +66 -567
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2482 -1846
- package/dist/inference/defaults.d.ts +8 -0
- package/dist/inference/defaults.d.ts.map +1 -0
- package/dist/inference/errors/classify.d.ts +5 -0
- package/dist/inference/errors/classify.d.ts.map +1 -0
- package/dist/inference/errors/extract.d.ts +3 -0
- package/dist/inference/errors/extract.d.ts.map +1 -0
- package/dist/inference/errors/index.d.ts +8 -11
- package/dist/inference/errors/index.d.ts.map +1 -0
- package/dist/inference/errors/llm-error.d.ts +14 -0
- package/dist/inference/errors/llm-error.d.ts.map +1 -0
- package/dist/inference/errors/types.d.ts +18 -0
- package/dist/inference/errors/types.d.ts.map +1 -0
- package/dist/inference/errors/utils.d.ts +5 -0
- package/dist/inference/errors/utils.d.ts.map +1 -0
- package/dist/inference/index.d.ts +17 -49
- package/dist/inference/index.d.ts.map +1 -0
- package/dist/inference/index.js +7 -7
- package/dist/inference/middleware-support.d.ts +14 -0
- package/dist/inference/middleware-support.d.ts.map +1 -0
- package/dist/{model-messages-n_ZMZwIm.d.ts → inference/model-messages.d.ts} +4 -6
- package/dist/inference/model-messages.d.ts.map +1 -0
- package/dist/inference/retry.d.ts +73 -0
- package/dist/inference/retry.d.ts.map +1 -0
- package/dist/inference/stream.d.ts +16 -0
- package/dist/inference/stream.d.ts.map +1 -0
- package/dist/inference/toolset.d.ts +26 -0
- package/dist/inference/toolset.d.ts.map +1 -0
- package/dist/inference/types.d.ts +129 -0
- package/dist/inference/types.d.ts.map +1 -0
- package/dist/intervention/follow-up-policy.d.ts +41 -0
- package/dist/intervention/follow-up-policy.d.ts.map +1 -0
- package/dist/intervention/index.d.ts +5 -0
- package/dist/intervention/index.d.ts.map +1 -0
- package/dist/intervention/intervention.d.ts +130 -0
- package/dist/intervention/intervention.d.ts.map +1 -0
- package/dist/intervention/types.d.ts +74 -0
- package/dist/intervention/types.d.ts.map +1 -0
- package/dist/logger/index.d.ts +5 -47
- package/dist/logger/index.d.ts.map +1 -0
- package/dist/logger/logger.d.ts +46 -0
- package/dist/logger/logger.d.ts.map +1 -0
- package/dist/{types-RSCv7nQ4.d.ts → logger/types.d.ts} +6 -7
- package/dist/logger/types.d.ts.map +1 -0
- package/dist/mcp/auth.d.ts +109 -0
- package/dist/mcp/auth.d.ts.map +1 -0
- package/dist/mcp/diagnostics.d.ts +23 -0
- package/dist/mcp/diagnostics.d.ts.map +1 -0
- package/dist/mcp/factories.d.ts +47 -0
- package/dist/mcp/factories.d.ts.map +1 -0
- package/dist/mcp/index.d.ts +14 -175
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/manager.d.ts +45 -0
- package/dist/mcp/manager.d.ts.map +1 -0
- package/dist/mcp/modules.d.ts +6 -0
- package/dist/mcp/modules.d.ts.map +1 -0
- package/dist/{types-DMjoFKKv.d.ts → mcp/types.d.ts} +18 -19
- package/dist/mcp/types.d.ts.map +1 -0
- package/dist/memory/config.d.ts +4 -0
- package/dist/memory/config.d.ts.map +1 -0
- package/dist/memory/format.d.ts +8 -0
- package/dist/memory/format.d.ts.map +1 -0
- package/dist/memory/index.d.ts +5 -0
- package/dist/memory/index.d.ts.map +1 -0
- package/dist/memory/index.js +14 -0
- package/dist/memory/middleware.d.ts +14 -0
- package/dist/memory/middleware.d.ts.map +1 -0
- package/dist/memory/types.d.ts +232 -0
- package/dist/memory/types.d.ts.map +1 -0
- package/dist/middleware/approval.d.ts +70 -0
- package/dist/middleware/approval.d.ts.map +1 -0
- package/dist/middleware/index.d.ts +24 -110
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +2 -2
- package/dist/middleware/prompt-cache/cache.d.ts +44 -0
- package/dist/middleware/prompt-cache/cache.d.ts.map +1 -0
- package/dist/middleware/prompt-cache/index.d.ts +14 -0
- package/dist/middleware/prompt-cache/index.d.ts.map +1 -0
- package/dist/middleware/prompt-cache/types.d.ts +50 -0
- package/dist/middleware/prompt-cache/types.d.ts.map +1 -0
- package/dist/middleware/runner.d.ts +100 -0
- package/dist/middleware/runner.d.ts.map +1 -0
- package/dist/middleware/telemetry/index.d.ts +12 -0
- package/dist/middleware/telemetry/index.d.ts.map +1 -0
- package/dist/middleware/telemetry/otel.d.ts +4 -0
- package/dist/middleware/telemetry/otel.d.ts.map +1 -0
- package/dist/middleware/telemetry/provider.d.ts +3 -0
- package/dist/middleware/telemetry/provider.d.ts.map +1 -0
- package/dist/middleware/telemetry/types.d.ts +150 -0
- package/dist/middleware/telemetry/types.d.ts.map +1 -0
- package/dist/middleware/types.d.ts +371 -0
- package/dist/middleware/types.d.ts.map +1 -0
- package/dist/models/cache/adapters.d.ts +4 -0
- package/dist/models/cache/adapters.d.ts.map +1 -0
- package/dist/models/cache/index.d.ts +5 -0
- package/dist/models/cache/index.d.ts.map +1 -0
- package/dist/models/cache/manager.d.ts +32 -0
- package/dist/models/cache/manager.d.ts.map +1 -0
- package/dist/models/cache/types.d.ts +17 -0
- package/dist/models/cache/types.d.ts.map +1 -0
- package/dist/models/capability-resolver.d.ts +104 -0
- package/dist/models/capability-resolver.d.ts.map +1 -0
- package/dist/models/identifiers.d.ts +23 -0
- package/dist/models/identifiers.d.ts.map +1 -0
- package/dist/models/index.d.ts +35 -256
- package/dist/models/index.d.ts.map +1 -0
- package/dist/models/index.js +1 -1
- package/dist/models/overrides.d.ts +10 -0
- package/dist/models/overrides.d.ts.map +1 -0
- package/dist/models/profiles.d.ts +38 -0
- package/dist/models/profiles.d.ts.map +1 -0
- package/dist/models/reasoning/config.d.ts +49 -0
- package/dist/models/reasoning/config.d.ts.map +1 -0
- package/dist/models/reasoning/index.d.ts +12 -4
- package/dist/models/reasoning/index.d.ts.map +1 -0
- package/dist/models/reasoning/index.js +1 -1
- package/dist/models/reasoning/providers.d.ts +63 -0
- package/dist/models/reasoning/providers.d.ts.map +1 -0
- package/dist/{types-CQaXbRsS.d.ts → models/reasoning/types.d.ts} +7 -8
- package/dist/models/reasoning/types.d.ts.map +1 -0
- package/dist/models/remote/fetcher.d.ts +13 -0
- package/dist/models/remote/fetcher.d.ts.map +1 -0
- package/dist/models/remote/index.d.ts +8 -0
- package/dist/models/remote/index.d.ts.map +1 -0
- package/dist/models/remote/network.d.ts +6 -0
- package/dist/models/remote/network.d.ts.map +1 -0
- package/dist/models/remote/source.d.ts +16 -0
- package/dist/models/remote/source.d.ts.map +1 -0
- package/dist/models/remote/transform.d.ts +4 -0
- package/dist/models/remote/transform.d.ts.map +1 -0
- package/dist/models/remote/types.d.ts +28 -0
- package/dist/models/remote/types.d.ts.map +1 -0
- package/dist/models/resolver.d.ts +26 -0
- package/dist/models/resolver.d.ts.map +1 -0
- package/dist/models/types.d.ts +137 -0
- package/dist/models/types.d.ts.map +1 -0
- package/dist/plugin/compatibility.d.ts +11 -0
- package/dist/plugin/compatibility.d.ts.map +1 -0
- package/dist/plugin/define.d.ts +77 -0
- package/dist/plugin/define.d.ts.map +1 -0
- package/dist/plugin/event-bus.d.ts +31 -0
- package/dist/plugin/event-bus.d.ts.map +1 -0
- package/dist/plugin/index.d.ts +9 -458
- package/dist/plugin/index.d.ts.map +1 -0
- package/dist/plugin/loader.d.ts +63 -0
- package/dist/plugin/loader.d.ts.map +1 -0
- package/dist/plugin/registry.d.ts +81 -0
- package/dist/plugin/registry.d.ts.map +1 -0
- package/dist/plugin/settings.d.ts +36 -0
- package/dist/plugin/settings.d.ts.map +1 -0
- package/dist/plugin/types.d.ts +168 -0
- package/dist/plugin/types.d.ts.map +1 -0
- package/dist/profiles/apply.d.ts +17 -0
- package/dist/profiles/apply.d.ts.map +1 -0
- package/dist/profiles/builtins.d.ts +18 -0
- package/dist/profiles/builtins.d.ts.map +1 -0
- package/dist/profiles/index.d.ts +12 -55
- package/dist/profiles/index.d.ts.map +1 -0
- package/dist/profiles/patterns.d.ts +12 -0
- package/dist/profiles/patterns.d.ts.map +1 -0
- package/dist/profiles/types.d.ts +48 -0
- package/dist/profiles/types.d.ts.map +1 -0
- package/dist/prompt/builder/builder.d.ts +27 -0
- package/dist/prompt/builder/builder.d.ts.map +1 -0
- package/dist/prompt/builder/index.d.ts +11 -0
- package/dist/prompt/builder/index.d.ts.map +1 -0
- package/dist/prompt/builder/priorities.d.ts +13 -0
- package/dist/prompt/builder/priorities.d.ts.map +1 -0
- package/dist/prompt/builder/sections.d.ts +30 -0
- package/dist/prompt/builder/sections.d.ts.map +1 -0
- package/dist/prompt/environment.d.ts +46 -0
- package/dist/prompt/environment.d.ts.map +1 -0
- package/dist/prompt/index.d.ts +31 -220
- package/dist/prompt/index.d.ts.map +1 -0
- package/dist/prompt/index.js +3 -1
- package/dist/prompt/instructions.d.ts +104 -0
- package/dist/prompt/instructions.d.ts.map +1 -0
- package/dist/prompt/templates.d.ts +56 -0
- package/dist/prompt/templates.d.ts.map +1 -0
- package/dist/prompt/types.d.ts +218 -0
- package/dist/prompt/types.d.ts.map +1 -0
- package/dist/safety/errors.d.ts +18 -0
- package/dist/safety/errors.d.ts.map +1 -0
- package/dist/safety/handler.d.ts +16 -0
- package/dist/safety/handler.d.ts.map +1 -0
- package/dist/safety/index.d.ts +11 -133
- package/dist/safety/index.d.ts.map +1 -0
- package/dist/safety/patterns.d.ts +17 -0
- package/dist/safety/patterns.d.ts.map +1 -0
- package/dist/safety/policy.d.ts +31 -0
- package/dist/safety/policy.d.ts.map +1 -0
- package/dist/safety/presets.d.ts +43 -0
- package/dist/safety/presets.d.ts.map +1 -0
- package/dist/safety/risk.d.ts +14 -0
- package/dist/safety/risk.d.ts.map +1 -0
- package/dist/safety/types.d.ts +165 -0
- package/dist/safety/types.d.ts.map +1 -0
- package/dist/sandbox/index.d.ts +2 -81
- package/dist/sandbox/index.d.ts.map +1 -0
- package/dist/sandbox/types.d.ts +79 -0
- package/dist/sandbox/types.d.ts.map +1 -0
- package/dist/skill/discovery/constants.d.ts +6 -0
- package/dist/skill/discovery/constants.d.ts.map +1 -0
- package/dist/skill/discovery/dedupe.d.ts +3 -0
- package/dist/skill/discovery/dedupe.d.ts.map +1 -0
- package/dist/skill/discovery/discover.d.ts +3 -0
- package/dist/skill/discovery/discover.d.ts.map +1 -0
- package/dist/skill/discovery/fs.d.ts +4 -0
- package/dist/skill/discovery/fs.d.ts.map +1 -0
- package/dist/skill/discovery/index.d.ts +6 -0
- package/dist/skill/discovery/index.d.ts.map +1 -0
- package/dist/skill/discovery/scan.d.ts +3 -0
- package/dist/skill/discovery/scan.d.ts.map +1 -0
- package/dist/skill/discovery/types.d.ts +15 -0
- package/dist/skill/discovery/types.d.ts.map +1 -0
- package/dist/skill/index.d.ts +67 -89
- package/dist/skill/index.d.ts.map +1 -0
- package/dist/skill/index.js +2 -2
- package/dist/skill/loader/constants.d.ts +5 -0
- package/dist/skill/loader/constants.d.ts.map +1 -0
- package/dist/skill/loader/frontmatter.d.ts +5 -0
- package/dist/skill/loader/frontmatter.d.ts.map +1 -0
- package/dist/skill/loader/index.d.ts +8 -0
- package/dist/skill/loader/index.d.ts.map +1 -0
- package/dist/skill/loader/metadata.d.ts +3 -0
- package/dist/skill/loader/metadata.d.ts.map +1 -0
- package/dist/skill/loader/resources.d.ts +5 -0
- package/dist/skill/loader/resources.d.ts.map +1 -0
- package/dist/skill/registry.d.ts +177 -0
- package/dist/skill/registry.d.ts.map +1 -0
- package/dist/skill/tools.d.ts +77 -0
- package/dist/skill/tools.d.ts.map +1 -0
- package/dist/skill/types.d.ts +291 -0
- package/dist/skill/types.d.ts.map +1 -0
- package/dist/storage/file/helpers.d.ts +16 -0
- package/dist/storage/file/helpers.d.ts.map +1 -0
- package/dist/storage/file/index.d.ts +6 -0
- package/dist/storage/file/index.d.ts.map +1 -0
- package/dist/storage/file/storage.d.ts +29 -0
- package/dist/storage/file/storage.d.ts.map +1 -0
- package/dist/storage/file/types.d.ts +6 -0
- package/dist/storage/file/types.d.ts.map +1 -0
- package/dist/storage/index.d.ts +11 -188
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +2 -1
- package/dist/storage/lock.d.ts +18 -0
- package/dist/storage/lock.d.ts.map +1 -0
- package/dist/storage/manager/default.d.ts +11 -0
- package/dist/storage/manager/default.d.ts.map +1 -0
- package/dist/storage/manager/index.d.ts +12 -0
- package/dist/storage/manager/index.d.ts.map +1 -0
- package/dist/storage/manager/session-manager.d.ts +57 -0
- package/dist/storage/manager/session-manager.d.ts.map +1 -0
- package/dist/storage/manager/types.d.ts +42 -0
- package/dist/storage/manager/types.d.ts.map +1 -0
- package/dist/storage/memory.d.ts +22 -0
- package/dist/storage/memory.d.ts.map +1 -0
- package/dist/storage/paths.d.ts +37 -0
- package/dist/storage/paths.d.ts.map +1 -0
- package/dist/storage/types.d.ts +205 -0
- package/dist/storage/types.d.ts.map +1 -0
- package/dist/storage/utils.d.ts +77 -0
- package/dist/storage/utils.d.ts.map +1 -0
- package/dist/subagents/index.d.ts +8 -179
- package/dist/subagents/index.d.ts.map +1 -0
- package/dist/subagents/index.js +5 -4
- package/dist/subagents/installation.d.ts +23 -0
- package/dist/subagents/installation.d.ts.map +1 -0
- package/dist/subagents/results.d.ts +15 -0
- package/dist/subagents/results.d.ts.map +1 -0
- package/dist/subagents/roles/discovery.d.ts +38 -0
- package/dist/subagents/roles/discovery.d.ts.map +1 -0
- package/dist/subagents/roles/index.d.ts +5 -0
- package/dist/subagents/roles/index.d.ts.map +1 -0
- package/dist/subagents/roles/markdown-profile.d.ts +61 -0
- package/dist/subagents/roles/markdown-profile.d.ts.map +1 -0
- package/dist/subagents/tool-factories.d.ts +11 -0
- package/dist/subagents/tool-factories.d.ts.map +1 -0
- package/dist/subagents/tools.d.ts +13 -0
- package/dist/subagents/tools.d.ts.map +1 -0
- package/dist/subagents/types.d.ts +21 -0
- package/dist/subagents/types.d.ts.map +1 -0
- package/dist/team/coordinator/coordinator.d.ts +342 -0
- package/dist/team/coordinator/coordinator.d.ts.map +1 -0
- package/dist/team/coordinator/inbox.d.ts +99 -0
- package/dist/team/coordinator/inbox.d.ts.map +1 -0
- package/dist/team/coordinator/index.d.ts +19 -0
- package/dist/team/coordinator/index.d.ts.map +1 -0
- package/dist/team/coordinator/planning.d.ts +33 -0
- package/dist/team/coordinator/planning.d.ts.map +1 -0
- package/dist/team/coordinator/policy.d.ts +31 -0
- package/dist/team/coordinator/policy.d.ts.map +1 -0
- package/dist/team/coordinator/round-engine.d.ts +25 -0
- package/dist/team/coordinator/round-engine.d.ts.map +1 -0
- package/dist/team/coordinator/synthesis.d.ts +20 -0
- package/dist/team/coordinator/synthesis.d.ts.map +1 -0
- package/dist/team/coordinator/turn.d.ts +107 -0
- package/dist/team/coordinator/turn.d.ts.map +1 -0
- package/dist/team/coordinator/types.d.ts +344 -0
- package/dist/team/coordinator/types.d.ts.map +1 -0
- package/dist/team/events.d.ts +148 -0
- package/dist/team/events.d.ts.map +1 -0
- package/dist/team/execution.d.ts +51 -0
- package/dist/team/execution.d.ts.map +1 -0
- package/dist/team/index.d.ts +23 -545
- package/dist/team/index.d.ts.map +1 -0
- package/dist/team/index.js +2 -2
- package/dist/team/mailbox.d.ts +91 -0
- package/dist/team/mailbox.d.ts.map +1 -0
- package/dist/team/notifications.d.ts +23 -0
- package/dist/team/notifications.d.ts.map +1 -0
- package/dist/team/permissions.d.ts +88 -0
- package/dist/team/permissions.d.ts.map +1 -0
- package/dist/team/shutdown.d.ts +38 -0
- package/dist/team/shutdown.d.ts.map +1 -0
- package/dist/team/task-board.d.ts +161 -0
- package/dist/team/task-board.d.ts.map +1 -0
- package/dist/team/types.d.ts +233 -0
- package/dist/team/types.d.ts.map +1 -0
- package/dist/team/work-loop.d.ts +30 -0
- package/dist/team/work-loop.d.ts.map +1 -0
- package/dist/tool/executor.d.ts +59 -0
- package/dist/tool/executor.d.ts.map +1 -0
- package/dist/tool/host/index.d.ts +7 -38
- package/dist/tool/host/index.d.ts.map +1 -0
- package/dist/tool/host/local.d.ts +15 -0
- package/dist/tool/host/local.d.ts.map +1 -0
- package/dist/tool/host/registry.d.ts +17 -0
- package/dist/tool/host/registry.d.ts.map +1 -0
- package/dist/{types-C_LCeYNg.d.ts → tool/host/types.d.ts} +6 -7
- package/dist/tool/host/types.d.ts.map +1 -0
- package/dist/tool/index.d.ts +21 -285
- package/dist/tool/index.d.ts.map +1 -0
- package/dist/tool/index.js +4 -3
- package/dist/tool/registry.d.ts +130 -0
- package/dist/tool/registry.d.ts.map +1 -0
- package/dist/tool/replay.d.ts +11 -0
- package/dist/tool/replay.d.ts.map +1 -0
- package/dist/tool/tool-search.d.ts +50 -0
- package/dist/tool/tool-search.d.ts.map +1 -0
- package/dist/tool/tool.d.ts +308 -0
- package/dist/tool/tool.d.ts.map +1 -0
- package/dist/tool/truncation.d.ts +34 -0
- package/dist/tool/truncation.d.ts.map +1 -0
- package/dist/tool/turn-tools.d.ts +71 -0
- package/dist/tool/turn-tools.d.ts.map +1 -0
- package/dist/tracking/file-tracking.d.ts +25 -0
- package/dist/tracking/file-tracking.d.ts.map +1 -0
- package/dist/tracking/index.d.ts +9 -0
- package/dist/tracking/index.d.ts.map +1 -0
- package/dist/tracking/turn-tracker/diff.d.ts +11 -0
- package/dist/tracking/turn-tracker/diff.d.ts.map +1 -0
- package/dist/tracking/turn-tracker/index.d.ts +11 -0
- package/dist/tracking/turn-tracker/index.d.ts.map +1 -0
- package/dist/tracking/turn-tracker/tracker.d.ts +31 -0
- package/dist/tracking/turn-tracker/tracker.d.ts.map +1 -0
- package/dist/tracking/turn-tracker/types.d.ts +66 -0
- package/dist/tracking/turn-tracker/types.d.ts.map +1 -0
- package/dist/types/compaction.d.ts +142 -0
- package/dist/types/compaction.d.ts.map +1 -0
- package/dist/types/doom-loop.d.ts +25 -0
- package/dist/types/doom-loop.d.ts.map +1 -0
- package/dist/types/events.d.ts +194 -0
- package/dist/types/events.d.ts.map +1 -0
- package/dist/types/index.d.ts +17 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/messages.d.ts +119 -0
- package/dist/types/messages.d.ts.map +1 -0
- package/dist/types/stream.d.ts +172 -0
- package/dist/types/stream.d.ts.map +1 -0
- package/dist/types/tool.d.ts +309 -0
- package/dist/types/tool.d.ts.map +1 -0
- package/dist/types/turn-source.d.ts +36 -0
- package/dist/types/turn-source.d.ts.map +1 -0
- package/dist/utils/sleep.d.ts +7 -0
- package/dist/utils/sleep.d.ts.map +1 -0
- package/package.json +45 -8
- package/dist/chunk-CJI7PVS2.js +0 -58
- package/dist/chunk-V6ETEYST.js +0 -2091
- package/dist/index-BCqEGzBj.d.ts +0 -251
- package/dist/instance-Bg61WSyz.d.ts +0 -6004
- package/dist/llm-error-D93FNNLY.d.ts +0 -32
- package/dist/turn-tools/index.d.ts +0 -12
- package/dist/turn-tools/index.js +0 -1
- package/dist/{chunk-O2WCYSXQ.js → chunk-3NBTQHVV.js} +0 -0
- package/dist/{chunk-Q742PSH3.js → chunk-MJML3A2F.js} +36 -36
package/dist/chunk-V6ETEYST.js
DELETED
|
@@ -1,2091 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
Inference,
|
|
3
|
-
buildModelCallContext
|
|
4
|
-
} from "./chunk-NS7D7JJU.js";
|
|
5
|
-
import {
|
|
6
|
-
currentScope,
|
|
7
|
-
executeAgentToolCall,
|
|
8
|
-
snapshotScope,
|
|
9
|
-
streamWithinScope,
|
|
10
|
-
withinScope
|
|
11
|
-
} from "./chunk-MWPU2EVV.js";
|
|
12
|
-
import {
|
|
13
|
-
LLMError
|
|
14
|
-
} from "./chunk-STDJYXYK.js";
|
|
15
|
-
import {
|
|
16
|
-
extractModelId,
|
|
17
|
-
extractProvider
|
|
18
|
-
} from "./chunk-I6PKJ7XQ.js";
|
|
19
|
-
import {
|
|
20
|
-
resolveCapability
|
|
21
|
-
} from "./chunk-FII65CN7.js";
|
|
22
|
-
import {
|
|
23
|
-
silentLogger
|
|
24
|
-
} from "./chunk-S6AKEPAX.js";
|
|
25
|
-
|
|
26
|
-
// src/execution/task/observer.ts
|
|
27
|
-
function defaultAgentTaskCheckpointStrategy(input) {
|
|
28
|
-
switch (input.event.type) {
|
|
29
|
-
case "step-finish":
|
|
30
|
-
return "step-finish";
|
|
31
|
-
case "tool-result":
|
|
32
|
-
return "tool-result";
|
|
33
|
-
case "tool-error":
|
|
34
|
-
return "tool-error";
|
|
35
|
-
case "turn-boundary":
|
|
36
|
-
return input.event.boundary;
|
|
37
|
-
case "complete":
|
|
38
|
-
return "task-complete";
|
|
39
|
-
default:
|
|
40
|
-
return void 0;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// src/execution/task/runner.ts
|
|
45
|
-
import { randomUUID } from "crypto";
|
|
46
|
-
|
|
47
|
-
// src/execution/clone-usage.ts
|
|
48
|
-
function cloneUsage(usage) {
|
|
49
|
-
return { ...usage };
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// src/execution/turn-state.ts
|
|
53
|
-
var EMPTY_USAGE = {
|
|
54
|
-
inputTokens: 0,
|
|
55
|
-
outputTokens: 0,
|
|
56
|
-
totalTokens: 0
|
|
57
|
-
};
|
|
58
|
-
function normalizeUsage(usage) {
|
|
59
|
-
if (!usage) {
|
|
60
|
-
return cloneUsage(EMPTY_USAGE);
|
|
61
|
-
}
|
|
62
|
-
return {
|
|
63
|
-
inputTokens: usage.inputTokens ?? 0,
|
|
64
|
-
outputTokens: usage.outputTokens ?? 0,
|
|
65
|
-
totalTokens: usage.totalTokens ?? 0
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
function removeActiveToolCall(toolCalls, toolCallId) {
|
|
69
|
-
return toolCalls.filter((toolCall) => toolCall.toolCallId !== toolCallId);
|
|
70
|
-
}
|
|
71
|
-
function createAgentTurnState(options) {
|
|
72
|
-
const restore = options.restoreFrom;
|
|
73
|
-
return {
|
|
74
|
-
sessionId: options.sessionId,
|
|
75
|
-
phase: "initializing",
|
|
76
|
-
step: restore?.step ?? 0,
|
|
77
|
-
response: restore?.response ?? "",
|
|
78
|
-
usage: restore?.usage ? cloneUsage(restore.usage) : cloneUsage(EMPTY_USAGE),
|
|
79
|
-
eventCount: restore?.eventCount ?? 0,
|
|
80
|
-
activeToolCalls: [],
|
|
81
|
-
resolvedToolCalls: [],
|
|
82
|
-
startedAt: options.startedAt,
|
|
83
|
-
updatedAt: options.startedAt
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
function advanceAgentTurnState(state, event, updatedAt, options = {}) {
|
|
87
|
-
const next = {
|
|
88
|
-
...state,
|
|
89
|
-
usage: cloneUsage(state.usage),
|
|
90
|
-
activeToolCalls: state.activeToolCalls.map((toolCall) => ({ ...toolCall })),
|
|
91
|
-
resolvedToolCalls: state.resolvedToolCalls.map((toolCall) => ({
|
|
92
|
-
...toolCall,
|
|
93
|
-
...toolCall.metadata ? { metadata: structuredClone(toolCall.metadata) } : {}
|
|
94
|
-
})),
|
|
95
|
-
eventCount: state.eventCount + 1,
|
|
96
|
-
lastEvent: event,
|
|
97
|
-
updatedAt
|
|
98
|
-
};
|
|
99
|
-
switch (event.type) {
|
|
100
|
-
case "step-start":
|
|
101
|
-
next.phase = "running-model";
|
|
102
|
-
next.step = event.step;
|
|
103
|
-
next.maxSteps = event.maxSteps;
|
|
104
|
-
next.activeToolCalls = [];
|
|
105
|
-
next.resolvedToolCalls = [];
|
|
106
|
-
next.lastFinishReason = void 0;
|
|
107
|
-
delete next.error;
|
|
108
|
-
break;
|
|
109
|
-
case "text-delta":
|
|
110
|
-
next.response += event.text;
|
|
111
|
-
break;
|
|
112
|
-
case "tool-start":
|
|
113
|
-
next.phase = "running-tools";
|
|
114
|
-
next.activeToolCalls = [
|
|
115
|
-
...removeActiveToolCall(next.activeToolCalls, event.toolCallId),
|
|
116
|
-
{
|
|
117
|
-
toolCallId: event.toolCallId,
|
|
118
|
-
toolName: event.toolName,
|
|
119
|
-
input: event.input,
|
|
120
|
-
startedAt: updatedAt,
|
|
121
|
-
...options.toolReplayPolicy ? { replayPolicy: options.toolReplayPolicy } : {}
|
|
122
|
-
}
|
|
123
|
-
];
|
|
124
|
-
break;
|
|
125
|
-
case "tool-result":
|
|
126
|
-
next.phase = "running-tools";
|
|
127
|
-
next.activeToolCalls = removeActiveToolCall(
|
|
128
|
-
next.activeToolCalls,
|
|
129
|
-
event.toolCallId
|
|
130
|
-
);
|
|
131
|
-
next.resolvedToolCalls = [
|
|
132
|
-
...next.resolvedToolCalls,
|
|
133
|
-
{
|
|
134
|
-
toolCallId: event.toolCallId,
|
|
135
|
-
toolName: event.toolName,
|
|
136
|
-
outcome: "result",
|
|
137
|
-
value: event.result,
|
|
138
|
-
...event.metadata ? { metadata: structuredClone(event.metadata) } : {},
|
|
139
|
-
resolvedAt: updatedAt,
|
|
140
|
-
...options.toolReplayPolicy ? { replayPolicy: options.toolReplayPolicy } : {}
|
|
141
|
-
}
|
|
142
|
-
];
|
|
143
|
-
break;
|
|
144
|
-
case "tool-error":
|
|
145
|
-
next.phase = "running-tools";
|
|
146
|
-
next.activeToolCalls = removeActiveToolCall(
|
|
147
|
-
next.activeToolCalls,
|
|
148
|
-
event.toolCallId
|
|
149
|
-
);
|
|
150
|
-
next.resolvedToolCalls = [
|
|
151
|
-
...next.resolvedToolCalls,
|
|
152
|
-
{
|
|
153
|
-
toolCallId: event.toolCallId,
|
|
154
|
-
toolName: event.toolName,
|
|
155
|
-
outcome: "error",
|
|
156
|
-
value: event.error,
|
|
157
|
-
resolvedAt: updatedAt,
|
|
158
|
-
...options.toolReplayPolicy ? { replayPolicy: options.toolReplayPolicy } : {}
|
|
159
|
-
}
|
|
160
|
-
];
|
|
161
|
-
break;
|
|
162
|
-
case "step-finish":
|
|
163
|
-
next.phase = "committing-step";
|
|
164
|
-
next.step = event.step;
|
|
165
|
-
next.usage = normalizeUsage(event.usage ?? next.usage);
|
|
166
|
-
next.lastFinishReason = event.finishReason;
|
|
167
|
-
break;
|
|
168
|
-
case "turn-boundary":
|
|
169
|
-
next.lastBoundary = {
|
|
170
|
-
kind: event.boundary,
|
|
171
|
-
createdAt: updatedAt,
|
|
172
|
-
...event.step !== void 0 ? { step: event.step } : {},
|
|
173
|
-
...event.messageRole ? { messageRole: event.messageRole } : {},
|
|
174
|
-
...event.pendingToolCallCount !== void 0 ? { pendingToolCallCount: event.pendingToolCallCount } : {}
|
|
175
|
-
};
|
|
176
|
-
switch (event.boundary) {
|
|
177
|
-
case "input-commit-start":
|
|
178
|
-
case "input-commit-finish":
|
|
179
|
-
case "intervention-commit-start":
|
|
180
|
-
case "intervention-commit-finish":
|
|
181
|
-
next.phase = "committing-input";
|
|
182
|
-
break;
|
|
183
|
-
case "step-commit-start":
|
|
184
|
-
case "step-commit-finish":
|
|
185
|
-
next.phase = "committing-step";
|
|
186
|
-
break;
|
|
187
|
-
case "output-commit-start":
|
|
188
|
-
case "output-commit-finish":
|
|
189
|
-
next.phase = "committing-output";
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
break;
|
|
193
|
-
case "complete":
|
|
194
|
-
next.phase = "completed";
|
|
195
|
-
next.usage = normalizeUsage(event.usage ?? next.usage);
|
|
196
|
-
break;
|
|
197
|
-
case "error":
|
|
198
|
-
next.phase = "failed";
|
|
199
|
-
next.error = event.error.message;
|
|
200
|
-
break;
|
|
201
|
-
default:
|
|
202
|
-
break;
|
|
203
|
-
}
|
|
204
|
-
return next;
|
|
205
|
-
}
|
|
206
|
-
function failAgentTurnState(state, error, updatedAt) {
|
|
207
|
-
return {
|
|
208
|
-
...state,
|
|
209
|
-
usage: cloneUsage(state.usage),
|
|
210
|
-
activeToolCalls: state.activeToolCalls.map((toolCall) => ({ ...toolCall })),
|
|
211
|
-
resolvedToolCalls: state.resolvedToolCalls.map((toolCall) => ({
|
|
212
|
-
...toolCall,
|
|
213
|
-
...toolCall.metadata ? { metadata: structuredClone(toolCall.metadata) } : {}
|
|
214
|
-
})),
|
|
215
|
-
phase: "failed",
|
|
216
|
-
error: error.message,
|
|
217
|
-
updatedAt
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// src/execution/task/runner.ts
|
|
222
|
-
function normalizeNonEmpty(value, label) {
|
|
223
|
-
const normalized = value.trim();
|
|
224
|
-
if (!normalized) {
|
|
225
|
-
throw new Error(`${label} must not be empty`);
|
|
226
|
-
}
|
|
227
|
-
return normalized;
|
|
228
|
-
}
|
|
229
|
-
function sanitizeSegment(input) {
|
|
230
|
-
return input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
|
231
|
-
}
|
|
232
|
-
function buildRuntimeSessionId(prefix, key) {
|
|
233
|
-
const timestamp = Date.now().toString(36);
|
|
234
|
-
const suffix = randomUUID().slice(0, 8);
|
|
235
|
-
const normalizedPrefix = sanitizeSegment(prefix) || "runtime";
|
|
236
|
-
const normalizedKey = key ? sanitizeSegment(key) : "";
|
|
237
|
-
if (normalizedKey) {
|
|
238
|
-
return `${normalizedPrefix}:${normalizedKey}:${timestamp}:${suffix}`;
|
|
239
|
-
}
|
|
240
|
-
return `${normalizedPrefix}:${timestamp}:${suffix}`;
|
|
241
|
-
}
|
|
242
|
-
function nowIso() {
|
|
243
|
-
return (/* @__PURE__ */ new Date()).toISOString();
|
|
244
|
-
}
|
|
245
|
-
async function notifyObservers(observers, invoke, logger) {
|
|
246
|
-
for (const observer of observers) {
|
|
247
|
-
try {
|
|
248
|
-
await invoke(observer);
|
|
249
|
-
} catch (error) {
|
|
250
|
-
logger.warn("observer error", {
|
|
251
|
-
error: error instanceof Error ? error.message : String(error)
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
function createAgentTaskRunner(agent, options = {}) {
|
|
257
|
-
const prefix = options.sessionPrefix ?? "runtime";
|
|
258
|
-
const baseObservers = options.observers ?? [];
|
|
259
|
-
const checkpointStrategy = options.checkpointStrategy ?? defaultAgentTaskCheckpointStrategy;
|
|
260
|
-
const log = options.logger?.child("task-runner") ?? silentLogger;
|
|
261
|
-
return async (payload, context = {}) => {
|
|
262
|
-
const message = normalizeNonEmpty(payload.message, "payload.message");
|
|
263
|
-
const resolvedSessionId = payload.sessionId?.trim() || options.resolveSessionId?.(payload, context)?.trim() || buildRuntimeSessionId(prefix, context.fallbackSessionKey);
|
|
264
|
-
const sessionId = normalizeNonEmpty(resolvedSessionId, "sessionId");
|
|
265
|
-
const startedAt = nowIso();
|
|
266
|
-
const executionId = context.executionId?.trim() || `${sessionId}:${startedAt}`;
|
|
267
|
-
return withinScope(
|
|
268
|
-
{
|
|
269
|
-
kind: "task",
|
|
270
|
-
name: "agent-task",
|
|
271
|
-
sessionId,
|
|
272
|
-
taskId: context.fallbackSessionKey ?? sessionId,
|
|
273
|
-
attributes: {
|
|
274
|
-
...context.trigger ? { trigger: context.trigger } : {}
|
|
275
|
-
}
|
|
276
|
-
},
|
|
277
|
-
async () => {
|
|
278
|
-
const run = {
|
|
279
|
-
payload,
|
|
280
|
-
context,
|
|
281
|
-
sessionId,
|
|
282
|
-
executionId,
|
|
283
|
-
startedAt: context.restoreFrom?.startedAt ?? startedAt,
|
|
284
|
-
scope: snapshotScope()
|
|
285
|
-
};
|
|
286
|
-
const toolCalls = context.restoreFrom?.toolCalls.map((tc) => ({ ...tc })) ?? [];
|
|
287
|
-
let turnState = createAgentTurnState({
|
|
288
|
-
sessionId,
|
|
289
|
-
startedAt: context.restoreFrom?.startedAt ?? startedAt,
|
|
290
|
-
restoreFrom: context.restoreFrom ? {
|
|
291
|
-
response: context.restoreFrom.response,
|
|
292
|
-
usage: { ...context.restoreFrom.usage },
|
|
293
|
-
step: context.restoreFrom.step,
|
|
294
|
-
eventCount: context.restoreFrom.eventCount
|
|
295
|
-
} : void 0
|
|
296
|
-
});
|
|
297
|
-
const createSnapshot = () => ({
|
|
298
|
-
sessionId,
|
|
299
|
-
response: turnState.response,
|
|
300
|
-
usage: { ...turnState.usage },
|
|
301
|
-
toolCalls: toolCalls.map((toolCall) => ({ ...toolCall })),
|
|
302
|
-
eventCount: turnState.eventCount,
|
|
303
|
-
activeStep: turnState.step > 0 ? turnState.step : void 0,
|
|
304
|
-
lastEvent: turnState.lastEvent,
|
|
305
|
-
error: turnState.error,
|
|
306
|
-
startedAt: turnState.startedAt,
|
|
307
|
-
updatedAt: turnState.updatedAt,
|
|
308
|
-
turnState,
|
|
309
|
-
scope: currentScope() ?? run.scope
|
|
310
|
-
});
|
|
311
|
-
const emitCheckpoint = async (reason, event) => {
|
|
312
|
-
if (baseObservers.length === 0) {
|
|
313
|
-
return;
|
|
314
|
-
}
|
|
315
|
-
const checkpoint = {
|
|
316
|
-
run,
|
|
317
|
-
reason,
|
|
318
|
-
snapshot: createSnapshot(),
|
|
319
|
-
event,
|
|
320
|
-
createdAt: turnState.updatedAt
|
|
321
|
-
};
|
|
322
|
-
await notifyObservers(
|
|
323
|
-
baseObservers,
|
|
324
|
-
async (observer) => {
|
|
325
|
-
await observer.onCheckpoint?.(checkpoint);
|
|
326
|
-
},
|
|
327
|
-
log
|
|
328
|
-
);
|
|
329
|
-
};
|
|
330
|
-
await notifyObservers(
|
|
331
|
-
baseObservers,
|
|
332
|
-
async (observer) => {
|
|
333
|
-
await observer.onTaskStart?.(run, createSnapshot());
|
|
334
|
-
},
|
|
335
|
-
log
|
|
336
|
-
);
|
|
337
|
-
await emitCheckpoint("task-start");
|
|
338
|
-
const activateCtx = baseObservers.find((o) => o.activateContext)?.activateContext?.bind(void 0, sessionId, executionId);
|
|
339
|
-
try {
|
|
340
|
-
const processChatStream = async () => {
|
|
341
|
-
for await (const event of agent.chat(sessionId, message, {
|
|
342
|
-
abort: context.signal,
|
|
343
|
-
system: payload.system
|
|
344
|
-
})) {
|
|
345
|
-
turnState = advanceAgentTurnState(turnState, event, nowIso());
|
|
346
|
-
if (event.type === "tool-result") {
|
|
347
|
-
toolCalls.push({ name: event.toolName, result: event.result });
|
|
348
|
-
}
|
|
349
|
-
const snapshot = createSnapshot();
|
|
350
|
-
await notifyObservers(
|
|
351
|
-
baseObservers,
|
|
352
|
-
async (observer) => {
|
|
353
|
-
await observer.onTaskEvent?.(run, event, snapshot);
|
|
354
|
-
},
|
|
355
|
-
log
|
|
356
|
-
);
|
|
357
|
-
const checkpointReason = checkpointStrategy({
|
|
358
|
-
run,
|
|
359
|
-
event,
|
|
360
|
-
snapshot
|
|
361
|
-
});
|
|
362
|
-
if (checkpointReason) {
|
|
363
|
-
await emitCheckpoint(checkpointReason, event);
|
|
364
|
-
}
|
|
365
|
-
if (event.type === "error") {
|
|
366
|
-
throw event.error;
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
};
|
|
370
|
-
if (activateCtx) {
|
|
371
|
-
await activateCtx(processChatStream);
|
|
372
|
-
} else {
|
|
373
|
-
await processChatStream();
|
|
374
|
-
}
|
|
375
|
-
const result = {
|
|
376
|
-
response: turnState.response,
|
|
377
|
-
sessionId,
|
|
378
|
-
usage: { ...turnState.usage },
|
|
379
|
-
toolCalls
|
|
380
|
-
};
|
|
381
|
-
await notifyObservers(
|
|
382
|
-
baseObservers,
|
|
383
|
-
async (observer) => {
|
|
384
|
-
await observer.onTaskComplete?.(run, result, createSnapshot());
|
|
385
|
-
},
|
|
386
|
-
log
|
|
387
|
-
);
|
|
388
|
-
return result;
|
|
389
|
-
} catch (error) {
|
|
390
|
-
const normalizedError = error instanceof Error ? error : new Error(String(error));
|
|
391
|
-
turnState = failAgentTurnState(turnState, normalizedError, nowIso());
|
|
392
|
-
await notifyObservers(
|
|
393
|
-
baseObservers,
|
|
394
|
-
async (observer) => {
|
|
395
|
-
await observer.onTaskError?.(
|
|
396
|
-
run,
|
|
397
|
-
normalizedError,
|
|
398
|
-
createSnapshot()
|
|
399
|
-
);
|
|
400
|
-
},
|
|
401
|
-
log
|
|
402
|
-
);
|
|
403
|
-
await emitCheckpoint("task-error");
|
|
404
|
-
throw normalizedError;
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
);
|
|
408
|
-
};
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
// src/execution/turn-engine/commit-batch.ts
|
|
412
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
413
|
-
function createAgentTurnBoundaryEvent(boundary, metadata = {}) {
|
|
414
|
-
return {
|
|
415
|
-
type: "turn-boundary",
|
|
416
|
-
boundary,
|
|
417
|
-
...metadata.step !== void 0 ? { step: metadata.step } : {},
|
|
418
|
-
...metadata.messageRole ? { messageRole: metadata.messageRole } : {},
|
|
419
|
-
...metadata.pendingToolCallCount !== void 0 ? { pendingToolCallCount: metadata.pendingToolCallCount } : {}
|
|
420
|
-
};
|
|
421
|
-
}
|
|
422
|
-
function createAgentTurnStepCommitBatch(step, snapshot, options = {}) {
|
|
423
|
-
if (snapshot.toolCalls.length === 0) {
|
|
424
|
-
return void 0;
|
|
425
|
-
}
|
|
426
|
-
const createdAt = options.createdAt ?? /* @__PURE__ */ new Date();
|
|
427
|
-
const assistantMessage = {
|
|
428
|
-
id: options.assistantMessageId ?? randomUUID2(),
|
|
429
|
-
role: "assistant",
|
|
430
|
-
content: "",
|
|
431
|
-
finish: "tool-calls",
|
|
432
|
-
toolCalls: snapshot.toolCalls.map(({ toolCallId, toolName, args }) => ({
|
|
433
|
-
toolCallId,
|
|
434
|
-
toolName,
|
|
435
|
-
args
|
|
436
|
-
})),
|
|
437
|
-
createdAt
|
|
438
|
-
};
|
|
439
|
-
const toolMessages = snapshot.toolResults.map(
|
|
440
|
-
({ toolCallId, toolName, result, metadata }) => ({
|
|
441
|
-
id: options.toolMessageIds?.[toolCallId] ?? randomUUID2(),
|
|
442
|
-
role: "tool",
|
|
443
|
-
content: typeof result === "string" ? result : JSON.stringify(result),
|
|
444
|
-
toolCallId,
|
|
445
|
-
toolName,
|
|
446
|
-
result,
|
|
447
|
-
...metadata ? { metadata } : {},
|
|
448
|
-
createdAt
|
|
449
|
-
})
|
|
450
|
-
);
|
|
451
|
-
return {
|
|
452
|
-
startBoundary: createAgentTurnBoundaryEvent("step-commit-start", {
|
|
453
|
-
step,
|
|
454
|
-
pendingToolCallCount: snapshot.toolCalls.length
|
|
455
|
-
}),
|
|
456
|
-
finishBoundary: createAgentTurnBoundaryEvent("step-commit-finish", {
|
|
457
|
-
step
|
|
458
|
-
}),
|
|
459
|
-
messages: [assistantMessage, ...toolMessages]
|
|
460
|
-
};
|
|
461
|
-
}
|
|
462
|
-
function createAgentTurnInputCommit(options) {
|
|
463
|
-
const message = {
|
|
464
|
-
id: options.id ?? randomUUID2(),
|
|
465
|
-
role: "user",
|
|
466
|
-
content: options.content,
|
|
467
|
-
createdAt: options.createdAt ?? /* @__PURE__ */ new Date(),
|
|
468
|
-
...options.system ? { system: options.system } : {}
|
|
469
|
-
};
|
|
470
|
-
return {
|
|
471
|
-
startBoundary: createAgentTurnBoundaryEvent("input-commit-start", {
|
|
472
|
-
messageRole: "user"
|
|
473
|
-
}),
|
|
474
|
-
finishBoundary: createAgentTurnBoundaryEvent("input-commit-finish", {
|
|
475
|
-
messageRole: "user"
|
|
476
|
-
}),
|
|
477
|
-
messages: [message]
|
|
478
|
-
};
|
|
479
|
-
}
|
|
480
|
-
function createAgentTurnInterventionCommit(options) {
|
|
481
|
-
const message = {
|
|
482
|
-
id: options.id,
|
|
483
|
-
role: "user",
|
|
484
|
-
content: options.content,
|
|
485
|
-
createdAt: options.createdAt ?? /* @__PURE__ */ new Date()
|
|
486
|
-
};
|
|
487
|
-
return {
|
|
488
|
-
startBoundary: createAgentTurnBoundaryEvent("intervention-commit-start", {
|
|
489
|
-
messageRole: "user"
|
|
490
|
-
}),
|
|
491
|
-
finishBoundary: createAgentTurnBoundaryEvent("intervention-commit-finish", {
|
|
492
|
-
messageRole: "user"
|
|
493
|
-
}),
|
|
494
|
-
messages: [message]
|
|
495
|
-
};
|
|
496
|
-
}
|
|
497
|
-
function createAgentTurnOutputCommit(options) {
|
|
498
|
-
if (!options.text) {
|
|
499
|
-
return void 0;
|
|
500
|
-
}
|
|
501
|
-
const message = {
|
|
502
|
-
id: options.id ?? randomUUID2(),
|
|
503
|
-
role: "assistant",
|
|
504
|
-
content: options.text,
|
|
505
|
-
...options.usage ? { tokens: options.usage } : {},
|
|
506
|
-
createdAt: options.createdAt ?? /* @__PURE__ */ new Date()
|
|
507
|
-
};
|
|
508
|
-
return {
|
|
509
|
-
startBoundary: createAgentTurnBoundaryEvent("output-commit-start", {
|
|
510
|
-
messageRole: "assistant"
|
|
511
|
-
}),
|
|
512
|
-
finishBoundary: createAgentTurnBoundaryEvent("output-commit-finish", {
|
|
513
|
-
messageRole: "assistant"
|
|
514
|
-
}),
|
|
515
|
-
messages: [message]
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// src/execution/turn-engine/engine.ts
|
|
520
|
-
var AgentTurnEngine = class {
|
|
521
|
-
turnState;
|
|
522
|
-
pendingToolCalls = /* @__PURE__ */ new Map();
|
|
523
|
-
pendingToolResults = /* @__PURE__ */ new Map();
|
|
524
|
-
getToolReplayPolicy;
|
|
525
|
-
constructor(options) {
|
|
526
|
-
this.turnState = createAgentTurnState({
|
|
527
|
-
sessionId: options.sessionId,
|
|
528
|
-
startedAt: options.startedAt
|
|
529
|
-
});
|
|
530
|
-
this.getToolReplayPolicy = options.getToolReplayPolicy;
|
|
531
|
-
}
|
|
532
|
-
getState() {
|
|
533
|
-
return structuredClone(this.turnState);
|
|
534
|
-
}
|
|
535
|
-
hasPendingToolCalls() {
|
|
536
|
-
return this.pendingToolCalls.size > 0;
|
|
537
|
-
}
|
|
538
|
-
createStepCommitSnapshot() {
|
|
539
|
-
if (this.pendingToolCalls.size === 0) {
|
|
540
|
-
return void 0;
|
|
541
|
-
}
|
|
542
|
-
return {
|
|
543
|
-
toolCalls: Array.from(this.pendingToolCalls.entries()).map(
|
|
544
|
-
([toolCallId, { toolName, input, replayPolicy }]) => ({
|
|
545
|
-
toolCallId,
|
|
546
|
-
toolName,
|
|
547
|
-
args: input,
|
|
548
|
-
...replayPolicy ? { replayPolicy } : {}
|
|
549
|
-
})
|
|
550
|
-
),
|
|
551
|
-
toolResults: Array.from(this.pendingToolCalls.entries()).map(([toolCallId, { toolName, replayPolicy }]) => {
|
|
552
|
-
const resultData = this.pendingToolResults.get(toolCallId);
|
|
553
|
-
if (!resultData) {
|
|
554
|
-
return void 0;
|
|
555
|
-
}
|
|
556
|
-
return {
|
|
557
|
-
toolCallId,
|
|
558
|
-
toolName,
|
|
559
|
-
result: resultData.result,
|
|
560
|
-
...resultData.metadata ? { metadata: resultData.metadata } : {},
|
|
561
|
-
...replayPolicy ? { replayPolicy } : {}
|
|
562
|
-
};
|
|
563
|
-
}).filter((result) => result !== void 0)
|
|
564
|
-
};
|
|
565
|
-
}
|
|
566
|
-
recordEvent(event, updatedAt) {
|
|
567
|
-
const toolReplayPolicy = "toolName" in event ? this.getToolReplayPolicy?.(event.toolName) : void 0;
|
|
568
|
-
this.turnState = advanceAgentTurnState(this.turnState, event, updatedAt, {
|
|
569
|
-
toolReplayPolicy
|
|
570
|
-
});
|
|
571
|
-
switch (event.type) {
|
|
572
|
-
case "tool-start":
|
|
573
|
-
this.pendingToolCalls.set(event.toolCallId, {
|
|
574
|
-
toolName: event.toolName,
|
|
575
|
-
input: event.input,
|
|
576
|
-
replayPolicy: toolReplayPolicy
|
|
577
|
-
});
|
|
578
|
-
break;
|
|
579
|
-
case "tool-result":
|
|
580
|
-
this.pendingToolResults.set(event.toolCallId, {
|
|
581
|
-
toolName: event.toolName,
|
|
582
|
-
result: event.result,
|
|
583
|
-
...event.metadata ? { metadata: event.metadata } : {},
|
|
584
|
-
replayPolicy: toolReplayPolicy
|
|
585
|
-
});
|
|
586
|
-
break;
|
|
587
|
-
case "tool-error":
|
|
588
|
-
this.pendingToolResults.set(event.toolCallId, {
|
|
589
|
-
toolName: event.toolName,
|
|
590
|
-
result: `Error: ${event.error}`,
|
|
591
|
-
replayPolicy: toolReplayPolicy
|
|
592
|
-
});
|
|
593
|
-
break;
|
|
594
|
-
default:
|
|
595
|
-
break;
|
|
596
|
-
}
|
|
597
|
-
return this.getState();
|
|
598
|
-
}
|
|
599
|
-
createBoundaryEvent(boundary, metadata = {}) {
|
|
600
|
-
return createAgentTurnBoundaryEvent(boundary, metadata);
|
|
601
|
-
}
|
|
602
|
-
createInputCommit(options) {
|
|
603
|
-
return createAgentTurnInputCommit(options);
|
|
604
|
-
}
|
|
605
|
-
createInterventionCommit(options) {
|
|
606
|
-
return createAgentTurnInterventionCommit(options);
|
|
607
|
-
}
|
|
608
|
-
consumeStepCommit(step) {
|
|
609
|
-
const snapshot = this.createStepCommitSnapshot();
|
|
610
|
-
const batch = snapshot ? createAgentTurnStepCommitBatch(step, snapshot) : void 0;
|
|
611
|
-
if (!batch) {
|
|
612
|
-
return void 0;
|
|
613
|
-
}
|
|
614
|
-
this.pendingToolCalls.clear();
|
|
615
|
-
this.pendingToolResults.clear();
|
|
616
|
-
return batch;
|
|
617
|
-
}
|
|
618
|
-
createOutputCommit(options) {
|
|
619
|
-
return createAgentTurnOutputCommit(options);
|
|
620
|
-
}
|
|
621
|
-
};
|
|
622
|
-
function createAgentTurnEngine(options) {
|
|
623
|
-
return new AgentTurnEngine(options);
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
// src/agent/context/estimation.ts
|
|
627
|
-
function estimateTokens(text) {
|
|
628
|
-
return Math.ceil(text.length / 4);
|
|
629
|
-
}
|
|
630
|
-
function estimateMessageTokens(message) {
|
|
631
|
-
if (typeof message.content === "string") {
|
|
632
|
-
return estimateTokens(message.content);
|
|
633
|
-
}
|
|
634
|
-
if (Array.isArray(message.content)) {
|
|
635
|
-
let total = 0;
|
|
636
|
-
for (const part of message.content) {
|
|
637
|
-
if (typeof part === "string") {
|
|
638
|
-
total += estimateTokens(part);
|
|
639
|
-
} else if ("text" in part && typeof part.text === "string") {
|
|
640
|
-
total += estimateTokens(part.text);
|
|
641
|
-
} else if ("type" in part && part.type === "image") {
|
|
642
|
-
total += 765;
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
return total;
|
|
646
|
-
}
|
|
647
|
-
return 0;
|
|
648
|
-
}
|
|
649
|
-
function estimateConversationTokens(messages) {
|
|
650
|
-
let total = 0;
|
|
651
|
-
for (const message of messages) {
|
|
652
|
-
total += estimateMessageTokens(message);
|
|
653
|
-
total += 4;
|
|
654
|
-
}
|
|
655
|
-
return total;
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
// src/types/compaction.ts
|
|
659
|
-
var PRUNE_PROTECTED_TOOLS = ["skill"];
|
|
660
|
-
|
|
661
|
-
// src/agent/context/pruning.ts
|
|
662
|
-
var DEFAULT_CONTEXT_LIMITS = {
|
|
663
|
-
contextWindow: 128e3,
|
|
664
|
-
reserveTokens: 16e3,
|
|
665
|
-
// Reserve for output
|
|
666
|
-
protectedTokens: 4e4,
|
|
667
|
-
// Keep recent 40 k tokens
|
|
668
|
-
pruneMinimum: 2e4
|
|
669
|
-
// Don't prune until 20 k tokens
|
|
670
|
-
};
|
|
671
|
-
function getUsableTokenLimit(limits) {
|
|
672
|
-
return limits.contextWindow - limits.reserveTokens;
|
|
673
|
-
}
|
|
674
|
-
function isContextOverflowing(tokens, limits = DEFAULT_CONTEXT_LIMITS) {
|
|
675
|
-
return tokens > getUsableTokenLimit(limits);
|
|
676
|
-
}
|
|
677
|
-
function shouldPruneContext(tokens, limits = DEFAULT_CONTEXT_LIMITS) {
|
|
678
|
-
if (tokens < limits.pruneMinimum) return false;
|
|
679
|
-
return isContextOverflowing(tokens, limits);
|
|
680
|
-
}
|
|
681
|
-
function findCutPoint(messages, protectedTokens = DEFAULT_CONTEXT_LIMITS.protectedTokens) {
|
|
682
|
-
if (messages.length === 0) return 0;
|
|
683
|
-
let tokensFromEnd = 0;
|
|
684
|
-
let cutIndex = messages.length;
|
|
685
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
686
|
-
tokensFromEnd += estimateMessageTokens(messages[i]);
|
|
687
|
-
if (tokensFromEnd >= protectedTokens) {
|
|
688
|
-
cutIndex = i;
|
|
689
|
-
break;
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
if (cutIndex <= 1) return 0;
|
|
693
|
-
const startIndex = cutIndex >= messages.length ? messages.length - 1 : cutIndex;
|
|
694
|
-
for (let i = startIndex; i >= 1; i--) {
|
|
695
|
-
const msg = messages[i];
|
|
696
|
-
const prevMsg = messages[i - 1];
|
|
697
|
-
if (!msg || !prevMsg) continue;
|
|
698
|
-
if (msg.role === "tool") continue;
|
|
699
|
-
if (prevMsg.role === "assistant" || prevMsg.role === "user") {
|
|
700
|
-
return i;
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
return 0;
|
|
704
|
-
}
|
|
705
|
-
function pruneToolResults(messages, protectedTokens = DEFAULT_CONTEXT_LIMITS.protectedTokens, options) {
|
|
706
|
-
const protectedToolSet = /* @__PURE__ */ new Set([
|
|
707
|
-
...PRUNE_PROTECTED_TOOLS,
|
|
708
|
-
...options?.protectedTools ?? []
|
|
709
|
-
]);
|
|
710
|
-
let tokensFromEnd = 0;
|
|
711
|
-
const tokenPositions = [];
|
|
712
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
713
|
-
tokensFromEnd += estimateMessageTokens(messages[i]);
|
|
714
|
-
tokenPositions[i] = tokensFromEnd;
|
|
715
|
-
}
|
|
716
|
-
return messages.map((msg, i) => {
|
|
717
|
-
if (tokenPositions[i] < protectedTokens) return msg;
|
|
718
|
-
if (!("role" in msg) || msg.role !== "tool") return msg;
|
|
719
|
-
const toolMsg = msg;
|
|
720
|
-
if ("compactedAt" in toolMsg && toolMsg.compactedAt) return msg;
|
|
721
|
-
if (toolMsg.toolName && protectedToolSet.has(toolMsg.toolName)) return msg;
|
|
722
|
-
const currentTokens = estimateTokens(toolMsg.content);
|
|
723
|
-
if (currentTokens < 500) return msg;
|
|
724
|
-
return {
|
|
725
|
-
...toolMsg,
|
|
726
|
-
content: `[Output pruned - was ${currentTokens} tokens]`,
|
|
727
|
-
compactedAt: Date.now()
|
|
728
|
-
};
|
|
729
|
-
});
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
// src/agent/context/summarization.ts
|
|
733
|
-
import { generateText } from "ai";
|
|
734
|
-
var DEFAULT_SUMMARY_PROMPT = `You are summarizing a conversation to continue it with context.
|
|
735
|
-
|
|
736
|
-
Create a structured summary that captures:
|
|
737
|
-
1. **Goal**: What the user is trying to accomplish
|
|
738
|
-
2. **Progress**: What has been done so far
|
|
739
|
-
3. **Decisions**: Key decisions made during the conversation
|
|
740
|
-
4. **Current State**: Where we left off
|
|
741
|
-
5. **Next Steps**: What should happen next
|
|
742
|
-
|
|
743
|
-
Be concise but comprehensive. Include specific file paths, function names, and technical details that would be lost otherwise.
|
|
744
|
-
|
|
745
|
-
Format as a clear summary that could be given to another assistant to continue the work.`;
|
|
746
|
-
async function generateSummary(messages, options) {
|
|
747
|
-
const conversationText = messages.map((m) => {
|
|
748
|
-
const role = m.role.toUpperCase();
|
|
749
|
-
const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
|
|
750
|
-
return `[${role}]: ${content}`;
|
|
751
|
-
}).join("\n\n");
|
|
752
|
-
const prompt = options.customPrompt || DEFAULT_SUMMARY_PROMPT;
|
|
753
|
-
const { text } = await generateText({
|
|
754
|
-
model: options.model,
|
|
755
|
-
maxOutputTokens: options.maxTokens ?? 2e3,
|
|
756
|
-
system: prompt,
|
|
757
|
-
prompt: `Summarize this conversation:
|
|
758
|
-
|
|
759
|
-
${conversationText}`
|
|
760
|
-
});
|
|
761
|
-
return text;
|
|
762
|
-
}
|
|
763
|
-
async function pruneContext(messages, options = {}) {
|
|
764
|
-
const limits = options.limits ?? DEFAULT_CONTEXT_LIMITS;
|
|
765
|
-
let currentMessages = [...messages];
|
|
766
|
-
let tokensRemoved = 0;
|
|
767
|
-
let removedCount = 0;
|
|
768
|
-
let summarized = false;
|
|
769
|
-
let summary;
|
|
770
|
-
const initialTokens = estimateConversationTokens(currentMessages);
|
|
771
|
-
if (!shouldPruneContext(initialTokens, limits)) {
|
|
772
|
-
return {
|
|
773
|
-
messages: currentMessages,
|
|
774
|
-
removedCount: 0,
|
|
775
|
-
tokensRemoved: 0,
|
|
776
|
-
summarized: false
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
|
-
const prunedMessages = pruneToolResults(
|
|
780
|
-
currentMessages,
|
|
781
|
-
limits.protectedTokens
|
|
782
|
-
);
|
|
783
|
-
const afterPruneTokens = estimateConversationTokens(prunedMessages);
|
|
784
|
-
tokensRemoved = initialTokens - afterPruneTokens;
|
|
785
|
-
currentMessages = prunedMessages;
|
|
786
|
-
if (!isContextOverflowing(afterPruneTokens, limits)) {
|
|
787
|
-
return {
|
|
788
|
-
messages: currentMessages,
|
|
789
|
-
removedCount: 0,
|
|
790
|
-
tokensRemoved,
|
|
791
|
-
summarized: false
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
const cutIndex = findCutPoint(currentMessages, limits.protectedTokens);
|
|
795
|
-
if (cutIndex === 0) {
|
|
796
|
-
return {
|
|
797
|
-
messages: currentMessages,
|
|
798
|
-
removedCount: 0,
|
|
799
|
-
tokensRemoved,
|
|
800
|
-
summarized: false
|
|
801
|
-
};
|
|
802
|
-
}
|
|
803
|
-
const toSummarize = currentMessages.slice(0, cutIndex);
|
|
804
|
-
const toKeep = currentMessages.slice(cutIndex);
|
|
805
|
-
removedCount = toSummarize.length;
|
|
806
|
-
tokensRemoved += estimateConversationTokens(toSummarize);
|
|
807
|
-
if (options.model) {
|
|
808
|
-
summary = await generateSummary(toSummarize, {
|
|
809
|
-
model: options.model,
|
|
810
|
-
customPrompt: options.summaryPrompt
|
|
811
|
-
});
|
|
812
|
-
summarized = true;
|
|
813
|
-
const summaryMessage = {
|
|
814
|
-
id: crypto.randomUUID(),
|
|
815
|
-
role: "system",
|
|
816
|
-
content: `## Previous Conversation Summary
|
|
817
|
-
|
|
818
|
-
${summary}`,
|
|
819
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
820
|
-
};
|
|
821
|
-
currentMessages = [summaryMessage, ...toKeep];
|
|
822
|
-
} else {
|
|
823
|
-
currentMessages = toKeep;
|
|
824
|
-
}
|
|
825
|
-
return {
|
|
826
|
-
messages: currentMessages,
|
|
827
|
-
removedCount,
|
|
828
|
-
tokensRemoved,
|
|
829
|
-
summarized,
|
|
830
|
-
summary
|
|
831
|
-
};
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
// src/agent/context/manager.ts
|
|
835
|
-
var ContextManager = class {
|
|
836
|
-
limits;
|
|
837
|
-
model;
|
|
838
|
-
summaryPrompt;
|
|
839
|
-
constructor(options) {
|
|
840
|
-
this.limits = { ...DEFAULT_CONTEXT_LIMITS, ...options?.limits };
|
|
841
|
-
this.model = options?.model;
|
|
842
|
-
this.summaryPrompt = options?.summaryPrompt;
|
|
843
|
-
}
|
|
844
|
-
/** Get a copy of the current context limits. */
|
|
845
|
-
getLimits() {
|
|
846
|
-
return { ...this.limits };
|
|
847
|
-
}
|
|
848
|
-
/** Update context limits (e.g. when switching models). */
|
|
849
|
-
setLimits(limits) {
|
|
850
|
-
this.limits = { ...this.limits, ...limits };
|
|
851
|
-
}
|
|
852
|
-
/** Set the model used for summarisation. */
|
|
853
|
-
setModel(model) {
|
|
854
|
-
this.model = model;
|
|
855
|
-
}
|
|
856
|
-
/** Estimate total tokens for a message array. */
|
|
857
|
-
estimateTokens(messages) {
|
|
858
|
-
return estimateConversationTokens(messages);
|
|
859
|
-
}
|
|
860
|
-
/** Check whether the context is overflowing. */
|
|
861
|
-
isOverflowing(messages) {
|
|
862
|
-
const tokens = this.estimateTokens(messages);
|
|
863
|
-
return isContextOverflowing(tokens, this.limits);
|
|
864
|
-
}
|
|
865
|
-
/** Check whether pruning should be triggered. */
|
|
866
|
-
shouldPrune(messages) {
|
|
867
|
-
const tokens = this.estimateTokens(messages);
|
|
868
|
-
return shouldPruneContext(tokens, this.limits);
|
|
869
|
-
}
|
|
870
|
-
/** Prune context to fit within limits. */
|
|
871
|
-
async prune(messages) {
|
|
872
|
-
return pruneContext(messages, {
|
|
873
|
-
model: this.model,
|
|
874
|
-
limits: this.limits,
|
|
875
|
-
summaryPrompt: this.summaryPrompt
|
|
876
|
-
});
|
|
877
|
-
}
|
|
878
|
-
/**
|
|
879
|
-
* Get a snapshot of token statistics.
|
|
880
|
-
*
|
|
881
|
-
* Useful for dashboards, logging, or deciding whether to prune.
|
|
882
|
-
*/
|
|
883
|
-
getStats(messages) {
|
|
884
|
-
const tokens = this.estimateTokens(messages);
|
|
885
|
-
const limit = getUsableTokenLimit(this.limits);
|
|
886
|
-
return {
|
|
887
|
-
tokens,
|
|
888
|
-
limit,
|
|
889
|
-
available: Math.max(0, limit - tokens),
|
|
890
|
-
utilizationPercent: Math.round(tokens / limit * 100),
|
|
891
|
-
isOverflowing: isContextOverflowing(tokens, this.limits),
|
|
892
|
-
shouldPrune: shouldPruneContext(tokens, this.limits)
|
|
893
|
-
};
|
|
894
|
-
}
|
|
895
|
-
};
|
|
896
|
-
|
|
897
|
-
// src/execution/turn-runner/prepare.ts
|
|
898
|
-
function prepareModelStep(options) {
|
|
899
|
-
const modelMessages = Array.from(options.toModelMessages(options.messages));
|
|
900
|
-
return {
|
|
901
|
-
step: options.step,
|
|
902
|
-
messages: options.messages,
|
|
903
|
-
modelMessages,
|
|
904
|
-
inferenceInput: {
|
|
905
|
-
sessionID: options.sessionId,
|
|
906
|
-
turnID: options.turnTracker?.getCurrentTurnId?.() ?? void 0,
|
|
907
|
-
step: options.step,
|
|
908
|
-
model: options.config.model,
|
|
909
|
-
system: options.systemPrompts,
|
|
910
|
-
messages: modelMessages,
|
|
911
|
-
abort: options.abort,
|
|
912
|
-
tools: options.tools,
|
|
913
|
-
mcpTools: options.mcpTools,
|
|
914
|
-
cwd: options.config.cwd,
|
|
915
|
-
host: options.host,
|
|
916
|
-
humanInputController: options.humanInputController,
|
|
917
|
-
temperature: options.config.temperature,
|
|
918
|
-
topP: options.config.topP,
|
|
919
|
-
maxOutputTokens: options.config.maxOutputTokens,
|
|
920
|
-
maxSteps: options.config.maxSteps,
|
|
921
|
-
reasoningLevel: options.reasoningLevel,
|
|
922
|
-
customStreamProvider: options.config.streamProvider,
|
|
923
|
-
turnTracker: options.turnTracker,
|
|
924
|
-
intervention: options.intervention,
|
|
925
|
-
middleware: options.middleware,
|
|
926
|
-
toolExecutionMode: options.toolExecutionMode,
|
|
927
|
-
telemetry: options.config.telemetry
|
|
928
|
-
},
|
|
929
|
-
stepProcessing: {
|
|
930
|
-
maxSteps: options.config.maxSteps,
|
|
931
|
-
doomLoopThreshold: options.config.doomLoopThreshold,
|
|
932
|
-
enforceDoomLoop: options.config.enforceDoomLoop,
|
|
933
|
-
onDoomLoop: options.config.onDoomLoop,
|
|
934
|
-
contextTokenLimit: options.config.contextWindow ? getUsableTokenLimit({
|
|
935
|
-
contextWindow: options.config.contextWindow,
|
|
936
|
-
reserveTokens: options.config.reserveTokens ?? DEFAULT_CONTEXT_LIMITS.reserveTokens
|
|
937
|
-
}) : void 0
|
|
938
|
-
}
|
|
939
|
-
};
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
// src/execution/step-processing/doom-loop.ts
|
|
943
|
-
var DEFAULT_DOOM_LOOP_THRESHOLD = 3;
|
|
944
|
-
var DoomLoopError = class extends Error {
|
|
945
|
-
toolName;
|
|
946
|
-
repeatCount;
|
|
947
|
-
input;
|
|
948
|
-
constructor(toolName, repeatCount, input) {
|
|
949
|
-
super(
|
|
950
|
-
`Doom loop detected: "${toolName}" called ${repeatCount} times with identical input`
|
|
951
|
-
);
|
|
952
|
-
this.name = "DoomLoopError";
|
|
953
|
-
this.toolName = toolName;
|
|
954
|
-
this.repeatCount = repeatCount;
|
|
955
|
-
this.input = input;
|
|
956
|
-
}
|
|
957
|
-
};
|
|
958
|
-
function hashInput(input) {
|
|
959
|
-
return JSON.stringify(input);
|
|
960
|
-
}
|
|
961
|
-
async function recordToolCallAndCheckDoomLoop(options) {
|
|
962
|
-
const {
|
|
963
|
-
recentToolCalls,
|
|
964
|
-
toolName,
|
|
965
|
-
input,
|
|
966
|
-
processorOptions,
|
|
967
|
-
threshold,
|
|
968
|
-
emitEvent
|
|
969
|
-
} = options;
|
|
970
|
-
recentToolCalls.push({
|
|
971
|
-
toolName,
|
|
972
|
-
inputHash: hashInput(input)
|
|
973
|
-
});
|
|
974
|
-
if (recentToolCalls.length > threshold) {
|
|
975
|
-
recentToolCalls.shift();
|
|
976
|
-
}
|
|
977
|
-
if (recentToolCalls.length !== threshold) {
|
|
978
|
-
return;
|
|
979
|
-
}
|
|
980
|
-
const first = recentToolCalls[0];
|
|
981
|
-
const isLoop = recentToolCalls.every(
|
|
982
|
-
(call) => call.toolName === first.toolName && call.inputHash === first.inputHash
|
|
983
|
-
);
|
|
984
|
-
if (!isLoop) {
|
|
985
|
-
return;
|
|
986
|
-
}
|
|
987
|
-
if (processorOptions.rememberedDoomLoopTools?.has(toolName)) {
|
|
988
|
-
return;
|
|
989
|
-
}
|
|
990
|
-
const doomError = new DoomLoopError(toolName, threshold, input);
|
|
991
|
-
await emitEvent({
|
|
992
|
-
type: "doom-loop",
|
|
993
|
-
toolName,
|
|
994
|
-
repeatCount: threshold
|
|
995
|
-
});
|
|
996
|
-
if (processorOptions.onDoomLoop) {
|
|
997
|
-
const action = await processorOptions.onDoomLoop({
|
|
998
|
-
tool: toolName,
|
|
999
|
-
repeatCount: threshold,
|
|
1000
|
-
input,
|
|
1001
|
-
sessionId: processorOptions.sessionID ?? "unknown"
|
|
1002
|
-
});
|
|
1003
|
-
switch (action) {
|
|
1004
|
-
case "allow":
|
|
1005
|
-
return;
|
|
1006
|
-
case "remember":
|
|
1007
|
-
processorOptions.rememberedDoomLoopTools?.add(toolName);
|
|
1008
|
-
return;
|
|
1009
|
-
case "deny":
|
|
1010
|
-
throw doomError;
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
if (processorOptions.enforceDoomLoop ?? true) {
|
|
1014
|
-
throw doomError;
|
|
1015
|
-
}
|
|
1016
|
-
options.warn?.(`[StepProcessing] ${doomError.message}`);
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
// src/execution/step-processing/overflow.ts
|
|
1020
|
-
var ContextOverflowError = class extends Error {
|
|
1021
|
-
inputTokens;
|
|
1022
|
-
limit;
|
|
1023
|
-
constructor(inputTokens, limit) {
|
|
1024
|
-
super(`Context overflow: ${inputTokens} tokens exceeds limit of ${limit}`);
|
|
1025
|
-
this.name = "ContextOverflowError";
|
|
1026
|
-
this.inputTokens = inputTokens;
|
|
1027
|
-
this.limit = limit;
|
|
1028
|
-
}
|
|
1029
|
-
};
|
|
1030
|
-
async function handleContextOverflow(options) {
|
|
1031
|
-
const limit = options.processorOptions.contextTokenLimit;
|
|
1032
|
-
const inputTokens = options.usage?.inputTokens;
|
|
1033
|
-
if (!limit || !inputTokens || inputTokens <= limit) {
|
|
1034
|
-
return;
|
|
1035
|
-
}
|
|
1036
|
-
await options.emitEvent({
|
|
1037
|
-
type: "context-overflow",
|
|
1038
|
-
inputTokens,
|
|
1039
|
-
limit
|
|
1040
|
-
});
|
|
1041
|
-
if (options.processorOptions.onContextOverflow) {
|
|
1042
|
-
await options.processorOptions.onContextOverflow(inputTokens, limit);
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
// src/execution/step-processing/process.ts
|
|
1047
|
-
function normalizeToolResultChunk(output) {
|
|
1048
|
-
if (output && typeof output === "object" && "__cuylabsAgentToolResult" in output && output.__cuylabsAgentToolResult === true) {
|
|
1049
|
-
const structured = output;
|
|
1050
|
-
return {
|
|
1051
|
-
result: structured.output,
|
|
1052
|
-
...structured.metadata ? { metadata: structured.metadata } : {}
|
|
1053
|
-
};
|
|
1054
|
-
}
|
|
1055
|
-
return { result: output };
|
|
1056
|
-
}
|
|
1057
|
-
async function processStepStream(stream, options) {
|
|
1058
|
-
const { abort, onEvent } = options;
|
|
1059
|
-
const normalizeError = options.normalizeError ?? ((error2) => error2 instanceof Error ? error2 : new Error(String(error2)));
|
|
1060
|
-
const doomLoopThreshold = options.doomLoopThreshold ?? DEFAULT_DOOM_LOOP_THRESHOLD;
|
|
1061
|
-
const maxSteps = options.maxSteps ?? 50;
|
|
1062
|
-
const log = options.logger;
|
|
1063
|
-
let stepCount = options.currentStep ?? 1;
|
|
1064
|
-
let sawStartStep = false;
|
|
1065
|
-
let text = "";
|
|
1066
|
-
const toolResults = [];
|
|
1067
|
-
const recentToolCalls = [];
|
|
1068
|
-
let usage;
|
|
1069
|
-
let finishReason;
|
|
1070
|
-
let error;
|
|
1071
|
-
let hasToolCalls = false;
|
|
1072
|
-
await onEvent({ type: "step-start", step: stepCount, maxSteps });
|
|
1073
|
-
await onEvent({ type: "status", status: "processing" });
|
|
1074
|
-
try {
|
|
1075
|
-
for await (const rawChunk of stream.fullStream) {
|
|
1076
|
-
const chunk = rawChunk;
|
|
1077
|
-
log?.debug(`Chunk received: ${chunk.type}`);
|
|
1078
|
-
abort.throwIfAborted();
|
|
1079
|
-
switch (chunk.type) {
|
|
1080
|
-
case "start-step":
|
|
1081
|
-
if (!sawStartStep) {
|
|
1082
|
-
sawStartStep = true;
|
|
1083
|
-
break;
|
|
1084
|
-
}
|
|
1085
|
-
stepCount++;
|
|
1086
|
-
await onEvent({ type: "step-start", step: stepCount, maxSteps });
|
|
1087
|
-
await onEvent({ type: "status", status: "processing" });
|
|
1088
|
-
break;
|
|
1089
|
-
case "text-start":
|
|
1090
|
-
await onEvent({ type: "text-start" });
|
|
1091
|
-
break;
|
|
1092
|
-
case "text-delta":
|
|
1093
|
-
text += chunk.text;
|
|
1094
|
-
await onEvent({ type: "text-delta", text: chunk.text });
|
|
1095
|
-
break;
|
|
1096
|
-
case "text-end":
|
|
1097
|
-
await onEvent({ type: "text-end" });
|
|
1098
|
-
break;
|
|
1099
|
-
case "reasoning-start":
|
|
1100
|
-
await onEvent({ type: "status", status: "reasoning" });
|
|
1101
|
-
await onEvent({ type: "reasoning-start", id: chunk.id });
|
|
1102
|
-
break;
|
|
1103
|
-
case "reasoning-delta":
|
|
1104
|
-
await onEvent({
|
|
1105
|
-
type: "reasoning-delta",
|
|
1106
|
-
id: chunk.id,
|
|
1107
|
-
text: chunk.text
|
|
1108
|
-
});
|
|
1109
|
-
break;
|
|
1110
|
-
case "reasoning-end":
|
|
1111
|
-
await onEvent({ type: "reasoning-end", id: chunk.id });
|
|
1112
|
-
break;
|
|
1113
|
-
case "tool-call":
|
|
1114
|
-
hasToolCalls = true;
|
|
1115
|
-
await onEvent({ type: "status", status: "calling-tool" });
|
|
1116
|
-
await onEvent({
|
|
1117
|
-
type: "tool-start",
|
|
1118
|
-
toolName: chunk.toolName,
|
|
1119
|
-
toolCallId: chunk.toolCallId,
|
|
1120
|
-
input: chunk.input
|
|
1121
|
-
});
|
|
1122
|
-
await recordToolCallAndCheckDoomLoop({
|
|
1123
|
-
recentToolCalls,
|
|
1124
|
-
toolName: chunk.toolName,
|
|
1125
|
-
input: chunk.input,
|
|
1126
|
-
processorOptions: options,
|
|
1127
|
-
threshold: doomLoopThreshold,
|
|
1128
|
-
emitEvent: onEvent,
|
|
1129
|
-
warn: (message) => process.stderr.write(`${message}
|
|
1130
|
-
`)
|
|
1131
|
-
});
|
|
1132
|
-
break;
|
|
1133
|
-
case "tool-result": {
|
|
1134
|
-
const normalized = normalizeToolResultChunk(chunk.output);
|
|
1135
|
-
toolResults.push({
|
|
1136
|
-
toolName: chunk.toolName,
|
|
1137
|
-
toolCallId: chunk.toolCallId,
|
|
1138
|
-
result: normalized.result,
|
|
1139
|
-
...normalized.metadata ? { metadata: normalized.metadata } : {}
|
|
1140
|
-
});
|
|
1141
|
-
await onEvent({
|
|
1142
|
-
type: "tool-result",
|
|
1143
|
-
toolName: chunk.toolName,
|
|
1144
|
-
toolCallId: chunk.toolCallId,
|
|
1145
|
-
result: normalized.result,
|
|
1146
|
-
...normalized.metadata ? { metadata: normalized.metadata } : {}
|
|
1147
|
-
});
|
|
1148
|
-
break;
|
|
1149
|
-
}
|
|
1150
|
-
case "tool-error":
|
|
1151
|
-
await onEvent({
|
|
1152
|
-
type: "tool-error",
|
|
1153
|
-
toolName: chunk.toolName,
|
|
1154
|
-
toolCallId: chunk.toolCallId,
|
|
1155
|
-
error: String(chunk.error)
|
|
1156
|
-
});
|
|
1157
|
-
break;
|
|
1158
|
-
case "computer-call":
|
|
1159
|
-
hasToolCalls = true;
|
|
1160
|
-
await onEvent({ type: "status", status: "calling-tool" });
|
|
1161
|
-
await onEvent({
|
|
1162
|
-
type: "computer-call",
|
|
1163
|
-
callId: chunk.callId,
|
|
1164
|
-
action: chunk.action,
|
|
1165
|
-
pendingSafetyChecks: chunk.pendingSafetyChecks
|
|
1166
|
-
});
|
|
1167
|
-
break;
|
|
1168
|
-
case "finish-step":
|
|
1169
|
-
finishReason = chunk.finishReason;
|
|
1170
|
-
if (chunk.usage) {
|
|
1171
|
-
usage = {
|
|
1172
|
-
inputTokens: chunk.usage.inputTokens,
|
|
1173
|
-
outputTokens: chunk.usage.outputTokens,
|
|
1174
|
-
totalTokens: chunk.usage.totalTokens
|
|
1175
|
-
};
|
|
1176
|
-
await handleContextOverflow({
|
|
1177
|
-
usage,
|
|
1178
|
-
processorOptions: options,
|
|
1179
|
-
emitEvent: onEvent
|
|
1180
|
-
});
|
|
1181
|
-
}
|
|
1182
|
-
await onEvent({
|
|
1183
|
-
type: "step-finish",
|
|
1184
|
-
step: stepCount,
|
|
1185
|
-
usage,
|
|
1186
|
-
finishReason
|
|
1187
|
-
});
|
|
1188
|
-
if (!sawStartStep) {
|
|
1189
|
-
stepCount++;
|
|
1190
|
-
}
|
|
1191
|
-
break;
|
|
1192
|
-
case "finish":
|
|
1193
|
-
if (chunk.totalUsage) {
|
|
1194
|
-
usage = {
|
|
1195
|
-
inputTokens: chunk.totalUsage.inputTokens,
|
|
1196
|
-
outputTokens: chunk.totalUsage.outputTokens,
|
|
1197
|
-
totalTokens: chunk.totalUsage.totalTokens
|
|
1198
|
-
};
|
|
1199
|
-
}
|
|
1200
|
-
break;
|
|
1201
|
-
case "step-usage":
|
|
1202
|
-
usage = {
|
|
1203
|
-
inputTokens: chunk.usage.inputTokens,
|
|
1204
|
-
outputTokens: chunk.usage.outputTokens,
|
|
1205
|
-
totalTokens: chunk.usage.totalTokens
|
|
1206
|
-
};
|
|
1207
|
-
break;
|
|
1208
|
-
case "error":
|
|
1209
|
-
throw chunk.error;
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1212
|
-
} catch (caught) {
|
|
1213
|
-
error = normalizeError(caught);
|
|
1214
|
-
await onEvent({ type: "status", status: "error" });
|
|
1215
|
-
await onEvent({ type: "error", error });
|
|
1216
|
-
}
|
|
1217
|
-
if (!error) {
|
|
1218
|
-
await onEvent({ type: "status", status: "idle" });
|
|
1219
|
-
}
|
|
1220
|
-
let result = "continue";
|
|
1221
|
-
if (error || !hasToolCalls) {
|
|
1222
|
-
result = "stop";
|
|
1223
|
-
}
|
|
1224
|
-
return {
|
|
1225
|
-
result,
|
|
1226
|
-
text,
|
|
1227
|
-
toolResults,
|
|
1228
|
-
usage,
|
|
1229
|
-
finishReason,
|
|
1230
|
-
error
|
|
1231
|
-
};
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
// src/execution/turn-runner/stream-step.ts
|
|
1235
|
-
function buildStepModelCallContext(options) {
|
|
1236
|
-
const input = options.preparedStep.inferenceInput;
|
|
1237
|
-
const ctx = buildModelCallContext(input);
|
|
1238
|
-
if (input.step == null) {
|
|
1239
|
-
ctx.step = options.preparedStep.step;
|
|
1240
|
-
}
|
|
1241
|
-
return ctx;
|
|
1242
|
-
}
|
|
1243
|
-
function normalizeModelStepError(options, error) {
|
|
1244
|
-
const model = options.preparedStep.inferenceInput.model;
|
|
1245
|
-
return LLMError.from(error, {
|
|
1246
|
-
provider: extractProvider(model),
|
|
1247
|
-
model: extractModelId(model)
|
|
1248
|
-
});
|
|
1249
|
-
}
|
|
1250
|
-
async function* runModelStep(options) {
|
|
1251
|
-
return yield* streamWithinScope(
|
|
1252
|
-
{
|
|
1253
|
-
kind: "model",
|
|
1254
|
-
name: "model-step",
|
|
1255
|
-
sessionId: options.preparedStep.inferenceInput.sessionID,
|
|
1256
|
-
step: options.preparedStep.step
|
|
1257
|
-
},
|
|
1258
|
-
(async function* () {
|
|
1259
|
-
const { preparedStep, turnEngine, applyCommitBatch } = options;
|
|
1260
|
-
const eventQueue = [];
|
|
1261
|
-
let resolveNext = null;
|
|
1262
|
-
let streamDone = false;
|
|
1263
|
-
let streamError;
|
|
1264
|
-
const intervention = preparedStep.inferenceInput.intervention;
|
|
1265
|
-
const middleware = preparedStep.inferenceInput.middleware;
|
|
1266
|
-
const emitQueuedEvent = async (event) => {
|
|
1267
|
-
middleware?.emitEvent(event);
|
|
1268
|
-
eventQueue.push(event);
|
|
1269
|
-
if (resolveNext) {
|
|
1270
|
-
resolveNext();
|
|
1271
|
-
resolveNext = null;
|
|
1272
|
-
}
|
|
1273
|
-
};
|
|
1274
|
-
if (intervention) {
|
|
1275
|
-
intervention.onApplied = (item) => {
|
|
1276
|
-
eventQueue.push({
|
|
1277
|
-
type: "intervention-applied",
|
|
1278
|
-
id: item.id,
|
|
1279
|
-
message: item.message
|
|
1280
|
-
});
|
|
1281
|
-
if (resolveNext) {
|
|
1282
|
-
resolveNext();
|
|
1283
|
-
resolveNext = null;
|
|
1284
|
-
}
|
|
1285
|
-
};
|
|
1286
|
-
intervention.onDeferredQueued = (item) => {
|
|
1287
|
-
eventQueue.push({
|
|
1288
|
-
type: "follow-up-queued",
|
|
1289
|
-
id: item.id,
|
|
1290
|
-
message: item.message
|
|
1291
|
-
});
|
|
1292
|
-
if (resolveNext) {
|
|
1293
|
-
resolveNext();
|
|
1294
|
-
resolveNext = null;
|
|
1295
|
-
}
|
|
1296
|
-
};
|
|
1297
|
-
}
|
|
1298
|
-
const stream = await Inference.streamStep({
|
|
1299
|
-
...preparedStep.inferenceInput,
|
|
1300
|
-
onEvent: emitQueuedEvent
|
|
1301
|
-
});
|
|
1302
|
-
const processPromise = processStepStream(stream, {
|
|
1303
|
-
sessionID: preparedStep.inferenceInput.sessionID,
|
|
1304
|
-
abort: preparedStep.inferenceInput.abort,
|
|
1305
|
-
normalizeError: (error) => normalizeModelStepError(options, error),
|
|
1306
|
-
currentStep: preparedStep.step,
|
|
1307
|
-
maxSteps: preparedStep.stepProcessing.maxSteps,
|
|
1308
|
-
doomLoopThreshold: preparedStep.stepProcessing.doomLoopThreshold ?? 3,
|
|
1309
|
-
enforceDoomLoop: preparedStep.stepProcessing.enforceDoomLoop ?? true,
|
|
1310
|
-
onDoomLoop: preparedStep.stepProcessing.onDoomLoop,
|
|
1311
|
-
rememberedDoomLoopTools: options.rememberedDoomLoopTools,
|
|
1312
|
-
contextTokenLimit: preparedStep.stepProcessing.contextTokenLimit,
|
|
1313
|
-
onContextOverflow: async () => {
|
|
1314
|
-
},
|
|
1315
|
-
onEvent: emitQueuedEvent
|
|
1316
|
-
}).then((result2) => {
|
|
1317
|
-
streamDone = true;
|
|
1318
|
-
if (resolveNext) {
|
|
1319
|
-
resolveNext();
|
|
1320
|
-
resolveNext = null;
|
|
1321
|
-
}
|
|
1322
|
-
return result2;
|
|
1323
|
-
}).catch((error) => {
|
|
1324
|
-
streamError = error instanceof Error ? error : new Error(String(error));
|
|
1325
|
-
streamDone = true;
|
|
1326
|
-
if (resolveNext) {
|
|
1327
|
-
resolveNext();
|
|
1328
|
-
resolveNext = null;
|
|
1329
|
-
}
|
|
1330
|
-
return null;
|
|
1331
|
-
});
|
|
1332
|
-
while (!streamDone || eventQueue.length > 0) {
|
|
1333
|
-
while (eventQueue.length > 0) {
|
|
1334
|
-
const event = eventQueue.shift();
|
|
1335
|
-
turnEngine.recordEvent(event, (/* @__PURE__ */ new Date()).toISOString());
|
|
1336
|
-
yield event;
|
|
1337
|
-
if (event.type === "intervention-applied") {
|
|
1338
|
-
yield* applyCommitBatch(
|
|
1339
|
-
turnEngine.createInterventionCommit({
|
|
1340
|
-
id: event.id,
|
|
1341
|
-
content: event.message
|
|
1342
|
-
})
|
|
1343
|
-
);
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
if (!streamDone) {
|
|
1347
|
-
await new Promise((resolve) => {
|
|
1348
|
-
resolveNext = resolve;
|
|
1349
|
-
});
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
if (streamError) {
|
|
1353
|
-
throw streamError;
|
|
1354
|
-
}
|
|
1355
|
-
const result = await processPromise;
|
|
1356
|
-
if (!result) {
|
|
1357
|
-
throw new Error(
|
|
1358
|
-
`Agent step ${preparedStep.step} produced no step-processing result`
|
|
1359
|
-
);
|
|
1360
|
-
}
|
|
1361
|
-
if (middleware?.hasMiddleware) {
|
|
1362
|
-
const revised = await middleware.runModelOutput(
|
|
1363
|
-
{
|
|
1364
|
-
text: result.text,
|
|
1365
|
-
usage: result.usage,
|
|
1366
|
-
finishReason: result.finishReason
|
|
1367
|
-
},
|
|
1368
|
-
buildStepModelCallContext(options)
|
|
1369
|
-
);
|
|
1370
|
-
result.text = revised.text;
|
|
1371
|
-
result.usage = revised.usage;
|
|
1372
|
-
result.finishReason = revised.finishReason;
|
|
1373
|
-
}
|
|
1374
|
-
return result;
|
|
1375
|
-
})()
|
|
1376
|
-
);
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
// src/types/messages.ts
|
|
1380
|
-
function accumulateUsage(current, next) {
|
|
1381
|
-
if (!next) return current;
|
|
1382
|
-
if (!current) {
|
|
1383
|
-
return {
|
|
1384
|
-
inputTokens: next.inputTokens ?? 0,
|
|
1385
|
-
outputTokens: next.outputTokens ?? 0,
|
|
1386
|
-
totalTokens: next.totalTokens ?? 0,
|
|
1387
|
-
cacheReadTokens: (next.cacheReadTokens ?? 0) || void 0,
|
|
1388
|
-
cacheWriteTokens: (next.cacheWriteTokens ?? 0) || void 0
|
|
1389
|
-
};
|
|
1390
|
-
}
|
|
1391
|
-
const cacheRead = (current.cacheReadTokens ?? 0) + (next.cacheReadTokens ?? 0);
|
|
1392
|
-
const cacheWrite = (current.cacheWriteTokens ?? 0) + (next.cacheWriteTokens ?? 0);
|
|
1393
|
-
return {
|
|
1394
|
-
inputTokens: (current.inputTokens ?? 0) + (next.inputTokens ?? 0),
|
|
1395
|
-
outputTokens: (current.outputTokens ?? 0) + (next.outputTokens ?? 0),
|
|
1396
|
-
totalTokens: (current.totalTokens ?? 0) + (next.totalTokens ?? 0),
|
|
1397
|
-
cacheReadTokens: cacheRead || void 0,
|
|
1398
|
-
cacheWriteTokens: cacheWrite || void 0
|
|
1399
|
-
};
|
|
1400
|
-
}
|
|
1401
|
-
|
|
1402
|
-
// src/execution/turn-runner/tool-batch.ts
|
|
1403
|
-
function cloneToolResultRecord(options) {
|
|
1404
|
-
return new Map(
|
|
1405
|
-
options.snapshot.toolResults.map((toolResult) => [
|
|
1406
|
-
toolResult.toolCallId,
|
|
1407
|
-
structuredClone(toolResult)
|
|
1408
|
-
])
|
|
1409
|
-
);
|
|
1410
|
-
}
|
|
1411
|
-
function recordToolResult(toolCall, event, result, accumulators, metadata) {
|
|
1412
|
-
accumulators.events.push(event);
|
|
1413
|
-
accumulators.toolResultsByCallId.set(toolCall.toolCallId, {
|
|
1414
|
-
toolCallId: toolCall.toolCallId,
|
|
1415
|
-
toolName: toolCall.toolName,
|
|
1416
|
-
result,
|
|
1417
|
-
...metadata ? { metadata } : {},
|
|
1418
|
-
...toolCall.replayPolicy ? { replayPolicy: toolCall.replayPolicy } : {}
|
|
1419
|
-
});
|
|
1420
|
-
if (accumulators.turnState.value) {
|
|
1421
|
-
accumulators.turnState.value = advanceAgentTurnState(
|
|
1422
|
-
accumulators.turnState.value,
|
|
1423
|
-
event,
|
|
1424
|
-
(/* @__PURE__ */ new Date()).toISOString(),
|
|
1425
|
-
{
|
|
1426
|
-
...toolCall.replayPolicy ? { toolReplayPolicy: toolCall.replayPolicy } : {}
|
|
1427
|
-
}
|
|
1428
|
-
);
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
async function isParallelSafe(tool, args, cwd) {
|
|
1432
|
-
const initialized = await tool.init({ cwd });
|
|
1433
|
-
const cap = initialized.capabilities?.parallelSafe;
|
|
1434
|
-
const safe = resolveCapability(
|
|
1435
|
-
cap,
|
|
1436
|
-
args,
|
|
1437
|
-
/* fallback */
|
|
1438
|
-
false
|
|
1439
|
-
);
|
|
1440
|
-
return { safe, initialized };
|
|
1441
|
-
}
|
|
1442
|
-
async function executeBatchEntry(toolCall, options, accumulators, preInitialized) {
|
|
1443
|
-
const tool = options.tools[toolCall.toolName];
|
|
1444
|
-
if (!tool) {
|
|
1445
|
-
const errorMessage = `Tool '${toolCall.toolName}' is not registered`;
|
|
1446
|
-
recordToolResult(
|
|
1447
|
-
toolCall,
|
|
1448
|
-
{
|
|
1449
|
-
type: "tool-error",
|
|
1450
|
-
toolName: toolCall.toolName,
|
|
1451
|
-
toolCallId: toolCall.toolCallId,
|
|
1452
|
-
error: errorMessage
|
|
1453
|
-
},
|
|
1454
|
-
`Error: ${errorMessage}`,
|
|
1455
|
-
accumulators
|
|
1456
|
-
);
|
|
1457
|
-
return;
|
|
1458
|
-
}
|
|
1459
|
-
try {
|
|
1460
|
-
const executed = await executeAgentToolCall({
|
|
1461
|
-
toolName: toolCall.toolName,
|
|
1462
|
-
tool,
|
|
1463
|
-
toolCallId: toolCall.toolCallId,
|
|
1464
|
-
params: toolCall.args,
|
|
1465
|
-
cwd: options.cwd,
|
|
1466
|
-
abort: options.abort,
|
|
1467
|
-
sessionID: options.sessionId,
|
|
1468
|
-
turnID: options.turnTracker?.getCurrentTurnId?.() ?? void 0,
|
|
1469
|
-
messageID: toolCall.toolCallId,
|
|
1470
|
-
...options.host ? { host: options.host } : {},
|
|
1471
|
-
...options.humanInputController ? { humanInputController: options.humanInputController } : {},
|
|
1472
|
-
...options.turnTracker ? { turnTracker: options.turnTracker } : {},
|
|
1473
|
-
...options.middleware ? { middleware: options.middleware } : {},
|
|
1474
|
-
onEvent: async (event) => {
|
|
1475
|
-
accumulators.events.push(event);
|
|
1476
|
-
},
|
|
1477
|
-
...preInitialized ? { initialized: preInitialized } : {}
|
|
1478
|
-
});
|
|
1479
|
-
recordToolResult(
|
|
1480
|
-
toolCall,
|
|
1481
|
-
{
|
|
1482
|
-
type: "tool-result",
|
|
1483
|
-
toolName: toolCall.toolName,
|
|
1484
|
-
toolCallId: toolCall.toolCallId,
|
|
1485
|
-
result: executed.output,
|
|
1486
|
-
...executed.metadata ? { metadata: executed.metadata } : {}
|
|
1487
|
-
},
|
|
1488
|
-
executed.output,
|
|
1489
|
-
accumulators,
|
|
1490
|
-
executed.metadata
|
|
1491
|
-
);
|
|
1492
|
-
} catch (error) {
|
|
1493
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1494
|
-
recordToolResult(
|
|
1495
|
-
toolCall,
|
|
1496
|
-
{
|
|
1497
|
-
type: "tool-error",
|
|
1498
|
-
toolName: toolCall.toolName,
|
|
1499
|
-
toolCallId: toolCall.toolCallId,
|
|
1500
|
-
error: errorMessage
|
|
1501
|
-
},
|
|
1502
|
-
`Error: ${errorMessage}`,
|
|
1503
|
-
accumulators
|
|
1504
|
-
);
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
async function runToolBatch(options) {
|
|
1508
|
-
const toolResultsByCallId = cloneToolResultRecord(options);
|
|
1509
|
-
const events = [];
|
|
1510
|
-
const turnState = {
|
|
1511
|
-
value: options.turnState ? structuredClone(options.turnState) : void 0
|
|
1512
|
-
};
|
|
1513
|
-
const accumulators = { events, toolResultsByCallId, turnState };
|
|
1514
|
-
const pending = options.snapshot.toolCalls.filter(
|
|
1515
|
-
(tc) => !toolResultsByCallId.has(tc.toolCallId)
|
|
1516
|
-
);
|
|
1517
|
-
const parallelGroup = [];
|
|
1518
|
-
const serialGroup = [];
|
|
1519
|
-
for (const toolCall of pending) {
|
|
1520
|
-
const tool = options.tools[toolCall.toolName];
|
|
1521
|
-
if (!tool) {
|
|
1522
|
-
serialGroup.push({ toolCall });
|
|
1523
|
-
continue;
|
|
1524
|
-
}
|
|
1525
|
-
let safe = false;
|
|
1526
|
-
let initialized;
|
|
1527
|
-
try {
|
|
1528
|
-
const result = await isParallelSafe(tool, toolCall.args, options.cwd);
|
|
1529
|
-
safe = result.safe;
|
|
1530
|
-
initialized = result.initialized;
|
|
1531
|
-
} catch {
|
|
1532
|
-
}
|
|
1533
|
-
if (safe && initialized) {
|
|
1534
|
-
parallelGroup.push({ toolCall, initialized });
|
|
1535
|
-
} else {
|
|
1536
|
-
serialGroup.push({ toolCall, initialized });
|
|
1537
|
-
}
|
|
1538
|
-
}
|
|
1539
|
-
if (parallelGroup.length > 0) {
|
|
1540
|
-
await Promise.all(
|
|
1541
|
-
parallelGroup.map(
|
|
1542
|
-
({ toolCall, initialized }) => executeBatchEntry(toolCall, options, accumulators, initialized)
|
|
1543
|
-
)
|
|
1544
|
-
);
|
|
1545
|
-
}
|
|
1546
|
-
for (const { toolCall, initialized } of serialGroup) {
|
|
1547
|
-
if (options.intervention?.hasPending && initialized) {
|
|
1548
|
-
const interruptPolicy = initialized.capabilities?.onInterrupt ?? "finish";
|
|
1549
|
-
if (interruptPolicy === "cancel") {
|
|
1550
|
-
recordToolResult(
|
|
1551
|
-
toolCall,
|
|
1552
|
-
{
|
|
1553
|
-
type: "tool-error",
|
|
1554
|
-
toolName: toolCall.toolName,
|
|
1555
|
-
toolCallId: toolCall.toolCallId,
|
|
1556
|
-
error: "Tool cancelled: user sent a new message"
|
|
1557
|
-
},
|
|
1558
|
-
"Error: Tool cancelled: user sent a new message",
|
|
1559
|
-
accumulators
|
|
1560
|
-
);
|
|
1561
|
-
continue;
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
await executeBatchEntry(toolCall, options, accumulators, initialized);
|
|
1565
|
-
}
|
|
1566
|
-
return {
|
|
1567
|
-
snapshot: {
|
|
1568
|
-
toolCalls: options.snapshot.toolCalls.map(
|
|
1569
|
-
(toolCall) => structuredClone(toolCall)
|
|
1570
|
-
),
|
|
1571
|
-
toolResults: options.snapshot.toolCalls.map((toolCall) => toolResultsByCallId.get(toolCall.toolCallId)).filter((toolResult) => toolResult !== void 0)
|
|
1572
|
-
},
|
|
1573
|
-
...turnState.value ? { turnState: turnState.value } : {},
|
|
1574
|
-
events
|
|
1575
|
-
};
|
|
1576
|
-
}
|
|
1577
|
-
|
|
1578
|
-
// src/execution/turn-runner/commit.ts
|
|
1579
|
-
async function* commitStep(options) {
|
|
1580
|
-
return yield* streamWithinScope(
|
|
1581
|
-
{
|
|
1582
|
-
kind: "commit",
|
|
1583
|
-
name: "step-commit",
|
|
1584
|
-
step: options.step
|
|
1585
|
-
},
|
|
1586
|
-
(async function* () {
|
|
1587
|
-
if (options.finishReason !== "tool-calls") {
|
|
1588
|
-
return false;
|
|
1589
|
-
}
|
|
1590
|
-
const batch = options.turnEngine.consumeStepCommit(options.step);
|
|
1591
|
-
if (!batch) {
|
|
1592
|
-
return false;
|
|
1593
|
-
}
|
|
1594
|
-
yield* options.applyCommitBatch(batch);
|
|
1595
|
-
return true;
|
|
1596
|
-
})()
|
|
1597
|
-
);
|
|
1598
|
-
}
|
|
1599
|
-
async function* commitOutput(options) {
|
|
1600
|
-
return yield* streamWithinScope(
|
|
1601
|
-
{
|
|
1602
|
-
kind: "commit",
|
|
1603
|
-
name: "output-commit"
|
|
1604
|
-
},
|
|
1605
|
-
(async function* () {
|
|
1606
|
-
const batch = options.turnEngine.createOutputCommit({
|
|
1607
|
-
text: options.text,
|
|
1608
|
-
usage: options.usage
|
|
1609
|
-
});
|
|
1610
|
-
if (!batch) {
|
|
1611
|
-
return false;
|
|
1612
|
-
}
|
|
1613
|
-
yield* options.applyCommitBatch(batch, { emitMessages: true });
|
|
1614
|
-
return true;
|
|
1615
|
-
})()
|
|
1616
|
-
);
|
|
1617
|
-
}
|
|
1618
|
-
|
|
1619
|
-
// src/execution/workflow-state.ts
|
|
1620
|
-
function cloneMessageSnapshot(message) {
|
|
1621
|
-
return {
|
|
1622
|
-
...message,
|
|
1623
|
-
...message.role === "assistant" && message.toolCalls ? {
|
|
1624
|
-
toolCalls: message.toolCalls.map((toolCall) => ({ ...toolCall }))
|
|
1625
|
-
} : {},
|
|
1626
|
-
...message.role === "assistant" && message.tokens ? {
|
|
1627
|
-
tokens: { ...message.tokens }
|
|
1628
|
-
} : {},
|
|
1629
|
-
...message.role === "assistant" && message.error ? {
|
|
1630
|
-
error: { ...message.error }
|
|
1631
|
-
} : {},
|
|
1632
|
-
...message.role === "tool" && message.metadata ? {
|
|
1633
|
-
metadata: structuredClone(message.metadata)
|
|
1634
|
-
} : {}
|
|
1635
|
-
};
|
|
1636
|
-
}
|
|
1637
|
-
function createAgentWorkflowTurnState(options) {
|
|
1638
|
-
const pendingInput = options.initialInput ? cloneMessageSnapshot(options.initialInput) : void 0;
|
|
1639
|
-
return {
|
|
1640
|
-
sessionId: options.sessionId,
|
|
1641
|
-
systemPrompts: [...options.systemPrompts ?? []],
|
|
1642
|
-
messages: (options.initialMessages ?? []).map(cloneMessageSnapshot),
|
|
1643
|
-
phase: pendingInput ? "input-commit" : "model-step",
|
|
1644
|
-
...pendingInput ? { pendingInput } : {},
|
|
1645
|
-
step: options.initialStep ?? 1,
|
|
1646
|
-
maxSteps: options.maxSteps,
|
|
1647
|
-
replayDecisions: {},
|
|
1648
|
-
startedAt: options.startedAt,
|
|
1649
|
-
updatedAt: options.startedAt
|
|
1650
|
-
};
|
|
1651
|
-
}
|
|
1652
|
-
function cloneAgentWorkflowTurnState(state) {
|
|
1653
|
-
return {
|
|
1654
|
-
...state,
|
|
1655
|
-
systemPrompts: [...state.systemPrompts],
|
|
1656
|
-
messages: state.messages.map(cloneMessageSnapshot),
|
|
1657
|
-
...state.pendingInput ? {
|
|
1658
|
-
pendingInput: cloneMessageSnapshot(
|
|
1659
|
-
state.pendingInput
|
|
1660
|
-
)
|
|
1661
|
-
} : {},
|
|
1662
|
-
...state.usage ? { usage: cloneUsage(state.usage) } : {},
|
|
1663
|
-
...state.turnState ? { turnState: structuredClone(state.turnState) } : {},
|
|
1664
|
-
...state.lastModelStep ? { lastModelStep: structuredClone(state.lastModelStep) } : {},
|
|
1665
|
-
replayDecisions: Object.fromEntries(
|
|
1666
|
-
Object.entries(state.replayDecisions).map(([toolCallId, decision]) => [
|
|
1667
|
-
toolCallId,
|
|
1668
|
-
{ ...decision }
|
|
1669
|
-
])
|
|
1670
|
-
),
|
|
1671
|
-
...state.pendingInterventions?.length ? {
|
|
1672
|
-
pendingInterventions: state.pendingInterventions.map(
|
|
1673
|
-
(intervention) => ({ ...intervention })
|
|
1674
|
-
)
|
|
1675
|
-
} : {},
|
|
1676
|
-
...state.queuedFollowUps?.length ? {
|
|
1677
|
-
queuedFollowUps: state.queuedFollowUps.map((intervention) => ({
|
|
1678
|
-
...intervention
|
|
1679
|
-
}))
|
|
1680
|
-
} : {}
|
|
1681
|
-
};
|
|
1682
|
-
}
|
|
1683
|
-
function applyWorkflowInterventions(state, interventions, updatedAt) {
|
|
1684
|
-
if (interventions.length === 0) {
|
|
1685
|
-
return state;
|
|
1686
|
-
}
|
|
1687
|
-
const injected = interventions.map(
|
|
1688
|
-
(intervention) => ({
|
|
1689
|
-
id: intervention.id,
|
|
1690
|
-
role: "user",
|
|
1691
|
-
createdAt: intervention.createdAt,
|
|
1692
|
-
content: intervention.message
|
|
1693
|
-
})
|
|
1694
|
-
);
|
|
1695
|
-
return {
|
|
1696
|
-
...state,
|
|
1697
|
-
messages: [...state.messages, ...injected],
|
|
1698
|
-
pendingInterventions: void 0,
|
|
1699
|
-
updatedAt
|
|
1700
|
-
};
|
|
1701
|
-
}
|
|
1702
|
-
function drainWorkflowInterventions(state, updatedAt) {
|
|
1703
|
-
if (!state.pendingInterventions?.length) {
|
|
1704
|
-
return state;
|
|
1705
|
-
}
|
|
1706
|
-
return applyWorkflowInterventions(
|
|
1707
|
-
state,
|
|
1708
|
-
state.pendingInterventions,
|
|
1709
|
-
updatedAt
|
|
1710
|
-
);
|
|
1711
|
-
}
|
|
1712
|
-
function queueWorkflowFollowUps(state, followUps, updatedAt) {
|
|
1713
|
-
if (followUps.length === 0) {
|
|
1714
|
-
return state;
|
|
1715
|
-
}
|
|
1716
|
-
return {
|
|
1717
|
-
...state,
|
|
1718
|
-
queuedFollowUps: [
|
|
1719
|
-
...state.queuedFollowUps ?? [],
|
|
1720
|
-
...followUps.map((followUp) => ({ ...followUp }))
|
|
1721
|
-
],
|
|
1722
|
-
updatedAt
|
|
1723
|
-
};
|
|
1724
|
-
}
|
|
1725
|
-
|
|
1726
|
-
// src/execution/workflow-snapshot.ts
|
|
1727
|
-
function snapshotAgentWorkflowMessage(message) {
|
|
1728
|
-
switch (message.role) {
|
|
1729
|
-
case "user":
|
|
1730
|
-
return {
|
|
1731
|
-
id: message.id,
|
|
1732
|
-
role: "user",
|
|
1733
|
-
createdAt: message.createdAt.toISOString(),
|
|
1734
|
-
content: message.content,
|
|
1735
|
-
...message.system ? { system: message.system } : {}
|
|
1736
|
-
};
|
|
1737
|
-
case "assistant":
|
|
1738
|
-
return {
|
|
1739
|
-
id: message.id,
|
|
1740
|
-
role: "assistant",
|
|
1741
|
-
createdAt: message.createdAt.toISOString(),
|
|
1742
|
-
content: message.content,
|
|
1743
|
-
...message.finish ? { finish: message.finish } : {},
|
|
1744
|
-
...message.tokens ? { tokens: { ...message.tokens } } : {},
|
|
1745
|
-
...message.cost !== void 0 ? { cost: message.cost } : {},
|
|
1746
|
-
...message.error ? { error: { ...message.error } } : {},
|
|
1747
|
-
...message.toolCalls ? {
|
|
1748
|
-
toolCalls: message.toolCalls.map((toolCall) => ({
|
|
1749
|
-
toolCallId: toolCall.toolCallId,
|
|
1750
|
-
toolName: toolCall.toolName,
|
|
1751
|
-
args: toolCall.args
|
|
1752
|
-
}))
|
|
1753
|
-
} : {}
|
|
1754
|
-
};
|
|
1755
|
-
case "tool":
|
|
1756
|
-
return {
|
|
1757
|
-
id: message.id,
|
|
1758
|
-
role: "tool",
|
|
1759
|
-
createdAt: message.createdAt.toISOString(),
|
|
1760
|
-
content: message.content,
|
|
1761
|
-
toolCallId: message.toolCallId,
|
|
1762
|
-
toolName: message.toolName,
|
|
1763
|
-
result: message.result,
|
|
1764
|
-
...message.metadata ? { metadata: structuredClone(message.metadata) } : {},
|
|
1765
|
-
...message.compactedAt !== void 0 ? { compactedAt: message.compactedAt } : {}
|
|
1766
|
-
};
|
|
1767
|
-
case "system":
|
|
1768
|
-
return {
|
|
1769
|
-
id: message.id,
|
|
1770
|
-
role: "system",
|
|
1771
|
-
createdAt: message.createdAt.toISOString(),
|
|
1772
|
-
content: message.content
|
|
1773
|
-
};
|
|
1774
|
-
}
|
|
1775
|
-
}
|
|
1776
|
-
function snapshotAgentWorkflowMessages(messages) {
|
|
1777
|
-
return messages.map((message) => snapshotAgentWorkflowMessage(message));
|
|
1778
|
-
}
|
|
1779
|
-
function restoreAgentWorkflowMessage(snapshot) {
|
|
1780
|
-
const createdAt = new Date(snapshot.createdAt);
|
|
1781
|
-
switch (snapshot.role) {
|
|
1782
|
-
case "user":
|
|
1783
|
-
return {
|
|
1784
|
-
id: snapshot.id,
|
|
1785
|
-
role: "user",
|
|
1786
|
-
createdAt,
|
|
1787
|
-
content: snapshot.content,
|
|
1788
|
-
...snapshot.system ? { system: snapshot.system } : {}
|
|
1789
|
-
};
|
|
1790
|
-
case "assistant":
|
|
1791
|
-
return {
|
|
1792
|
-
id: snapshot.id,
|
|
1793
|
-
role: "assistant",
|
|
1794
|
-
createdAt,
|
|
1795
|
-
content: snapshot.content,
|
|
1796
|
-
...snapshot.finish ? { finish: snapshot.finish } : {},
|
|
1797
|
-
...snapshot.tokens ? { tokens: { ...snapshot.tokens } } : {},
|
|
1798
|
-
...snapshot.cost !== void 0 ? { cost: snapshot.cost } : {},
|
|
1799
|
-
...snapshot.error ? { error: { ...snapshot.error } } : {},
|
|
1800
|
-
...snapshot.toolCalls ? {
|
|
1801
|
-
toolCalls: snapshot.toolCalls.map((toolCall) => ({
|
|
1802
|
-
toolCallId: toolCall.toolCallId,
|
|
1803
|
-
toolName: toolCall.toolName,
|
|
1804
|
-
args: toolCall.args
|
|
1805
|
-
}))
|
|
1806
|
-
} : {}
|
|
1807
|
-
};
|
|
1808
|
-
case "tool":
|
|
1809
|
-
return {
|
|
1810
|
-
id: snapshot.id,
|
|
1811
|
-
role: "tool",
|
|
1812
|
-
createdAt,
|
|
1813
|
-
content: snapshot.content,
|
|
1814
|
-
toolCallId: snapshot.toolCallId,
|
|
1815
|
-
toolName: snapshot.toolName,
|
|
1816
|
-
result: snapshot.result,
|
|
1817
|
-
...snapshot.metadata ? { metadata: structuredClone(snapshot.metadata) } : {},
|
|
1818
|
-
...snapshot.compactedAt !== void 0 ? { compactedAt: snapshot.compactedAt } : {}
|
|
1819
|
-
};
|
|
1820
|
-
case "system":
|
|
1821
|
-
return {
|
|
1822
|
-
id: snapshot.id,
|
|
1823
|
-
role: "system",
|
|
1824
|
-
createdAt,
|
|
1825
|
-
content: snapshot.content
|
|
1826
|
-
};
|
|
1827
|
-
}
|
|
1828
|
-
}
|
|
1829
|
-
function restoreAgentWorkflowMessages(snapshots) {
|
|
1830
|
-
return snapshots.map(restoreAgentWorkflowMessage);
|
|
1831
|
-
}
|
|
1832
|
-
|
|
1833
|
-
// src/execution/workflow-planner/helpers.ts
|
|
1834
|
-
function cloneRelevantReplayDecisions(state, snapshot) {
|
|
1835
|
-
return Object.fromEntries(
|
|
1836
|
-
snapshot.toolCalls.flatMap((toolCall) => {
|
|
1837
|
-
const decision = state.replayDecisions[toolCall.toolCallId];
|
|
1838
|
-
return decision ? [[toolCall.toolCallId, { ...decision }]] : [];
|
|
1839
|
-
})
|
|
1840
|
-
);
|
|
1841
|
-
}
|
|
1842
|
-
function findAllUnresolvedToolCalls(snapshot) {
|
|
1843
|
-
const resolvedIds = new Set(
|
|
1844
|
-
snapshot.toolResults.map((toolResult) => toolResult.toolCallId)
|
|
1845
|
-
);
|
|
1846
|
-
return snapshot.toolCalls.filter(
|
|
1847
|
-
(toolCall) => !resolvedIds.has(toolCall.toolCallId)
|
|
1848
|
-
);
|
|
1849
|
-
}
|
|
1850
|
-
|
|
1851
|
-
// src/execution/workflow-planner/plan.ts
|
|
1852
|
-
function planNextAgentWorkflowOperation(state) {
|
|
1853
|
-
switch (state.phase) {
|
|
1854
|
-
case "input-commit":
|
|
1855
|
-
if (!state.pendingInput) {
|
|
1856
|
-
throw new Error(
|
|
1857
|
-
`Workflow state for session '${state.sessionId}' is in input-commit phase without a pending input message`
|
|
1858
|
-
);
|
|
1859
|
-
}
|
|
1860
|
-
return {
|
|
1861
|
-
kind: "input-commit",
|
|
1862
|
-
sessionId: state.sessionId,
|
|
1863
|
-
messages: [structuredClone(state.pendingInput)]
|
|
1864
|
-
};
|
|
1865
|
-
case "model-step":
|
|
1866
|
-
return {
|
|
1867
|
-
kind: "model-step",
|
|
1868
|
-
sessionId: state.sessionId,
|
|
1869
|
-
step: state.step,
|
|
1870
|
-
maxSteps: state.maxSteps,
|
|
1871
|
-
systemPrompts: [...state.systemPrompts],
|
|
1872
|
-
messages: state.messages.map((message) => structuredClone(message))
|
|
1873
|
-
};
|
|
1874
|
-
case "tool-batch": {
|
|
1875
|
-
if (!state.lastModelStep?.stepCommit) {
|
|
1876
|
-
throw new Error(
|
|
1877
|
-
`Workflow state for session '${state.sessionId}' is in tool-batch phase without a stepCommit snapshot`
|
|
1878
|
-
);
|
|
1879
|
-
}
|
|
1880
|
-
const allUnresolved = findAllUnresolvedToolCalls(
|
|
1881
|
-
state.lastModelStep.stepCommit
|
|
1882
|
-
);
|
|
1883
|
-
if (allUnresolved.length === 0) {
|
|
1884
|
-
throw new Error(
|
|
1885
|
-
`Workflow state for session '${state.sessionId}' is in tool-batch phase without unresolved tool calls`
|
|
1886
|
-
);
|
|
1887
|
-
}
|
|
1888
|
-
if (allUnresolved.length === 1) {
|
|
1889
|
-
return {
|
|
1890
|
-
kind: "tool-call",
|
|
1891
|
-
step: state.step,
|
|
1892
|
-
sessionId: state.sessionId,
|
|
1893
|
-
toolCall: structuredClone(allUnresolved[0]),
|
|
1894
|
-
turnState: state.turnState ? structuredClone(state.turnState) : void 0,
|
|
1895
|
-
replayDecision: cloneRelevantReplayDecisions(
|
|
1896
|
-
state,
|
|
1897
|
-
state.lastModelStep.stepCommit
|
|
1898
|
-
)[allUnresolved[0].toolCallId]
|
|
1899
|
-
};
|
|
1900
|
-
}
|
|
1901
|
-
return {
|
|
1902
|
-
kind: "tool-batch",
|
|
1903
|
-
step: state.step,
|
|
1904
|
-
sessionId: state.sessionId,
|
|
1905
|
-
toolCalls: allUnresolved.map((tc) => structuredClone(tc)),
|
|
1906
|
-
turnState: state.turnState ? structuredClone(state.turnState) : void 0,
|
|
1907
|
-
replayDecisions: cloneRelevantReplayDecisions(
|
|
1908
|
-
state,
|
|
1909
|
-
state.lastModelStep.stepCommit
|
|
1910
|
-
)
|
|
1911
|
-
};
|
|
1912
|
-
}
|
|
1913
|
-
case "step-commit":
|
|
1914
|
-
if (!state.lastModelStep?.stepCommit) {
|
|
1915
|
-
throw new Error(
|
|
1916
|
-
`Workflow state for session '${state.sessionId}' is in step-commit phase without a stepCommit snapshot`
|
|
1917
|
-
);
|
|
1918
|
-
}
|
|
1919
|
-
return {
|
|
1920
|
-
kind: "step-commit",
|
|
1921
|
-
sessionId: state.sessionId,
|
|
1922
|
-
step: state.step,
|
|
1923
|
-
snapshot: structuredClone(state.lastModelStep.stepCommit)
|
|
1924
|
-
};
|
|
1925
|
-
case "output-commit":
|
|
1926
|
-
if (!state.lastModelStep) {
|
|
1927
|
-
throw new Error(
|
|
1928
|
-
`Workflow state for session '${state.sessionId}' is in output-commit phase without a last model step`
|
|
1929
|
-
);
|
|
1930
|
-
}
|
|
1931
|
-
return {
|
|
1932
|
-
kind: "output-commit",
|
|
1933
|
-
sessionId: state.sessionId,
|
|
1934
|
-
text: state.lastModelStep.text,
|
|
1935
|
-
...state.lastModelStep.usage ? { usage: { ...state.lastModelStep.usage } } : {}
|
|
1936
|
-
};
|
|
1937
|
-
case "completed":
|
|
1938
|
-
case "failed":
|
|
1939
|
-
return void 0;
|
|
1940
|
-
}
|
|
1941
|
-
}
|
|
1942
|
-
|
|
1943
|
-
// src/execution/workflow-planner/apply.ts
|
|
1944
|
-
function applyAgentWorkflowModelStepResult(state, result, updatedAt) {
|
|
1945
|
-
const next = cloneAgentWorkflowTurnState(state);
|
|
1946
|
-
next.lastModelStep = structuredClone(result);
|
|
1947
|
-
next.turnState = structuredClone(result.turnState);
|
|
1948
|
-
next.usage = accumulateUsage(next.usage, result.usage);
|
|
1949
|
-
next.updatedAt = updatedAt;
|
|
1950
|
-
next.phase = result.finishReason === "tool-calls" ? "tool-batch" : "output-commit";
|
|
1951
|
-
return next;
|
|
1952
|
-
}
|
|
1953
|
-
function applyAgentWorkflowToolBatchResult(state, result, updatedAt) {
|
|
1954
|
-
if (state.phase !== "tool-batch") {
|
|
1955
|
-
throw new Error(
|
|
1956
|
-
`Cannot apply a tool-batch result while workflow state is in '${state.phase}' phase`
|
|
1957
|
-
);
|
|
1958
|
-
}
|
|
1959
|
-
const next = cloneAgentWorkflowTurnState(state);
|
|
1960
|
-
next.updatedAt = updatedAt;
|
|
1961
|
-
next.phase = "step-commit";
|
|
1962
|
-
if (!next.lastModelStep) {
|
|
1963
|
-
throw new Error(
|
|
1964
|
-
`Workflow state for session '${state.sessionId}' has no model step to update after tool-batch`
|
|
1965
|
-
);
|
|
1966
|
-
}
|
|
1967
|
-
next.lastModelStep.stepCommit = structuredClone(result.stepCommit);
|
|
1968
|
-
if (result.turnState) {
|
|
1969
|
-
next.turnState = structuredClone(result.turnState);
|
|
1970
|
-
}
|
|
1971
|
-
return next;
|
|
1972
|
-
}
|
|
1973
|
-
function applyAgentWorkflowToolCallResult(state, result, updatedAt) {
|
|
1974
|
-
if (state.phase !== "tool-batch") {
|
|
1975
|
-
throw new Error(
|
|
1976
|
-
`Cannot apply a tool-call result while workflow state is in '${state.phase}' phase`
|
|
1977
|
-
);
|
|
1978
|
-
}
|
|
1979
|
-
if (!state.lastModelStep?.stepCommit) {
|
|
1980
|
-
throw new Error(
|
|
1981
|
-
`Workflow state for session '${state.sessionId}' has no stepCommit snapshot in tool-batch phase`
|
|
1982
|
-
);
|
|
1983
|
-
}
|
|
1984
|
-
const next = cloneAgentWorkflowTurnState(state);
|
|
1985
|
-
const snapshot = structuredClone(state.lastModelStep.stepCommit);
|
|
1986
|
-
const existingResultIndex = snapshot.toolResults.findIndex(
|
|
1987
|
-
(toolResult) => toolResult.toolCallId === result.toolResult.toolCallId
|
|
1988
|
-
);
|
|
1989
|
-
if (existingResultIndex >= 0) {
|
|
1990
|
-
snapshot.toolResults[existingResultIndex] = structuredClone(
|
|
1991
|
-
result.toolResult
|
|
1992
|
-
);
|
|
1993
|
-
} else {
|
|
1994
|
-
snapshot.toolResults.push(structuredClone(result.toolResult));
|
|
1995
|
-
}
|
|
1996
|
-
next.lastModelStep = {
|
|
1997
|
-
...next.lastModelStep,
|
|
1998
|
-
stepCommit: snapshot
|
|
1999
|
-
};
|
|
2000
|
-
next.updatedAt = updatedAt;
|
|
2001
|
-
if (result.turnState) {
|
|
2002
|
-
next.turnState = structuredClone(result.turnState);
|
|
2003
|
-
}
|
|
2004
|
-
next.phase = snapshot.toolResults.length >= snapshot.toolCalls.length ? "step-commit" : "tool-batch";
|
|
2005
|
-
return next;
|
|
2006
|
-
}
|
|
2007
|
-
function applyAgentWorkflowCommitResult(state, result, updatedAt) {
|
|
2008
|
-
const next = cloneAgentWorkflowTurnState(state);
|
|
2009
|
-
next.messages = [
|
|
2010
|
-
...next.messages,
|
|
2011
|
-
...result.messages.map((message) => structuredClone(message))
|
|
2012
|
-
];
|
|
2013
|
-
next.updatedAt = updatedAt;
|
|
2014
|
-
switch (state.phase) {
|
|
2015
|
-
case "input-commit":
|
|
2016
|
-
next.phase = "model-step";
|
|
2017
|
-
delete next.pendingInput;
|
|
2018
|
-
return next;
|
|
2019
|
-
case "step-commit":
|
|
2020
|
-
next.step = state.step + 1;
|
|
2021
|
-
next.phase = "model-step";
|
|
2022
|
-
delete next.lastModelStep;
|
|
2023
|
-
return next;
|
|
2024
|
-
case "output-commit":
|
|
2025
|
-
next.phase = "completed";
|
|
2026
|
-
next.finalResponse = state.lastModelStep?.text ?? state.finalResponse;
|
|
2027
|
-
delete next.lastModelStep;
|
|
2028
|
-
return next;
|
|
2029
|
-
default:
|
|
2030
|
-
throw new Error(
|
|
2031
|
-
`Cannot apply a commit result while workflow state is in '${state.phase}' phase`
|
|
2032
|
-
);
|
|
2033
|
-
}
|
|
2034
|
-
}
|
|
2035
|
-
function recordAgentWorkflowReplayDecision(state, decision, updatedAt) {
|
|
2036
|
-
const next = cloneAgentWorkflowTurnState(state);
|
|
2037
|
-
next.replayDecisions[decision.toolCallId] = { ...decision };
|
|
2038
|
-
next.updatedAt = updatedAt;
|
|
2039
|
-
return next;
|
|
2040
|
-
}
|
|
2041
|
-
function failAgentWorkflowTurnState(state, error, updatedAt) {
|
|
2042
|
-
const next = cloneAgentWorkflowTurnState(state);
|
|
2043
|
-
next.phase = "failed";
|
|
2044
|
-
next.error = error.message;
|
|
2045
|
-
next.updatedAt = updatedAt;
|
|
2046
|
-
return next;
|
|
2047
|
-
}
|
|
2048
|
-
|
|
2049
|
-
export {
|
|
2050
|
-
createAgentTurnStepCommitBatch,
|
|
2051
|
-
createAgentTurnState,
|
|
2052
|
-
advanceAgentTurnState,
|
|
2053
|
-
failAgentTurnState,
|
|
2054
|
-
AgentTurnEngine,
|
|
2055
|
-
createAgentTurnEngine,
|
|
2056
|
-
estimateTokens,
|
|
2057
|
-
estimateMessageTokens,
|
|
2058
|
-
estimateConversationTokens,
|
|
2059
|
-
PRUNE_PROTECTED_TOOLS,
|
|
2060
|
-
DEFAULT_CONTEXT_LIMITS,
|
|
2061
|
-
getUsableTokenLimit,
|
|
2062
|
-
findCutPoint,
|
|
2063
|
-
ContextManager,
|
|
2064
|
-
prepareModelStep,
|
|
2065
|
-
DoomLoopError,
|
|
2066
|
-
ContextOverflowError,
|
|
2067
|
-
processStepStream,
|
|
2068
|
-
runModelStep,
|
|
2069
|
-
accumulateUsage,
|
|
2070
|
-
runToolBatch,
|
|
2071
|
-
commitStep,
|
|
2072
|
-
commitOutput,
|
|
2073
|
-
defaultAgentTaskCheckpointStrategy,
|
|
2074
|
-
createAgentTaskRunner,
|
|
2075
|
-
createAgentWorkflowTurnState,
|
|
2076
|
-
cloneAgentWorkflowTurnState,
|
|
2077
|
-
applyWorkflowInterventions,
|
|
2078
|
-
drainWorkflowInterventions,
|
|
2079
|
-
queueWorkflowFollowUps,
|
|
2080
|
-
snapshotAgentWorkflowMessage,
|
|
2081
|
-
snapshotAgentWorkflowMessages,
|
|
2082
|
-
restoreAgentWorkflowMessage,
|
|
2083
|
-
restoreAgentWorkflowMessages,
|
|
2084
|
-
planNextAgentWorkflowOperation,
|
|
2085
|
-
applyAgentWorkflowModelStepResult,
|
|
2086
|
-
applyAgentWorkflowToolBatchResult,
|
|
2087
|
-
applyAgentWorkflowToolCallResult,
|
|
2088
|
-
applyAgentWorkflowCommitResult,
|
|
2089
|
-
recordAgentWorkflowReplayDecision,
|
|
2090
|
-
failAgentWorkflowTurnState
|
|
2091
|
-
};
|