@sema-agent/core 7.69.1 → 7.71.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3205 -0
- package/dist/agents/agent-definition.d.ts +18 -0
- package/dist/agents/agent-definition.js +10 -0
- package/dist/agents/agent-transcript-tool.d.ts +2 -1
- package/dist/agents/agent-transcript-tool.js +45 -19
- package/dist/agents/cascade.d.ts +10 -0
- package/dist/agents/cascade.js +33 -5
- package/dist/agents/cc-peer-directory.d.ts +1 -1
- package/dist/agents/cc-peer-directory.js +2 -1
- package/dist/agents/child-model-seat.d.ts +1 -1
- package/dist/agents/composition-allowance.d.ts +63 -19
- package/dist/agents/composition-allowance.js +62 -45
- package/dist/agents/composition-placement.d.ts +22 -4
- package/dist/agents/composition-placement.js +10 -1
- package/dist/agents/cross-session-envelope.d.ts +4 -5
- package/dist/agents/cross-session-envelope.js +4 -5
- package/dist/agents/inherited-tool-pool.d.ts +5 -1
- package/dist/agents/inherited-tool-pool.js +7 -2
- package/dist/agents/list-agents-tool.js +2 -1
- package/dist/agents/parked-resume-drive.d.ts +38 -0
- package/dist/agents/parked-resume-drive.js +57 -0
- package/dist/agents/peer-admission.js +4 -3
- package/dist/agents/peer-held-queue.d.ts +4 -2
- package/dist/agents/peer-held-queue.js +2 -1
- package/dist/agents/peer-session-drain.d.ts +2 -0
- package/dist/agents/peer-session-drain.js +49 -29
- package/dist/agents/repair-loop.js +15 -11
- package/dist/agents/retain-ledger.d.ts +71 -18
- package/dist/agents/retain-ledger.js +47 -13
- package/dist/agents/roster-store.d.ts +11 -3
- package/dist/agents/roster-store.js +6 -2
- package/dist/agents/send-message-tool.d.ts +14 -2
- package/dist/agents/send-message-tool.js +57 -16
- package/dist/agents/subagent.d.ts +24 -7
- package/dist/agents/subagent.js +287 -154
- package/dist/agents/tool-filter.js +1 -2
- package/dist/agents/verify.d.ts +4 -1
- package/dist/agents/verify.js +34 -17
- package/dist/agents/yield-adoption.js +13 -2
- package/dist/bench/metrics.js +2 -2
- package/dist/brain/anthropic.d.ts +2 -1
- package/dist/brain/anthropic.js +3 -3
- package/dist/brain/circuit-breaker.js +1 -1
- package/dist/brain/claude-model-id.d.ts +11 -0
- package/dist/brain/claude-model-id.js +3 -1
- package/dist/brain/model-lane.d.ts +2 -1
- package/dist/brain/model-lane.js +22 -9
- package/dist/brain/open-responses.d.ts +77 -1
- package/dist/brain/open-responses.js +1 -1
- package/dist/brain/openai.d.ts +2 -1
- package/dist/brain/openai.js +3 -3
- package/dist/brain/reasoning.d.ts +8 -1
- package/dist/brain/reasoning.js +3 -0
- package/dist/brain/reference-model-traits.d.ts +13 -12
- package/dist/brain/reference-model-traits.js +11 -10
- package/dist/brain/request-route.d.ts +1 -1
- package/dist/brain/request-route.js +2 -2
- package/dist/brain/route-adjudicator.d.ts +72 -2
- package/dist/brain/route-adjudicator.js +210 -69
- package/dist/brain/route-conformance.js +35 -0
- package/dist/brain/routing.js +2 -2
- package/dist/brain/spend-meter.d.ts +56 -0
- package/dist/brain/spend-meter.js +263 -0
- package/dist/brain/stream-shared.d.ts +1 -1
- package/dist/brain/stream-shared.js +3 -1
- package/dist/config/catalog.js +10 -1
- package/dist/config/defaults.d.ts +3 -0
- package/dist/config/defaults.js +1 -0
- package/dist/core/a2a-bound-grant.d.ts +110 -0
- package/dist/core/a2a-bound-grant.js +83 -0
- package/dist/core/a2a-task-state.d.ts +153 -51
- package/dist/core/a2a-task-state.js +85 -45
- package/dist/core/a2a.d.ts +62 -14
- package/dist/core/a2a.js +298 -57
- package/dist/core/agent-config-dir.d.ts +53 -6
- package/dist/core/agent-config-dir.js +59 -6
- package/dist/core/agent-definition.d.ts +1 -1
- package/dist/core/agent-state.d.ts +10 -1
- package/dist/core/agent-state.js +11 -4
- package/dist/core/allow-entry.d.ts +80 -42
- package/dist/core/allow-entry.js +119 -62
- package/dist/core/allow-rule-shadow.d.ts +25 -3
- package/dist/core/allow-rule-shadow.js +7 -0
- package/dist/core/approval-object.js +2 -2
- package/dist/core/artifact-host.d.ts +109 -6
- package/dist/core/artifact-host.js +68 -0
- package/dist/core/ask-headline.d.ts +10 -9
- package/dist/core/ask-headline.js +9 -3
- package/dist/core/ask-origin.d.ts +143 -49
- package/dist/core/ask-origin.js +91 -53
- package/dist/core/ask-question.d.ts +74 -39
- package/dist/core/ask-question.js +150 -23
- package/dist/core/ask-unresolvable-notice.d.ts +80 -10
- package/dist/core/ask-unresolvable-notice.js +52 -14
- package/dist/core/attachment-source.d.ts +1 -1
- package/dist/core/attachment-source.js +2 -0
- package/dist/core/auto-compaction.d.ts +17 -53
- package/dist/core/auto-compaction.js +6 -10
- package/dist/core/auto-mode-directive.d.ts +17 -5
- package/dist/core/auto-mode-directive.js +12 -3
- package/dist/core/auto-mode.d.ts +34 -5
- package/dist/core/auto-mode.js +43 -5
- package/dist/core/auto-strip.js +2 -0
- package/dist/core/background-agent-store.d.ts +100 -11
- package/dist/core/background-agent-store.js +64 -6
- package/dist/core/background-shell.d.ts +9 -0
- package/dist/core/background-shell.js +10 -0
- package/dist/core/caller-text.d.ts +4 -35
- package/dist/core/caller-text.js +2 -23
- package/dist/core/caller-tool-name.d.ts +6 -0
- package/dist/core/caller-tool-name.js +2 -2
- package/dist/core/canonical-json.d.ts +9 -0
- package/dist/core/canonical-json.js +6 -0
- package/dist/core/checkpoint-features.d.ts +79 -500
- package/dist/core/checkpoint-features.js +53 -19
- package/dist/core/checkpoint-generation.d.ts +89 -19
- package/dist/core/checkpoint-generation.js +89 -14
- package/dist/core/checkpoint-queries.d.ts +109 -18
- package/dist/core/checkpoint-queries.js +117 -11
- package/dist/core/checkpoint-rekey.d.ts +2 -1
- package/dist/core/checkpoint-rekey.js +2 -2
- package/dist/core/checkpoint-requirements.d.ts +76 -8
- package/dist/core/checkpoint-requirements.js +14 -7
- package/dist/core/checkpoint-row-verdict.d.ts +71 -19
- package/dist/core/checkpoint-row-verdict.js +93 -68
- package/dist/core/checkpoint-store.d.ts +139 -109
- package/dist/core/checkpoint-store.js +50 -34
- package/dist/core/classifier-unavailable-arm.d.ts +6 -1
- package/dist/core/classifier-unavailable-arm.js +8 -5
- package/dist/core/command-sandbox.d.ts +5 -3
- package/dist/core/command-sandbox.js +17 -9
- package/dist/core/config-refusal-codes.d.ts +7 -5
- package/dist/core/config-refusal-codes.js +8 -2
- package/dist/core/config-refusal-input.d.ts +46 -0
- package/dist/core/config-refusal-input.js +62 -0
- package/dist/core/context-edit.d.ts +18 -1
- package/dist/core/context-edit.js +13 -2
- package/dist/core/context-guard.d.ts +60 -13
- package/dist/core/context-guard.js +77 -35
- package/dist/core/context-settings.d.ts +2 -1
- package/dist/core/context-settings.js +10 -6
- package/dist/core/corrupt-session-form.d.ts +97 -0
- package/dist/core/corrupt-session-form.js +54 -0
- package/dist/core/cross-boundary-taint.d.ts +3 -3
- package/dist/core/data-root.d.ts +32 -0
- package/dist/core/data-root.js +86 -0
- package/dist/core/decision-receipt.d.ts +2 -0
- package/dist/core/decision-receipt.js +3 -2
- package/dist/core/declaration-words.d.ts +38 -0
- package/dist/core/declaration-words.js +32 -0
- package/dist/core/delegation-frames.d.ts +76 -35
- package/dist/core/delegation-frames.js +21 -1
- package/dist/core/durable-sync.d.ts +9 -0
- package/dist/core/durable-sync.js +37 -0
- package/dist/core/effective-path-target.d.ts +23 -0
- package/dist/core/effective-path-target.js +15 -1
- package/dist/core/engine-attestation.d.ts +5 -1
- package/dist/core/engine-attestation.js +1 -0
- package/dist/core/engine-capabilities.d.ts +123 -11
- package/dist/core/engine-capabilities.js +1 -1
- package/dist/core/engine-notice.d.ts +313 -163
- package/dist/core/engine-notice.js +13 -19
- package/dist/core/engine-version.js +1 -1
- package/dist/core/entries-not-applied.d.ts +22 -0
- package/dist/core/entries-not-applied.js +27 -0
- package/dist/core/exec-gate.d.ts +8 -1
- package/dist/core/exec-gate.js +24 -9
- package/dist/core/exec-outcome.d.ts +102 -0
- package/dist/core/exec-outcome.js +79 -0
- package/dist/core/existing-target.d.ts +45 -0
- package/dist/core/existing-target.js +54 -8
- package/dist/core/fast-tier-door.d.ts +2 -2
- package/dist/core/fast-tier-door.js +3 -3
- package/dist/core/file-history-store.d.ts +230 -27
- package/dist/core/file-history-store.js +234 -45
- package/dist/core/gate-fold.js +21 -8
- package/dist/core/gate-lanes.js +72 -45
- package/dist/core/gate-outcome.d.ts +3 -1
- package/dist/core/gate-outcome.js +7 -1
- package/dist/core/git-worktree-env.d.ts +25 -5
- package/dist/core/git-worktree-env.js +38 -13
- package/dist/core/governance-codes.d.ts +231 -43
- package/dist/core/governance-codes.js +552 -47
- package/dist/core/grant-holder.d.ts +53 -0
- package/dist/core/grant-holder.js +80 -0
- package/dist/core/hands-band.d.ts +1 -1
- package/dist/core/hooks.d.ts +80 -14
- package/dist/core/hooks.js +6 -2
- package/dist/core/host-floor.d.ts +1 -1
- package/dist/core/host-floor.js +1 -1
- package/dist/core/identity-rekey.d.ts +2 -1
- package/dist/core/identity-rekey.js +5 -5
- package/dist/core/image-admission.d.ts +2 -2
- package/dist/core/image-admission.js +1 -1
- package/dist/core/isolation-scope.d.ts +42 -17
- package/dist/core/isolation-scope.js +12 -4
- package/dist/core/leg-identity.d.ts +17 -2
- package/dist/core/leg-identity.js +6 -1
- package/dist/core/locked-config.d.ts +93 -17
- package/dist/core/locked-config.js +109 -36
- package/dist/core/mailbox-store.d.ts +4 -0
- package/dist/core/mailbox-store.js +7 -0
- package/dist/core/mcp-call-meta.d.ts +52 -7
- package/dist/core/mcp-call-meta.js +21 -2
- package/dist/core/mcp-failure.d.ts +13 -4
- package/dist/core/mcp-failure.js +10 -0
- package/dist/core/mcp-host-read.d.ts +1 -1
- package/dist/core/mcp-injection-drop.d.ts +30 -13
- package/dist/core/mcp-injection-drop.js +25 -7
- package/dist/core/mcp-leg-wait.d.ts +88 -0
- package/dist/core/mcp-leg-wait.js +100 -0
- package/dist/core/mcp-name-judge.js +1 -2
- package/dist/core/mcp-probe.d.ts +30 -1
- package/dist/core/mcp-probe.js +5 -3
- package/dist/core/mcp-read-bound.d.ts +51 -0
- package/dist/core/mcp-read-bound.js +49 -0
- package/dist/core/mcp-server-link.js +4 -3
- package/dist/core/mcp-server-spec.d.ts +115 -26
- package/dist/core/mcp-server-spec.js +52 -19
- package/dist/core/mcp-server-unavailable-notice.d.ts +15 -6
- package/dist/core/mcp-server-unavailable-notice.js +12 -11
- package/dist/core/mcp-stderr-lines.d.ts +69 -0
- package/dist/core/mcp-stderr-lines.js +333 -0
- package/dist/core/mcp.d.ts +32 -9
- package/dist/core/mcp.js +189 -46
- package/dist/core/member-outcome.d.ts +302 -0
- package/dist/core/member-outcome.js +305 -0
- package/dist/core/memory-engine/consolidation.js +3 -3
- package/dist/core/memory-engine/content-origin.js +5 -4
- package/dist/core/memory-engine/control-objects.js +6 -4
- package/dist/core/memory-engine/delegation-settlement.js +5 -5
- package/dist/core/memory-engine/distiller.js +2 -2
- package/dist/core/memory-engine/dual-root.d.ts +12 -5
- package/dist/core/memory-engine/dual-root.js +13 -7
- package/dist/core/memory-engine/engine.d.ts +27 -31
- package/dist/core/memory-engine/engine.js +122 -80
- package/dist/core/memory-engine/file-backend.d.ts +23 -5
- package/dist/core/memory-engine/file-backend.js +29 -32
- package/dist/core/memory-engine/frontmatter.js +1 -1
- package/dist/core/memory-engine/index-copies.d.ts +8 -6
- package/dist/core/memory-engine/index-copies.js +2 -1
- package/dist/core/memory-engine/index.d.ts +4 -2
- package/dist/core/memory-engine/index.js +4 -2
- package/dist/core/memory-engine/layout.d.ts +197 -29
- package/dist/core/memory-engine/layout.js +271 -59
- package/dist/core/memory-engine/memory-backend-contract.js +20 -20
- package/dist/core/memory-engine/memory-deployment.d.ts +29 -16
- package/dist/core/memory-engine/memory-deployment.js +38 -28
- package/dist/core/memory-engine/mount-failed-notice.d.ts +71 -4
- package/dist/core/memory-engine/mount-failed-notice.js +54 -3
- package/dist/core/memory-engine/projection-ledger.d.ts +48 -0
- package/dist/core/memory-engine/projection-ledger.js +130 -0
- package/dist/core/memory-engine/scope-contract.js +2 -2
- package/dist/core/memory-engine/sync-client.js +1 -2
- package/dist/core/memory-engine/types.d.ts +10 -4
- package/dist/core/memory.js +3 -5
- package/dist/core/mode-policy.d.ts +87 -16
- package/dist/core/mode-policy.js +69 -29
- package/dist/core/model-seat.d.ts +13 -1
- package/dist/core/mods/classic-events.d.ts +13 -1
- package/dist/core/mods/dollar.js +2 -1
- package/dist/core/mods/extension-call.d.ts +3 -0
- package/dist/core/mods/extension-call.js +3 -0
- package/dist/core/mods/host.d.ts +2 -1
- package/dist/core/mods/host.js +7 -6
- package/dist/core/mods/kernel/dispatch.d.ts +4 -0
- package/dist/core/mods/kernel/dispatch.js +3 -3
- package/dist/core/mods/kernel/events.d.ts +11 -3
- package/dist/core/mods/kernel/events.js +4 -4
- package/dist/core/mods/kernel/index.d.ts +1 -1
- package/dist/core/mods/kernel/index.js +1 -1
- package/dist/core/mods/kernel/registration.d.ts +5 -2
- package/dist/core/mods/kernel/registration.js +19 -3
- package/dist/core/mods/message-display.d.ts +6 -3
- package/dist/core/mods/message-display.js +13 -5
- package/dist/core/mods/package.d.ts +12 -1
- package/dist/core/mods/package.js +36 -9
- package/dist/core/mods/stations.d.ts +15 -2
- package/dist/core/mods/stations.js +22 -6
- package/dist/core/mods/teammate-stations.d.ts +78 -0
- package/dist/core/mods/teammate-stations.js +108 -0
- package/dist/core/mounted-mcp.js +1 -2
- package/dist/core/namespaced-rule-name.d.ts +1 -1
- package/dist/core/namespaced-rule-name.js +1 -1
- package/dist/core/native-signal.d.ts +13 -0
- package/dist/core/native-signal.js +18 -0
- package/dist/core/notice-fact.d.ts +28 -0
- package/dist/core/notice-fact.js +25 -0
- package/dist/core/owner-identity.d.ts +8 -3
- package/dist/core/owner-identity.js +6 -3
- package/dist/core/parent-spec-seat.d.ts +16 -6
- package/dist/core/parent-spec-seat.js +28 -6
- package/dist/core/park-resumability.d.ts +25 -18
- package/dist/core/park-resumability.js +12 -4
- package/dist/core/park-selfcheck.js +2 -1
- package/dist/core/path-rule-binding.js +1 -1
- package/dist/core/peer-seat.d.ts +1 -2
- package/dist/core/permission-rule-consent.d.ts +50 -1
- package/dist/core/permission-rule-consent.js +121 -14
- package/dist/core/permission-rule-model.d.ts +145 -43
- package/dist/core/permission-rule-model.js +155 -26
- package/dist/core/permission-rule-org.d.ts +13 -0
- package/dist/core/permission-rule-org.js +9 -1
- package/dist/core/permission-rule-provider.d.ts +112 -8
- package/dist/core/permission-rule-provider.js +439 -29
- package/dist/core/permission-rule-session.d.ts +35 -5
- package/dist/core/permission-rule-session.js +35 -2
- package/dist/core/permission-rule-store.d.ts +24 -3
- package/dist/core/permission-rule-store.js +56 -14
- package/dist/core/permission-rule-sync.js +5 -2
- package/dist/core/permission-rules.d.ts +2 -2
- package/dist/core/permission-rules.js +9 -5
- package/dist/core/persisted-rule-arms.d.ts +10 -4
- package/dist/core/persisted-rule-arms.js +16 -11
- package/dist/core/persisted-rule-buckets.d.ts +66 -0
- package/dist/core/persisted-rule-buckets.js +57 -0
- package/dist/core/plan-review-facts.d.ts +33 -0
- package/dist/core/plan-review-facts.js +25 -0
- package/dist/core/prefix-declaration.d.ts +50 -0
- package/dist/core/prefix-declaration.js +13 -0
- package/dist/core/present-plan-tool.d.ts +13 -3
- package/dist/core/present-plan-tool.js +14 -3
- package/dist/core/pricing.d.ts +5 -1
- package/dist/core/pricing.js +8 -5
- package/dist/core/principal-name.d.ts +67 -5
- package/dist/core/principal-name.js +61 -16
- package/dist/core/process-identity.d.ts +11 -7
- package/dist/core/process-identity.js +26 -36
- package/dist/core/process-table.d.ts +67 -0
- package/dist/core/process-table.js +177 -0
- package/dist/core/protocol-http-auth.d.ts +75 -12
- package/dist/core/protocol-http-auth.js +223 -26
- package/dist/core/protocol-revocation.d.ts +29 -10
- package/dist/core/protocol-revocation.js +9 -5
- package/dist/core/read-only-shell.d.ts +1 -1
- package/dist/core/read-only-shell.js +1 -1
- package/dist/core/read-root-grant-screen.d.ts +19 -7
- package/dist/core/read-root-grant-screen.js +14 -5
- package/dist/core/reminder-mint.d.ts +6 -0
- package/dist/core/reminder-mint.js +13 -0
- package/dist/core/remote-env.d.ts +153 -11
- package/dist/core/remote-env.js +20 -0
- package/dist/core/request-copy-projection.js +97 -18
- package/dist/core/resource-limit-reasons.d.ts +52 -0
- package/dist/core/resource-limit-reasons.js +6 -0
- package/dist/core/resume-at-refusal.d.ts +10 -6
- package/dist/core/resume-at-refusal.js +2 -2
- package/dist/core/resume-config-judge.d.ts +3 -2
- package/dist/core/resume-config-judge.js +3 -2
- package/dist/core/resume-startup-cause.d.ts +35 -6
- package/dist/core/resume-startup-cause.js +53 -10
- package/dist/core/retention.d.ts +12 -2
- package/dist/core/retention.js +6 -1
- package/dist/core/retired-keys.d.ts +5 -0
- package/dist/core/retired-keys.js +12 -0
- package/dist/core/rewind-conversation.d.ts +58 -0
- package/dist/core/rewind-conversation.js +1 -0
- package/dist/core/rewrite-rejudge.d.ts +9 -1
- package/dist/core/rewrite-rejudge.js +11 -1
- package/dist/core/roles.d.ts +61 -3
- package/dist/core/roles.js +81 -28
- package/dist/core/rule-lane-reads.d.ts +2 -1
- package/dist/core/rule-lane-reads.js +54 -29
- package/dist/core/rule-offer-read.js +8 -4
- package/dist/core/rule-owner.d.ts +6 -1
- package/dist/core/rule-owner.js +8 -2
- package/dist/core/rule-store-fault.d.ts +4 -2
- package/dist/core/rule-store-fault.js +4 -1
- package/dist/core/runner/advertised-writable-dirs.d.ts +17 -0
- package/dist/core/runner/advertised-writable-dirs.js +15 -9
- package/dist/core/runner/announce-once-ledger.js +12 -11
- package/dist/core/runner/assemble-result.d.ts +36 -17
- package/dist/core/runner/assemble-result.js +35 -8
- package/dist/core/runner/auto-strip-notice.d.ts +1 -1
- package/dist/core/runner/boundary-reminders.d.ts +104 -0
- package/dist/core/runner/boundary-reminders.js +108 -0
- package/dist/core/runner/branch-window.d.ts +25 -2
- package/dist/core/runner/branch-window.js +47 -11
- package/dist/core/runner/branch-writeback.d.ts +21 -7
- package/dist/core/runner/branch-writeback.js +44 -6
- package/dist/core/runner/chain-refusal-throw.d.ts +19 -0
- package/dist/core/runner/chain-refusal-throw.js +30 -0
- package/dist/core/runner/changes-git.d.ts +21 -0
- package/dist/core/runner/changes-git.js +291 -0
- package/dist/core/runner/changes-history.d.ts +80 -0
- package/dist/core/runner/changes-history.js +351 -0
- package/dist/core/runner/checkpoint-scope.d.ts +16 -8
- package/dist/core/runner/checkpoint-scope.js +6 -4
- package/dist/core/runner/child-tree.d.ts +31 -20
- package/dist/core/runner/child-tree.js +24 -9
- package/dist/core/runner/classifier-ladder.d.ts +4 -2
- package/dist/core/runner/classifier-ladder.js +14 -12
- package/dist/core/runner/clock-and-limits.d.ts +0 -3
- package/dist/core/runner/clock-and-limits.js +1 -2
- package/dist/core/runner/command-sandbox-frame.js +2 -1
- package/dist/core/runner/compact-session.js +27 -51
- package/dist/core/runner/compaction-restate.js +2 -1
- package/dist/core/runner/constraint-layers.d.ts +120 -0
- package/dist/core/runner/constraint-layers.js +115 -0
- package/dist/core/runner/construction-doors.js +2 -0
- package/dist/core/runner/content-ask-bindings.d.ts +3 -3
- package/dist/core/runner/continuation-gate.d.ts +8 -4
- package/dist/core/runner/continuation-gate.js +5 -1
- package/dist/core/runner/continues-from.d.ts +7 -0
- package/dist/core/runner/continues-from.js +9 -0
- package/dist/core/runner/contracts.d.ts +225 -55
- package/dist/core/runner/cross-boundary-lane.js +2 -1
- package/dist/core/runner/decide-continuation.d.ts +2 -2
- package/dist/core/runner/delegation-owner.d.ts +246 -45
- package/dist/core/runner/delegation-owner.js +237 -63
- package/dist/core/runner/denial-limit-arms.js +3 -4
- package/dist/core/runner/earlier-grammar-notice.js +5 -3
- package/dist/core/runner/env-capability-census.js +2 -1
- package/dist/core/runner/expire-settle.d.ts +17 -0
- package/dist/core/runner/expire-settle.js +8 -2
- package/dist/core/runner/file-history-request.d.ts +4 -3
- package/dist/core/runner/file-history-request.js +4 -1
- package/dist/core/runner/file-history-restore.d.ts +46 -12
- package/dist/core/runner/file-history-restore.js +45 -10
- package/dist/core/runner/finish-reason-seat.js +13 -4
- package/dist/core/runner/gate-exit.d.ts +30 -1
- package/dist/core/runner/gate-exit.js +37 -14
- package/dist/core/runner/halt-attribution.js +1 -1
- package/dist/core/runner/initial-run-state.d.ts +1 -1
- package/dist/core/runner/initial-run-state.js +2 -2
- package/dist/core/runner/left-as-is-seat.js +1 -1
- package/dist/core/runner/mcp-redial.d.ts +15 -4
- package/dist/core/runner/mcp-redial.js +53 -6
- package/dist/core/runner/memory-capture-optout.d.ts +7 -11
- package/dist/core/runner/memory-capture-optout.js +7 -4
- package/dist/core/runner/memory-phase-refusals.d.ts +19 -0
- package/dist/core/runner/memory-phase-refusals.js +18 -0
- package/dist/core/runner/messages-omitted-seat.d.ts +24 -1
- package/dist/core/runner/messages-omitted-seat.js +30 -9
- package/dist/core/runner/model-fallback-seat.d.ts +18 -5
- package/dist/core/runner/model-fallback-seat.js +29 -24
- package/dist/core/runner/model-lane-seat.d.ts +23 -1
- package/dist/core/runner/model-lane-seat.js +20 -2
- package/dist/core/runner/nested-memory-content.js +1 -1
- package/dist/core/runner/nested-memory-lane.d.ts +74 -59
- package/dist/core/runner/nested-memory-lane.js +335 -114
- package/dist/core/runner/own-model-money-door.d.ts +13 -0
- package/dist/core/runner/own-model-money-door.js +17 -0
- package/dist/core/runner/park-commit.d.ts +29 -6
- package/dist/core/runner/park-commit.js +20 -8
- package/dist/core/runner/permission-rule-lanes.d.ts +9 -0
- package/dist/core/runner/permission-rule-lanes.js +51 -11
- package/dist/core/runner/person-path-rows.d.ts +124 -21
- package/dist/core/runner/person-path-rows.js +179 -20
- package/dist/core/runner/placement-fence.d.ts +8 -2
- package/dist/core/runner/placement-fence.js +8 -3
- package/dist/core/runner/policy-throw.d.ts +3 -2
- package/dist/core/runner/policy-throw.js +2 -2
- package/dist/core/runner/prefix-ledger.d.ts +57 -3
- package/dist/core/runner/prefix-ledger.js +98 -8
- package/dist/core/runner/prepare-acquire-reconcile.d.ts +24 -14
- package/dist/core/runner/prepare-acquire-reconcile.js +44 -78
- package/dist/core/runner/prepare-advisor.js +2 -1
- package/dist/core/runner/prepare-artifact.d.ts +18 -2
- package/dist/core/runner/prepare-artifact.js +8 -3
- package/dist/core/runner/prepare-ask-lane.d.ts +12 -0
- package/dist/core/runner/prepare-ask-lane.js +19 -8
- package/dist/core/runner/prepare-boundary-parks.js +12 -5
- package/dist/core/runner/prepare-caps-and-workflow.js +37 -25
- package/dist/core/runner/prepare-config-doors.d.ts +22 -18
- package/dist/core/runner/prepare-config-doors.js +143 -127
- package/dist/core/runner/prepare-context-lane.d.ts +32 -11
- package/dist/core/runner/prepare-context-lane.js +77 -48
- package/dist/core/runner/prepare-defer-classify.d.ts +16 -0
- package/dist/core/runner/prepare-defer-classify.js +30 -8
- package/dist/core/runner/prepare-delegation-surface.d.ts +2 -0
- package/dist/core/runner/prepare-delegation-surface.js +8 -4
- package/dist/core/runner/prepare-execution-env.d.ts +7 -1
- package/dist/core/runner/prepare-execution-env.js +18 -8
- package/dist/core/runner/prepare-file-history.d.ts +26 -0
- package/dist/core/runner/prepare-file-history.js +19 -2
- package/dist/core/runner/prepare-gate-stations.d.ts +10 -0
- package/dist/core/runner/prepare-gate-stations.js +15 -6
- package/dist/core/runner/prepare-hands-readface.d.ts +28 -7
- package/dist/core/runner/prepare-hands-readface.js +83 -23
- package/dist/core/runner/prepare-inherited-gate.d.ts +28 -14
- package/dist/core/runner/prepare-inherited-gate.js +35 -17
- package/dist/core/runner/prepare-leg-adoption.d.ts +2 -2
- package/dist/core/runner/prepare-memory-engine-session.js +4 -2
- package/dist/core/runner/prepare-memory.d.ts +8 -1
- package/dist/core/runner/prepare-memory.js +37 -33
- package/dist/core/runner/prepare-offload-wrappers.d.ts +7 -7
- package/dist/core/runner/prepare-offload-wrappers.js +26 -17
- package/dist/core/runner/prepare-park-ask.d.ts +8 -11
- package/dist/core/runner/prepare-park-ask.js +18 -12
- package/dist/core/runner/prepare-policy-chain.d.ts +29 -1
- package/dist/core/runner/prepare-policy-chain.js +69 -33
- package/dist/core/runner/prepare-project-context.d.ts +4 -0
- package/dist/core/runner/prepare-project-context.js +9 -8
- package/dist/core/runner/prepare-prompt-assembly.d.ts +3 -0
- package/dist/core/runner/prepare-prompt-assembly.js +6 -5
- package/dist/core/runner/prepare-protocol-tools.d.ts +2 -2
- package/dist/core/runner/prepare-protocol-tools.js +44 -24
- package/dist/core/runner/prepare-question-face.d.ts +4 -9
- package/dist/core/runner/prepare-question-face.js +8 -3
- package/dist/core/runner/prepare-suspend-saga.d.ts +11 -2
- package/dist/core/runner/prepare-suspend-saga.js +28 -8
- package/dist/core/runner/prepare-task.d.ts +4 -7
- package/dist/core/runner/prepare-task.js +203 -74
- package/dist/core/runner/prepare-tool-disclosure-mount.js +10 -5
- package/dist/core/runner/prepare-turn-wiring.d.ts +3 -1
- package/dist/core/runner/prepare-turn-wiring.js +15 -11
- package/dist/core/runner/prepare-wiring-manifest.d.ts +6 -19
- package/dist/core/runner/prepare-wiring-manifest.js +17 -35
- package/dist/core/runner/prepare-workspace-restore.d.ts +4 -11
- package/dist/core/runner/prepare-workspace-restore.js +60 -42
- package/dist/core/runner/read-root-grant.d.ts +49 -13
- package/dist/core/runner/read-root-grant.js +54 -21
- package/dist/core/runner/read-session-changes.d.ts +9 -0
- package/dist/core/runner/read-session-changes.js +192 -0
- package/dist/core/runner/remote-env-retry.d.ts +4 -4
- package/dist/core/runner/resume-admission.d.ts +14 -7
- package/dist/core/runner/resume-admission.js +28 -16
- package/dist/core/runner/resume-apply.js +9 -6
- package/dist/core/runner/resume-checkpoint-screen.d.ts +7 -2
- package/dist/core/runner/resume-checkpoint-screen.js +32 -17
- package/dist/core/runner/resume-claim.d.ts +2 -2
- package/dist/core/runner/resume-claim.js +4 -4
- package/dist/core/runner/resume-internals-and-config.d.ts +3 -0
- package/dist/core/runner/resume-internals-and-config.js +10 -7
- package/dist/core/runner/resume-policy-outcome.d.ts +5 -4
- package/dist/core/runner/resume-policy-outcome.js +8 -6
- package/dist/core/runner/resume-preflight.d.ts +3 -0
- package/dist/core/runner/resume-preflight.js +10 -3
- package/dist/core/runner/retired-name-policy.d.ts +15 -0
- package/dist/core/runner/retired-name-policy.js +37 -0
- package/dist/core/runner/retired-runner-deps.js +3 -1
- package/dist/core/runner/rewind-conversation.d.ts +10 -0
- package/dist/core/runner/rewind-conversation.js +107 -0
- package/dist/core/runner/rewind-files.js +56 -24
- package/dist/core/runner/rewind-outcome.d.ts +27 -0
- package/dist/core/runner/rewind-outcome.js +14 -0
- package/dist/core/runner/rewind-target.d.ts +28 -0
- package/dist/core/runner/rewind-target.js +58 -0
- package/dist/core/runner/role-resolution-table.d.ts +3 -16
- package/dist/core/runner/role-resolution-table.js +1 -3
- package/dist/core/runner/role-seat-defaulted.d.ts +14 -5
- package/dist/core/runner/role-seat-defaulted.js +17 -13
- package/dist/core/runner/rule-store-unreadable-notice.d.ts +8 -6
- package/dist/core/runner/rule-store-unreadable-notice.js +6 -4
- package/dist/core/runner/run-attachment-seats.js +2 -1
- package/dist/core/runner/run-clock-and-content.js +2 -0
- package/dist/core/runner/run-compaction-machinery.js +2 -2
- package/dist/core/runner/run-harness-handlers.js +43 -11
- package/dist/core/runner/run-identity-wiring.d.ts +2 -0
- package/dist/core/runner/run-identity-wiring.js +5 -2
- package/dist/core/runner/run-leg.js +30 -29
- package/dist/core/runner/run-notification-lane.d.ts +3 -0
- package/dist/core/runner/run-notification-lane.js +4 -4
- package/dist/core/runner/run-settle-and-teardown.d.ts +4 -2
- package/dist/core/runner/run-settle-and-teardown.js +78 -51
- package/dist/core/runner/run-stop-and-final-verify.d.ts +4 -0
- package/dist/core/runner/run-stop-and-final-verify.js +71 -73
- package/dist/core/runner/run-telemetry-and-budget-seats.js +14 -8
- package/dist/core/runner/run-terminal-adoption.d.ts +1 -1
- package/dist/core/runner/run-terminal-adoption.js +3 -3
- package/dist/core/runner/run-turn-boundary.js +10 -6
- package/dist/core/runner/runtask.d.ts +29 -20
- package/dist/core/runner/runtask.js +35 -16
- package/dist/core/runner/sandbox-network-seat.js +1 -1
- package/dist/core/runner/seat-model-doors.d.ts +6 -5
- package/dist/core/runner/seat-model-doors.js +4 -3
- package/dist/core/runner/session-call-grant-station.d.ts +64 -0
- package/dist/core/runner/session-call-grant-station.js +119 -0
- package/dist/core/runner/session-file-state-replay.d.ts +47 -8
- package/dist/core/runner/session-file-state-replay.js +99 -13
- package/dist/core/runner/session-files-open.d.ts +64 -0
- package/dist/core/runner/session-files-open.js +33 -0
- package/dist/core/runner/session-prompt-seats.d.ts +95 -0
- package/dist/core/runner/session-prompt-seats.js +62 -0
- package/dist/core/runner/session-read-file-states.d.ts +37 -41
- package/dist/core/runner/session-read-file-states.js +14 -6
- package/dist/core/runner/session-rule-policy.d.ts +5 -0
- package/dist/core/runner/session-rule-policy.js +16 -9
- package/dist/core/runner/session-verb-doors.d.ts +41 -4
- package/dist/core/runner/session-verb-doors.js +66 -11
- package/dist/core/runner/session-write-ledger.d.ts +8 -0
- package/dist/core/runner/session-write-ledger.js +16 -0
- package/dist/core/runner/shared-read-classifier.d.ts +14 -3
- package/dist/core/runner/shared-read-classifier.js +14 -6
- package/dist/core/runner/shell-env-withheld.d.ts +4 -2
- package/dist/core/runner/shell-env-withheld.js +3 -2
- package/dist/core/runner/side-call-account.d.ts +47 -5
- package/dist/core/runner/side-call-account.js +42 -4
- package/dist/core/runner/skipped-rules-notice.d.ts +5 -5
- package/dist/core/runner/skipped-rules-notice.js +3 -3
- package/dist/core/runner/stop-tail-notice.d.ts +7 -0
- package/dist/core/runner/stop-tail-notice.js +23 -8
- package/dist/core/runner/stream-reap.js +4 -2
- package/dist/core/runner/stream-settle-backstop.d.ts +1 -1
- package/dist/core/runner/stream-settle-backstop.js +20 -20
- package/dist/core/runner/sub-agent-deny-lists.d.ts +26 -7
- package/dist/core/runner/sub-agent-deny-lists.js +23 -15
- package/dist/core/runner/task-start-doors.d.ts +7 -3
- package/dist/core/runner/task-start-doors.js +72 -31
- package/dist/core/runner/terminal-account.js +26 -11
- package/dist/core/runner/terminal-projection.d.ts +4 -2
- package/dist/core/runner/terminal-projection.js +2 -2
- package/dist/core/runner/tool-defer-gate.d.ts +1 -1
- package/dist/core/runner/tool-end-body.d.ts +8 -1
- package/dist/core/runner/tool-end-body.js +4 -3
- package/dist/core/runner/tool-face-overlay.js +6 -4
- package/dist/core/runner/tool-result-media-seat.d.ts +2 -1
- package/dist/core/runner/tool-table-view.js +1 -1
- package/dist/core/runner/tool-turn-repair-seat.d.ts +2 -2
- package/dist/core/runner/tool-turn-repair-seat.js +12 -7
- package/dist/core/runner/trim-stretch.d.ts +43 -0
- package/dist/core/runner/trim-stretch.js +34 -0
- package/dist/core/runner/turn-attachments.d.ts +22 -1
- package/dist/core/runner/turn-attachments.js +27 -5
- package/dist/core/runner/unreadable-person-rows.d.ts +39 -0
- package/dist/core/runner/unreadable-person-rows.js +20 -0
- package/dist/core/runner/verdict-refusal.d.ts +22 -7
- package/dist/core/runner/verdict-refusal.js +35 -3
- package/dist/core/runner/workspace-sync.d.ts +49 -0
- package/dist/core/runner/workspace-sync.js +170 -0
- package/dist/core/runner-deps.d.ts +63 -34
- package/dist/core/scheduler.d.ts +34 -14
- package/dist/core/secret-env.d.ts +188 -18
- package/dist/core/secret-env.js +291 -56
- package/dist/core/sensitive-path-policy.js +3 -2
- package/dist/core/session-call-grant-screen.d.ts +58 -0
- package/dist/core/session-call-grant-screen.js +18 -0
- package/dist/core/session-call-grant.d.ts +93 -0
- package/dist/core/session-call-grant.js +524 -0
- package/dist/core/session-changes.d.ts +260 -0
- package/dist/core/session-changes.js +40 -0
- package/dist/core/session-checkout.d.ts +90 -3
- package/dist/core/session-checkout.js +142 -9
- package/dist/core/session-log-transfer.js +13 -7
- package/dist/core/session-policy-store.d.ts +54 -12
- package/dist/core/session-policy-store.js +66 -26
- package/dist/core/session-store.d.ts +41 -11
- package/dist/core/session-store.js +59 -16
- package/dist/core/session.d.ts +92 -13
- package/dist/core/session.js +8 -1
- package/dist/core/shared-artifact-reads.d.ts +93 -0
- package/dist/core/shared-artifact-reads.js +94 -0
- package/dist/core/shell-read-silence.d.ts +3 -3
- package/dist/core/shell-read-silence.js +3 -1
- package/dist/core/shell-run-candidates.d.ts +23 -6
- package/dist/core/shell-run-candidates.js +34 -11
- package/dist/core/skill-grant.d.ts +11 -6
- package/dist/core/skill-grant.js +24 -16
- package/dist/core/skills-directory.d.ts +9 -45
- package/dist/core/skills-directory.js +9 -722
- package/dist/core/spend-account.d.ts +232 -0
- package/dist/core/spend-account.js +289 -0
- package/dist/core/store-contracts/background-agent-store-contract.js +85 -0
- package/dist/core/store-contracts/checkpoint-store-contract.d.ts +28 -6
- package/dist/core/store-contracts/checkpoint-store-contract.js +423 -35
- package/dist/core/store-contracts/file-history-store-contract.d.ts +11 -3
- package/dist/core/store-contracts/file-history-store-contract.js +66 -6
- package/dist/core/store-contracts/grant-fixture.d.ts +52 -0
- package/dist/core/store-contracts/grant-fixture.js +84 -0
- package/dist/core/store-contracts/mailbox-store-contract.d.ts +2 -1
- package/dist/core/store-contracts/mailbox-store-contract.js +22 -11
- package/dist/core/store-contracts/peer-directory-contract.js +8 -0
- package/dist/core/store-contracts/permission-rule-sync-contract.js +3 -3
- package/dist/core/store-contracts/session-deletion-cascade-contract.js +23 -4
- package/dist/core/store-contracts/session-policy-store-contract.js +9 -0
- package/dist/core/store-contracts/session-repo-contract.js +56 -1
- package/dist/core/store-contracts/session-store-contract.d.ts +35 -2
- package/dist/core/store-contracts/session-store-contract.js +579 -6
- package/dist/core/store-contracts/tool-result-store-contract.js +8 -7
- package/dist/core/store-contracts/workflow-journal-store-contract.js +80 -8
- package/dist/core/suspend-lane-reasons.d.ts +13 -0
- package/dist/core/suspend-lane-reasons.js +5 -0
- package/dist/core/synthetic-read-verdict.d.ts +5 -3
- package/dist/core/synthetic-read-verdict.js +1 -1
- package/dist/core/task-event.d.ts +57 -53
- package/dist/core/task-limits.d.ts +30 -8
- package/dist/core/task-notification.d.ts +50 -19
- package/dist/core/task-notification.js +54 -18
- package/dist/core/task-registry-agent.d.ts +36 -31
- package/dist/core/task-registry-agent.js +116 -35
- package/dist/core/task-registry-monitor.js +2 -1
- package/dist/core/task-registry-shared.d.ts +112 -20
- package/dist/core/task-registry-shared.js +33 -7
- package/dist/core/task-registry-workflow.d.ts +9 -1
- package/dist/core/task-registry-workflow.js +11 -3
- package/dist/core/task-registry.d.ts +47 -28
- package/dist/core/task-registry.js +77 -20
- package/dist/core/task-result.d.ts +199 -35
- package/dist/core/task-spec-members.d.ts +21 -3
- package/dist/core/task-spec-members.js +11 -2
- package/dist/core/task-spec.d.ts +59 -48
- package/dist/core/task-start-judge.js +10 -3
- package/dist/core/task-stream.d.ts +2 -1
- package/dist/core/terminal-cause.d.ts +94 -3
- package/dist/core/tool-catalog-entries.js +2 -2
- package/dist/core/tool-check-reading.js +2 -1
- package/dist/core/tool-errors.js +2 -0
- package/dist/core/tool-face-reader.d.ts +3 -2
- package/dist/core/tool-gate-phase.d.ts +16 -0
- package/dist/core/tool-gate-phase.js +1 -0
- package/dist/core/tool-list-grammar.d.ts +0 -47
- package/dist/core/tool-list-grammar.js +1 -75
- package/dist/core/tool-model-gate.d.ts +7 -11
- package/dist/core/tool-model-gate.js +5 -8
- package/dist/core/tool-mount-plan.d.ts +7 -0
- package/dist/core/tool-mount-plan.js +25 -1
- package/dist/core/tool-mount-static.js +3 -2
- package/dist/core/tool-name-aliases.d.ts +81 -106
- package/dist/core/tool-name-aliases.js +59 -155
- package/dist/core/tool-name-readings.d.ts +6 -0
- package/dist/core/tool-name-readings.js +10 -1
- package/dist/core/tool-policy.d.ts +211 -64
- package/dist/core/tool-policy.js +146 -81
- package/dist/core/tool-registry.d.ts +2 -0
- package/dist/core/tool-registry.js +3 -0
- package/dist/core/tool-result-bytes.d.ts +27 -3
- package/dist/core/tool-result-bytes.js +53 -0
- package/dist/core/tool-result-store.d.ts +11 -28
- package/dist/core/tool-result-store.js +7 -38
- package/dist/core/tool-roster.d.ts +33 -22
- package/dist/core/tool-roster.js +28 -18
- package/dist/core/tool-spec-members.d.ts +12 -0
- package/dist/core/tool-spec-members.js +31 -0
- package/dist/core/tool-spec.d.ts +46 -29
- package/dist/core/trace.d.ts +21 -64
- package/dist/core/trace.js +2 -3
- package/dist/core/types.d.ts +7 -7
- package/dist/core/types.js +2 -2
- package/dist/core/unavailable-landing.d.ts +72 -0
- package/dist/core/unavailable-landing.js +18 -0
- package/dist/core/untrusted-egress.d.ts +27 -5
- package/dist/core/untrusted-egress.js +32 -10
- package/dist/core/untrusted-text.d.ts +8 -0
- package/dist/core/untrusted-text.js +14 -0
- package/dist/core/usage-window-store.d.ts +11 -1
- package/dist/core/usage-window-store.js +5 -0
- package/dist/core/user-attachment.d.ts +89 -48
- package/dist/core/user-attachment.js +168 -76
- package/dist/core/user-row-origin.d.ts +10 -0
- package/dist/core/user-row-origin.js +6 -0
- package/dist/core/wiring-manifest.d.ts +95 -30
- package/dist/core/wiring-manifest.js +65 -13
- package/dist/core/workflow-journal-store.d.ts +70 -14
- package/dist/core/workflow-journal-store.js +68 -16
- package/dist/core/workflow-run-store-contract.js +158 -1
- package/dist/core/workflow-run-store.d.ts +138 -23
- package/dist/core/workflow-run-store.js +91 -13
- package/dist/engine/compaction/compaction.d.ts +15 -3
- package/dist/engine/compaction/compaction.js +29 -10
- package/dist/engine/execution-env/kill-tree.js +44 -49
- package/dist/engine/execution-env/node-execution-env.d.ts +6 -1
- package/dist/engine/execution-env/node-execution-env.js +22 -11
- package/dist/engine/harness/agent-harness.d.ts +23 -5
- package/dist/engine/harness/agent-harness.js +28 -5
- package/dist/engine/harness/types.d.ts +118 -30
- package/dist/engine/harness/types.js +36 -4
- package/dist/engine/llm/rejected-images.js +1 -1
- package/dist/engine/llm/tool-turns.d.ts +1 -1
- package/dist/engine/llm/types.d.ts +27 -6
- package/dist/engine/llm/types.js +5 -2
- package/dist/engine/loop/agent-loop.js +43 -11
- package/dist/engine/loop/types.d.ts +11 -0
- package/dist/engine/session/import-validate.d.ts +9 -0
- package/dist/engine/session/import-validate.js +50 -9
- package/dist/engine/session/memory-repo.d.ts +20 -4
- package/dist/engine/session/memory-repo.js +28 -5
- package/dist/engine/session/memory-storage.d.ts +5 -0
- package/dist/engine/session/memory-storage.js +8 -3
- package/dist/engine/session/parent-chain-guard.js +1 -1
- package/dist/engine/session/path-to-root.js +1 -1
- package/dist/engine/session/repo-utils.d.ts +28 -12
- package/dist/engine/session/repo-utils.js +26 -7
- package/dist/engine/session/session.d.ts +30 -10
- package/dist/engine/session/session.js +52 -20
- package/dist/engine/session/storage-base.d.ts +20 -7
- package/dist/engine/session/storage-base.js +15 -3
- package/dist/fixtures/index.d.ts +3 -1
- package/dist/fixtures/index.js +3 -0
- package/dist/host-env.d.ts +17 -0
- package/dist/host-env.js +1 -0
- package/dist/index.d.ts +113 -53
- package/dist/index.js +88 -39
- package/dist/internal/harness-types.d.ts +1 -1
- package/dist/internal/harness.d.ts +5 -3
- package/dist/internal/harness.js +4 -3
- package/dist/internal/llm.d.ts +1 -1
- package/dist/internal/llm.js +1 -1
- package/dist/orchestration/run-workflow-tool.d.ts +53 -13
- package/dist/orchestration/run-workflow-tool.js +305 -133
- package/dist/orchestration/workflow-catalog.d.ts +254 -0
- package/dist/orchestration/workflow-catalog.js +702 -0
- package/dist/orchestration/workflow-governance.d.ts +1 -1
- package/dist/orchestration/workflow-meta.d.ts +11 -1
- package/dist/orchestration/workflow-meta.js +48 -0
- package/dist/orchestration/workflow-observe.d.ts +8 -10
- package/dist/orchestration/workflow-observe.js +6 -1
- package/dist/orchestration/workflow-park-adoption.d.ts +355 -100
- package/dist/orchestration/workflow-park-adoption.js +676 -298
- package/dist/orchestration/workflow-requirements.d.ts +51 -0
- package/dist/orchestration/workflow-requirements.js +54 -0
- package/dist/orchestration/workflow-script-runner.d.ts +18 -0
- package/dist/orchestration/workflow-script-store.d.ts +19 -64
- package/dist/orchestration/workflow-script-store.js +1 -24
- package/dist/orchestration/workflow-tree-id.d.ts +66 -0
- package/dist/orchestration/workflow-tree-id.js +66 -0
- package/dist/orchestration/workflow-types.d.ts +258 -47
- package/dist/orchestration/workflow-types.js +32 -5
- package/dist/orchestration/workflow.d.ts +86 -46
- package/dist/orchestration/workflow.js +1050 -225
- package/dist/prompt-assembly/catalog/constitution.js +5 -1
- package/dist/prompt-assembly/catalog/core-behavior.d.ts +3 -4
- package/dist/prompt-assembly/catalog/core-behavior.js +67 -24
- package/dist/prompt-assembly/catalog/engine.d.ts +36 -0
- package/dist/prompt-assembly/catalog/engine.js +4 -0
- package/dist/prompt-assembly/catalog/environment.js +2 -2
- package/dist/prompt-assembly/catalog/events.d.ts +32 -0
- package/dist/prompt-assembly/catalog/events.js +4 -0
- package/dist/prompt-assembly/catalog/locales/zh-Hans/core-behavior.js +79 -44
- package/dist/prompt-assembly/catalog/locales/zh-Hans/engine.js +4 -0
- package/dist/prompt-assembly/catalog/locales/zh-Hans/environment.js +2 -2
- package/dist/prompt-assembly/catalog/locales/zh-Hans/events.js +4 -0
- package/dist/prompt-assembly/catalog/locales/zh-Hans/mechanism.js +2 -2
- package/dist/prompt-assembly/catalog/mechanism.js +2 -2
- package/dist/prompt-assembly/catalog/schema.d.ts +10 -3
- package/dist/prompt-assembly/catalog/schema.js +3 -0
- package/dist/prompt-assembly/catalog/sections.js +3 -14
- package/dist/prompt-assembly/epoch.d.ts +26 -0
- package/dist/prompt-assembly/epoch.js +29 -0
- package/dist/prompt-assembly/event-registry.js +4 -0
- package/dist/prompt-assembly/select.js +1 -0
- package/dist/prompt-assembly/tool-catalog.d.ts +11 -8
- package/dist/prompt-assembly/tool-catalog.js +21 -7
- package/dist/prompt-assembly/turn-snapshot.d.ts +1 -1
- package/dist/prompt-assembly/types.d.ts +3 -0
- package/dist/prompts/default.d.ts +6 -3
- package/dist/prompts/default.js +6 -0
- package/dist/shell/lex.d.ts +10 -7
- package/dist/shell/lex.js +56 -6
- package/dist/stores/file/adoption/adopt.d.ts +12 -0
- package/dist/stores/file/adoption/adopt.js +78 -31
- package/dist/stores/file/adoption/marker.d.ts +48 -26
- package/dist/stores/file/adoption/marker.js +24 -11
- package/dist/stores/file/background-agent-store.d.ts +5 -0
- package/dist/stores/file/background-agent-store.js +26 -5
- package/dist/stores/file/checkpoint-store.d.ts +11 -10
- package/dist/stores/file/checkpoint-store.js +36 -10
- package/dist/stores/file/data-root-declaration.js +2 -1
- package/dist/stores/file/descriptor-seat.d.ts +100 -0
- package/dist/stores/file/descriptor-seat.js +150 -0
- package/dist/stores/file/file-history-store.d.ts +6 -0
- package/dist/stores/file/file-history-store.js +23 -5
- package/dist/stores/file/fs-atomic.d.ts +127 -79
- package/dist/stores/file/fs-atomic.js +313 -253
- package/dist/stores/file/index.d.ts +24 -5
- package/dist/stores/file/index.js +49 -21
- package/dist/stores/file/ledger-damage.js +6 -10
- package/dist/stores/file/lock-reading.d.ts +158 -0
- package/dist/stores/file/lock-reading.js +252 -0
- package/dist/stores/file/mailbox-store.d.ts +8 -5
- package/dist/stores/file/mailbox-store.js +23 -14
- package/dist/stores/file/permission-rule-adopt.js +11 -11
- package/dist/stores/file/permission-rule-store.d.ts +14 -3
- package/dist/stores/file/permission-rule-store.js +33 -37
- package/dist/stores/file/process-anchor.d.ts +93 -0
- package/dist/stores/file/process-anchor.js +392 -0
- package/dist/stores/file/session-policy-store.d.ts +18 -2
- package/dist/stores/file/session-policy-store.js +56 -5
- package/dist/stores/file/session-store.d.ts +46 -1
- package/dist/stores/file/session-store.js +129 -25
- package/dist/stores/file/shared-ledger.d.ts +3 -3
- package/dist/stores/file/task-list-store.js +1 -1
- package/dist/stores/file/tool-result-store.js +2 -1
- package/dist/stores/file/usage-window-store.js +1 -1
- package/dist/stores/file/workflow-journal-store.d.ts +19 -6
- package/dist/stores/file/workflow-journal-store.js +43 -48
- package/dist/stores/file/workflow-run-store.d.ts +20 -4
- package/dist/stores/file/workflow-run-store.js +95 -12
- package/dist/tools/artifact/artifact-text.d.ts +29 -11
- package/dist/tools/artifact/artifact-text.js +13 -6
- package/dist/tools/artifact/artifact-tool.d.ts +45 -8
- package/dist/tools/artifact/artifact-tool.js +256 -46
- package/dist/tools/artifact/conformance.d.ts +27 -5
- package/dist/tools/artifact/conformance.js +420 -45
- package/dist/tools/artifact/local-stub.d.ts +2 -2
- package/dist/tools/artifact/local-stub.js +29 -26
- package/dist/tools/fs/bash-failure-output.d.ts +64 -0
- package/dist/tools/fs/bash-failure-output.js +40 -0
- package/dist/tools/fs/bash-program-position.d.ts +17 -7
- package/dist/tools/fs/bash-program-position.js +20 -14
- package/dist/tools/fs/bash-readonly-classifier.d.ts +7 -4
- package/dist/tools/fs/bash-readonly-classifier.js +9 -2
- package/dist/tools/fs/bound-open.d.ts +9 -8
- package/dist/tools/fs/bound-open.js +6 -4
- package/dist/tools/fs/dead-cwd.d.ts +8 -0
- package/dist/tools/fs/dead-cwd.js +7 -7
- package/dist/tools/fs/file-read-check.d.ts +8 -6
- package/dist/tools/fs/file-read-check.js +8 -4
- package/dist/tools/fs/file-write-check.d.ts +14 -0
- package/dist/tools/fs/file-write-check.js +35 -0
- package/dist/tools/fs/find-actions.d.ts +200 -0
- package/dist/tools/fs/find-actions.js +791 -0
- package/dist/tools/fs/fs-bash.d.ts +6 -3
- package/dist/tools/fs/fs-bash.js +75 -65
- package/dist/tools/fs/fs-pdf.js +16 -5
- package/dist/tools/fs/fs-read.js +5 -3
- package/dist/tools/fs/fs-shared.d.ts +67 -32
- package/dist/tools/fs/fs-shared.js +70 -39
- package/dist/tools/fs/fs-write.d.ts +23 -3
- package/dist/tools/fs/fs-write.js +139 -34
- package/dist/tools/fs/index.d.ts +15 -2
- package/dist/tools/fs/index.js +8 -4
- package/dist/tools/fs/program-read-model.d.ts +17 -1
- package/dist/tools/fs/program-read-model.js +7 -2
- package/dist/tools/fs/program-read-model.rows.js +5 -1
- package/dist/tools/fs/read-deny-home.js +12 -5
- package/dist/tools/fs/read-deny.d.ts +6 -1
- package/dist/tools/fs/read-deny.js +6 -1
- package/dist/tools/fs/read-floor.d.ts +22 -0
- package/dist/tools/fs/read-floor.js +15 -6
- package/dist/tools/fs/removal-actions.d.ts +43 -0
- package/dist/tools/fs/removal-actions.js +25 -0
- package/dist/tools/fs/removal-targets.d.ts +4 -5
- package/dist/tools/fs/removal-targets.js +115 -6
- package/dist/tools/fs/safety.d.ts +39 -1
- package/dist/tools/fs/safety.js +61 -2
- package/dist/tools/fs/shell-climb.d.ts +46 -0
- package/dist/tools/fs/shell-climb.js +79 -0
- package/dist/tools/fs/shell-read-bindings.d.ts +56 -7
- package/dist/tools/fs/shell-read-bindings.js +175 -26
- package/dist/tools/fs/shell-read-check.d.ts +11 -2
- package/dist/tools/fs/shell-read-check.js +78 -24
- package/dist/tools/fs/shell-read-command-environment.d.ts +56 -0
- package/dist/tools/fs/shell-read-command-environment.js +75 -0
- package/dist/tools/fs/shell-read-establish.js +97 -37
- package/dist/tools/fs/shell-read-judge.d.ts +62 -9
- package/dist/tools/fs/shell-read-judge.js +67 -25
- package/dist/tools/fs/shell-read-lost-walk.d.ts +19 -0
- package/dist/tools/fs/shell-read-lost-walk.js +35 -0
- package/dist/tools/fs/shell-read-plan.d.ts +7 -0
- package/dist/tools/fs/shell-read-plan.js +47 -13
- package/dist/tools/fs/shell-read-sourced.d.ts +4 -3
- package/dist/tools/fs/shell-read-sourced.js +28 -3
- package/dist/tools/fs/shell-read-start.d.ts +7 -0
- package/dist/tools/fs/shell-read-word.js +1 -0
- package/dist/tools/fs/shell-read-workdir.d.ts +9 -11
- package/dist/tools/fs/shell-read-workdir.js +23 -28
- package/dist/tools/fs/shell-read-write-targets.d.ts +17 -8
- package/dist/tools/fs/shell-read-write-targets.js +54 -9
- package/dist/tools/monitor.d.ts +2 -1
- package/dist/tools/monitor.js +2 -0
- package/dist/tools/scheduler-tools.d.ts +7 -4
- package/dist/tools/scheduler-tools.js +60 -20
- package/dist/tools/task-list.d.ts +11 -1
- package/dist/tools/task-list.js +187 -134
- package/dist/tools/todo.d.ts +1 -1
- package/dist/tools/worktree.js +10 -9
- package/package.json +6 -2
- package/test/export-surface.snapshot.json +760 -36
- package/wire-changes/core-stores-sql@7.68.7.json +39 -0
- package/wire-changes/core-stores-sql@7.70.0.json +414 -0
- package/wire-changes/core-stores-sql@7.71.0.json +40 -0
- package/wire-changes/core@7.68.7.json +140 -0
- package/wire-changes/core@7.70.0.json +14689 -0
- package/wire-changes/core@7.71.0.json +5827 -0
- package/wire-changes/mods-kernel@7.68.7.json +39 -0
- package/wire-changes/mods-kernel@7.70.0.json +75 -0
- package/wire-changes/mods-kernel@7.71.0.json +52 -0
- package/wire-changes/primitives@7.68.7.json +39 -0
- package/wire-changes/primitives@7.70.0.json +807 -0
- package/wire-changes/primitives@7.71.0.json +473 -0
- package/wire-changes/wiki-gate@7.68.7.json +39 -0
- package/wire-changes/wiki-gate@7.70.0.json +40 -0
- package/wire-changes/wiki-gate@7.71.0.json +40 -0
- package/dist/core/cache-break-detector.d.ts +0 -98
- package/dist/core/cache-break-detector.js +0 -146
- package/dist/core/compaction-retired-members.d.ts +0 -12
- package/dist/core/compaction-retired-members.js +0 -22
- package/dist/core/frontmatter-fence.d.ts +0 -10
- package/dist/core/frontmatter-fence.js +0 -6
- package/dist/core/loopback-host.d.ts +0 -18
- package/dist/core/loopback-host.js +0 -40
- package/dist/core/permission-rule-syntax.d.ts +0 -46
- package/dist/core/permission-rule-syntax.js +0 -52
- package/dist/core/protocol-naming.d.ts +0 -95
- package/dist/core/protocol-naming.js +0 -70
- package/dist/core/protocol-table.d.ts +0 -88
- package/dist/core/protocol-table.js +0 -47
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { presetRoleBaseOf, resolveModelDisplayLabel } from "../core/roles.js";
|
|
2
|
+
import { SPEND_OUTPUT_FLOOR_TOKENS, spendNodeMint } from "../core/spend-account.js";
|
|
3
|
+
import { SPEND_ACCOUNT_CLOSED_CODE } from "../brain/spend-meter.js";
|
|
2
4
|
import { describeRejectedValue } from "../core/tool-search-setting.js";
|
|
3
5
|
import { takeSeat } from "../core/swappable-deps.js";
|
|
4
6
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -10,15 +12,19 @@ import { thrownFailureOf } from "../core/runner/terminal-account.js";
|
|
|
10
12
|
import { deliverEngineNotice } from "../core/engine-notice.js";
|
|
11
13
|
import { judgeCheckpointRow } from "../core/checkpoint-row-verdict.js";
|
|
12
14
|
import { applyParentSpecSeat } from "../core/parent-spec-seat.js";
|
|
15
|
+
import { ANONYMOUS_SCOPE, callScopeOf, isolationScopeOf } from "../core/isolation-scope.js";
|
|
13
16
|
import { TERMINAL_CAUSE_IS_REPLAYABLE, isTerminalCauseKind } from "../core/terminal-cause.js";
|
|
14
17
|
import { terminalProjection } from "../core/runner/terminal-projection.js";
|
|
15
18
|
import { steeringError } from "../core/runner/steer-admission.js";
|
|
19
|
+
import { answeringOnce } from "../core/runner/delegation-owner.js";
|
|
16
20
|
import { builtinAgentDefinitions } from "../agents/builtin-agents.js";
|
|
17
21
|
import { GENERAL_PURPOSE_SUBAGENT_TYPE, markerFragment } from "../agents/subagent.js";
|
|
18
22
|
import { runnerRoleMap } from "../agents/child-model-seat.js";
|
|
19
23
|
import { namesRoleBase } from "../prompt-assembly/role-base.js";
|
|
20
24
|
import { createSafeNotifier } from "../core/safe-notify.js";
|
|
21
|
-
import {
|
|
25
|
+
import { isWorkflowRunId, workflowRunCreationIdOf, WORKFLOW_RUN_ID_CHARACTERS } from "../core/workflow-run-store.js";
|
|
26
|
+
import { treeIdOf } from "./workflow-tree-id.js";
|
|
27
|
+
import { assertJournalStoreGivesClaimsBack, callKeyOrdinal, clampRunIdText, journalKeepsLaunches, readWorkflowLaunchRecord, oversizeJournalResult, journalOversizeTombstone, readWorkflowJournalEntry, JOURNAL_OVERSIZE_ERROR_CODE, MAX_JOURNAL_RESULT_BYTES, WorkflowJournalIncompatibleError, } from "../core/workflow-journal-store.js";
|
|
22
28
|
import { isWorkflowRunActive, closeWorkflowChannel, markWorkflowActive, publishWorkflowEvent, readWorkflowParkedDecisions, registerWorkflowParkDelivery } from "./workflow-observe.js";
|
|
23
29
|
import { isDurablePause, resumeNeverStarted } from "../agents/suspend-guard.js";
|
|
24
30
|
import { RUNNING_AGENT_OBSERVE_EVERY_BEATS } from "../config/defaults.js";
|
|
@@ -30,6 +36,8 @@ import { OUTPUT_TOOL_NAME, TOOL_CATALOG_ENTRIES } from "../core/tool-catalog-ent
|
|
|
30
36
|
import { readDelegationReview } from "../core/classifier-unavailable-arm.js";
|
|
31
37
|
import { judgeHostToolCeiling, refuseUnusableDefinition } from "../core/runner/sub-agent-deny-lists.js";
|
|
32
38
|
import { definitionSelectorLayer, withDefinitionServers } from "../agents/inherited-tool-pool.js";
|
|
39
|
+
import { isToolSelectorLayer } from "../agents/tool-filter.js";
|
|
40
|
+
import { legRetiredNameView, selectorLayerUnderView } from "../core/tool-name-aliases.js";
|
|
33
41
|
import { snapshotToolNameList } from "../core/tool-name-list.js";
|
|
34
42
|
import { snapshotDefinitionLists } from "../agents/agent-definition.js";
|
|
35
43
|
import { holdKeeperDeclarations } from "../agents/retain-ledger.js";
|
|
@@ -37,12 +45,14 @@ import { snapshotAndValidateMcpEntries } from "../core/locked-config.js";
|
|
|
37
45
|
import { compileOutputSchema } from "../core/runner/strict-output-schema.js";
|
|
38
46
|
import { callerPlacementSeats } from "../core/runner/child-tree.js";
|
|
39
47
|
import { judgedOwnerSeat } from "../core/runner/delegation-owner.js";
|
|
40
|
-
import { WorkflowBudgetExceededError, WorkflowNestingError, WorkflowAgentBlockedError, WorkflowAgentParkedError, WorkflowAgentSchemaError, WorkflowAgentStalledError, WorkflowMaxAgentsError, WORKFLOW_SPAWN_BLOCKED_ERROR_CODE, PARK_NOT_PENDING_STATUSES, runParkedOf,
|
|
41
|
-
import {
|
|
48
|
+
import { WorkflowBudgetExceededError, WorkflowNestingError, WorkflowAgentBlockedError, WorkflowAgentParkedError, WorkflowAgentSchemaError, WorkflowAgentStalledError, WorkflowMaxAgentsError, WORKFLOW_SPAWN_BLOCKED_ERROR_CODE, WORKFLOW_AGENT_OUTLIVED_RUN_CODE, PARK_NOT_PENDING_STATUSES, WORKFLOW_AGENT_PARKED_ERROR_CODE, WORKFLOW_STORE_WAIT_BOUND_MS, firstFailedAgentCodeOf, parkHolderAmong, runParkedOf, workflowRowStatusOf } from "./workflow-types.js";
|
|
49
|
+
import { memberOutcomeOf, memberRefusalsOf } from "../core/member-outcome.js";
|
|
50
|
+
import { CLAIM_REMAINING_UNREADABLE_NOTE, claimRemainingOf, isAnswerRecordClaimHolder, readWorkflowRunTreeWithin, runThatDrove, storeErrorClassOf, workflowLineForkReason, workflowLineTailOf, workflowParkDecisionOf, workflowRunChildrenIn, workflowRunInTree, workflowRunsBelow, workflowRunTreeOfOne, WORKFLOW_TREE_OVER_BOUND_REASON } from "./workflow-park-adoption.js";
|
|
42
51
|
import { WorkflowScriptError } from "./workflow-meta.js";
|
|
43
52
|
import { firstByteLaneKnobMs, STALL_FIRST_BYTE_MS, STALL_FIRST_TOKEN_MS } from "../brain/timeout.js";
|
|
44
|
-
import { asThrownError, isErrorLike, readMember, thrownIs, thrownName, thrownText } from "../core/thrown-value.js";
|
|
53
|
+
import { asThrownError, codedRefusal, isErrorLike, readMember, thrownIs, thrownName, thrownText } from "../core/thrown-value.js";
|
|
45
54
|
import { bindSettledRun } from "../core/workflow-settled-run.js";
|
|
55
|
+
import { nativeSignalOf } from "../core/native-signal.js";
|
|
46
56
|
import { persistTaskArtifact } from "../core/tool-result-store.js";
|
|
47
57
|
import { formatWorkflowRun, WORKFLOW_RECORD_WHOLE } from "../core/task-registry-shared.js";
|
|
48
58
|
const WORKFLOW_TOOL_NAME = (() => {
|
|
@@ -59,6 +69,7 @@ const MAX_ACTIVITY = 30;
|
|
|
59
69
|
const MAX_REVIEWED_SCHEMA_BYTES = 4096;
|
|
60
70
|
const MAX_REVIEW_REASON_CHARS = 500;
|
|
61
71
|
const MAX_REVIEWED_PROMPT_CHARS = 2_000;
|
|
72
|
+
const MAX_MEMBER_STOPPER_CHARS = 256;
|
|
62
73
|
const MAX_SCHEMA_WALK_DEPTH = 32;
|
|
63
74
|
function isUsableSchema(v) {
|
|
64
75
|
if (v === true)
|
|
@@ -118,10 +129,11 @@ NOTE: You are running inside a workflow script. Your final text response is retu
|
|
|
118
129
|
export const WORKFLOW_SUBAGENT_APPEND_SCHEMA = `---
|
|
119
130
|
|
|
120
131
|
NOTE: You are running inside a workflow script. You MUST return your final answer by calling the ${OUTPUT_TOOL_NAME} tool exactly once — the tool's input schema defines the required shape. Do your work, then call ${OUTPUT_TOOL_NAME}; do NOT put your answer in a text response (the script reads ONLY the tool call). If validation fails, read the error and call ${OUTPUT_TOOL_NAME} again with a corrected shape.`;
|
|
132
|
+
function workflowLaunchTypeWord(agentType, registry) {
|
|
133
|
+
return agentType === undefined || (agentType === GENERAL_PURPOSE_SUBAGENT_TYPE && !registry.some((d) => d.name === agentType)) ? undefined : agentType;
|
|
134
|
+
}
|
|
121
135
|
export function applyWorkflowAgentType(spec, agentType, registry) {
|
|
122
|
-
if (agentType === undefined)
|
|
123
|
-
return { spec };
|
|
124
|
-
if (agentType === GENERAL_PURPOSE_SUBAGENT_TYPE && !registry.some((d) => d.name === agentType))
|
|
136
|
+
if (workflowLaunchTypeWord(agentType, registry) === undefined)
|
|
125
137
|
return { spec };
|
|
126
138
|
const def = registry.find((d) => d.name === agentType);
|
|
127
139
|
if (!def) {
|
|
@@ -149,9 +161,9 @@ export function applyWorkflowAgentType(spec, agentType, registry) {
|
|
|
149
161
|
out.mcp = withDefinitionServers(out.mcp !== undefined ? snapshotAndValidateMcpEntries(out.mcp) : undefined, ownServers);
|
|
150
162
|
const lists = { allowTools: snapshotToolNameList(def.allowTools), denyTools: snapshotToolNameList(def.denyTools) };
|
|
151
163
|
if (lists.allowTools == null && lists.denyTools == null)
|
|
152
|
-
return { spec: out };
|
|
164
|
+
return { spec: out, agentType: def.name };
|
|
153
165
|
refuseUnusableDefinition(def.name, lists);
|
|
154
|
-
return { spec: out, definitionToolLists: { agentType: def.name, layer: definitionSelectorLayer({ ...lists, ...(ownServers !== undefined ? { mcp: ownServers } : {}) }) } };
|
|
166
|
+
return { spec: out, agentType: def.name, definitionToolLists: { agentType: def.name, layer: definitionSelectorLayer({ ...lists, ...(ownServers !== undefined ? { mcp: ownServers } : {}) }) } };
|
|
155
167
|
}
|
|
156
168
|
export function workflowAgentRegistry(opts) {
|
|
157
169
|
const deployment = (opts.agents ?? []).map(snapshotDefinitionLists);
|
|
@@ -184,7 +196,18 @@ function withWorkflowChildSeats(typed, inheritedModelSnap, inheritedThinkingSnap
|
|
|
184
196
|
}
|
|
185
197
|
return { ...seated, ...preset };
|
|
186
198
|
}
|
|
187
|
-
export function workflowAgentCallKey(ordinal, spec, opts) {
|
|
199
|
+
export function workflowAgentCallKey(ordinal, spec, opts, position) {
|
|
200
|
+
return callKeyOf(ordinal, workflowAgentSpecHash(spec, opts), position ?? "");
|
|
201
|
+
}
|
|
202
|
+
function callKeyOf(ordinal, specHash, place) {
|
|
203
|
+
return `${ordinal}:${specHash}${place !== undefined ? `@${place}` : ""}`;
|
|
204
|
+
}
|
|
205
|
+
function callKeySpec(callKey) {
|
|
206
|
+
const colon = callKey.indexOf(":");
|
|
207
|
+
const at = callKey.indexOf("@");
|
|
208
|
+
return callKey.slice(colon + 1, at >= 0 ? at : undefined);
|
|
209
|
+
}
|
|
210
|
+
function workflowAgentSpecHash(spec, opts) {
|
|
188
211
|
const identity = {
|
|
189
212
|
...spec,
|
|
190
213
|
signal: undefined,
|
|
@@ -196,8 +219,19 @@ export function workflowAgentCallKey(ordinal, spec, opts) {
|
|
|
196
219
|
outputSchema: opts.schema ?? spec.outputSchema,
|
|
197
220
|
isolation: opts.isolation ? opts.isolation : undefined,
|
|
198
221
|
};
|
|
199
|
-
return
|
|
222
|
+
return boundInputHashOf(identity);
|
|
223
|
+
}
|
|
224
|
+
function callKeyPosition(callKey) {
|
|
225
|
+
const at = callKey.indexOf("@");
|
|
226
|
+
return at >= 0 && at < callKey.length - 1 ? callKey.slice(at + 1) : undefined;
|
|
227
|
+
}
|
|
228
|
+
function madeAtEvent(position, prefix, n) {
|
|
229
|
+
if (!position.startsWith(prefix))
|
|
230
|
+
return false;
|
|
231
|
+
const segment = position.slice(prefix.length).split(".", 1)[0];
|
|
232
|
+
return (segment[0] === "c" || segment[0] === "p" || segment[0] === "f") && segment.slice(1) === String(n);
|
|
200
233
|
}
|
|
234
|
+
const fanOutScopeStore = new AsyncLocalStorage();
|
|
201
235
|
function resolveChildSessionIdAtSpawn(spec) {
|
|
202
236
|
if (spec.sessionId)
|
|
203
237
|
return spec.sessionId;
|
|
@@ -306,6 +340,12 @@ function runStoreUnreadableRefusal(fromRunId, cause) {
|
|
|
306
340
|
const what = cause === undefined ? `no answer within ${WORKFLOW_STORE_WAIT_BOUND_MS}ms, or records that name each other in a loop` : storeErrorClassOf(cause.err);
|
|
307
341
|
return new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record, or that of a run it was resumed from, could not be read from the run store (${what}), so its parks cannot be proven.`, { reason: "store_threw" });
|
|
308
342
|
}
|
|
343
|
+
function journalStoreClaimRefusal(fromRunId, err) {
|
|
344
|
+
return new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the journal store threw while the workflow's resume claim was taken (${storeErrorClassOf(err)}), so nothing guards the resume against another one; nothing ran. Resume again once the journal store answers.`, { reason: "store_threw" });
|
|
345
|
+
}
|
|
346
|
+
function priorRecordMissingRefusal(fromRunId) {
|
|
347
|
+
return new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record is not in the run store under this scope (never recorded under it, reaped, or deleted with the session that started it), so its parks cannot be proven.`, { reason: "record_missing" });
|
|
348
|
+
}
|
|
309
349
|
const workflowDepthStore = new AsyncLocalStorage();
|
|
310
350
|
function currentWorkflowDepth() {
|
|
311
351
|
return workflowDepthStore.getStore()?.depth ?? 0;
|
|
@@ -408,7 +448,16 @@ function readLegApprovalWaitedMs(result, announce) {
|
|
|
408
448
|
}
|
|
409
449
|
return raw;
|
|
410
450
|
}
|
|
411
|
-
export const
|
|
451
|
+
export const TERMINAL_WRITE_RETRY_DELAYS_MS = Object.freeze([1_000, 10_000, 60_000]);
|
|
452
|
+
function terminalWriteCause(o) {
|
|
453
|
+
return o.cause === "threw" ? `the run store refused it: ${storeErrorClassOf(o.err)}`
|
|
454
|
+
: o.cause === "timeout" ? `the run store did not answer within ${WORKFLOW_STORE_WAIT_BOUND_MS}ms`
|
|
455
|
+
: o.cause === "not_own" ? "the run store holds no row of this run's own under its id"
|
|
456
|
+
: "the run store answered that the row had moved";
|
|
457
|
+
}
|
|
458
|
+
const SETTLE_ROW_READ_FIRST = " A host that settles this row reads it first: a row that reads ended is left as it is; only one that still reads running, and is this run's (an explicit run id may have been reused — docs/KNOWN-LIMITS.md KL-4486-a), is changed, at the rev it read.";
|
|
459
|
+
const WORKFLOW_FAILURE_SETTLE_MS = 5_000;
|
|
460
|
+
const SPEND_STOP_CODES = new Set(["limits.max_tokens_exceeded", "limits.max_cost_exceeded", SPEND_ACCOUNT_CLOSED_CODE]);
|
|
412
461
|
export const WORKFLOW_JOURNAL_APPEND_TIMEOUT_MS = 30_000;
|
|
413
462
|
const REAL_WORKFLOW_TIMERS = {
|
|
414
463
|
setTimeout(fn, ms) {
|
|
@@ -426,15 +475,23 @@ async function finalizeWithin(timers, p, fallback, holdsProcess = false) {
|
|
|
426
475
|
return await Promise.race([
|
|
427
476
|
p,
|
|
428
477
|
new Promise((resolve) => {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
handle.ref
|
|
478
|
+
try {
|
|
479
|
+
handle = timers.setTimeout(() => resolve(fallback), WORKFLOW_STORE_WAIT_BOUND_MS);
|
|
480
|
+
if (holdsProcess && typeof handle === "object" && handle !== null && "ref" in handle && typeof handle.ref === "function")
|
|
481
|
+
handle.ref();
|
|
482
|
+
}
|
|
483
|
+
catch {
|
|
484
|
+
}
|
|
432
485
|
}),
|
|
433
486
|
]);
|
|
434
487
|
}
|
|
435
488
|
finally {
|
|
436
|
-
|
|
437
|
-
|
|
489
|
+
try {
|
|
490
|
+
if (handle !== undefined)
|
|
491
|
+
timers.clearTimeout(handle);
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
}
|
|
438
495
|
}
|
|
439
496
|
}
|
|
440
497
|
function defaultConcurrency() {
|
|
@@ -547,12 +604,18 @@ export const workflowResumeClaimFallback = {
|
|
|
547
604
|
export function takeWorkflowResumeClaim(store, input) {
|
|
548
605
|
if (store.resumeClaim === undefined)
|
|
549
606
|
return Promise.resolve({ ...workflowResumeClaimFallback.acquire(store, input), fallback: true });
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
607
|
+
let asked;
|
|
608
|
+
try {
|
|
609
|
+
asked = Promise.resolve(store.resumeClaim(input));
|
|
610
|
+
}
|
|
611
|
+
catch (err) {
|
|
612
|
+
return Promise.reject(err);
|
|
613
|
+
}
|
|
614
|
+
return asked
|
|
615
|
+
.then((v) => {
|
|
616
|
+
const granted = Boolean(v.granted);
|
|
617
|
+
return { granted, ...(v.holder !== undefined ? { holder: v.holder } : {}), ...(granted ? {} : { lapse: claimRemainingOf(v, Date.now()) }), fallback: false };
|
|
618
|
+
});
|
|
556
619
|
}
|
|
557
620
|
export async function releaseWorkflowResumeClaim(store, input, fallback) {
|
|
558
621
|
if (fallback)
|
|
@@ -575,6 +638,12 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
575
638
|
const depth = Math.max(alsDepth, internalDepth ?? 0);
|
|
576
639
|
if (depth >= 1)
|
|
577
640
|
throw new WorkflowNestingError();
|
|
641
|
+
const givenRunId = opts.runId ?? undefined;
|
|
642
|
+
for (const [seat, id] of [["runId", givenRunId], ["resumeFromRunId", opts.resumeFromRunId]]) {
|
|
643
|
+
if (id !== undefined && !isWorkflowRunId(id)) {
|
|
644
|
+
throw codedRefusal("config.invalid_argument", `runWorkflow: ${seat} ${JSON.stringify(String(id).slice(0, 80))} is not a workflow run id — a run id is ${WORKFLOW_RUN_ID_CHARACTERS}`);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
578
647
|
if (opts.resumeFromRunId !== undefined && opts.journalStore === undefined) {
|
|
579
648
|
throw new Error("runWorkflow: resumeFromRunId requires a journalStore to load the prior run's journal");
|
|
580
649
|
}
|
|
@@ -594,16 +663,23 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
594
663
|
throw new Error("runWorkflow: launch is the record a continuation of this run reads back, and requires a journalStore that keeps launch records (recordLaunch and loadLaunch)");
|
|
595
664
|
}
|
|
596
665
|
const now = opts.now ?? (() => Date.now());
|
|
597
|
-
const
|
|
666
|
+
const givenScope = callScopeOf(undefined, { scope: opts.scope }), seatScope = opts.parentSpecSeat !== undefined ? isolationScopeOf(opts.parentSpecSeat) : undefined;
|
|
667
|
+
if (givenScope !== undefined && seatScope !== undefined && givenScope !== seatScope) {
|
|
668
|
+
throw codedRefusal("config.invalid_argument", `runWorkflow: scope ${JSON.stringify(givenScope)} contradicts parentSpecSeat, whose identity files the run under ${JSON.stringify(seatScope)} — hand one of the two, or the same scope in both (\`scope\` speaks only for a run whose agents run as nobody)`);
|
|
669
|
+
}
|
|
670
|
+
const scope = seatScope ?? givenScope ?? ANONYMOUS_SCOPE;
|
|
598
671
|
const parkedResume = opts.parkedResume === undefined ? undefined : readWorkflowParkedDecisions(opts.parkedResume, "runWorkflow: parkedResume"), claimHolder = opts.holder;
|
|
672
|
+
const spentAtAdmission = new Set();
|
|
599
673
|
let launchUnkept = false;
|
|
600
|
-
const runId =
|
|
601
|
-
if (
|
|
602
|
-
throw new Error(`startWorkflow: runId "${
|
|
674
|
+
const runId = givenRunId ?? randomUUID();
|
|
675
|
+
if (givenRunId !== undefined && isWorkflowRunActive(runId)) {
|
|
676
|
+
throw new Error(`startWorkflow: runId "${runId}" is already an active workflow run in this process`);
|
|
603
677
|
}
|
|
604
678
|
if (opts.resumeFromRunId !== undefined && isWorkflowRunActive(opts.resumeFromRunId)) {
|
|
605
679
|
throw new Error(`startWorkflow: resumeFromRunId "${opts.resumeFromRunId}" is still an active workflow run in this process — stop it before resuming from it`);
|
|
606
680
|
}
|
|
681
|
+
let resumeFrom = opts.resumeFromRunId;
|
|
682
|
+
let resumeAsked = opts.resumeFromRunId !== undefined ? internals?.resumeAsked : undefined;
|
|
607
683
|
const concurrency = normalizeConcurrency(opts.concurrency);
|
|
608
684
|
const agentRegistry = workflowAgentRegistry(opts);
|
|
609
685
|
const holdKeeper = holdKeeperDeclarations(runner);
|
|
@@ -614,6 +690,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
614
690
|
const maxLogChars = normalizeWorkflowHardCap("maxLogChars", opts.maxLogChars);
|
|
615
691
|
const maxResultChars = normalizeWorkflowHardCap("maxResultChars", opts.maxResultChars);
|
|
616
692
|
const budgetCeiling = normalizeWorkflowHardCap("budget", opts.budget);
|
|
693
|
+
const mintWfSpend = spendNodeMint(opts.spendParent, "RunWorkflowOptions.spendParent");
|
|
617
694
|
const totalTimeoutMs = normalizeWorkflowTimerCap("totalTimeoutMs", opts.totalTimeoutMs);
|
|
618
695
|
const stallMs = normalizeWorkflowStallMs(opts.stallMs);
|
|
619
696
|
const agentMaxRetries = normalizeWorkflowHardCap("agentMaxRetries", opts.agentMaxRetries) ?? WORKFLOW_AGENT_MAX_RETRIES;
|
|
@@ -623,12 +700,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
623
700
|
const taskArtifacts = opts.taskArtifacts;
|
|
624
701
|
const cancelController = new AbortController();
|
|
625
702
|
const timeoutController = totalTimeoutMs !== undefined ? new AbortController() : undefined;
|
|
626
|
-
const
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
703
|
+
const hostSignals = new Map();
|
|
704
|
+
const composable = (s) => {
|
|
705
|
+
const kept = hostSignals.get(s);
|
|
706
|
+
if (kept !== undefined)
|
|
707
|
+
return kept.signal;
|
|
708
|
+
const f = nativeSignalOf(s);
|
|
709
|
+
if (f.signal !== s)
|
|
710
|
+
hostSignals.set(s, f);
|
|
711
|
+
return f.signal;
|
|
712
|
+
};
|
|
632
713
|
let timeoutTimer;
|
|
633
714
|
let keeperHold;
|
|
634
715
|
let storeRev = 0;
|
|
@@ -638,36 +719,93 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
638
719
|
notifier.notify(() => opts.onEvent?.(e), "workflow.onEvent");
|
|
639
720
|
};
|
|
640
721
|
let persistTail = Promise.resolve();
|
|
641
|
-
|
|
722
|
+
let persistEpoch = 0;
|
|
723
|
+
let vouched = true;
|
|
724
|
+
let createAnswer;
|
|
725
|
+
const creationId = randomUUID();
|
|
726
|
+
const ownRow = (row) => row != null && row.id === runId && row.scope === scope && workflowRunCreationIdOf(row) === creationId;
|
|
727
|
+
let endingCreateSent = false;
|
|
728
|
+
const writeOwnRow = async (s, snapshot) => {
|
|
729
|
+
const writeEnding = async (row) => {
|
|
730
|
+
if (!ownRow(row))
|
|
731
|
+
return { ok: false, cause: "not_own" };
|
|
732
|
+
if (row.status !== "running")
|
|
733
|
+
return { ok: true };
|
|
734
|
+
const rev = typeof row.rev === "number" ? row.rev : 0;
|
|
735
|
+
snapshot.rev = rev;
|
|
736
|
+
return (await s.update(runId, scope, snapshot, { rev, creationId })) ? { ok: true } : { ok: false, cause: "cas_lost" };
|
|
737
|
+
};
|
|
738
|
+
const row = await s.get(runId);
|
|
739
|
+
if (row == null && endingCreateSent)
|
|
740
|
+
return { ok: false, cause: "not_own", mayAppear: true };
|
|
741
|
+
if (row != null || snapshot.status === "running" || createAnswer?.ok === true)
|
|
742
|
+
return writeEnding(row);
|
|
743
|
+
endingCreateSent = true;
|
|
744
|
+
snapshot.rev = 0;
|
|
745
|
+
try {
|
|
746
|
+
await s.put(runId, snapshot);
|
|
747
|
+
return { ok: true };
|
|
748
|
+
}
|
|
749
|
+
catch (err) {
|
|
750
|
+
if (err?.code !== "workflow_run.already_exists")
|
|
751
|
+
throw err;
|
|
752
|
+
const back = await s.get(runId);
|
|
753
|
+
return back == null ? { ok: false, cause: "not_own", mayAppear: true } : writeEnding(back);
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
const persist = (mode, given) => {
|
|
642
757
|
if (!store)
|
|
643
758
|
return Promise.resolve({ ok: true });
|
|
644
|
-
const snapshot = structuredClone(run);
|
|
759
|
+
const snapshot = given ?? structuredClone(run);
|
|
760
|
+
const epoch = persistEpoch;
|
|
645
761
|
const next = persistTail.then(async () => {
|
|
762
|
+
if (epoch !== persistEpoch)
|
|
763
|
+
return { ok: false, cause: "cas_lost" };
|
|
646
764
|
try {
|
|
647
765
|
if (mode === "create") {
|
|
648
766
|
snapshot.rev = storeRev;
|
|
649
|
-
await
|
|
767
|
+
const created = await Promise.resolve()
|
|
768
|
+
.then(() => store.put(runId, snapshot))
|
|
769
|
+
.then(() => undefined, (err) => ({ err }));
|
|
770
|
+
createAnswer = created === undefined ? { ok: true } : { ok: false, err: created.err };
|
|
771
|
+
if (epoch !== persistEpoch)
|
|
772
|
+
createLandedLate();
|
|
773
|
+
if (created !== undefined)
|
|
774
|
+
throw created.err;
|
|
650
775
|
return { ok: true };
|
|
651
776
|
}
|
|
777
|
+
if (!vouched)
|
|
778
|
+
return await writeOwnRow(store, snapshot);
|
|
652
779
|
snapshot.rev = storeRev;
|
|
653
|
-
const won = await store.update(runId, scope, snapshot, { rev: storeRev });
|
|
780
|
+
const won = await store.update(runId, scope, snapshot, { rev: storeRev, creationId });
|
|
654
781
|
if (won)
|
|
655
782
|
storeRev += 1;
|
|
783
|
+
else
|
|
784
|
+
vouched = false;
|
|
656
785
|
return won ? { ok: true } : { ok: false, cause: "cas_lost" };
|
|
657
786
|
}
|
|
658
|
-
catch {
|
|
659
|
-
|
|
787
|
+
catch (err) {
|
|
788
|
+
vouched = false;
|
|
789
|
+
return { ok: false, cause: "threw", err };
|
|
660
790
|
}
|
|
661
791
|
});
|
|
662
792
|
persistTail = next;
|
|
663
793
|
return next;
|
|
664
794
|
};
|
|
795
|
+
const restartPersistTail = () => {
|
|
796
|
+
persistEpoch += 1;
|
|
797
|
+
persistTail = Promise.resolve();
|
|
798
|
+
vouched = false;
|
|
799
|
+
};
|
|
665
800
|
const t0 = now();
|
|
666
801
|
const run = {
|
|
667
802
|
id: runId,
|
|
668
803
|
scope,
|
|
804
|
+
creationId,
|
|
805
|
+
...(opts.resumeFromRunId === undefined ? { treeId: runId } : {}),
|
|
669
806
|
...(opts.name !== undefined ? { name: opts.name } : {}),
|
|
670
807
|
...(opts.description !== undefined ? { description: opts.description } : {}),
|
|
808
|
+
...(opts.editedFrom !== undefined ? { editedFrom: { name: opts.editedFrom.name, contentHash: opts.editedFrom.contentHash } } : {}),
|
|
671
809
|
...(opts.sourceTaskId !== undefined ? { sourceTaskId: opts.sourceTaskId } : {}),
|
|
672
810
|
...(opts.originatingSessionId !== undefined ? { originatingSessionId: opts.originatingSessionId } : {}),
|
|
673
811
|
status: "running",
|
|
@@ -685,13 +823,19 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
685
823
|
startedAt: t0,
|
|
686
824
|
createdAt: t0,
|
|
687
825
|
};
|
|
826
|
+
const signalSources = [cancelController.signal];
|
|
827
|
+
if (opts.signal)
|
|
828
|
+
signalSources.push(composable(opts.signal));
|
|
829
|
+
if (timeoutController)
|
|
830
|
+
signalSources.push(timeoutController.signal);
|
|
831
|
+
const workflowSignal = signalSources.length === 1 ? signalSources[0] : AbortSignal.any(signalSources);
|
|
688
832
|
markWorkflowActive(runId, scope);
|
|
689
833
|
if (timeoutController) {
|
|
690
834
|
timeoutTimer = setTimeout(() => timeoutController.abort(new Error("workflow total timeout")), totalTimeoutMs);
|
|
691
835
|
timeoutTimer.unref?.();
|
|
692
836
|
}
|
|
693
837
|
emit({ type: "run_start", runId, scope, ts: t0 });
|
|
694
|
-
|
|
838
|
+
const recordLanded = store === undefined ? Promise.resolve({ ok: true }) : finalizeWithin(timers, persist("create"), { ok: false, cause: "timeout" }, true);
|
|
695
839
|
let openOrdinal = 0;
|
|
696
840
|
const openOrder = new Map();
|
|
697
841
|
const agentPhaseOf = new Map();
|
|
@@ -710,6 +854,18 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
710
854
|
}
|
|
711
855
|
return undefined;
|
|
712
856
|
};
|
|
857
|
+
const settleRowOutcome = (rec, facts) => {
|
|
858
|
+
const outcome = memberOutcomeOf("workflow_member", rec.replayed === true ? "replayed" : "live", facts);
|
|
859
|
+
rec.outcome = outcome;
|
|
860
|
+
rec.status = workflowRowStatusOf(outcome.outcome);
|
|
861
|
+
return outcome;
|
|
862
|
+
};
|
|
863
|
+
const withMember = (result, member) => ({ ...result, member });
|
|
864
|
+
const lateMember = (rec, result, provenance, facts) => {
|
|
865
|
+
const member = rec?.outcome ?? memberOutcomeOf("workflow_member", provenance, facts);
|
|
866
|
+
const own = rec !== undefined && member.outcome === "killed" && result.terminal.kind === "failed" ? memberStops.get(rec.callKey)?.stoppedBy : undefined;
|
|
867
|
+
return withMember(own !== undefined ? { ...result, terminal: stoppedTerminalOf(result.terminal, own) } : result, member);
|
|
868
|
+
};
|
|
713
869
|
const countAgentFailures = (phase) => run.agents.reduce((n, a) => n + (a.status === "failed" && (phase === undefined || agentPhaseOf.get(a) === phase) ? 1 : 0), 0);
|
|
714
870
|
const phaseFailureExtra = (p) => {
|
|
715
871
|
const n = countAgentFailures(p);
|
|
@@ -726,10 +882,31 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
726
882
|
delete p.agentFailures;
|
|
727
883
|
}
|
|
728
884
|
};
|
|
885
|
+
const runStopper = () => !workflowSignal.aborted ? undefined : timeoutController !== undefined && timeoutController.signal.aborted && workflowSignal.reason === timeoutController.signal.reason ? "system" : "parent";
|
|
886
|
+
const memberStops = new Map();
|
|
887
|
+
const memberStopOf = (callKey) => {
|
|
888
|
+
let s = memberStops.get(callKey);
|
|
889
|
+
if (s === undefined)
|
|
890
|
+
memberStops.set(callKey, (s = { ctl: new AbortController() }));
|
|
891
|
+
return s;
|
|
892
|
+
};
|
|
893
|
+
const outlivedRun = new Set();
|
|
894
|
+
const memberSignalOf = (callKey, signal) => {
|
|
895
|
+
const own = memberStopOf(callKey).ctl.signal;
|
|
896
|
+
return signal === undefined ? own : AbortSignal.any([composable(signal), own]);
|
|
897
|
+
};
|
|
898
|
+
const stopperOf = (callKey) => memberStops.get(callKey)?.stoppedBy ?? runStopper();
|
|
899
|
+
const ownStopOf = (callKey, outcome) => (outcome?.outcome === "killed" ? memberStops.get(callKey)?.stoppedBy : undefined);
|
|
729
900
|
const closeAbandonedAgents = (endedAt) => {
|
|
730
901
|
for (const a of run.agents) {
|
|
731
902
|
if (a.status === "running") {
|
|
732
|
-
|
|
903
|
+
const stopper = stopperOf(a.callKey);
|
|
904
|
+
if (stopper === undefined)
|
|
905
|
+
outlivedRun.add(a.callKey);
|
|
906
|
+
settleRowOutcome(a, stopper !== undefined ? { from: "ended", status: "killed", stoppedBy: stopper } : { from: "ended", status: "failed", code: WORKFLOW_AGENT_OUTLIVED_RUN_CODE });
|
|
907
|
+
const own = memberStops.get(a.callKey)?.stoppedBy;
|
|
908
|
+
if (own !== undefined)
|
|
909
|
+
journalStoppedAtEnd(a, own);
|
|
733
910
|
a.endedAt = endedAt;
|
|
734
911
|
emit({ type: "agent_end", runId, label: a.label, ...(a.phase !== undefined ? { phase: a.phase } : {}), ...(a.groupId !== undefined ? { groupId: a.groupId } : {}), status: "failed", ts: endedAt });
|
|
735
912
|
}
|
|
@@ -776,12 +953,24 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
776
953
|
const sem = createSemaphore(concurrency);
|
|
777
954
|
const launchingCeiling = internals?.toolCeiling ?? undefined;
|
|
778
955
|
const hostCeiling = opts.toolCeiling ?? undefined;
|
|
779
|
-
const agentCeiling = launchingCeiling === undefined ? hostCeiling : hostCeiling === undefined ? launchingCeiling : [...launchingCeiling, ...hostCeiling];
|
|
780
956
|
const judgeHostCeiling = (spec) => {
|
|
781
957
|
if (hostCeiling !== undefined)
|
|
782
958
|
judgeHostToolCeiling(hostCeiling, spec, launchingCeiling);
|
|
783
959
|
};
|
|
784
|
-
const
|
|
960
|
+
const ceilingOf = (spec) => {
|
|
961
|
+
if (hostCeiling === undefined)
|
|
962
|
+
return launchingCeiling;
|
|
963
|
+
const view = legRetiredNameView(spec.tools ?? []);
|
|
964
|
+
const host = hostCeiling.map((l) => (isToolSelectorLayer(l) ? selectorLayerUnderView(l, view) : l));
|
|
965
|
+
return launchingCeiling === undefined ? host : [...launchingCeiling, ...host];
|
|
966
|
+
};
|
|
967
|
+
const definitionSeats = (launch) => {
|
|
968
|
+
const ceiling = ceilingOf(launch.spec);
|
|
969
|
+
return {
|
|
970
|
+
...(launch.definitionToolLists !== undefined ? { definitionToolLists: launch.definitionToolLists, toolCeiling: ceiling ?? [] } : ceiling !== undefined ? { toolCeiling: ceiling } : {}),
|
|
971
|
+
...(launch.agentType !== undefined ? { spawnAgentType: launch.agentType } : {}),
|
|
972
|
+
};
|
|
973
|
+
};
|
|
785
974
|
const spawnAttribution = {
|
|
786
975
|
isDelegatedChild: true,
|
|
787
976
|
...(parkLaneArmed(opts) ? { parkLaneHeld: true } : {}),
|
|
@@ -794,14 +983,13 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
794
983
|
...(opts.parentCenterSourceRevision !== undefined ? { parentCenterSourceRevision: opts.parentCenterSourceRevision } : {}),
|
|
795
984
|
...(opts.onForwardEvent ? { onForwardEvent: opts.onForwardEvent } : {}),
|
|
796
985
|
...(opts.inheritedGate !== undefined ? { inheritedGate: opts.inheritedGate } : {}),
|
|
797
|
-
...(agentCeiling !== undefined ? { toolCeiling: agentCeiling } : {}),
|
|
798
986
|
...((opts.rootSessionId ?? opts.originatingSessionId) !== undefined ? { rootSessionId: opts.rootSessionId ?? opts.originatingSessionId } : {}),
|
|
799
987
|
...(opts.rootSessionId !== undefined && opts.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: opts.rootSessionIncarnation } : {}),
|
|
800
988
|
...(opts.rootSessionId !== undefined && opts.rootSessionScope !== undefined ? { rootSessionScope: opts.rootSessionScope } : {}),
|
|
801
989
|
...(opts.placementRoot !== undefined ? { placementRoot: opts.placementRoot } : {}),
|
|
802
990
|
...(opts.placementTarget !== undefined ? { placementTarget: opts.placementTarget } : {}),
|
|
803
991
|
...(opts.crossBoundaryTree !== undefined ? { crossBoundaryTree: opts.crossBoundaryTree } : {}),
|
|
804
|
-
...(opts.delegationOwner !== undefined ? { delegationOwner: opts.delegationOwner } : {}),
|
|
992
|
+
...(opts.delegationOwner !== undefined ? { delegationOwner: answeringOnce(opts.delegationOwner) } : {}),
|
|
805
993
|
...(opts.originatingSessionId !== undefined ? { parentSessionId: opts.originatingSessionId } : {}),
|
|
806
994
|
};
|
|
807
995
|
const captureFloorSeatsNow = async () => {
|
|
@@ -822,11 +1010,12 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
822
1010
|
const bceParentToolCall = opts.parentToolCallId !== undefined ? { parentToolCallId: opts.parentToolCallId } : {};
|
|
823
1011
|
const waIdOf = (callKey) => `wa${createHash("sha256").update(`${runId}:${callKey}`).digest("hex").slice(0, 16)}`;
|
|
824
1012
|
const bceLive = new Map();
|
|
825
|
-
const bceSpawn = (callKey, label,
|
|
1013
|
+
const bceSpawn = (callKey, label, asked, replayed, sessionId, model) => {
|
|
826
1014
|
if (!bceSink)
|
|
827
1015
|
return;
|
|
1016
|
+
const agentType = workflowLaunchTypeWord(asked, agentRegistry);
|
|
828
1017
|
const id = waIdOf(callKey);
|
|
829
|
-
bceLive.set(id, { callKey, label, ...(agentType !== undefined ? { agentType } : {}), ...(sessionId !== undefined ? { sessionId } : {}), ...(sessionId !== undefined && judgedOwnerSeat(
|
|
1018
|
+
bceLive.set(id, { callKey, label, ...(agentType !== undefined ? { agentType } : {}), ...(sessionId !== undefined ? { sessionId } : {}), ...(sessionId !== undefined && judgedOwnerSeat(opts) === undefined ? { verified: true } : {}), ...(model !== undefined ? { model } : {}), generation: 1 });
|
|
830
1019
|
bceEmit({
|
|
831
1020
|
kind: "spawn",
|
|
832
1021
|
taskId: id,
|
|
@@ -926,15 +1115,31 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
926
1115
|
});
|
|
927
1116
|
};
|
|
928
1117
|
const budgetTotal = budgetCeiling ?? null;
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
1118
|
+
const wfSpend = mintWfSpend();
|
|
1119
|
+
if (budgetTotal !== null)
|
|
1120
|
+
wfSpend.setCeiling({ tokens: budgetTotal });
|
|
1121
|
+
const spent = () => wfSpend.subtreeSettled.tokens;
|
|
932
1122
|
const budget = {
|
|
933
1123
|
total: budgetTotal,
|
|
934
1124
|
spent,
|
|
935
|
-
remaining: () => (
|
|
1125
|
+
remaining: () => wfSpend.remaining("tokens") ?? Infinity,
|
|
936
1126
|
};
|
|
937
|
-
const
|
|
1127
|
+
const memberSpendParent = { seat: wfSpend, link: "task" };
|
|
1128
|
+
const budgetGate = () => {
|
|
1129
|
+
if (budgetTotal !== null && budgetTotal - spent() < SPEND_OUTPUT_FLOOR_TOKENS)
|
|
1130
|
+
throw new WorkflowBudgetExceededError(spent(), budgetTotal);
|
|
1131
|
+
};
|
|
1132
|
+
const ownBooked = { tokens: 0, costMicroUsd: 0 };
|
|
1133
|
+
const bookOwnSpend = () => {
|
|
1134
|
+
if (finalized)
|
|
1135
|
+
return;
|
|
1136
|
+
const own = wfSpend.ownSettled;
|
|
1137
|
+
run.stats.tokens += own.tokens - ownBooked.tokens;
|
|
1138
|
+
run.stats.costMicroUsd += own.costMicroUsd - ownBooked.costMicroUsd;
|
|
1139
|
+
ownBooked.tokens = own.tokens;
|
|
1140
|
+
ownBooked.costMicroUsd = own.costMicroUsd;
|
|
1141
|
+
};
|
|
1142
|
+
const accumulateStats = (result) => {
|
|
938
1143
|
const s = result.stats;
|
|
939
1144
|
run.stats.tokens += s.tokens ?? 0;
|
|
940
1145
|
run.stats.turns += s.turns ?? 0;
|
|
@@ -945,10 +1150,6 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
945
1150
|
run.stats.nested.tasks += s.nested.tasks ?? 0;
|
|
946
1151
|
run.stats.nested.costMicroUsd += s.nested.costMicroUsd ?? 0;
|
|
947
1152
|
}
|
|
948
|
-
if (live) {
|
|
949
|
-
liveTokens += s.tokens ?? 0;
|
|
950
|
-
liveNestedTokens += s.nested?.tokens ?? 0;
|
|
951
|
-
}
|
|
952
1153
|
};
|
|
953
1154
|
const activeUsageBeats = new Set();
|
|
954
1155
|
const settleActiveUsageBeats = () => {
|
|
@@ -964,6 +1165,72 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
964
1165
|
let resumeClaim;
|
|
965
1166
|
const replayByOrdinal = [];
|
|
966
1167
|
let divergence;
|
|
1168
|
+
const recordedOrdinalOfPosition = new Map();
|
|
1169
|
+
const recordedOrdinals = new Set();
|
|
1170
|
+
let priorRecordUnpositioned = false;
|
|
1171
|
+
const recordedOrdinalsOfSpec = new Map();
|
|
1172
|
+
const heldOrdinals = new Set();
|
|
1173
|
+
const startingOrdinals = new Set();
|
|
1174
|
+
const reachedPositions = new Set();
|
|
1175
|
+
const scopeOwner = {};
|
|
1176
|
+
const rootChain = { n: 0 };
|
|
1177
|
+
let pipelinesRunning = 0;
|
|
1178
|
+
const scopeHere = () => {
|
|
1179
|
+
const scope = fanOutScopeStore.getStore();
|
|
1180
|
+
return scope !== undefined && scope.owner === scopeOwner ? scope : undefined;
|
|
1181
|
+
};
|
|
1182
|
+
const ordinalFor = (position, inItem, spec) => {
|
|
1183
|
+
const taken = (o) => heldOrdinals.has(o) || startingOrdinals.has(o);
|
|
1184
|
+
const recorded = priorRecordUnpositioned ? (inItem ? recordedOrdinalsOfSpec.get(spec)?.find((o) => !taken(o)) : undefined) : recordedOrdinalOfPosition.get(position);
|
|
1185
|
+
let picked;
|
|
1186
|
+
if (recorded !== undefined && !taken(recorded))
|
|
1187
|
+
picked = { ordinal: recorded, adopted: true };
|
|
1188
|
+
else {
|
|
1189
|
+
let o = 0;
|
|
1190
|
+
while (taken(o) || (priorRecordUnpositioned ? inItem && parkedByOrdinal[o] !== undefined : recordedOrdinals.has(o)))
|
|
1191
|
+
o++;
|
|
1192
|
+
picked = { ordinal: o, adopted: false };
|
|
1193
|
+
}
|
|
1194
|
+
const ordinal = picked.ordinal;
|
|
1195
|
+
startingOrdinals.add(ordinal);
|
|
1196
|
+
queueMicrotask(() => startingOrdinals.delete(ordinal));
|
|
1197
|
+
return picked;
|
|
1198
|
+
};
|
|
1199
|
+
const fanOutSite = (kind) => {
|
|
1200
|
+
const enclosing = scopeHere();
|
|
1201
|
+
const prefix = enclosing !== undefined ? `${enclosing.path}.` : "";
|
|
1202
|
+
const n = (enclosing?.chain ?? rootChain).n++;
|
|
1203
|
+
return { site: `${prefix}${kind}${n}`, enclosing, prefix, n };
|
|
1204
|
+
};
|
|
1205
|
+
const notMadeAt = (what, at) => {
|
|
1206
|
+
if (opts.resumeFromRunId === undefined || parkedLeg !== undefined || resumeRefusal !== undefined || finalized)
|
|
1207
|
+
return undefined;
|
|
1208
|
+
let missing;
|
|
1209
|
+
let waiting;
|
|
1210
|
+
for (const [position, ordinal] of recordedOrdinalOfPosition) {
|
|
1211
|
+
if (reachedPositions.has(position) || !madeAtEvent(position, at.prefix, at.n))
|
|
1212
|
+
continue;
|
|
1213
|
+
if (missing === undefined || ordinal < missing.ordinal)
|
|
1214
|
+
missing = { position, ordinal };
|
|
1215
|
+
if (parkedByOrdinal[ordinal]?.kind === "pending" && (waiting === undefined || ordinal < waiting.ordinal))
|
|
1216
|
+
waiting = { position, ordinal };
|
|
1217
|
+
}
|
|
1218
|
+
if (waiting !== undefined) {
|
|
1219
|
+
const refusal = parkedCallNotMadeError(waiting.ordinal, waiting.position, what);
|
|
1220
|
+
resumeRefusal ??= refusal;
|
|
1221
|
+
throw refusal;
|
|
1222
|
+
}
|
|
1223
|
+
return missing;
|
|
1224
|
+
};
|
|
1225
|
+
const joinFanOut = (kind, at) => {
|
|
1226
|
+
const missing = notMadeAt(kind, at);
|
|
1227
|
+
if (missing !== undefined)
|
|
1228
|
+
noteDivergence(missing.ordinal, `the ${kind} ended without the call the resumed run made at ${missing.position} — an item, a stage, a thunk or a call the script no longer reaches`);
|
|
1229
|
+
};
|
|
1230
|
+
const admitRecord = (rec) => {
|
|
1231
|
+
run.agents.push(rec);
|
|
1232
|
+
heldOrdinals.add(callKeyOrdinal(rec.callKey));
|
|
1233
|
+
};
|
|
967
1234
|
let resumeRefusal;
|
|
968
1235
|
const refusalTerminal = (thrown) => (workflowSignal?.aborted !== true ? resumeRefusal : thrown === resumeRefusal ? (workflowSignal.reason ?? new Error("workflow aborted")) : thrown);
|
|
969
1236
|
let parkedLeg;
|
|
@@ -976,40 +1243,42 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
976
1243
|
const status = t.detail?.kind === "coded" ? t.detail.detail.status : undefined;
|
|
977
1244
|
return PARK_NOT_PENDING_STATUSES.find((s) => s === status);
|
|
978
1245
|
};
|
|
1246
|
+
const completedRunsAgain = new Set();
|
|
979
1247
|
const askedAgainBit = (callKey) => {
|
|
980
1248
|
const status = stepAskedAgainAfter(callKey);
|
|
981
|
-
return status === "expired" || status === "absent" ? { workflowStepAskedAgain: true } : {};
|
|
1249
|
+
return status === "expired" || status === "absent" || completedRunsAgain.has(callKey) ? { workflowStepAskedAgain: true } : {};
|
|
982
1250
|
};
|
|
983
1251
|
const memberAt = (callKey, label) => ({ runId, label, ...(askedAgainBit(callKey).workflowStepAskedAgain === true ? { askedAgain: true } : {}) });
|
|
984
1252
|
const memberSeat = (callKey, label) => ({ workflowMember: memberAt(callKey, label) });
|
|
985
1253
|
const memberStamp = (e, callKey, label) => stampWorkflowMember(e, memberAt(callKey, label));
|
|
986
1254
|
const storeWithin = (p) => finalizeWithin(timers, p.then((value) => ({ ok: true, value }), () => ({ ok: false })), { ok: false }, true);
|
|
987
|
-
let
|
|
988
|
-
const
|
|
1255
|
+
let admissionTree;
|
|
1256
|
+
const treeAtAdmission = (fromRunId) => (admissionTree ??= store === undefined ? Promise.resolve("unreadable") : readWorkflowRunTreeWithin(store, fromRunId, scope, storeWithin));
|
|
989
1257
|
const endOf = (r) => ({ runId: r.id, status: r.status, ...(r.errorCode !== undefined ? { errorCode: r.errorCode } : {}) });
|
|
990
1258
|
const continuationThatTook = async (key, fromRunId) => {
|
|
991
|
-
const
|
|
992
|
-
if (typeof
|
|
1259
|
+
const tree = await treeAtAdmission(fromRunId);
|
|
1260
|
+
if (typeof tree === "string")
|
|
993
1261
|
return undefined;
|
|
994
|
-
const took = runThatDrove(
|
|
1262
|
+
const took = runThatDrove(workflowRunsBelow(tree, fromRunId).filter((r) => r.id !== runId), key.token, key.callKey);
|
|
995
1263
|
return took === undefined ? undefined : endOf(took);
|
|
996
1264
|
};
|
|
997
1265
|
const continuedBeforeOf = async (fromRunId) => {
|
|
998
|
-
const
|
|
999
|
-
if (typeof
|
|
1266
|
+
const tree = await treeAtAdmission(fromRunId);
|
|
1267
|
+
if (typeof tree === "string")
|
|
1000
1268
|
return undefined;
|
|
1001
|
-
const earlier =
|
|
1269
|
+
const earlier = workflowRunChildrenIn(tree, fromRunId).filter((r) => r.id !== runId).sort((a, b) => b.startedAt - a.startedAt)[0];
|
|
1002
1270
|
return earlier === undefined ? undefined : endOf(earlier);
|
|
1003
1271
|
};
|
|
1004
1272
|
const PASS_ATTEMPTS = 3;
|
|
1005
1273
|
const passParksFrom = async (from, keys) => {
|
|
1006
1274
|
let open = keys;
|
|
1007
1275
|
for (let attempt = 0; attempt < PASS_ATTEMPTS && open.length > 0 && store !== undefined; attempt++) {
|
|
1008
|
-
const
|
|
1009
|
-
if (typeof
|
|
1276
|
+
const tree = await readWorkflowRunTreeWithin(store, from, scope, storeWithin);
|
|
1277
|
+
if (typeof tree === "string")
|
|
1010
1278
|
return;
|
|
1011
|
-
const
|
|
1012
|
-
const
|
|
1279
|
+
const named = workflowRunInTree(tree, from);
|
|
1280
|
+
const records = tree.records.filter((r) => r.id !== runId);
|
|
1281
|
+
const entryOf = (key) => named.parks?.find((p) => p.token === key.token && p.parkedBy === from);
|
|
1013
1282
|
const stand = (key) => {
|
|
1014
1283
|
key.parkedBy = runId;
|
|
1015
1284
|
const settled = entryOf(key)?.settledDecisions;
|
|
@@ -1023,16 +1292,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1023
1292
|
const entry = entryOf(key);
|
|
1024
1293
|
if (entry === undefined || entry.passedTo !== undefined)
|
|
1025
1294
|
return false;
|
|
1026
|
-
const holder =
|
|
1295
|
+
const holder = parkHolderAmong(key.token, records);
|
|
1027
1296
|
return holder.kind === "held" && holder.runId === from;
|
|
1028
1297
|
});
|
|
1029
1298
|
if (open.length === 0)
|
|
1030
1299
|
return;
|
|
1031
|
-
const next = structuredClone(
|
|
1300
|
+
const next = structuredClone(named);
|
|
1032
1301
|
for (const p of next.parks ?? [])
|
|
1033
1302
|
if (p.parkedBy === from && open.some((key) => key.token === p.token))
|
|
1034
1303
|
p.passedTo = runId;
|
|
1035
|
-
const won = await storeWithin(Promise.resolve().then(() => store.update(from, scope, next, { rev:
|
|
1304
|
+
const won = await storeWithin(Promise.resolve().then(() => store.update(from, scope, next, { rev: named.rev ?? 0, creationId: workflowRunCreationIdOf(named) }, { cause: "park_pass" })));
|
|
1036
1305
|
if (won.ok && won.value) {
|
|
1037
1306
|
for (const key of open)
|
|
1038
1307
|
stand(key);
|
|
@@ -1052,7 +1321,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1052
1321
|
const parkedError = () => {
|
|
1053
1322
|
const p = parkedLeg;
|
|
1054
1323
|
const gate = p.paused.terminal.gate;
|
|
1055
|
-
return new WorkflowAgentParkedError(p.label, gate.kind, p.paused.terminal.checkpointId, gate.kind === "resource_limit" ? gate.reason : undefined,
|
|
1324
|
+
return new WorkflowAgentParkedError(p.label, gate.kind, p.paused.terminal.checkpointId, gate.kind === "resource_limit" ? gate.reason : undefined, askedAgainBit(p.callKey).workflowStepAskedAgain === true);
|
|
1056
1325
|
};
|
|
1057
1326
|
const parkWaits = new Map();
|
|
1058
1327
|
const takenParkTokens = new Set();
|
|
@@ -1152,13 +1421,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1152
1421
|
wakeParksSettled();
|
|
1153
1422
|
};
|
|
1154
1423
|
};
|
|
1155
|
-
const parkedResumeFor = (token) => parkedResume?.find((d) => d.token === token);
|
|
1424
|
+
const parkedResumeFor = (token) => parkedResume?.find((d) => d.token === token && !spentAtAdmission.has(d));
|
|
1156
1425
|
const parkedCallChangedError = (ordinal) => Object.assign(new Error(`workflow resume: ordinal ${ordinal} is PARKED on a checkpoint, but the call at that ordinal changed (its call key differs from the journaled one) ` +
|
|
1157
1426
|
(divergence === undefined
|
|
1158
1427
|
? `while no earlier call diverged from the record — the difference is in this call's own inputs (${CALL_INPUTS_THAT_MOVE}). `
|
|
1159
1428
|
: `after replay stopped at agent #${divergence.ordinal} (${divergence.reason}) — the calls from there on ran live, so this call may have been built from a live result rather than the recorded one. `) +
|
|
1160
1429
|
"A fresh spawn there would run beside the pinned child. Resume with the calls up to it unchanged, or decide the checkpoint " +
|
|
1161
1430
|
"through the deployment's approval channel and start a fresh run."), { code: "workflow.parked_call_changed" });
|
|
1431
|
+
const parkedCallNotMadeError = (ordinal, position, what) => Object.assign(new Error(`workflow resume: ordinal ${ordinal} is PARKED on a checkpoint (recorded at ${position}), but ${what === "call" ? "a call now stands where the fan-out it was made under stood" : `the ${what} at its place ended without that call`} — ` +
|
|
1432
|
+
"the script no longer makes it there, or it was refused before its record. Resume with a script that makes the parked call where it was, " +
|
|
1433
|
+
"or decide the checkpoint through the deployment's approval channel and start a fresh run."), { code: "workflow.parked_call_changed" });
|
|
1162
1434
|
let inFlightLegs = 0;
|
|
1163
1435
|
let legsIdleResolve;
|
|
1164
1436
|
let retired = false;
|
|
@@ -1169,6 +1441,9 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1169
1441
|
keeperHold?.release();
|
|
1170
1442
|
if (timeoutTimer)
|
|
1171
1443
|
clearTimeout(timeoutTimer);
|
|
1444
|
+
for (const f of hostSignals.values())
|
|
1445
|
+
f.release();
|
|
1446
|
+
hostSignals.clear();
|
|
1172
1447
|
};
|
|
1173
1448
|
const legStart = () => {
|
|
1174
1449
|
inFlightLegs += 1;
|
|
@@ -1192,6 +1467,23 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1192
1467
|
});
|
|
1193
1468
|
}
|
|
1194
1469
|
};
|
|
1470
|
+
const membersStop = new AbortController();
|
|
1471
|
+
const stopAndSettleMembers = async () => {
|
|
1472
|
+
if (inFlightLegs === 0 || workflowSignal.aborted)
|
|
1473
|
+
return;
|
|
1474
|
+
membersStop.abort(new Error("workflow failed"));
|
|
1475
|
+
const bound = new AbortController();
|
|
1476
|
+
const timer = timers.setTimeout(() => bound.abort(), WORKFLOW_FAILURE_SETTLE_MS);
|
|
1477
|
+
const onRunAbort = () => bound.abort();
|
|
1478
|
+
workflowSignal.addEventListener("abort", onRunAbort, { once: true });
|
|
1479
|
+
try {
|
|
1480
|
+
await awaitLegsIdle(bound.signal);
|
|
1481
|
+
}
|
|
1482
|
+
finally {
|
|
1483
|
+
timers.clearTimeout(timer);
|
|
1484
|
+
workflowSignal.removeEventListener("abort", onRunAbort);
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1195
1487
|
const parkSeat = opts.checkpointStore;
|
|
1196
1488
|
const parkedByOrdinal = [];
|
|
1197
1489
|
const errText = (err) => (thrownText(err));
|
|
@@ -1217,7 +1509,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1217
1509
|
};
|
|
1218
1510
|
const parkMaterialOf = async (key, ordinal) => {
|
|
1219
1511
|
let entry;
|
|
1220
|
-
if (key.originRunId ===
|
|
1512
|
+
if (key.originRunId === resumeFrom)
|
|
1221
1513
|
entry = replayByOrdinal[ordinal];
|
|
1222
1514
|
else if (journalStore) {
|
|
1223
1515
|
const loaded = await finalizeWithin(timers, new Promise((resolve) => resolve(journalStore.load(key.originRunId, scope)))
|
|
@@ -1266,12 +1558,12 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1266
1558
|
return claimHolder === undefined || claimHolder === "" ? text : text.split(claimHolder).join("<holder>");
|
|
1267
1559
|
};
|
|
1268
1560
|
const noteDecision = (drive, callKey, result, code) => {
|
|
1269
|
-
if (drive.decisionId === undefined ||
|
|
1561
|
+
if (drive.decisionId === undefined || finalized)
|
|
1270
1562
|
return;
|
|
1271
|
-
const decisions = (run.
|
|
1563
|
+
const decisions = (run.decisions ??= []);
|
|
1272
1564
|
if (decisions.some((d) => d.decisionId === drive.decisionId && d.callKey === callKey))
|
|
1273
1565
|
return;
|
|
1274
|
-
decisions.push({ ordinal: callKeyOrdinal(callKey), callKey, decisionId: drive.decisionId, result, ...(code !== undefined && code !== "" ? { code } : {}) });
|
|
1566
|
+
decisions.push({ ordinal: callKeyOrdinal(callKey), callKey, decisionId: drive.decisionId, result, ...(code !== undefined && code !== "" ? { code: withoutToken(code, drive.token) } : {}) });
|
|
1275
1567
|
};
|
|
1276
1568
|
const codeOf = (err) => {
|
|
1277
1569
|
const c = readMember(err, "code");
|
|
@@ -1308,7 +1600,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1308
1600
|
const gate = truth.cp.gate;
|
|
1309
1601
|
const outcome = entry !== undefined ? entry.outcome : gate.kind === "resource_limit" && gate.reason === "preempt" ? { gate: "resource_limit", decision: "continue" } : undefined;
|
|
1310
1602
|
if (outcome !== undefined) {
|
|
1311
|
-
const accounted = entry?.decisionId !== undefined
|
|
1603
|
+
const accounted = entry?.decisionId !== undefined ? { decisionId: entry.decisionId } : {};
|
|
1312
1604
|
return { kind: "drive", drive: { token: truth.key.token, outcome, ...(entry?.inheritedGate !== undefined ? { inheritedGate: entry.inheritedGate } : {}), sessionId: paused.sessionId || undefined, paused, row: judgeCheckpointRow(truth.cp), ...accounted } };
|
|
1313
1605
|
}
|
|
1314
1606
|
return { kind: "repark", paused };
|
|
@@ -1331,6 +1623,26 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1331
1623
|
takeParkWait(w);
|
|
1332
1624
|
taken.push({ at, w, d });
|
|
1333
1625
|
});
|
|
1626
|
+
if (taken.some(({ d }) => d.decisionId !== undefined)) {
|
|
1627
|
+
const tree = store === undefined ? workflowRunTreeOfOne(run) : await readWorkflowRunTreeWithin(store, runId, scope, storeWithin, run);
|
|
1628
|
+
for (const t of [...taken]) {
|
|
1629
|
+
if (t.d.decisionId === undefined)
|
|
1630
|
+
continue;
|
|
1631
|
+
const was = typeof tree === "string" ? undefined : workflowParkDecisionOf(t.d.token, t.d.decisionId, tree);
|
|
1632
|
+
if (typeof tree !== "string" && was?.kind !== "spent")
|
|
1633
|
+
continue;
|
|
1634
|
+
seatParkWait(t.w);
|
|
1635
|
+
taken.splice(taken.indexOf(t), 1);
|
|
1636
|
+
if (was?.kind === "spent") {
|
|
1637
|
+
emitRunLog(`[park] a decision for the parked leg "${t.w.rec.label.slice(0, 80)}" was not applied — it was already refused${was.code !== undefined ? ` (${withoutToken(was.code, t.w.key.token)})` : ""}; the park stands and needs a new decision.`);
|
|
1638
|
+
results[t.at] = "spent";
|
|
1639
|
+
}
|
|
1640
|
+
else {
|
|
1641
|
+
emitRunLog(`[park] a decision for the parked leg "${t.w.rec.label.slice(0, 80)}" was not applied — the run store's records of this workflow could not be read to judge it; the park stands.`);
|
|
1642
|
+
results[t.at] = "unreadable";
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1334
1646
|
for (const { at, w, d } of taken) {
|
|
1335
1647
|
const ordinal = callKeyOrdinal(w.rec.callKey);
|
|
1336
1648
|
let disposition;
|
|
@@ -1361,6 +1673,83 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1361
1673
|
}
|
|
1362
1674
|
return parkedLeg !== undefined || finalized ? ending() : { kind: "live", results };
|
|
1363
1675
|
};
|
|
1676
|
+
const stopMember = async (callKey, stoppedBy) => {
|
|
1677
|
+
const rec = run.agents.find((a) => a.callKey === callKey);
|
|
1678
|
+
if (rec === undefined)
|
|
1679
|
+
return { answer: "not_found" };
|
|
1680
|
+
const wait = parkWaits.get(callKey);
|
|
1681
|
+
if (wait !== undefined && wait.waiting && !finalized && parkedLeg === undefined) {
|
|
1682
|
+
const seat = parkSeat;
|
|
1683
|
+
if (seat === undefined)
|
|
1684
|
+
return { answer: "park_arbiter_unreachable" };
|
|
1685
|
+
takeParkWait(wait);
|
|
1686
|
+
const token = wait.key.token;
|
|
1687
|
+
let gaveUp = false;
|
|
1688
|
+
const isThisPark = (row) => row !== null && row.token === token && row.sessionId === wait.key.sessionId;
|
|
1689
|
+
const attempt = Promise.resolve()
|
|
1690
|
+
.then(() => seat.get(token))
|
|
1691
|
+
.then(async (row) => {
|
|
1692
|
+
if (gaveUp || !isThisPark(row))
|
|
1693
|
+
return "unreachable";
|
|
1694
|
+
if (row.status !== "pending")
|
|
1695
|
+
return false;
|
|
1696
|
+
if ((await seat.expire(token, row.scope, claimHolder !== undefined ? { holder: claimHolder } : undefined)) === true)
|
|
1697
|
+
return true;
|
|
1698
|
+
const after = await seat.get(token);
|
|
1699
|
+
return isThisPark(after) && after.status !== "pending" ? false : "unreachable";
|
|
1700
|
+
})
|
|
1701
|
+
.then((won) => (gaveUp ? "unreachable" : won), () => "unreachable");
|
|
1702
|
+
const won = await finalizeWithin(timers, attempt, "unreachable");
|
|
1703
|
+
if (won === "unreachable")
|
|
1704
|
+
gaveUp = true;
|
|
1705
|
+
if (won !== true) {
|
|
1706
|
+
seatParkWait(wait);
|
|
1707
|
+
return won === false ? { answer: "park_resume_won" } : { answer: "park_arbiter_unreachable" };
|
|
1708
|
+
}
|
|
1709
|
+
const first = memberStopOf(callKey);
|
|
1710
|
+
first.stoppedBy ??= stoppedBy;
|
|
1711
|
+
stoppedBy = first.stoppedBy;
|
|
1712
|
+
takenParkTokens.add(wait.key.token);
|
|
1713
|
+
if (finalized || parkedLeg !== undefined) {
|
|
1714
|
+
seatParkWait(wait);
|
|
1715
|
+
return { answer: "stopped", stoppedBy };
|
|
1716
|
+
}
|
|
1717
|
+
const cpId = wait.paused.terminal.checkpointId;
|
|
1718
|
+
const settled = {
|
|
1719
|
+
taskId: callKey,
|
|
1720
|
+
sessionId: wait.paused.sessionId,
|
|
1721
|
+
terminal: { kind: "failed", message: `the call was stopped (by ${stoppedBy}) while it waited on an approval${cpId !== undefined ? ` (checkpoint ${cpId}, now expired)` : ""}. It did not run on; it is recorded as stopped and the script continues.` },
|
|
1722
|
+
result: "", resultEntryIds: [],
|
|
1723
|
+
continuesFrom: { none: "unsettled" },
|
|
1724
|
+
stats: { turns: 0, tokens: 0, costMicroUsd: 0, usageMissing: true },
|
|
1725
|
+
};
|
|
1726
|
+
wait.answer({ kind: "settle", result: settled });
|
|
1727
|
+
return { answer: "stopped", stoppedBy };
|
|
1728
|
+
}
|
|
1729
|
+
const own = memberStops.get(callKey);
|
|
1730
|
+
if (own?.stoppedBy !== undefined)
|
|
1731
|
+
return { answer: "stopped", stoppedBy: own.stoppedBy };
|
|
1732
|
+
if (rec.status === "parked")
|
|
1733
|
+
return parkedLeg !== undefined || finalized ? { answer: "already_terminal", status: "parked" } : { answer: "park_resume_won" };
|
|
1734
|
+
if (finalized && outlivedRun.has(callKey)) {
|
|
1735
|
+
if (!journalStoppedAtEnd(rec, stoppedBy))
|
|
1736
|
+
return { answer: "already_terminal", status: rec.outcome?.outcome ?? rec.status };
|
|
1737
|
+
const s = memberStopOf(callKey);
|
|
1738
|
+
s.stoppedBy = stoppedBy;
|
|
1739
|
+
s.ctl.abort(new Error(`workflow agent stopped by ${stoppedBy}`));
|
|
1740
|
+
return { answer: "stopped", stoppedBy };
|
|
1741
|
+
}
|
|
1742
|
+
if (rec.status !== "running" || finalized)
|
|
1743
|
+
return { answer: "already_terminal", status: rec.outcome?.outcome ?? rec.status };
|
|
1744
|
+
if (workflowSignal.aborted) {
|
|
1745
|
+
memberStopOf(callKey).ctl.abort(new Error(`workflow agent stopped by ${runStopper() ?? stoppedBy}`));
|
|
1746
|
+
return { answer: "stopped", stoppedBy: runStopper() ?? stoppedBy };
|
|
1747
|
+
}
|
|
1748
|
+
const s = memberStopOf(callKey);
|
|
1749
|
+
s.stoppedBy = stoppedBy;
|
|
1750
|
+
s.ctl.abort(new Error(`workflow agent stopped by ${stoppedBy}`));
|
|
1751
|
+
return { answer: "stopped", stoppedBy };
|
|
1752
|
+
};
|
|
1364
1753
|
const assertChildParkSeat = (s) => {
|
|
1365
1754
|
const seat = s.checkpointStore;
|
|
1366
1755
|
if (seat === undefined || seat === "disabled")
|
|
@@ -1386,10 +1775,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1386
1775
|
});
|
|
1387
1776
|
};
|
|
1388
1777
|
let journalTail = Promise.resolve();
|
|
1778
|
+
let journalSealed = false;
|
|
1389
1779
|
const JOURNAL_DRAIN_MAX_MS = 5_000;
|
|
1390
1780
|
const awaitedAppends = new Map();
|
|
1391
1781
|
const lastAppendByCall = new Map();
|
|
1392
|
-
const trackJournalWrite = (append, callKey) => {
|
|
1782
|
+
const trackJournalWrite = (append, callKey, drainedLate = false) => {
|
|
1393
1783
|
const start = () => {
|
|
1394
1784
|
try {
|
|
1395
1785
|
return Promise.resolve(append());
|
|
@@ -1401,8 +1791,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1401
1791
|
const prior = lastAppendByCall.get(callKey);
|
|
1402
1792
|
const write = prior === undefined ? start() : prior.then(start, start);
|
|
1403
1793
|
lastAppendByCall.set(callKey, write.catch(() => undefined));
|
|
1404
|
-
if (finalized)
|
|
1794
|
+
if (finalized) {
|
|
1795
|
+
if (drainedLate && !journalSealed)
|
|
1796
|
+
journalTail = journalTail.then(() => write).catch(() => undefined);
|
|
1405
1797
|
return Promise.resolve();
|
|
1798
|
+
}
|
|
1406
1799
|
const written = new Promise((resolve, reject) => {
|
|
1407
1800
|
const handle = timers.setTimeout(() => {
|
|
1408
1801
|
awaitedAppends.delete(handle);
|
|
@@ -1428,13 +1821,14 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1428
1821
|
return written;
|
|
1429
1822
|
};
|
|
1430
1823
|
const durableApprovalInherit = (s) => s.durableApproval === undefined && opts.defaultDurableApproval !== undefined && !launchUnkept ? { durableApproval: { ...opts.defaultDurableApproval } } : {};
|
|
1824
|
+
const parkGapInherit = (s) => s.durableApproval === undefined && opts.durableApprovalWithheld !== undefined && opts.durableApprovalWithheld.length > 0 ? { workflowParkGap: opts.durableApprovalWithheld } : {};
|
|
1431
1825
|
const journalDurableResult = (result) => {
|
|
1432
1826
|
const t = result.terminal;
|
|
1433
1827
|
if (t === undefined || t.kind !== "failed" || typeof t.message !== "string" || t.message === "")
|
|
1434
1828
|
return result;
|
|
1435
1829
|
return { ...result, terminal: { ...t, message: boundedRedactedSummary(t.message, MAX_TRANSCRIPT_CHARS) } };
|
|
1436
1830
|
};
|
|
1437
|
-
const journalAppend = async (callKey, result, label) => {
|
|
1831
|
+
const journalAppend = async (callKey, result, label, stoppedBy) => {
|
|
1438
1832
|
const dbg = typeof process !== "undefined" && process.env?.SEMA_DEBUG_WORKFLOW_JOURNAL === "1";
|
|
1439
1833
|
const trace = (step) => {
|
|
1440
1834
|
if (dbg)
|
|
@@ -1444,6 +1838,10 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1444
1838
|
trace("SKIP (no journalStore on this run)");
|
|
1445
1839
|
return;
|
|
1446
1840
|
}
|
|
1841
|
+
if (finalized && stoppedBy === undefined && memberStops.get(callKey)?.stoppedBy !== undefined) {
|
|
1842
|
+
trace("SKIP (the run's end wrote this member's stopped arm)");
|
|
1843
|
+
return;
|
|
1844
|
+
}
|
|
1447
1845
|
const stored = journalDurableResult(result);
|
|
1448
1846
|
let serialized;
|
|
1449
1847
|
try {
|
|
@@ -1452,6 +1850,19 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1452
1850
|
catch {
|
|
1453
1851
|
serialized = undefined;
|
|
1454
1852
|
}
|
|
1853
|
+
if (stoppedBy !== undefined) {
|
|
1854
|
+
let arm;
|
|
1855
|
+
try {
|
|
1856
|
+
arm = JSON.stringify({ result: stored, stoppedBy });
|
|
1857
|
+
}
|
|
1858
|
+
catch {
|
|
1859
|
+
arm = undefined;
|
|
1860
|
+
}
|
|
1861
|
+
const leg = arm !== undefined && oversizeJournalResult(arm) ? journalOversizeTombstone(stored, Buffer.byteLength(arm, "utf8"), "stopped") : stored;
|
|
1862
|
+
await trackJournalWrite(() => journalStore.append(runId, scope, { callKey, stopped: { result: leg, stoppedBy } }), callKey, true);
|
|
1863
|
+
trace(`APPENDED stopped (scope=${scope})`);
|
|
1864
|
+
return;
|
|
1865
|
+
}
|
|
1455
1866
|
if (serialized !== undefined && oversizeJournalResult(serialized)) {
|
|
1456
1867
|
const bytes = Buffer.byteLength(serialized, "utf8");
|
|
1457
1868
|
if (!finalized)
|
|
@@ -1478,6 +1889,24 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1478
1889
|
throw err;
|
|
1479
1890
|
}
|
|
1480
1891
|
};
|
|
1892
|
+
const journalStoppedAtEnd = (a, stoppedBy) => {
|
|
1893
|
+
if (journalSealed)
|
|
1894
|
+
return false;
|
|
1895
|
+
const leg = {
|
|
1896
|
+
taskId: a.callKey,
|
|
1897
|
+
sessionId: a.sessionId ?? "",
|
|
1898
|
+
terminal: { kind: "failed", message: `the call was stopped (by ${stoppedBy}) and the workflow run ended before its leg did; it is recorded as stopped` },
|
|
1899
|
+
result: "", resultEntryIds: [],
|
|
1900
|
+
continuesFrom: { none: "unsettled" },
|
|
1901
|
+
stats: { turns: 0, tokens: 0, costMicroUsd: 0, usageMissing: true },
|
|
1902
|
+
};
|
|
1903
|
+
void journalAppend(a.callKey, leg, a.label, stoppedBy).catch(() => undefined);
|
|
1904
|
+
return true;
|
|
1905
|
+
};
|
|
1906
|
+
const stoppedTerminalOf = (terminal, stoppedBy) => {
|
|
1907
|
+
const message = `the call was stopped (by ${stoppedBy}): a stop of this member alone`;
|
|
1908
|
+
return terminal.kind === "failed" ? { ...terminal, message } : { kind: "failed", message };
|
|
1909
|
+
};
|
|
1481
1910
|
const journalAppendParked = async (callKey, paused) => {
|
|
1482
1911
|
if (!journalStore)
|
|
1483
1912
|
return false;
|
|
@@ -1485,13 +1914,13 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1485
1914
|
return true;
|
|
1486
1915
|
};
|
|
1487
1916
|
const pausesCounted = new WeakSet();
|
|
1488
|
-
const parkAgentLeg = async (rec, paused, activityTail
|
|
1917
|
+
const parkAgentLeg = async (rec, paused, activityTail) => {
|
|
1489
1918
|
const s = paused.stats;
|
|
1490
1919
|
if (!pausesCounted.has(paused)) {
|
|
1491
1920
|
pausesCounted.add(paused);
|
|
1492
|
-
accumulateStats(paused
|
|
1921
|
+
accumulateStats(paused);
|
|
1493
1922
|
}
|
|
1494
|
-
rec
|
|
1923
|
+
settleRowOutcome(rec, { from: "result", result: paused });
|
|
1495
1924
|
rec.parkedCheckpointToken = paused.terminal.token;
|
|
1496
1925
|
rec.taskStatus = terminalProjection(paused.terminal).status;
|
|
1497
1926
|
foldAgentSession(rec, paused);
|
|
@@ -1541,6 +1970,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1541
1970
|
};
|
|
1542
1971
|
const reviveParkedRecord = (rec) => {
|
|
1543
1972
|
rec.status = "running";
|
|
1973
|
+
delete rec.outcome;
|
|
1544
1974
|
delete rec.parkedCheckpointToken;
|
|
1545
1975
|
delete rec.endedAt;
|
|
1546
1976
|
delete rec.taskStatus;
|
|
@@ -1556,7 +1986,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1556
1986
|
const rec = { label, callKey, ...(groupId !== undefined ? { groupId } : {}), phase, prompt, ...(model !== undefined ? { model } : {}), ...(d.kind === "repark" ? { replayed: true } : {}), status: "running", queuedAt: at, startedAt: at };
|
|
1557
1987
|
if (d.kind === "repark" && run.resume)
|
|
1558
1988
|
run.resume.replayed += 1;
|
|
1559
|
-
|
|
1989
|
+
admitRecord(rec);
|
|
1560
1990
|
if (phaseInstance)
|
|
1561
1991
|
agentPhaseOf.set(rec, phaseInstance);
|
|
1562
1992
|
emit({ type: "agent_start", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), callKey, prompt, ...(model !== undefined ? { model } : {}), ...(d.kind === "repark" ? { replayed: true } : {}), ts: at });
|
|
@@ -1567,9 +1997,8 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1567
1997
|
};
|
|
1568
1998
|
const settleParkedCall = async (rec, result, activityTail, agentOpts) => {
|
|
1569
1999
|
if (finalized)
|
|
1570
|
-
return result;
|
|
1571
|
-
await settleAgentResult(rec, result, activityTail, agentOpts);
|
|
1572
|
-
return result;
|
|
2000
|
+
return lateMember(rec, result, rec.replayed === true ? "replayed" : "live", { from: "result", result, schemaRequested: Boolean(agentOpts.schema), parked: false });
|
|
2001
|
+
return await settleAgentResult(rec, result, activityTail, agentOpts);
|
|
1573
2002
|
};
|
|
1574
2003
|
const createActivityCapture = (callKey, label, groupId, rec) => {
|
|
1575
2004
|
const tail = [];
|
|
@@ -1627,7 +2056,9 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1627
2056
|
const MAX_GROUP_DEPTH = 32;
|
|
1628
2057
|
let finalized = false;
|
|
1629
2058
|
const latchFinalized = () => {
|
|
2059
|
+
bookOwnSpend();
|
|
1630
2060
|
finalized = true;
|
|
2061
|
+
wfSpend.close();
|
|
1631
2062
|
if (inFlightLegs === 0)
|
|
1632
2063
|
retire();
|
|
1633
2064
|
};
|
|
@@ -1654,6 +2085,144 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1654
2085
|
return;
|
|
1655
2086
|
emitLogLine(message);
|
|
1656
2087
|
};
|
|
2088
|
+
const afterAnswer = [];
|
|
2089
|
+
const persistTerminal = async (ending) => {
|
|
2090
|
+
if (!store)
|
|
2091
|
+
return;
|
|
2092
|
+
const terminal = structuredClone(run);
|
|
2093
|
+
const first = await finalizeWithin(timers, persist("update", structuredClone(terminal)), { ok: false, cause: "timeout" }, true);
|
|
2094
|
+
if (first.ok)
|
|
2095
|
+
return;
|
|
2096
|
+
if (first.cause === "timeout")
|
|
2097
|
+
restartPersistTail();
|
|
2098
|
+
if (first.cause === "not_own" && first.mayAppear !== true) {
|
|
2099
|
+
emitLogLine(`record: this run's ${ending} record was not written — the run store holds no row of this run's own under its id (gone, or another run's), and none is written.`);
|
|
2100
|
+
afterAnswer.push(() => noOwnRow(ending));
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2103
|
+
terminalTries = { ending, terminal, state: "trying" };
|
|
2104
|
+
emitLogLine(first.cause === "timeout"
|
|
2105
|
+
? `record: this run's ${ending} record was not confirmed written (${terminalWriteCause(first)}) — the write is tried again after the run has answered.`
|
|
2106
|
+
: `record: this run's ${ending} record was not written (${terminalWriteCause(first)}) — its record reads running until a later write lands; the write is tried again after the run has answered.`);
|
|
2107
|
+
const tries = terminalTries;
|
|
2108
|
+
afterAnswer.push(() => continueTerminalWrite(tries, first, 0));
|
|
2109
|
+
};
|
|
2110
|
+
let terminalTries;
|
|
2111
|
+
let toldUnwritten = false;
|
|
2112
|
+
let catchingUp = false;
|
|
2113
|
+
const tellUnwritten = (message, detail) => {
|
|
2114
|
+
if (toldUnwritten || catchingUp)
|
|
2115
|
+
return;
|
|
2116
|
+
toldUnwritten = true;
|
|
2117
|
+
deliverEngineNotice(undefined, { code: "workflow.record_unwritten", message: `${message}${SETTLE_ROW_READ_FIRST}`, detail });
|
|
2118
|
+
};
|
|
2119
|
+
const createLandedLate = () => {
|
|
2120
|
+
const tries = terminalTries;
|
|
2121
|
+
if (tries === undefined)
|
|
2122
|
+
return;
|
|
2123
|
+
const unanswered = { ok: false, cause: "timeout" };
|
|
2124
|
+
catchingUp = true;
|
|
2125
|
+
void answeredWithin(() => persist("update", structuredClone(tries.terminal)), unanswered, unanswered)
|
|
2126
|
+
.then((out) => {
|
|
2127
|
+
catchingUp = false;
|
|
2128
|
+
if (out.ok)
|
|
2129
|
+
tries.state = "written";
|
|
2130
|
+
else if (out.cause === "timeout")
|
|
2131
|
+
restartPersistTail();
|
|
2132
|
+
if (tries.state !== "stopped" || out.ok)
|
|
2133
|
+
return;
|
|
2134
|
+
if (out.cause === "not_own")
|
|
2135
|
+
noOwnRow(tries.ending);
|
|
2136
|
+
else
|
|
2137
|
+
readBackAndTell(tries, out);
|
|
2138
|
+
})
|
|
2139
|
+
.catch(() => undefined);
|
|
2140
|
+
};
|
|
2141
|
+
const noOwnRow = (ending) => {
|
|
2142
|
+
const answer = createAnswer;
|
|
2143
|
+
if (answer === undefined || answer.ok)
|
|
2144
|
+
return;
|
|
2145
|
+
tellUnwritten(`workflow run "${runId}": its ${ending} record was not written — the run store did not confirm creating its row (${terminalWriteCause({ cause: "threw", err: answer.err })}) and holds no row of this run's own; the run has ended, and its row may still appear and read running.`, { runId, ending, cause: "create_unconfirmed", storeErrorClass: storeErrorClassOf(answer.err) });
|
|
2146
|
+
};
|
|
2147
|
+
const letGo = (h) => h?.unref?.();
|
|
2148
|
+
const answeredWithin = (ask, unanswered, threw) => new Promise((resolve) => {
|
|
2149
|
+
let bound;
|
|
2150
|
+
try {
|
|
2151
|
+
bound = timers.setTimeout(() => resolve(unanswered), WORKFLOW_STORE_WAIT_BOUND_MS);
|
|
2152
|
+
letGo(bound);
|
|
2153
|
+
}
|
|
2154
|
+
catch {
|
|
2155
|
+
}
|
|
2156
|
+
Promise.resolve()
|
|
2157
|
+
.then(ask)
|
|
2158
|
+
.then(resolve, () => resolve(threw))
|
|
2159
|
+
.then(() => {
|
|
2160
|
+
try {
|
|
2161
|
+
if (bound !== undefined)
|
|
2162
|
+
timers.clearTimeout(bound);
|
|
2163
|
+
}
|
|
2164
|
+
catch {
|
|
2165
|
+
}
|
|
2166
|
+
});
|
|
2167
|
+
});
|
|
2168
|
+
const continueTerminalWrite = (tries, last, tried) => {
|
|
2169
|
+
if (tries.state === "written")
|
|
2170
|
+
return;
|
|
2171
|
+
if (last.ok) {
|
|
2172
|
+
tries.state = "written";
|
|
2173
|
+
return;
|
|
2174
|
+
}
|
|
2175
|
+
if (last.cause === "not_own" && last.mayAppear !== true) {
|
|
2176
|
+
tries.state = "stopped";
|
|
2177
|
+
noOwnRow(tries.ending);
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
const delay = TERMINAL_WRITE_RETRY_DELAYS_MS[tried];
|
|
2181
|
+
if (delay !== undefined) {
|
|
2182
|
+
const unanswered = { ok: false, cause: "timeout" };
|
|
2183
|
+
const tryAgain = () => {
|
|
2184
|
+
if (tries.state === "written")
|
|
2185
|
+
return;
|
|
2186
|
+
void answeredWithin(() => persist("update", structuredClone(tries.terminal)), unanswered, unanswered)
|
|
2187
|
+
.then((next) => {
|
|
2188
|
+
if (!next.ok && next.cause === "timeout")
|
|
2189
|
+
restartPersistTail();
|
|
2190
|
+
continueTerminalWrite(tries, next, tried + 1);
|
|
2191
|
+
})
|
|
2192
|
+
.catch(() => undefined);
|
|
2193
|
+
};
|
|
2194
|
+
try {
|
|
2195
|
+
letGo(timers.setTimeout(tryAgain, delay));
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
catch {
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
tries.state = "stopped";
|
|
2202
|
+
readBackAndTell(tries, last);
|
|
2203
|
+
};
|
|
2204
|
+
const readBackAndTell = (tries, answered) => {
|
|
2205
|
+
if (answered.cause === "not_own" && answered.mayAppear !== true)
|
|
2206
|
+
return;
|
|
2207
|
+
const last = answered.cause !== "not_own" ? answered : createAnswer !== undefined && !createAnswer.ok ? { ok: false, cause: "threw", err: createAnswer.err } : { ok: false, cause: "timeout" };
|
|
2208
|
+
const cause = answered.cause === "not_own" ? "create_unconfirmed" : answered.cause;
|
|
2209
|
+
void answeredWithin(async () => {
|
|
2210
|
+
const row = await store?.get(runId);
|
|
2211
|
+
return ownRow(row) ? { read: true, own: true, running: row.status === "running" } : { read: true, own: false, running: false };
|
|
2212
|
+
}, { read: false }, { read: false })
|
|
2213
|
+
.then((back) => {
|
|
2214
|
+
if (tries.state === "written")
|
|
2215
|
+
return;
|
|
2216
|
+
if (back.read && !back.own)
|
|
2217
|
+
return noOwnRow(tries.ending);
|
|
2218
|
+
if (back.read && !back.running)
|
|
2219
|
+
return;
|
|
2220
|
+
tellUnwritten(back.read
|
|
2221
|
+
? `workflow run "${runId}": its ${tries.ending} record was not written (${terminalWriteCause(last)}) — the run has ended and its record still reads running.`
|
|
2222
|
+
: `workflow run "${runId}": its ${tries.ending} record was not confirmed written (${terminalWriteCause(last)}) — the run has ended and its record could not be read back.`, { runId, ending: tries.ending, cause, ...(last.cause === "threw" ? { storeErrorClass: storeErrorClassOf(last.err) } : {}) });
|
|
2223
|
+
})
|
|
2224
|
+
.catch(() => undefined);
|
|
2225
|
+
};
|
|
1657
2226
|
const yieldIntent = opts.preemptSignal;
|
|
1658
2227
|
const yieldLegs = new Set();
|
|
1659
2228
|
const onYieldIntent = () => {
|
|
@@ -1801,6 +2370,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1801
2370
|
if (effectiveSignal?.aborted)
|
|
1802
2371
|
throw new Error("workflow aborted");
|
|
1803
2372
|
if (maxAgents !== undefined && run.agents.length >= maxAgents) {
|
|
2373
|
+
run.refusedAtMemberCap = (run.refusedAtMemberCap ?? 0) + 1;
|
|
1804
2374
|
throw new WorkflowMaxAgentsError(maxAgents, budgetTotal, spent());
|
|
1805
2375
|
}
|
|
1806
2376
|
return effectiveSignal;
|
|
@@ -1812,7 +2382,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1812
2382
|
throw new TypeError(`agent({schema}) received an invalid JSON Schema: ${compiled.error}`);
|
|
1813
2383
|
}
|
|
1814
2384
|
assertSupportedAgentIsolation(agentOpts.isolation);
|
|
1815
|
-
const
|
|
2385
|
+
const statedLabel = agentOpts.label;
|
|
1816
2386
|
const phase = agentOpts.phase ?? currentPhase?.title;
|
|
1817
2387
|
const phaseInstance = resolveAgentPhase(agentOpts.phase);
|
|
1818
2388
|
const groupId = currentGroup;
|
|
@@ -1839,11 +2409,20 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1839
2409
|
...(inheritedPrincipal !== undefined ? { principal: inheritedPrincipal } : {}),
|
|
1840
2410
|
...(inheritedIsolationScope !== undefined ? { isolationScope: inheritedIsolationScope } : {}),
|
|
1841
2411
|
};
|
|
1842
|
-
const
|
|
2412
|
+
const specHash = workflowAgentSpecHash(specForIdentity, agentOpts);
|
|
1843
2413
|
const prompt = boundedRedactedSummary(spec.systemPrompt ? `${spec.systemPrompt}\n\n${spec.objective}` : spec.objective, MAX_TRANSCRIPT_CHARS);
|
|
1844
2414
|
const specForLabel = spec.model === undefined && typeDefModel !== undefined ? { ...spec, model: typeDefModel } : specForIdentity;
|
|
1845
2415
|
const model = workflowModelLabel(specForLabel, modelCatalog);
|
|
1846
|
-
|
|
2416
|
+
const scope = scopeHere();
|
|
2417
|
+
const inItem = scope?.item !== undefined;
|
|
2418
|
+
const event = { prefix: scope !== undefined ? `${scope.path}.` : "", n: (scope?.chain ?? rootChain).n++ };
|
|
2419
|
+
const position = `${event.prefix}c${event.n}`;
|
|
2420
|
+
const { ordinal, adopted } = ordinalFor(position, inItem, specHash);
|
|
2421
|
+
reachedPositions.add(position);
|
|
2422
|
+
const label = statedLabel ?? `agent-${ordinal + 1}`;
|
|
2423
|
+
const callKey = callKeyOf(ordinal, specHash, priorRecordUnpositioned ? undefined : position);
|
|
2424
|
+
const place = { ordinal, position, event, adopted, inItem, besidePipeline: (priorRecordUnpositioned ? !inItem : scope === undefined) && pipelinesRunning > 0 };
|
|
2425
|
+
return { label, phase, phaseInstance, groupId, inheritedModelSnap, inheritedModelRef: inheritedModelPick?.modelRef, inheritedModelError, inheritedThinkingSnap, callKey, place, prompt, model };
|
|
1847
2426
|
};
|
|
1848
2427
|
const reviewSpawnBeforeLaunch = async (lane, label, callKey, runSpec, effectiveSignal, agentType, driven) => {
|
|
1849
2428
|
if (opts.agentStations?.listens("agent.spawn") === true && !driven) {
|
|
@@ -1926,8 +2505,10 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1926
2505
|
},
|
|
1927
2506
|
askMessage: `Reviewing a workflow-spawned sub-agent ("${labelForReview}", ${lane}) about to be started. ` +
|
|
1928
2507
|
`Objective: ${objective}\nTools available to it: ${toolsNote}${remoteNote}${imagesNote}`,
|
|
2508
|
+
spendSeat: wfSpend,
|
|
1929
2509
|
}, effectiveSignal)
|
|
1930
2510
|
.catch(() => ({ kind: "unavailable", cause: "error" }));
|
|
2511
|
+
bookOwnSpend();
|
|
1931
2512
|
if (effectiveSignal?.aborted)
|
|
1932
2513
|
throw new Error("workflow aborted");
|
|
1933
2514
|
if (finalized)
|
|
@@ -1969,16 +2550,26 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1969
2550
|
};
|
|
1970
2551
|
return { onTurnEndUsage, rollbackUsageBeat, observedTokens: () => beatTokens };
|
|
1971
2552
|
};
|
|
1972
|
-
const settleAgentResult = async (rec, result, activityTail, agentOpts) => {
|
|
2553
|
+
const settleAgentResult = async (rec, result, activityTail, agentOpts, counted = false) => {
|
|
1973
2554
|
const s = result.stats;
|
|
1974
|
-
|
|
1975
|
-
|
|
2555
|
+
if (!counted)
|
|
2556
|
+
accumulateStats(result);
|
|
2557
|
+
const stopper = result.terminal.kind === "failed" ? stopperOf(rec.callKey) : undefined;
|
|
2558
|
+
const outcome = settleRowOutcome(rec, { from: "result", result, schemaRequested: Boolean(agentOpts.schema), parked: false, ...(stopper !== undefined ? { settled: { status: "killed", stoppedBy: stopper } } : {}) });
|
|
2559
|
+
const ownStop = ownStopOf(rec.callKey, outcome);
|
|
2560
|
+
if (ownStop !== undefined)
|
|
2561
|
+
result = { ...result, terminal: stoppedTerminalOf(result.terminal, ownStop) };
|
|
1976
2562
|
rec.taskStatus = terminalProjection(result.terminal).status;
|
|
1977
2563
|
foldAgentSession(rec, result);
|
|
1978
2564
|
setLegRunId(rec, result);
|
|
1979
2565
|
rec.endedAt = now();
|
|
1980
2566
|
rec.stats = { tokens: s.tokens ?? 0, turns: s.turns ?? 0, costMicroUsd: s.costMicroUsd };
|
|
1981
2567
|
const output = settleAgentError(rec, result.terminal, rec.label, boundedRedactedSummary(result.structuredOutput ?? result.result, MAX_TRANSCRIPT_CHARS));
|
|
2568
|
+
const schemaUnmet = outcome.outcome === "schema_unmet" ? new WorkflowAgentSchemaError(rec.label, result, outcome) : undefined;
|
|
2569
|
+
if (schemaUnmet !== undefined) {
|
|
2570
|
+
rec.errorCode = schemaUnmet.code;
|
|
2571
|
+
rec.errorMessage = boundedRedactedSummary(schemaUnmet.message, MAX_TRANSCRIPT_CHARS);
|
|
2572
|
+
}
|
|
1982
2573
|
if (result.stats.toolCalls !== undefined)
|
|
1983
2574
|
rec.toolCalls = result.stats.toolCalls;
|
|
1984
2575
|
if (activityTail.length > 0)
|
|
@@ -1987,13 +2578,15 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1987
2578
|
emit({ type: "agent_end", runId, label: rec.label, phase: rec.phase, ...(rec.groupId !== undefined ? { groupId: rec.groupId } : {}), status: rec.status, output, ...(rec.errorCode !== undefined ? { errorCode: rec.errorCode } : {}), ...(result.stats.toolCalls !== undefined ? { toolCalls: result.stats.toolCalls } : {}), ...(result.model !== undefined ? { modelResolved: result.model } : {}), ts: rec.endedAt });
|
|
1988
2579
|
void persist("update");
|
|
1989
2580
|
bceTerminal(rec.callKey, rec.status === "completed" ? "completed" : "failed", output, rec.stats);
|
|
1990
|
-
await journalAppend(rec.callKey, result, rec.label);
|
|
1991
|
-
if (
|
|
1992
|
-
throw
|
|
1993
|
-
|
|
1994
|
-
};
|
|
1995
|
-
const resumeArmOf = (callKey) => {
|
|
1996
|
-
const ordinal =
|
|
2581
|
+
await journalAppend(rec.callKey, result, rec.label, ownStop);
|
|
2582
|
+
if (schemaUnmet !== undefined)
|
|
2583
|
+
throw schemaUnmet;
|
|
2584
|
+
return withMember(result, outcome);
|
|
2585
|
+
};
|
|
2586
|
+
const resumeArmOf = (callKey, place) => {
|
|
2587
|
+
const ordinal = place.ordinal;
|
|
2588
|
+
const newPosition = place.inItem && !place.adopted;
|
|
2589
|
+
notMadeAt("call", place.event);
|
|
1997
2590
|
let drive;
|
|
1998
2591
|
const truth = opts.resumeFromRunId !== undefined ? parkedByOrdinal[ordinal] : undefined;
|
|
1999
2592
|
if (truth !== undefined) {
|
|
@@ -2011,8 +2604,33 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2011
2604
|
}
|
|
2012
2605
|
if (parkedLeg !== undefined && drive === undefined)
|
|
2013
2606
|
throw parkedError();
|
|
2014
|
-
if (drive !== undefined || opts.resumeFromRunId === undefined
|
|
2607
|
+
if (drive !== undefined || opts.resumeFromRunId === undefined)
|
|
2015
2608
|
return { kind: "live", drive };
|
|
2609
|
+
const stoppedEntry = replayByOrdinal[ordinal];
|
|
2610
|
+
if (stoppedEntry?.callKey === callKey && stoppedEntry.stopped !== undefined)
|
|
2611
|
+
return { kind: "replay", result: stoppedEntry.stopped.result, stoppedBy: stoppedEntry.stopped.stoppedBy };
|
|
2612
|
+
const runAgain = () => {
|
|
2613
|
+
const prior = replayByOrdinal[ordinal];
|
|
2614
|
+
if (prior?.callKey === callKey && prior.result !== undefined && TERMINAL_CAUSE_IS_REPLAYABLE[prior.result.terminal.kind])
|
|
2615
|
+
completedRunsAgain.add(callKey);
|
|
2616
|
+
return { kind: "live", drive: undefined };
|
|
2617
|
+
};
|
|
2618
|
+
if (divergence !== undefined)
|
|
2619
|
+
return runAgain();
|
|
2620
|
+
if (newPosition) {
|
|
2621
|
+
noteDivergence(ordinal, priorRecordUnpositioned
|
|
2622
|
+
? "a pipeline call the resumed run's record holds no call for — the record was written before pipeline calls had positions, and no call in it has this call's spec"
|
|
2623
|
+
: `a call at a pipeline position the resumed run never recorded (${place.position}) — an item, a stage or a call it did not reach, or one the script added`);
|
|
2624
|
+
return runAgain();
|
|
2625
|
+
}
|
|
2626
|
+
if (place.besidePipeline) {
|
|
2627
|
+
noteDivergence(ordinal, "a call outside the pipeline made while a pipeline of this run was running (written beside it, or the script runner did not carry the engine's context into the call) — its ordinal depends on how far the pipeline had got");
|
|
2628
|
+
return runAgain();
|
|
2629
|
+
}
|
|
2630
|
+
if (place.inItem && priorRecordUnpositioned) {
|
|
2631
|
+
noteDivergence(ordinal, "a pipeline call while the resumed run's record was written before pipeline calls had positions — its pipeline calls run live, as they did then (each on the ordinal of the recorded call with its spec, so a parked one is driven where it was)");
|
|
2632
|
+
return runAgain();
|
|
2633
|
+
}
|
|
2016
2634
|
const cached = replayByOrdinal[ordinal];
|
|
2017
2635
|
if (cached && cached.callKey === callKey && cached.result !== undefined && TERMINAL_CAUSE_IS_REPLAYABLE[cached.result.terminal.kind]) {
|
|
2018
2636
|
return { kind: "replay", result: cached.result };
|
|
@@ -2030,10 +2648,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2030
2648
|
: `the journaled result was ${cached.result?.terminal?.kind ?? "(no terminal record)"}, not completed`);
|
|
2031
2649
|
return { kind: "live", drive: undefined };
|
|
2032
2650
|
};
|
|
2033
|
-
const replayAgent = async (call, r, agentOpts) => {
|
|
2651
|
+
const replayAgent = async (call, r, agentOpts, stoppedBy) => {
|
|
2034
2652
|
const { label, callKey, groupId, phase, phaseInstance, prompt } = call;
|
|
2653
|
+
const replayFacts = { from: "result", result: r, schemaRequested: Boolean(agentOpts.schema), parked: false, ...(stoppedBy !== undefined ? { settled: { status: "killed", stoppedBy } } : {}) };
|
|
2035
2654
|
if (finalized)
|
|
2036
|
-
return r;
|
|
2655
|
+
return lateMember(undefined, r, "replayed", replayFacts);
|
|
2037
2656
|
const rs = r.stats;
|
|
2038
2657
|
const cachedOutput = boundedRedactedSummary(r.structuredOutput ?? r.result, MAX_TRANSCRIPT_CHARS);
|
|
2039
2658
|
const at = now();
|
|
@@ -2046,7 +2665,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2046
2665
|
prompt,
|
|
2047
2666
|
...(replayModel !== undefined ? { model: replayModel } : {}),
|
|
2048
2667
|
replayed: true,
|
|
2049
|
-
status:
|
|
2668
|
+
status: "running",
|
|
2050
2669
|
taskStatus: terminalProjection(r.terminal).status,
|
|
2051
2670
|
...(r.sessionId ? { sessionId: r.sessionId } : {}),
|
|
2052
2671
|
...(r.runId ? { taskRunId: r.runId } : {}),
|
|
@@ -2059,21 +2678,26 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2059
2678
|
};
|
|
2060
2679
|
if (run.resume)
|
|
2061
2680
|
run.resume.replayed += 1;
|
|
2062
|
-
|
|
2681
|
+
const replayOutcome = settleRowOutcome(replayRec, replayFacts);
|
|
2682
|
+
const schemaUnmet = replayOutcome.outcome === "schema_unmet" ? new WorkflowAgentSchemaError(label, r, replayOutcome) : undefined;
|
|
2683
|
+
if (schemaUnmet !== undefined) {
|
|
2684
|
+
replayRec.errorCode = schemaUnmet.code;
|
|
2685
|
+
replayRec.errorMessage = boundedRedactedSummary(schemaUnmet.message, MAX_TRANSCRIPT_CHARS);
|
|
2686
|
+
}
|
|
2687
|
+
admitRecord(replayRec);
|
|
2063
2688
|
if (phaseInstance)
|
|
2064
2689
|
agentPhaseOf.set(replayRec, phaseInstance);
|
|
2065
2690
|
emit({ type: "agent_start", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), callKey, prompt, ...(replayModel !== undefined ? { model: replayModel } : {}), replayed: true, ts: at });
|
|
2066
|
-
emit({ type: "agent_end", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), status: replayRec.status, output: cachedOutput, ...(rs.toolCalls !== undefined ? { toolCalls: rs.toolCalls } : {}), replayed: true, ts: at });
|
|
2691
|
+
emit({ type: "agent_end", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), status: replayRec.status, output: cachedOutput, ...(replayRec.errorCode !== undefined ? { errorCode: replayRec.errorCode } : {}), ...(rs.toolCalls !== undefined ? { toolCalls: rs.toolCalls } : {}), replayed: true, ts: at });
|
|
2067
2692
|
bceSpawn(callKey, label, agentOpts.agentType, true, r.sessionId || undefined, replayModel);
|
|
2068
2693
|
foldAgentSession(replayRec, r);
|
|
2069
2694
|
bceTerminal(callKey, replayRec.status === "completed" ? "completed" : "failed", cachedOutput, replayRec.stats);
|
|
2070
|
-
accumulateStats(r
|
|
2695
|
+
accumulateStats(r);
|
|
2071
2696
|
void persist("update");
|
|
2072
|
-
await journalAppend(callKey, r);
|
|
2073
|
-
if (
|
|
2074
|
-
throw
|
|
2075
|
-
|
|
2076
|
-
return r;
|
|
2697
|
+
await journalAppend(callKey, r, undefined, stoppedBy);
|
|
2698
|
+
if (schemaUnmet !== undefined)
|
|
2699
|
+
throw schemaUnmet;
|
|
2700
|
+
return withMember(r, replayOutcome);
|
|
2077
2701
|
};
|
|
2078
2702
|
const settledHandle = (label, callKey, settled) => {
|
|
2079
2703
|
settled.catch(() => undefined);
|
|
@@ -2085,6 +2709,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2085
2709
|
throw steeringError(`the task has already finished — workflow agent "${label}" was settled on this resume without running`);
|
|
2086
2710
|
},
|
|
2087
2711
|
result: () => settled,
|
|
2712
|
+
stop: () => stopMember(callKey, "parent"),
|
|
2088
2713
|
};
|
|
2089
2714
|
};
|
|
2090
2715
|
const ctx = {
|
|
@@ -2095,26 +2720,24 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2095
2720
|
emitRunLog(message);
|
|
2096
2721
|
},
|
|
2097
2722
|
async agent(spec, agentOpts = {}) {
|
|
2098
|
-
const
|
|
2099
|
-
const { label, phase, phaseInstance, groupId, inheritedModelSnap, inheritedModelRef, inheritedModelError, inheritedThinkingSnap, callKey, prompt, model } = prepareAgentCall(spec, agentOpts);
|
|
2723
|
+
const spawnSignal = assertAgentSpawnAllowed("ctx.agent", spec, agentOpts);
|
|
2724
|
+
const { label, phase, phaseInstance, groupId, inheritedModelSnap, inheritedModelRef, inheritedModelError, inheritedThinkingSnap, callKey, place, prompt, model } = prepareAgentCall(spec, agentOpts);
|
|
2725
|
+
const effectiveSignal = memberSignalOf(callKey, spawnSignal);
|
|
2100
2726
|
const call = { label, callKey, groupId, phase, phaseInstance, prompt };
|
|
2101
|
-
const arm = resumeArmOf(callKey);
|
|
2727
|
+
const arm = resumeArmOf(callKey, place);
|
|
2102
2728
|
const disposition = arm.kind === "dispose" ? arm.d : undefined;
|
|
2103
2729
|
if (disposition?.kind === "settle")
|
|
2104
2730
|
return await settleParkedCall(openDispositionRecord(disposition, call, agentOpts), disposition.result, [], agentOpts);
|
|
2105
2731
|
if (arm.kind === "replay")
|
|
2106
|
-
return await replayAgent(call, arm.result, agentOpts);
|
|
2732
|
+
return await replayAgent(call, arm.result, agentOpts, arm.stoppedBy);
|
|
2107
2733
|
let nextDrive = arm.kind === "live" ? arm.drive : undefined;
|
|
2108
2734
|
let rec;
|
|
2109
2735
|
if (disposition !== undefined) {
|
|
2110
2736
|
rec = openDispositionRecord(disposition, call, agentOpts);
|
|
2111
2737
|
}
|
|
2112
2738
|
else {
|
|
2113
|
-
if (budgetTotal !== null && spent() >= budgetTotal) {
|
|
2114
|
-
throw new WorkflowBudgetExceededError(spent(), budgetTotal);
|
|
2115
|
-
}
|
|
2116
2739
|
rec = { label, callKey, ...(groupId !== undefined ? { groupId } : {}), phase, prompt, ...(model !== undefined ? { model } : {}), status: "running", queuedAt: now() };
|
|
2117
|
-
|
|
2740
|
+
admitRecord(rec);
|
|
2118
2741
|
if (phaseInstance)
|
|
2119
2742
|
agentPhaseOf.set(rec, phaseInstance);
|
|
2120
2743
|
emit({ type: "agent_start", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), callKey, prompt, ...(model !== undefined ? { model } : {}), queuedAt: rec.queuedAt, ts: rec.queuedAt });
|
|
@@ -2122,7 +2745,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2122
2745
|
}
|
|
2123
2746
|
const { tail: activityTail, onActivity } = createActivityCapture(callKey, label, groupId, rec);
|
|
2124
2747
|
if (disposition !== undefined) {
|
|
2125
|
-
const answer = await parkAgentLeg(rec, disposition.paused, []
|
|
2748
|
+
const answer = await parkAgentLeg(rec, disposition.paused, []);
|
|
2126
2749
|
if (answer.kind === "settle")
|
|
2127
2750
|
return await settleParkedCall(rec, answer.result, activityTail, agentOpts);
|
|
2128
2751
|
nextDrive = answer.drive;
|
|
@@ -2132,6 +2755,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2132
2755
|
legStart();
|
|
2133
2756
|
const release = await sem.acquire();
|
|
2134
2757
|
let result;
|
|
2758
|
+
let keptFirstAnswer = false;
|
|
2135
2759
|
try {
|
|
2136
2760
|
adviseIsolationIfConcurrent(agentOpts);
|
|
2137
2761
|
if (effectiveSignal?.aborted)
|
|
@@ -2140,9 +2764,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2140
2764
|
throw new Error("workflow run already finalized — ctx.agent cannot spawn after the run ended");
|
|
2141
2765
|
if (parkedLeg !== undefined && drive === undefined)
|
|
2142
2766
|
throw parkedError();
|
|
2143
|
-
|
|
2144
|
-
throw new WorkflowBudgetExceededError(spent(), budgetTotal);
|
|
2145
|
-
}
|
|
2767
|
+
budgetGate();
|
|
2146
2768
|
rec.startedAt = now();
|
|
2147
2769
|
const bornChildSessionId = drive !== undefined ? drive.sessionId : resolveChildSessionIdAtSpawn(spec);
|
|
2148
2770
|
bceSpawn(callKey, label, agentOpts.agentType, false, bornChildSessionId, model);
|
|
@@ -2168,9 +2790,10 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2168
2790
|
opts.onForwardEvent(e.type === "task_progress" || e.type === "task_started" ? memberStamp(e, callKey, label) : e);
|
|
2169
2791
|
}
|
|
2170
2792
|
: undefined;
|
|
2171
|
-
const baseInternals = { ...(agentOpts.isolation ? { isolation: agentOpts.isolation } : {}), ...(opts.parentCwd !== undefined ? { parentCwd: opts.parentCwd } : {}), ...callerPlacementSeats(opts.parentCwd, opts.callerRoot), ...spawnAttribution, ...definitionSeats(typed), ...(await captureFloorSeatsNow()), ...(enrichedForward !== undefined ? { onForwardEvent: enrichedForward } : {}), delegationTaskType: "workflow", agentName: label, ...memberSeat(callKey, label), onWorkspaceResolved: createWorkspaceObserver(rec) };
|
|
2793
|
+
const baseInternals = { ...parkGapInherit(seatedSpec), ...(agentOpts.isolation ? { isolation: agentOpts.isolation } : {}), ...(opts.parentCwd !== undefined ? { parentCwd: opts.parentCwd } : {}), ...callerPlacementSeats(opts.parentCwd, opts.callerRoot), ...spawnAttribution, ...definitionSeats(typed), ...(await captureFloorSeatsNow()), ...(enrichedForward !== undefined ? { onForwardEvent: enrichedForward } : {}), delegationTaskType: "workflow", spendParent: memberSpendParent, agentName: label, ...memberSeat(callKey, label), onWorkspaceResolved: createWorkspaceObserver(rec) };
|
|
2172
2794
|
let attempts = 0;
|
|
2173
2795
|
let throttleRetried = false;
|
|
2796
|
+
let throttleFirst;
|
|
2174
2797
|
let lastAttemptReason;
|
|
2175
2798
|
let approvalWaivedAttempts = 0;
|
|
2176
2799
|
for (;;) {
|
|
@@ -2197,17 +2820,19 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2197
2820
|
}
|
|
2198
2821
|
};
|
|
2199
2822
|
const onCallerAbort = () => attemptCtl.abort(new Error("workflow aborted"));
|
|
2200
|
-
if (effectiveSignal?.aborted === true)
|
|
2823
|
+
if (effectiveSignal?.aborted === true || membersStop.signal.aborted)
|
|
2201
2824
|
onCallerAbort();
|
|
2202
|
-
else
|
|
2825
|
+
else {
|
|
2203
2826
|
effectiveSignal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
2827
|
+
membersStop.signal.addEventListener("abort", onCallerAbort, { once: true });
|
|
2828
|
+
}
|
|
2204
2829
|
armWatchdog();
|
|
2205
2830
|
const attemptSessionId = drive !== undefined ? drive.sessionId : attempts === 1 ? bornChildSessionId : resolveChildSessionIdAtSpawn(runSpec);
|
|
2206
2831
|
const attemptYield = legYieldSeats();
|
|
2207
2832
|
const attemptSpec = { ...runSpec, ...(attemptSessionId !== undefined ? { sessionId: attemptSessionId } : {}), signal: attemptCtl.signal, ...attemptYield?.spec };
|
|
2208
2833
|
if (attemptSessionId !== undefined && !finalized) {
|
|
2209
2834
|
bceBindSession(callKey, attemptSessionId);
|
|
2210
|
-
if (drive !== undefined || judgedOwnerSeat(
|
|
2835
|
+
if (drive !== undefined || judgedOwnerSeat(opts) === undefined)
|
|
2211
2836
|
verifyAgentSession(rec, attemptSessionId);
|
|
2212
2837
|
else
|
|
2213
2838
|
delete rec.sessionId;
|
|
@@ -2291,12 +2916,20 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2291
2916
|
const attemptHadSpend = rollbackUsageBeat();
|
|
2292
2917
|
activeUsageBeats.delete(activeBeat);
|
|
2293
2918
|
if (attemptError !== undefined && attemptHadSpend && !finalized && rec.stats !== undefined) {
|
|
2294
|
-
accumulateStats({ stats: rec.stats }
|
|
2919
|
+
accumulateStats({ stats: rec.stats });
|
|
2295
2920
|
}
|
|
2296
2921
|
disarmWatchdog();
|
|
2297
2922
|
effectiveSignal?.removeEventListener("abort", onCallerAbort);
|
|
2923
|
+
membersStop.signal.removeEventListener("abort", onCallerAbort);
|
|
2298
2924
|
}
|
|
2299
|
-
if (effectiveSignal?.aborted) {
|
|
2925
|
+
if (effectiveSignal?.aborted || membersStop.signal.aborted) {
|
|
2926
|
+
if (throttleFirst !== undefined && attemptResult?.terminal.kind !== "completed") {
|
|
2927
|
+
if (attemptResult !== undefined && !finalized)
|
|
2928
|
+
accumulateStats(attemptResult);
|
|
2929
|
+
result = throttleFirst;
|
|
2930
|
+
keptFirstAnswer = true;
|
|
2931
|
+
break;
|
|
2932
|
+
}
|
|
2300
2933
|
if (attemptError !== undefined)
|
|
2301
2934
|
throw attemptError;
|
|
2302
2935
|
if (attemptResult !== undefined) {
|
|
@@ -2307,7 +2940,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2307
2940
|
}
|
|
2308
2941
|
if (drive === undefined && stallFired && attemptResult?.terminal.kind !== "completed") {
|
|
2309
2942
|
if (attemptResult !== undefined && !finalized)
|
|
2310
|
-
accumulateStats(attemptResult
|
|
2943
|
+
accumulateStats(attemptResult);
|
|
2311
2944
|
if (attemptResult !== undefined && !finalized)
|
|
2312
2945
|
setLegRunId(rec, attemptResult);
|
|
2313
2946
|
const reported = attemptResult !== undefined && !finalized ? foldLegApprovalReport(rec, attemptResult) : undefined;
|
|
@@ -2328,6 +2961,13 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2328
2961
|
if (attemptError !== undefined)
|
|
2329
2962
|
throw attemptError;
|
|
2330
2963
|
result = attemptResult;
|
|
2964
|
+
if (throttleFirst !== undefined && result.terminal.kind === "failed" && SPEND_STOP_CODES.has(result.terminal.code ?? "")) {
|
|
2965
|
+
if (!finalized)
|
|
2966
|
+
accumulateStats(result);
|
|
2967
|
+
result = throttleFirst;
|
|
2968
|
+
keptFirstAnswer = true;
|
|
2969
|
+
break;
|
|
2970
|
+
}
|
|
2331
2971
|
const durationMs = now() - attemptStart;
|
|
2332
2972
|
const degraded = result.terminal.kind === "completed" &&
|
|
2333
2973
|
result.structuredOutput === undefined &&
|
|
@@ -2338,24 +2978,31 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2338
2978
|
throttleRetried = true;
|
|
2339
2979
|
lastAttemptReason = "throttled";
|
|
2340
2980
|
emitRunLog(`[${label}] throttled response (${(result.result ?? "").trim().length} chars in ${Math.round(durationMs / 1000)}s) — sleeping ${Math.round(throttleBackoffMs / 1000)}s before retry`);
|
|
2981
|
+
throttleFirst = result;
|
|
2341
2982
|
if (!finalized) {
|
|
2342
2983
|
setLegRunId(rec, result);
|
|
2343
|
-
accumulateStats(result
|
|
2984
|
+
accumulateStats(result);
|
|
2344
2985
|
void persist("update");
|
|
2345
2986
|
}
|
|
2346
2987
|
await new Promise((resolve) => {
|
|
2347
2988
|
const onAbort = () => {
|
|
2348
2989
|
timers.clearTimeout(t);
|
|
2990
|
+
effectiveSignal?.removeEventListener("abort", onAbort);
|
|
2991
|
+
membersStop.signal.removeEventListener("abort", onAbort);
|
|
2349
2992
|
resolve();
|
|
2350
2993
|
};
|
|
2351
2994
|
const t = timers.setTimeout(() => {
|
|
2352
2995
|
effectiveSignal?.removeEventListener("abort", onAbort);
|
|
2996
|
+
membersStop.signal.removeEventListener("abort", onAbort);
|
|
2353
2997
|
resolve();
|
|
2354
2998
|
}, throttleBackoffMs);
|
|
2355
2999
|
effectiveSignal?.addEventListener("abort", onAbort, { once: true });
|
|
3000
|
+
membersStop.signal.addEventListener("abort", onAbort, { once: true });
|
|
2356
3001
|
});
|
|
2357
|
-
if (effectiveSignal?.aborted)
|
|
2358
|
-
|
|
3002
|
+
if (effectiveSignal?.aborted || membersStop.signal.aborted) {
|
|
3003
|
+
keptFirstAnswer = true;
|
|
3004
|
+
break;
|
|
3005
|
+
}
|
|
2359
3006
|
continue;
|
|
2360
3007
|
}
|
|
2361
3008
|
if (degraded && throttleRetried) {
|
|
@@ -2377,14 +3024,13 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2377
3024
|
const unresumable = unresumableRowResult(drive, rec.callKey, err);
|
|
2378
3025
|
if (unresumable !== undefined)
|
|
2379
3026
|
return await settleParkedCall(rec, unresumable, activityTail, agentOpts);
|
|
2380
|
-
const answer = await parkAgentLeg(rec, drive.paused, activityTail
|
|
3027
|
+
const answer = await parkAgentLeg(rec, drive.paused, activityTail);
|
|
2381
3028
|
if (answer.kind === "settle")
|
|
2382
3029
|
return await settleParkedCall(rec, answer.result, activityTail, agentOpts);
|
|
2383
3030
|
nextDrive = answer.drive;
|
|
2384
3031
|
continue;
|
|
2385
3032
|
}
|
|
2386
3033
|
if (!finalized) {
|
|
2387
|
-
rec.status = "failed";
|
|
2388
3034
|
rec.endedAt = now();
|
|
2389
3035
|
const salvaged = thrownIs(err, WorkflowAgentStalledError) ? err.lastResult : undefined;
|
|
2390
3036
|
if (salvaged?.runId === undefined)
|
|
@@ -2416,10 +3062,22 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2416
3062
|
rec.attempts = err.attempts;
|
|
2417
3063
|
rec.lastAttemptReason = "stalled";
|
|
2418
3064
|
}
|
|
3065
|
+
const stopper = thrownIs(err, WorkflowBudgetExceededError) ? undefined : stopperOf(callKey);
|
|
3066
|
+
const thrownOutcome = settleRowOutcome(rec, thrownIs(err, WorkflowBudgetExceededError)
|
|
3067
|
+
? { from: "refused", budget: true }
|
|
3068
|
+
: (() => {
|
|
3069
|
+
const refused = salvaged !== undefined ? memberRefusalsOf(salvaged) : undefined;
|
|
3070
|
+
if (stopper !== undefined)
|
|
3071
|
+
return { from: "ended", status: "killed", stoppedBy: stopper, ...(refused !== undefined ? { refused } : {}) };
|
|
3072
|
+
const code = rec.errorCode ?? codeOf(err);
|
|
3073
|
+
return { from: "ended", status: "failed", ...(code !== undefined ? { code } : {}), ...(refused !== undefined ? { refused } : {}) };
|
|
3074
|
+
})());
|
|
3075
|
+
if (thrownIs(err, WorkflowBudgetExceededError))
|
|
3076
|
+
err.member = thrownOutcome;
|
|
2419
3077
|
emit({ type: "agent_end", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), status: "failed", ...(rec.output !== undefined ? { output: rec.output } : {}), ...(rec.errorCode !== undefined ? { errorCode: rec.errorCode } : {}), ts: rec.endedAt });
|
|
2420
3078
|
void persist("update");
|
|
2421
3079
|
release();
|
|
2422
|
-
const
|
|
3080
|
+
const thrownLeg = salvaged ?? {
|
|
2423
3081
|
taskId: callKey,
|
|
2424
3082
|
sessionId: "",
|
|
2425
3083
|
result: boundedRedactedSummary(thrownText(err), 500), resultEntryIds: [],
|
|
@@ -2430,10 +3088,15 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2430
3088
|
message: boundedRedactedSummary(thrownText(err), 500),
|
|
2431
3089
|
},
|
|
2432
3090
|
stats: { turns: 0, tokens: 0, costMicroUsd: 0, usageMissing: true },
|
|
2433
|
-
}
|
|
3091
|
+
};
|
|
3092
|
+
const ownStop = ownStopOf(callKey, thrownOutcome);
|
|
3093
|
+
const stoppedLeg = ownStop !== undefined ? { ...thrownLeg, terminal: stoppedTerminalOf(thrownLeg.terminal, ownStop) } : thrownLeg;
|
|
3094
|
+
const journaled = journalAppend(callKey, stoppedLeg, label, ownStop).catch(() => undefined);
|
|
2434
3095
|
if (!((thrownIs(err, WorkflowBudgetExceededError) || thrownIs(err, WorkflowAgentParkedError)) && rec.startedAt === undefined))
|
|
2435
3096
|
await journaled;
|
|
2436
3097
|
bceTerminal(callKey, "failed", rec.output ?? (thrownText(err)), rec.stats);
|
|
3098
|
+
if (ownStop !== undefined)
|
|
3099
|
+
return withMember(stoppedLeg, thrownOutcome);
|
|
2437
3100
|
}
|
|
2438
3101
|
throw err;
|
|
2439
3102
|
}
|
|
@@ -2442,52 +3105,49 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2442
3105
|
legEnd();
|
|
2443
3106
|
}
|
|
2444
3107
|
if (finalized)
|
|
2445
|
-
return result;
|
|
3108
|
+
return lateMember(rec, result, "live", { from: "result", result, schemaRequested: Boolean(agentOpts.schema) });
|
|
2446
3109
|
const unstartedDrive = drive !== undefined && resumeNeverStarted(result) ? drive : undefined;
|
|
2447
3110
|
if (unstartedDrive !== undefined)
|
|
2448
3111
|
emitRunLog(`[park] the parked leg "${label}" was driven but the approved action never started (${result.terminal.kind === "failed" ? result.terminal.code : ""}); the park stands.`);
|
|
2449
3112
|
if (drive !== undefined)
|
|
2450
3113
|
noteDecision(drive, rec.callKey, unstartedDrive !== undefined ? "refused" : "driven", unstartedDrive !== undefined && result.terminal.kind === "failed" ? result.terminal.code : undefined);
|
|
2451
|
-
const parkOn = isPausedResult(result) ?
|
|
3114
|
+
const parkOn = isPausedResult(result) ? result : unstartedDrive?.paused;
|
|
2452
3115
|
if (parkOn !== undefined) {
|
|
2453
|
-
const answer = await parkAgentLeg(rec, parkOn
|
|
3116
|
+
const answer = await parkAgentLeg(rec, parkOn, activityTail);
|
|
2454
3117
|
if (answer.kind === "settle")
|
|
2455
3118
|
return await settleParkedCall(rec, answer.result, activityTail, agentOpts);
|
|
2456
3119
|
nextDrive = answer.drive;
|
|
2457
3120
|
continue;
|
|
2458
3121
|
}
|
|
2459
|
-
await settleAgentResult(rec, result, activityTail, agentOpts);
|
|
2460
|
-
return result;
|
|
3122
|
+
return await settleAgentResult(rec, result, activityTail, agentOpts, keptFirstAnswer);
|
|
2461
3123
|
}
|
|
2462
3124
|
},
|
|
2463
3125
|
async agentStream(spec, agentOpts = {}) {
|
|
2464
|
-
const
|
|
2465
|
-
const { label, phase, phaseInstance, groupId, inheritedModelSnap, inheritedModelRef, inheritedModelError, inheritedThinkingSnap, callKey, prompt, model } = prepareAgentCall(spec, agentOpts);
|
|
3126
|
+
const spawnSignal = assertAgentSpawnAllowed("ctx.agentStream", spec, agentOpts);
|
|
3127
|
+
const { label, phase, phaseInstance, groupId, inheritedModelSnap, inheritedModelRef, inheritedModelError, inheritedThinkingSnap, callKey, place, prompt, model } = prepareAgentCall(spec, agentOpts);
|
|
3128
|
+
const effectiveSignal = memberSignalOf(callKey, spawnSignal);
|
|
2466
3129
|
const call = { label, callKey, groupId, phase, phaseInstance, prompt };
|
|
2467
|
-
const arm = resumeArmOf(callKey);
|
|
3130
|
+
const arm = resumeArmOf(callKey, place);
|
|
2468
3131
|
const disposition = arm.kind === "dispose" ? arm.d : undefined;
|
|
2469
3132
|
if (disposition?.kind === "settle")
|
|
2470
3133
|
return settledHandle(label, callKey, Promise.resolve(await settleParkedCall(openDispositionRecord(disposition, call, agentOpts), disposition.result, [], agentOpts)));
|
|
2471
3134
|
if (arm.kind === "replay")
|
|
2472
|
-
return settledHandle(label, callKey, replayAgent(call, arm.result, agentOpts));
|
|
3135
|
+
return settledHandle(label, callKey, replayAgent(call, arm.result, agentOpts, arm.stoppedBy));
|
|
2473
3136
|
let rec;
|
|
2474
3137
|
if (disposition !== undefined) {
|
|
2475
3138
|
rec = openDispositionRecord(disposition, call, agentOpts);
|
|
2476
3139
|
}
|
|
2477
3140
|
else {
|
|
2478
|
-
if (budgetTotal !== null && spent() >= budgetTotal) {
|
|
2479
|
-
throw new WorkflowBudgetExceededError(spent(), budgetTotal);
|
|
2480
|
-
}
|
|
2481
3141
|
rec = { label, callKey, ...(groupId !== undefined ? { groupId } : {}), phase, prompt, ...(model !== undefined ? { model } : {}), status: "running", queuedAt: now() };
|
|
2482
|
-
|
|
3142
|
+
admitRecord(rec);
|
|
2483
3143
|
if (phaseInstance)
|
|
2484
3144
|
agentPhaseOf.set(rec, phaseInstance);
|
|
2485
3145
|
emit({ type: "agent_start", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), callKey, prompt, ...(model !== undefined ? { model } : {}), queuedAt: rec.queuedAt, ts: rec.queuedAt });
|
|
2486
3146
|
void persist("update");
|
|
2487
3147
|
}
|
|
2488
3148
|
const { tail: activityTail, onActivity } = createActivityCapture(callKey, label, groupId, rec);
|
|
2489
|
-
const legAfterPark = async (paused, tail
|
|
2490
|
-
const answer = await parkAgentLeg(rec, paused, tail
|
|
3149
|
+
const legAfterPark = async (paused, tail) => {
|
|
3150
|
+
const answer = await parkAgentLeg(rec, paused, tail);
|
|
2491
3151
|
if (answer.kind === "settle")
|
|
2492
3152
|
return { kind: "settled", result: await settleParkedCall(rec, answer.result, tail, agentOpts) };
|
|
2493
3153
|
return await launch(answer.drive);
|
|
@@ -2502,13 +3162,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2502
3162
|
release();
|
|
2503
3163
|
}
|
|
2504
3164
|
};
|
|
2505
|
-
const recordFailed = () => {
|
|
3165
|
+
const recordFailed = (facts) => {
|
|
2506
3166
|
if (!finalized) {
|
|
2507
|
-
|
|
3167
|
+
const stopper = stopperOf(callKey);
|
|
3168
|
+
const outcome = settleRowOutcome(rec, facts ?? (stopper !== undefined ? { from: "ended", status: "killed", stoppedBy: stopper } : { from: "ended", status: "failed", ...(rec.errorCode !== undefined ? { code: rec.errorCode } : {}) }));
|
|
2508
3169
|
rec.endedAt = now();
|
|
2509
3170
|
emit({ type: "agent_end", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), status: "failed", ...(rec.errorCode !== undefined ? { errorCode: rec.errorCode } : {}), ts: rec.endedAt });
|
|
2510
3171
|
void persist("update");
|
|
3172
|
+
return outcome;
|
|
2511
3173
|
}
|
|
3174
|
+
return undefined;
|
|
2512
3175
|
};
|
|
2513
3176
|
const releaseLeg = () => {
|
|
2514
3177
|
if (!released)
|
|
@@ -2517,8 +3180,21 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2517
3180
|
};
|
|
2518
3181
|
try {
|
|
2519
3182
|
if (effectiveSignal?.aborted || finalized) {
|
|
2520
|
-
recordFailed();
|
|
3183
|
+
const queuedOutcome = recordFailed();
|
|
2521
3184
|
releaseLeg();
|
|
3185
|
+
const ownStop = finalized ? undefined : ownStopOf(callKey, queuedOutcome);
|
|
3186
|
+
if (ownStop !== undefined && queuedOutcome !== undefined) {
|
|
3187
|
+
const leg = {
|
|
3188
|
+
taskId: callKey,
|
|
3189
|
+
sessionId: "",
|
|
3190
|
+
terminal: { kind: "failed", message: `the call was stopped (by ${ownStop}) before it started` },
|
|
3191
|
+
result: "", resultEntryIds: [],
|
|
3192
|
+
continuesFrom: { none: "nothing_taken_in" },
|
|
3193
|
+
stats: { turns: 0, tokens: 0, costMicroUsd: 0, usageMissing: true },
|
|
3194
|
+
};
|
|
3195
|
+
await journalAppend(callKey, leg, label, ownStop).catch(() => undefined);
|
|
3196
|
+
return { kind: "settled", result: withMember(leg, queuedOutcome) };
|
|
3197
|
+
}
|
|
2522
3198
|
throw new Error(finalized ? "workflow run already finalized — ctx.agentStream cannot spawn after the run ended" : "workflow aborted");
|
|
2523
3199
|
}
|
|
2524
3200
|
if (parkedLeg !== undefined && drive === undefined) {
|
|
@@ -2528,16 +3204,19 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2528
3204
|
releaseLeg();
|
|
2529
3205
|
throw parked;
|
|
2530
3206
|
}
|
|
2531
|
-
if (budgetTotal !== null && spent()
|
|
3207
|
+
if (budgetTotal !== null && budgetTotal - spent() < SPEND_OUTPUT_FLOOR_TOKENS) {
|
|
2532
3208
|
if (drive !== undefined) {
|
|
2533
3209
|
emitRunLog(`[park] the parked leg "${label}" could not be driven — the run's token ceiling was reached before its turn; the park stands.`);
|
|
3210
|
+
noteDecision(drive, rec.callKey, "refused", "workflow.budget_exceeded");
|
|
2534
3211
|
releaseLeg();
|
|
2535
|
-
return await legAfterPark(drive.paused, []
|
|
3212
|
+
return await legAfterPark(drive.paused, []);
|
|
2536
3213
|
}
|
|
2537
3214
|
const refusal = new WorkflowBudgetExceededError(spent(), budgetTotal);
|
|
2538
3215
|
rec.errorCode = refusal.code;
|
|
2539
3216
|
rec.errorMessage = boundedRedactedSummary(refusal.message, MAX_TRANSCRIPT_CHARS);
|
|
2540
|
-
recordFailed();
|
|
3217
|
+
const refusedOutcome = recordFailed({ from: "refused", budget: true });
|
|
3218
|
+
if (refusedOutcome !== undefined)
|
|
3219
|
+
refusal.member = refusedOutcome;
|
|
2541
3220
|
releaseLeg();
|
|
2542
3221
|
void journalAppend(callKey, {
|
|
2543
3222
|
taskId: callKey,
|
|
@@ -2581,6 +3260,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2581
3260
|
const streamYield = legYieldSeats();
|
|
2582
3261
|
const runInternals = {
|
|
2583
3262
|
...streamYield?.internals,
|
|
3263
|
+
...parkGapInherit(seatedSpec),
|
|
2584
3264
|
onSessionVerified: (id) => void (verifyAgentSession(rec, id) && persist("update")),
|
|
2585
3265
|
...(inheritedModelRef !== undefined ? { inheritedModelRef } : {}),
|
|
2586
3266
|
...(drive === undefined && !spec.sessionId && childSessionId !== undefined ? { sessionIdMintedBySpawner: true } : {}),
|
|
@@ -2592,6 +3272,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2592
3272
|
...(await captureFloorSeatsNow()),
|
|
2593
3273
|
...(enrichedForwardS !== undefined ? { onForwardEvent: enrichedForwardS } : {}),
|
|
2594
3274
|
delegationTaskType: "workflow",
|
|
3275
|
+
spendParent: memberSpendParent,
|
|
2595
3276
|
agentName: label,
|
|
2596
3277
|
...memberSeat(callKey, label),
|
|
2597
3278
|
onActivity,
|
|
@@ -2610,7 +3291,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2610
3291
|
}
|
|
2611
3292
|
: {}),
|
|
2612
3293
|
};
|
|
2613
|
-
const legSpec = { ...runSpec, ...streamYield?.spec };
|
|
3294
|
+
const legSpec = { ...runSpec, ...streamYield?.spec, signal: runSpec.signal !== undefined ? AbortSignal.any([runSpec.signal, membersStop.signal]) : membersStop.signal };
|
|
2614
3295
|
stream = drive === undefined
|
|
2615
3296
|
? workflowDepthStore.run({ depth: depth + 1 }, () => runner.runTaskStream(legSpec, undefined, runInternals))
|
|
2616
3297
|
: await workflowDepthStore.run({ depth: depth + 1 }, () => {
|
|
@@ -2627,7 +3308,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2627
3308
|
const unresumable = unresumableRowResult(drive, rec.callKey, err);
|
|
2628
3309
|
if (unresumable !== undefined)
|
|
2629
3310
|
return { kind: "settled", result: await settleParkedCall(rec, unresumable, [], agentOpts) };
|
|
2630
|
-
return await legAfterPark(drive.paused, []
|
|
3311
|
+
return await legAfterPark(drive.paused, []);
|
|
2631
3312
|
}
|
|
2632
3313
|
const spawnMessage = thrownMessageOf(err);
|
|
2633
3314
|
if (!finalized && rec.errorMessage === undefined && spawnMessage !== undefined)
|
|
@@ -2652,7 +3333,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2652
3333
|
bceTerminal(callKey, "failed", thrownText(err), undefined);
|
|
2653
3334
|
throw err;
|
|
2654
3335
|
}
|
|
2655
|
-
if ((drive !== undefined || judgedOwnerSeat(
|
|
3336
|
+
if ((drive !== undefined || judgedOwnerSeat(opts) === undefined) && childSessionId !== undefined && !finalized) {
|
|
2656
3337
|
verifyAgentSession(rec, childSessionId);
|
|
2657
3338
|
void persist("update");
|
|
2658
3339
|
}
|
|
@@ -2663,7 +3344,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2663
3344
|
throw err;
|
|
2664
3345
|
}
|
|
2665
3346
|
};
|
|
2666
|
-
const firstLeg = disposition !== undefined ? await legAfterPark(disposition.paused, []
|
|
3347
|
+
const firstLeg = disposition !== undefined ? await legAfterPark(disposition.paused, []) : await launch(arm.kind === "live" ? arm.drive : undefined);
|
|
2667
3348
|
if (firstLeg.kind === "settled")
|
|
2668
3349
|
return settledHandle(label, callKey, Promise.resolve(firstLeg.result));
|
|
2669
3350
|
let leg = firstLeg;
|
|
@@ -2698,57 +3379,65 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2698
3379
|
activeUsageBeats.delete(activeBeat);
|
|
2699
3380
|
const partialSpend = rec.stats;
|
|
2700
3381
|
if (!finalized && partialSpend !== undefined && (partialSpend.tokens > 0 || partialSpend.turns > 0 || (partialSpend.costMicroUsd ?? 0) > 0)) {
|
|
2701
|
-
accumulateStats({ stats: partialSpend }
|
|
3382
|
+
accumulateStats({ stats: partialSpend });
|
|
2702
3383
|
}
|
|
3384
|
+
let failedOutcome;
|
|
2703
3385
|
try {
|
|
2704
|
-
recordFailed();
|
|
3386
|
+
failedOutcome = recordFailed();
|
|
2705
3387
|
}
|
|
2706
3388
|
finally {
|
|
2707
3389
|
releaseLeg();
|
|
2708
3390
|
}
|
|
2709
|
-
|
|
3391
|
+
const thrownLeg = {
|
|
2710
3392
|
taskId: callKey,
|
|
2711
3393
|
sessionId: "",
|
|
2712
3394
|
terminal: { kind: "failed", message: boundedRedactedSummary(thrownText(err), 500) },
|
|
2713
3395
|
result: boundedRedactedSummary(thrownText(err), 500), resultEntryIds: [],
|
|
2714
3396
|
continuesFrom: { none: "unsettled" },
|
|
2715
3397
|
stats: { turns: partialSpend?.turns ?? 0, tokens: partialSpend?.tokens ?? 0, costMicroUsd: partialSpend?.costMicroUsd ?? 0 },
|
|
2716
|
-
}
|
|
3398
|
+
};
|
|
3399
|
+
const ownStop = ownStopOf(callKey, failedOutcome);
|
|
3400
|
+
const stoppedLeg = ownStop !== undefined ? { ...thrownLeg, terminal: stoppedTerminalOf(thrownLeg.terminal, ownStop) } : thrownLeg;
|
|
3401
|
+
await journalAppend(callKey, stoppedLeg, undefined, ownStop).catch(() => undefined);
|
|
2717
3402
|
bceTerminal(callKey, "failed", thrownText(err), rec.stats);
|
|
3403
|
+
if (ownStop !== undefined && failedOutcome !== undefined)
|
|
3404
|
+
return withMember(stoppedLeg, failedOutcome);
|
|
2718
3405
|
throw err;
|
|
2719
3406
|
}
|
|
2720
3407
|
rollbackUsageBeat();
|
|
2721
3408
|
activeUsageBeats.delete(activeBeat);
|
|
2722
3409
|
releaseLeg();
|
|
2723
3410
|
if (finalized)
|
|
2724
|
-
return result;
|
|
3411
|
+
return lateMember(rec, result, "live", { from: "result", result, schemaRequested: Boolean(agentOpts.schema) });
|
|
2725
3412
|
const unstartedDrive = drive !== undefined && resumeNeverStarted(result) ? drive : undefined;
|
|
2726
3413
|
if (unstartedDrive !== undefined)
|
|
2727
3414
|
emitRunLog(`[park] the parked leg "${label}" was driven but the approved action never started (${result.terminal.kind === "failed" ? result.terminal.code : ""}); the park stands.`);
|
|
2728
3415
|
if (drive !== undefined)
|
|
2729
3416
|
noteDecision(drive, rec.callKey, unstartedDrive !== undefined ? "refused" : "driven", unstartedDrive !== undefined && result.terminal.kind === "failed" ? result.terminal.code : undefined);
|
|
2730
|
-
const parkOn = isPausedResult(result) ?
|
|
3417
|
+
const parkOn = isPausedResult(result) ? result : unstartedDrive?.paused;
|
|
2731
3418
|
if (parkOn !== undefined) {
|
|
2732
|
-
const next = await legAfterPark(parkOn
|
|
3419
|
+
const next = await legAfterPark(parkOn, activityTail);
|
|
2733
3420
|
if (next.kind === "settled")
|
|
2734
3421
|
return next.result;
|
|
2735
3422
|
leg = next;
|
|
2736
3423
|
continue;
|
|
2737
3424
|
}
|
|
2738
|
-
await settleAgentResult(rec, result, activityTail, agentOpts);
|
|
2739
|
-
return result;
|
|
3425
|
+
return await settleAgentResult(rec, result, activityTail, agentOpts);
|
|
2740
3426
|
}
|
|
2741
3427
|
})();
|
|
2742
3428
|
completion.catch(() => undefined);
|
|
2743
|
-
return { runId, label, callKey, steer, result: () => completion };
|
|
3429
|
+
return { runId, label, callKey, steer, result: () => completion, stop: () => stopMember(callKey, "parent") };
|
|
2744
3430
|
},
|
|
2745
3431
|
async parallel(thunks, fanOutOpts) {
|
|
2746
3432
|
const list = snapshotFanOutList("parallel", "the thunk list", thunks);
|
|
2747
3433
|
assertFanOutCallables("parallel", "item", list);
|
|
2748
3434
|
const errorsOut = fanOutOpts?.errors;
|
|
3435
|
+
const placed = list.length > 0 ? fanOutSite("f") : undefined;
|
|
2749
3436
|
const settled = await Promise.all(list.map((t, i) => Promise.resolve()
|
|
2750
|
-
.then(t)
|
|
3437
|
+
.then((v) => fanOutScopeStore.run({ owner: scopeOwner, path: `${placed.site}.t${i}`, item: placed.enclosing?.item, chain: { n: 0 } }, () => t(v)))
|
|
2751
3438
|
.then((v) => ({ ok: true, v }), (e) => ({ ok: false, e, i }))));
|
|
3439
|
+
if (placed !== undefined)
|
|
3440
|
+
joinFanOut("parallel", placed);
|
|
2752
3441
|
return foldFanOutSettled(settled, "parallel", errorsOut, emitRunLog, resumeRefusal);
|
|
2753
3442
|
},
|
|
2754
3443
|
async pipeline(items, ...stagesAndOpts) {
|
|
@@ -2765,10 +3454,22 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2765
3454
|
const stages = (fanOutOpts !== undefined ? stagesAndOpts.slice(0, -1) : stagesAndOpts);
|
|
2766
3455
|
assertFanOutCallables("pipeline", "stage", stages);
|
|
2767
3456
|
const errorsOut = fanOutOpts?.errors;
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
3457
|
+
const placed = itemList.length > 0 ? fanOutSite("p") : undefined;
|
|
3458
|
+
pipelinesRunning += 1;
|
|
3459
|
+
let settled;
|
|
3460
|
+
try {
|
|
3461
|
+
settled = await Promise.all(itemList.map((item, index) => {
|
|
3462
|
+
const itemScope = { owner: scopeOwner, path: `${placed.site}.i${index}`, item: `${placed.site}.i${index}`, chain: { n: 0 } };
|
|
3463
|
+
return stages
|
|
3464
|
+
.reduce((acc, stage) => acc.then((prev) => fanOutScopeStore.run(itemScope, () => stage(prev, item, index))), Promise.resolve(item))
|
|
3465
|
+
.then((v) => ({ ok: true, v }), (e) => ({ ok: false, e, i: index }));
|
|
3466
|
+
}));
|
|
3467
|
+
}
|
|
3468
|
+
finally {
|
|
3469
|
+
pipelinesRunning -= 1;
|
|
3470
|
+
}
|
|
3471
|
+
if (placed !== undefined)
|
|
3472
|
+
joinFanOut("pipeline", placed);
|
|
2772
3473
|
return foldFanOutSettled(settled, "pipeline", errorsOut, emitRunLog, resumeRefusal);
|
|
2773
3474
|
},
|
|
2774
3475
|
async phase(title, body) {
|
|
@@ -2900,66 +3601,134 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2900
3601
|
if (run.resume === undefined)
|
|
2901
3602
|
return;
|
|
2902
3603
|
for (const entry of parkedResume ?? []) {
|
|
2903
|
-
if (entry.decisionId === undefined)
|
|
3604
|
+
if (entry.decisionId === undefined || spentAtAdmission.has(entry))
|
|
2904
3605
|
continue;
|
|
2905
3606
|
const key = run.parks?.find((p) => p.token === entry.token);
|
|
2906
|
-
if (key === undefined || run.
|
|
3607
|
+
if (key === undefined || run.decisions?.some((d) => d.decisionId === entry.decisionId && d.callKey === key.callKey) === true)
|
|
2907
3608
|
continue;
|
|
2908
|
-
(run.
|
|
3609
|
+
(run.decisions ??= []).push({ ordinal: callKeyOrdinal(key.callKey), callKey: key.callKey, decisionId: entry.decisionId, result: "not_reached", ...(run.errorCode !== undefined ? { code: run.errorCode } : {}) });
|
|
2909
3610
|
}
|
|
2910
3611
|
};
|
|
2911
3612
|
const done = (async () => {
|
|
2912
3613
|
try {
|
|
2913
3614
|
keeperHold = holdKeeper({ agents: agentRegistry, tools: [launchingTool] });
|
|
2914
3615
|
const runBody = async () => {
|
|
2915
|
-
|
|
3616
|
+
let launch;
|
|
3617
|
+
try {
|
|
3618
|
+
launch = opts.launch === undefined ? undefined : (readWorkflowLaunchRecord(opts.launch) ?? "unkeepable");
|
|
3619
|
+
}
|
|
3620
|
+
catch {
|
|
3621
|
+
launch = "unkeepable";
|
|
3622
|
+
}
|
|
2916
3623
|
if (launch !== undefined && journalKeepsLaunches(journalStore)) {
|
|
2917
|
-
const
|
|
3624
|
+
const record = launch;
|
|
3625
|
+
const landed = record === "unkeepable" ? undefined : await recordLanded;
|
|
3626
|
+
const kept = record === "unkeepable" ? "unkeepable"
|
|
3627
|
+
: !landed.ok ? `record_${landed.cause}`
|
|
3628
|
+
: await finalizeWithin(timers, new Promise((resolve) => resolve(journalStore.recordLaunch(runId, scope, record))).then(() => "kept", () => "threw"), "timeout", true);
|
|
2918
3629
|
if (kept !== "kept") {
|
|
2919
3630
|
launchUnkept = true;
|
|
2920
|
-
|
|
3631
|
+
const why = kept === "unkeepable" ? "it is not a record a store keeps"
|
|
3632
|
+
: kept === "timeout" ? `the journal store did not answer within ${WORKFLOW_STORE_WAIT_BOUND_MS}ms`
|
|
3633
|
+
: kept === "threw" ? "the journal store refused it"
|
|
3634
|
+
: kept === "record_timeout" ? `the run's record was not written first: the run store did not answer within ${WORKFLOW_STORE_WAIT_BOUND_MS}ms`
|
|
3635
|
+
: "the run's record was not written first: the run store refused it";
|
|
3636
|
+
emitRunLog(`launch: this run's launch record was not kept (${why}) — nothing could continue a card this run parked on, so its agents do not park on approvals.`);
|
|
2921
3637
|
}
|
|
2922
3638
|
}
|
|
2923
3639
|
if (opts.resumeFromRunId !== undefined && journalStore) {
|
|
2924
3640
|
const usingFallback = journalStore.resumeClaim === undefined;
|
|
3641
|
+
const named = opts.resumeFromRunId;
|
|
2925
3642
|
let walkThrew;
|
|
2926
3643
|
const walkWithin = (p) => storeWithin(p.catch((err) => ((walkThrew ??= { err }), Promise.reject(err))));
|
|
2927
|
-
const
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
3644
|
+
const readTree = () => readWorkflowRunTreeWithin(store, named, scope, walkWithin);
|
|
3645
|
+
const treeRefusal = async (tree) => {
|
|
3646
|
+
if (tree === "over_bound")
|
|
3647
|
+
return new Error(`startWorkflow: resume from "${clampRunIdText(named)}" was REFUSED — ${WORKFLOW_TREE_OVER_BOUND_REASON}.`);
|
|
3648
|
+
if (walkThrew === undefined) {
|
|
3649
|
+
const got = await storeWithin(Promise.resolve().then(() => store.get(named)));
|
|
3650
|
+
if (got.ok && (got.value === null || got.value.scope !== scope))
|
|
3651
|
+
return priorRecordMissingRefusal(clampRunIdText(named));
|
|
3652
|
+
}
|
|
3653
|
+
return runStoreUnreadableRefusal(clampRunIdText(named), walkThrew);
|
|
3654
|
+
};
|
|
3655
|
+
const heldKey = internals?.resumeClaimKey;
|
|
3656
|
+
const keyTree = store === undefined || heldKey !== undefined ? undefined : await readTree();
|
|
3657
|
+
if (typeof keyTree === "string")
|
|
3658
|
+
throw await treeRefusal(keyTree);
|
|
3659
|
+
const root = heldKey ?? (keyTree === undefined ? named : keyTree.root.id);
|
|
3660
|
+
const otherRoot = () => new Error(`startWorkflow: resume from "${clampRunIdText(named)}" was REFUSED — the workflow's records now lead to another first run than the one its resume claim was taken for (a run of the workflow was removed or created again meanwhile), so its claim cannot hold it. Resume again.`);
|
|
2932
3661
|
if (finalized)
|
|
2933
3662
|
throw new Error("workflow run already finalized — its resume admission takes no claim after the run ended");
|
|
2934
|
-
const verdict = takeWorkflowResumeClaim(journalStore, { sourceRunId:
|
|
2935
|
-
resumeClaim = { sourceRunId:
|
|
2936
|
-
|
|
3663
|
+
const verdict = takeWorkflowResumeClaim(journalStore, { sourceRunId: root, newRunId: runId, scope });
|
|
3664
|
+
resumeClaim = { sourceRunId: root, verdict, fallback: usingFallback };
|
|
3665
|
+
let decision;
|
|
3666
|
+
try {
|
|
3667
|
+
decision = await verdict;
|
|
3668
|
+
}
|
|
3669
|
+
catch (err) {
|
|
3670
|
+
throw journalStoreClaimRefusal(clampRunIdText(named), err);
|
|
3671
|
+
}
|
|
2937
3672
|
if (!decision.granted) {
|
|
2938
|
-
const
|
|
2939
|
-
const
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
3673
|
+
const forAnswer = isAnswerRecordClaimHolder(decision.holder);
|
|
3674
|
+
const holder = decision.holder !== undefined && !forAnswer ? clampRunIdText(decision.holder) : "";
|
|
3675
|
+
const lapse = decision.lapse;
|
|
3676
|
+
throw new Error(`startWorkflow: resume from "${clampRunIdText(named)}" was REFUSED — ` +
|
|
3677
|
+
(forAnswer
|
|
3678
|
+
? "another leg of the workflow holds the resume claim on it for a moment, to record a person's answer to continuing it (no run holds it): resume again once it gives the claim back. If that leg's process stopped without giving the claim back, "
|
|
3679
|
+
: `another run already holds the resume claim on it${holder ? ` (holder: ${holder})` : " (holder unknown to the store)"}. ` +
|
|
3680
|
+
"Two concurrent resumes of one source run fork its execution: both replay the same prefix and then " +
|
|
3681
|
+
"re-run the whole suffix live, duplicating every side effect. Wait for the holder to reach a terminal " +
|
|
3682
|
+
"state (or stop it) and resume again. If the holder's process stopped without giving the claim back, ") +
|
|
3683
|
+
`the claim lapses ${lapse?.kind === "at" ? `at ${new Date(lapse.at).toISOString()} at the latest` : `when the journal store's expiry frees it${lapse?.kind === "unreadable" ? ` (${CLAIM_REMAINING_UNREADABLE_NOTE})` : ""}`}, and the same resume goes through then.`);
|
|
2946
3684
|
}
|
|
2947
|
-
|
|
3685
|
+
if (store !== undefined) {
|
|
3686
|
+
const tree = await readTree();
|
|
3687
|
+
if (typeof tree === "string")
|
|
3688
|
+
throw await treeRefusal(tree);
|
|
3689
|
+
if (tree.root.id !== root)
|
|
3690
|
+
throw otherRoot();
|
|
3691
|
+
admissionTree = Promise.resolve(tree);
|
|
3692
|
+
for (const e of parkedResume ?? []) {
|
|
3693
|
+
const was = e.decisionId === undefined ? undefined : workflowParkDecisionOf(e.token, e.decisionId, tree);
|
|
3694
|
+
if (was?.kind !== "spent")
|
|
3695
|
+
continue;
|
|
3696
|
+
spentAtAdmission.add(e);
|
|
3697
|
+
emitRunLog(`resume: a decision this resume carries was not applied — the workflow's records say it is already ${was.reason === "decision_spent" ? "refused" : "settled"}${was.code !== undefined ? ` (${withoutToken(was.code, e.token)})` : ""}; the run goes on as if the resume did not carry it.`);
|
|
3698
|
+
}
|
|
3699
|
+
if ((parkedResume ?? []).every((e) => spentAtAdmission.has(e))) {
|
|
3700
|
+
const tail = workflowLineTailOf(tree, named);
|
|
3701
|
+
if (tail.kind === "fork")
|
|
3702
|
+
throw new Error(`startWorkflow: resume from "${clampRunIdText(named)}" was REFUSED — ${workflowLineForkReason(tail.leaves.map((l) => clampRunIdText(l)))}.`);
|
|
3703
|
+
if (tail.runId !== named) {
|
|
3704
|
+
if (heldKey !== undefined)
|
|
3705
|
+
throw new Error(`startWorkflow: resume from "${clampRunIdText(named)}" was REFUSED — the run was continued again (as "${clampRunIdText(tail.runId)}") after this resume chose it and before its claim was held, so it is not continued from there. Resume again to continue from what the workflow's records say now.`);
|
|
3706
|
+
if (isWorkflowRunActive(tail.runId))
|
|
3707
|
+
throw new Error(`startWorkflow: resumeFromRunId "${clampRunIdText(named)}" was continued as "${clampRunIdText(tail.runId)}", which is still an active workflow run in this process — stop it before resuming from it`);
|
|
3708
|
+
resumeFrom = tail.runId;
|
|
3709
|
+
resumeAsked = named;
|
|
3710
|
+
}
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
if (resumeAsked !== undefined)
|
|
3714
|
+
emitRunLog(`resume: run "${clampRunIdText(resumeAsked)}" was named, and it had already been continued — this run continues the last run of that line, "${clampRunIdText(resumeFrom)}" (its completed calls replay; what it did not reach runs live).`);
|
|
3715
|
+
const from = resumeFrom;
|
|
3716
|
+
const entries = judgedJournal(from, await journalStore.load(from, scope));
|
|
2948
3717
|
for (const e of entries) {
|
|
2949
3718
|
const ordinal = callKeyOrdinal(e.callKey);
|
|
2950
3719
|
if (e.parked === undefined) {
|
|
2951
|
-
const t = e.result.terminal;
|
|
3720
|
+
const t = (e.result ?? e.stopped?.result)?.terminal;
|
|
2952
3721
|
if (t === null || typeof t !== "object" || !isTerminalCauseKind(t.kind)) {
|
|
2953
|
-
throw new WorkflowJournalIncompatibleError(
|
|
3722
|
+
throw new WorkflowJournalIncompatibleError(from, ordinal);
|
|
2954
3723
|
}
|
|
2955
3724
|
}
|
|
2956
3725
|
replayByOrdinal[ordinal] = e;
|
|
2957
3726
|
}
|
|
2958
|
-
const fromRunId = clampRunIdText(
|
|
3727
|
+
const fromRunId = clampRunIdText(from);
|
|
2959
3728
|
let prior = null;
|
|
2960
3729
|
if (opts.store !== undefined) {
|
|
2961
3730
|
try {
|
|
2962
|
-
prior = await opts.store.get(
|
|
3731
|
+
prior = await opts.store.get(from);
|
|
2963
3732
|
}
|
|
2964
3733
|
catch (err) {
|
|
2965
3734
|
throw runStoreUnreadableRefusal(fromRunId, { err });
|
|
@@ -2968,7 +3737,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2968
3737
|
prior = null;
|
|
2969
3738
|
}
|
|
2970
3739
|
if (opts.store !== undefined && prior === null)
|
|
2971
|
-
throw
|
|
3740
|
+
throw priorRecordMissingRefusal(fromRunId);
|
|
2972
3741
|
if (parkSeat !== undefined && prior !== null && prior.status === "running")
|
|
2973
3742
|
throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run is still recorded as running; a run that could park must have finished before it is resumed (a crashed park-capable run is decided through the deployment's approval channel, not resumed).`, { reason: "record_not_terminal" });
|
|
2974
3743
|
if (prior?.resumeAdmissionIncomplete === true)
|
|
@@ -3001,9 +3770,9 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3001
3770
|
for (const [ord, e] of replayByOrdinal.entries()) {
|
|
3002
3771
|
if (e?.parked === undefined)
|
|
3003
3772
|
continue;
|
|
3004
|
-
offerCandidate(ord, { callKey: e.callKey, sessionId: e.parked.sessionId, token: e.parked.terminal.token, originRunId:
|
|
3773
|
+
offerCandidate(ord, { callKey: e.callKey, sessionId: e.parked.sessionId, token: e.parked.terminal.token, originRunId: from });
|
|
3005
3774
|
const settled = candidates.get(ord);
|
|
3006
|
-
settled.originRunId =
|
|
3775
|
+
settled.originRunId = from;
|
|
3007
3776
|
delete settled.originUnconfirmed;
|
|
3008
3777
|
}
|
|
3009
3778
|
for (const rec of recordParks === undefined && Array.isArray(prior?.agents) ? prior.agents : []) {
|
|
@@ -3011,16 +3780,48 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3011
3780
|
continue;
|
|
3012
3781
|
if (typeof rec.callKey !== "string" || !/^\d+:/.test(rec.callKey))
|
|
3013
3782
|
throw parkBindingBroken(-1, "a parked agent row is malformed or its call key has no ordinal");
|
|
3014
|
-
offerCandidate(callKeyOrdinal(rec.callKey), { callKey: rec.callKey, sessionId: rec.sessionId ?? "", token: rec.parkedCheckpointToken ?? "", originRunId:
|
|
3783
|
+
offerCandidate(callKeyOrdinal(rec.callKey), { callKey: rec.callKey, sessionId: rec.sessionId ?? "", token: rec.parkedCheckpointToken ?? "", originRunId: from, originUnconfirmed: true });
|
|
3015
3784
|
}
|
|
3016
3785
|
if (noParksList && candidates.size === 0)
|
|
3017
3786
|
throw parksUnreadable("neither its journal nor its own parked agent rows names a park to derive (a park it inherited and never reached is recorded in that list alone)");
|
|
3018
3787
|
const inherited = [];
|
|
3019
3788
|
for (const [ord, key] of [...candidates.entries()].sort((a, b) => a[0] - b[0])) {
|
|
3020
|
-
if (replayByOrdinal[ord]?.result !== undefined)
|
|
3789
|
+
if (replayByOrdinal[ord]?.result !== undefined || replayByOrdinal[ord]?.stopped !== undefined)
|
|
3021
3790
|
continue;
|
|
3022
3791
|
inherited.push(key);
|
|
3023
3792
|
}
|
|
3793
|
+
const placeAtOrdinal = new Map();
|
|
3794
|
+
const specsAtOrdinal = new Map();
|
|
3795
|
+
let marked = false;
|
|
3796
|
+
const notePlace = (callKey) => {
|
|
3797
|
+
const ord = callKeyOrdinal(callKey);
|
|
3798
|
+
const position = callKeyPosition(callKey) ?? null;
|
|
3799
|
+
const seen = placeAtOrdinal.get(ord);
|
|
3800
|
+
const recordedAt = position === null ? undefined : recordedOrdinalOfPosition.get(position);
|
|
3801
|
+
if ((seen !== undefined && seen !== position) || (recordedAt !== undefined && recordedAt !== ord))
|
|
3802
|
+
throw new WorkflowJournalIncompatibleError(from, ord);
|
|
3803
|
+
placeAtOrdinal.set(ord, position);
|
|
3804
|
+
recordedOrdinals.add(ord);
|
|
3805
|
+
marked ||= callKey.includes("@");
|
|
3806
|
+
specsAtOrdinal.set(ord, (specsAtOrdinal.get(ord) ?? new Set()).add(callKeySpec(callKey)));
|
|
3807
|
+
if (position !== null)
|
|
3808
|
+
recordedOrdinalOfPosition.set(position, ord);
|
|
3809
|
+
};
|
|
3810
|
+
for (const e of entries)
|
|
3811
|
+
notePlace(e.callKey);
|
|
3812
|
+
for (const key of candidates.values())
|
|
3813
|
+
notePlace(key.callKey);
|
|
3814
|
+
for (const rec of Array.isArray(prior?.agents) ? prior.agents : []) {
|
|
3815
|
+
if (rec === null || typeof rec !== "object" || typeof rec.callKey !== "string" || !/^\d+:/.test(rec.callKey))
|
|
3816
|
+
continue;
|
|
3817
|
+
notePlace(rec.callKey);
|
|
3818
|
+
}
|
|
3819
|
+
priorRecordUnpositioned = recordedOrdinals.size > 0 && !marked;
|
|
3820
|
+
if (priorRecordUnpositioned) {
|
|
3821
|
+
for (const [ord, specs] of [...specsAtOrdinal].sort(([a], [b]) => a - b))
|
|
3822
|
+
for (const s of specs)
|
|
3823
|
+
recordedOrdinalsOfSpec.set(s, [...(recordedOrdinalsOfSpec.get(s) ?? []), ord]);
|
|
3824
|
+
}
|
|
3024
3825
|
if (parkSeat === undefined) {
|
|
3025
3826
|
if (inherited.length > 0) {
|
|
3026
3827
|
throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — it is responsible for ${inherited.length} recorded park(s) and this workflow holds no checkpoint store to prove them against (RunWorkflowOptions.checkpointStore); without the seat a parked call would run live beside its pinned child.`, { reason: "capability_not_armed" });
|
|
@@ -3045,20 +3846,22 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3045
3846
|
parkedByOrdinal[ord] = truth;
|
|
3046
3847
|
}
|
|
3047
3848
|
}
|
|
3849
|
+
const fromCreationId = prior === null ? null : workflowRunCreationIdOf(prior);
|
|
3850
|
+
const treeOfPrior = store === undefined || prior === null ? undefined : await treeIdOf(store, prior, scope, storeWithin);
|
|
3048
3851
|
if (!finalized) {
|
|
3049
3852
|
for (const key of inherited)
|
|
3050
3853
|
if (key.generation !== undefined)
|
|
3051
3854
|
key.generation += 1;
|
|
3052
3855
|
run.parks = inherited;
|
|
3053
3856
|
delete run.resumeAdmissionIncomplete;
|
|
3857
|
+
run.resume = { fromRunId, ...(fromCreationId !== null ? { fromCreationId } : {}), ...(resumeAsked !== undefined ? { asked: clampRunIdText(resumeAsked) } : {}), journalEntries: entries.length, replayed: 0 };
|
|
3858
|
+
if (treeOfPrior !== undefined && typeof treeOfPrior === "object")
|
|
3859
|
+
run.treeId = treeOfPrior.treeId;
|
|
3054
3860
|
}
|
|
3055
|
-
const continuedBefore = await continuedBeforeOf(
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
replayed: 0,
|
|
3060
|
-
...(continuedBefore !== undefined ? { continuedBefore } : {}),
|
|
3061
|
-
};
|
|
3861
|
+
const continuedBefore = await continuedBeforeOf(from);
|
|
3862
|
+
workflowSignal.throwIfAborted();
|
|
3863
|
+
if (continuedBefore !== undefined && run.resume !== undefined)
|
|
3864
|
+
run.resume = { ...run.resume, continuedBefore };
|
|
3062
3865
|
if (entries.length === 0) {
|
|
3063
3866
|
emitRunLog("resume: the prior run's journal yielded NO entries under this run's scope — nothing will replay; the entire script runs live. " +
|
|
3064
3867
|
"The prior run id may be unknown or pruned, recorded under a different scope, or its journal unreadable.");
|
|
@@ -3068,6 +3871,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3068
3871
|
}
|
|
3069
3872
|
void persist("update");
|
|
3070
3873
|
}
|
|
3874
|
+
workflowSignal.throwIfAborted();
|
|
3071
3875
|
return fn(ctx);
|
|
3072
3876
|
};
|
|
3073
3877
|
const bodyPromise = workflowDepthStore.run({ depth: depth + 1 }, runBody);
|
|
@@ -3133,13 +3937,15 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3133
3937
|
settleUnreachedDecisions();
|
|
3134
3938
|
await settleRecordArtifact();
|
|
3135
3939
|
emit({ type: "run_end", runId, status: "completed", ...(completedRunFailures > 0 ? { agentFailures: completedRunFailures } : {}), ts: run.endedAt });
|
|
3136
|
-
await
|
|
3940
|
+
await persistTerminal("completed");
|
|
3137
3941
|
return { result, runId, run };
|
|
3138
3942
|
}
|
|
3139
3943
|
catch (err) {
|
|
3140
3944
|
await awaitParksSettled();
|
|
3141
3945
|
if (parkedLeg !== undefined)
|
|
3142
3946
|
await awaitLegsIdle(workflowSignal);
|
|
3947
|
+
else
|
|
3948
|
+
await stopAndSettleMembers();
|
|
3143
3949
|
latchFinalized();
|
|
3144
3950
|
const unsettledOnFailure = settleActiveUsageBeats();
|
|
3145
3951
|
stampBudgetOvershoot(unsettledOnFailure);
|
|
@@ -3158,10 +3964,8 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3158
3964
|
closeAbandonedAgents(run.endedAt);
|
|
3159
3965
|
{
|
|
3160
3966
|
const thrownCode = readMember(err, "code");
|
|
3161
|
-
const
|
|
3162
|
-
|
|
3163
|
-
.sort((a, b) => (a.endedAt ?? Number.POSITIVE_INFINITY) - (b.endedAt ?? Number.POSITIVE_INFINITY))[0];
|
|
3164
|
-
const code = typeof thrownCode === "string" && thrownCode !== "" ? thrownCode : firstFailed?.errorCode;
|
|
3967
|
+
const thrown = typeof thrownCode === "string" && thrownCode !== "" && (thrownCode !== WORKFLOW_AGENT_PARKED_ERROR_CODE || parkedLeg !== undefined) ? thrownCode : undefined;
|
|
3968
|
+
const code = thrown ?? firstFailedAgentCodeOf(run.agents);
|
|
3165
3969
|
if (code !== undefined)
|
|
3166
3970
|
run.errorCode = code;
|
|
3167
3971
|
}
|
|
@@ -3173,7 +3977,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3173
3977
|
settleUnreachedDecisions();
|
|
3174
3978
|
await settleRecordArtifact();
|
|
3175
3979
|
emit({ type: "run_end", runId, status: "failed", ...(failedRunFailures > 0 ? { agentFailures: failedRunFailures } : {}), ts: run.endedAt });
|
|
3176
|
-
await
|
|
3980
|
+
await persistTerminal("failed");
|
|
3177
3981
|
if (err !== null && (typeof err === "object" || typeof err === "function")) {
|
|
3178
3982
|
try {
|
|
3179
3983
|
Object.defineProperty(err, "workflowRun", { value: run, enumerable: false, configurable: true });
|
|
@@ -3187,6 +3991,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3187
3991
|
latchFinalized();
|
|
3188
3992
|
yieldIntent?.removeEventListener("abort", onYieldIntent);
|
|
3189
3993
|
yieldLegs.clear();
|
|
3994
|
+
journalSealed = true;
|
|
3190
3995
|
await new Promise((resolve) => {
|
|
3191
3996
|
const t = setTimeout(() => {
|
|
3192
3997
|
emitLogLine(`resume-journal: terminal drain did not settle within ${JOURNAL_DRAIN_MAX_MS}ms — tail entries may be missing; a resume from this run re-runs those agents live.`);
|
|
@@ -3224,6 +4029,19 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3224
4029
|
}
|
|
3225
4030
|
workflowSignal?.removeEventListener("abort", suspendOnParks);
|
|
3226
4031
|
closeWorkflowChannel(runId);
|
|
4032
|
+
for (const go of afterAnswer.splice(0)) {
|
|
4033
|
+
try {
|
|
4034
|
+
letGo(timers.setTimeout(go, 0));
|
|
4035
|
+
}
|
|
4036
|
+
catch {
|
|
4037
|
+
try {
|
|
4038
|
+
letGo(setTimeout(go, 0));
|
|
4039
|
+
}
|
|
4040
|
+
catch {
|
|
4041
|
+
void Promise.resolve().then(go).catch(() => undefined);
|
|
4042
|
+
}
|
|
4043
|
+
}
|
|
4044
|
+
}
|
|
3227
4045
|
}
|
|
3228
4046
|
})();
|
|
3229
4047
|
bindSettledRun(done, run);
|
|
@@ -3232,6 +4050,13 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3232
4050
|
done,
|
|
3233
4051
|
cancel: (reason) => cancelController.abort(reason ? new Error(reason) : undefined),
|
|
3234
4052
|
parked: () => runParkedOf(run),
|
|
4053
|
+
stopAgent: async (callKey, o) => {
|
|
4054
|
+
const by = o?.stoppedBy;
|
|
4055
|
+
if (by !== undefined && (typeof by !== "string" || by.trim() === "" || by.length > MAX_MEMBER_STOPPER_CHARS))
|
|
4056
|
+
throw new TypeError(`WorkflowHandle.stopAgent: stoppedBy must be a non-empty string of at most ${MAX_MEMBER_STOPPER_CHARS} characters`);
|
|
4057
|
+
return stopMember(callKey, by ?? "parent");
|
|
4058
|
+
},
|
|
4059
|
+
recordLanded: () => recordLanded.then((o) => o.ok),
|
|
3235
4060
|
};
|
|
3236
4061
|
}
|
|
3237
4062
|
export async function runWorkflow(runner, fn, opts = {}, internals) {
|