@sema-agent/core 7.70.0 → 7.71.1
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 +740 -0
- package/dist/agents/agent-transcript-tool.js +43 -19
- package/dist/agents/inherited-tool-pool.d.ts +5 -1
- package/dist/agents/inherited-tool-pool.js +6 -0
- package/dist/agents/retain-ledger.js +2 -0
- package/dist/agents/send-message-tool.d.ts +12 -1
- package/dist/agents/send-message-tool.js +47 -9
- package/dist/agents/subagent.js +31 -10
- package/dist/agents/tool-filter.js +1 -2
- package/dist/agents/verify.js +13 -2
- package/dist/agents/yield-adoption.js +11 -1
- package/dist/brain/claude-model-id.d.ts +11 -0
- package/dist/brain/claude-model-id.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/allow-entry.js +1 -2
- package/dist/core/ask-origin.d.ts +55 -21
- package/dist/core/ask-origin.js +19 -11
- package/dist/core/ask-question.d.ts +4 -7
- package/dist/core/ask-question.js +2 -4
- package/dist/core/ask-unresolvable-notice.d.ts +17 -3
- package/dist/core/ask-unresolvable-notice.js +18 -4
- package/dist/core/attachment-source.d.ts +1 -1
- package/dist/core/attachment-source.js +2 -0
- package/dist/core/auto-compaction.d.ts +14 -4
- package/dist/core/auto-compaction.js +3 -2
- package/dist/core/auto-strip.js +2 -0
- package/dist/core/caller-text.d.ts +2 -33
- package/dist/core/caller-text.js +2 -23
- package/dist/core/caller-tool-name.js +1 -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 +43 -80
- package/dist/core/checkpoint-features.js +10 -20
- package/dist/core/checkpoint-generation.d.ts +89 -19
- package/dist/core/checkpoint-generation.js +89 -14
- package/dist/core/checkpoint-queries.d.ts +95 -15
- package/dist/core/checkpoint-queries.js +108 -7
- package/dist/core/checkpoint-rekey.d.ts +2 -1
- package/dist/core/checkpoint-rekey.js +2 -2
- package/dist/core/checkpoint-requirements.d.ts +21 -7
- package/dist/core/checkpoint-requirements.js +2 -5
- package/dist/core/checkpoint-row-verdict.d.ts +3 -4
- package/dist/core/checkpoint-row-verdict.js +20 -41
- package/dist/core/checkpoint-store.d.ts +69 -41
- package/dist/core/checkpoint-store.js +28 -14
- 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 +1 -1
- package/dist/core/config-refusal-codes.js +1 -0
- package/dist/core/declaration-words.d.ts +2 -1
- package/dist/core/declaration-words.js +13 -2
- 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 +14 -9
- package/dist/core/engine-capabilities.js +1 -1
- package/dist/core/engine-notice.d.ts +62 -32
- package/dist/core/engine-version.js +1 -1
- package/dist/core/entries-not-applied.d.ts +1 -1
- package/dist/core/entries-not-applied.js +1 -0
- package/dist/core/file-history-store.d.ts +95 -11
- package/dist/core/file-history-store.js +117 -19
- package/dist/core/gate-fold.js +13 -7
- package/dist/core/gate-lanes.js +9 -9
- package/dist/core/governance-codes.d.ts +56 -7
- package/dist/core/governance-codes.js +105 -7
- package/dist/core/grant-holder.d.ts +53 -0
- package/dist/core/grant-holder.js +80 -0
- package/dist/core/hooks.d.ts +7 -3
- package/dist/core/hooks.js +2 -2
- package/dist/core/locked-config.d.ts +7 -1
- package/dist/core/locked-config.js +9 -2
- package/dist/core/mcp-call-meta.d.ts +52 -7
- package/dist/core/mcp-call-meta.js +21 -2
- package/dist/core/mcp-host-read.d.ts +1 -1
- package/dist/core/mcp-server-spec.d.ts +18 -0
- package/dist/core/mcp-server-spec.js +1 -0
- package/dist/core/mcp.js +2 -2
- package/dist/core/member-outcome.d.ts +22 -1
- package/dist/core/member-outcome.js +18 -6
- package/dist/core/memory-engine/delegation-settlement.js +5 -5
- package/dist/core/memory-engine/engine.js +19 -19
- package/dist/core/memory-engine/file-backend.d.ts +7 -2
- package/dist/core/memory-engine/file-backend.js +14 -12
- package/dist/core/memory-engine/frontmatter.js +1 -1
- package/dist/core/memory-engine/index.d.ts +1 -0
- package/dist/core/memory-engine/index.js +1 -0
- package/dist/core/memory-engine/layout.d.ts +34 -9
- package/dist/core/memory-engine/layout.js +36 -19
- package/dist/core/memory-engine/memory-deployment.js +8 -8
- package/dist/core/memory-engine/mount-failed-notice.d.ts +8 -5
- package/dist/core/memory-engine/mount-failed-notice.js +5 -2
- package/dist/core/mode-policy.d.ts +5 -0
- package/dist/core/mode-policy.js +6 -0
- package/dist/core/mods/host.d.ts +2 -1
- package/dist/core/mods/host.js +7 -6
- 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/package.d.ts +12 -1
- package/dist/core/mods/package.js +36 -9
- package/dist/core/mods/stations.d.ts +7 -1
- package/dist/core/mods/stations.js +17 -3
- package/dist/core/mods/teammate-stations.d.ts +4 -1
- package/dist/core/mods/teammate-stations.js +1 -1
- package/dist/core/native-signal.d.ts +13 -0
- package/dist/core/native-signal.js +18 -0
- package/dist/core/park-resumability.d.ts +16 -14
- package/dist/core/park-resumability.js +9 -4
- package/dist/core/path-rule-binding.js +1 -1
- package/dist/core/permission-rule-model.d.ts +11 -5
- package/dist/core/permission-rule-model.js +5 -3
- package/dist/core/permission-rule-org.js +1 -1
- package/dist/core/permission-rule-provider.d.ts +5 -1
- package/dist/core/permission-rule-provider.js +6 -1
- package/dist/core/permission-rule-session.d.ts +35 -5
- package/dist/core/permission-rule-session.js +32 -1
- package/dist/core/permission-rule-store.d.ts +5 -1
- package/dist/core/permission-rule-store.js +28 -5
- package/dist/core/permission-rules.d.ts +2 -2
- package/dist/core/permission-rules.js +2 -3
- package/dist/core/principal-name.d.ts +12 -0
- package/dist/core/principal-name.js +6 -2
- package/dist/core/read-root-grant-screen.d.ts +7 -6
- package/dist/core/read-root-grant-screen.js +7 -8
- package/dist/core/remote-env.d.ts +42 -8
- package/dist/core/resume-config-judge.js +1 -1
- package/dist/core/resume-startup-cause.d.ts +19 -4
- package/dist/core/resume-startup-cause.js +25 -6
- package/dist/core/rewind-conversation.d.ts +4 -0
- package/dist/core/rewrite-rejudge.d.ts +9 -1
- package/dist/core/rewrite-rejudge.js +11 -1
- package/dist/core/rule-offer-read.js +3 -2
- package/dist/core/runner/assemble-result.d.ts +21 -11
- package/dist/core/runner/assemble-result.js +24 -4
- package/dist/core/runner/boundary-reminders.d.ts +104 -0
- package/dist/core/runner/boundary-reminders.js +108 -0
- package/dist/core/runner/branch-writeback.d.ts +21 -7
- package/dist/core/runner/branch-writeback.js +44 -6
- package/dist/core/runner/command-sandbox-frame.js +2 -1
- package/dist/core/runner/compact-session.js +11 -4
- package/dist/core/runner/constraint-layers.d.ts +24 -5
- package/dist/core/runner/constraint-layers.js +21 -2
- package/dist/core/runner/continuation-gate.js +3 -1
- package/dist/core/runner/contracts.d.ts +83 -13
- package/dist/core/runner/cross-boundary-lane.js +2 -1
- package/dist/core/runner/delegation-owner.d.ts +246 -45
- package/dist/core/runner/delegation-owner.js +237 -63
- 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 +11 -3
- package/dist/core/runner/file-history-restore.js +11 -3
- package/dist/core/runner/gate-exit.d.ts +22 -1
- package/dist/core/runner/gate-exit.js +12 -14
- package/dist/core/runner/nested-memory-content.js +1 -1
- package/dist/core/runner/nested-memory-lane.d.ts +10 -2
- package/dist/core/runner/nested-memory-lane.js +29 -8
- 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 +4 -2
- package/dist/core/runner/park-commit.js +2 -1
- package/dist/core/runner/permission-rule-lanes.d.ts +4 -0
- package/dist/core/runner/permission-rule-lanes.js +7 -0
- package/dist/core/runner/person-path-rows.js +1 -1
- 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/prepare-acquire-reconcile.d.ts +23 -14
- package/dist/core/runner/prepare-acquire-reconcile.js +33 -15
- package/dist/core/runner/prepare-artifact.d.ts +14 -1
- package/dist/core/runner/prepare-artifact.js +7 -2
- package/dist/core/runner/prepare-ask-lane.d.ts +8 -0
- package/dist/core/runner/prepare-ask-lane.js +14 -5
- package/dist/core/runner/prepare-boundary-parks.js +5 -4
- package/dist/core/runner/prepare-config-doors.d.ts +9 -4
- package/dist/core/runner/prepare-config-doors.js +25 -8
- package/dist/core/runner/prepare-defer-classify.d.ts +8 -4
- package/dist/core/runner/prepare-defer-classify.js +6 -6
- package/dist/core/runner/prepare-execution-env.d.ts +4 -1
- package/dist/core/runner/prepare-execution-env.js +8 -3
- package/dist/core/runner/prepare-file-history.d.ts +26 -0
- package/dist/core/runner/prepare-file-history.js +15 -1
- package/dist/core/runner/prepare-inherited-gate.d.ts +8 -3
- package/dist/core/runner/prepare-inherited-gate.js +9 -2
- package/dist/core/runner/prepare-leg-adoption.d.ts +2 -2
- package/dist/core/runner/prepare-park-ask.js +8 -5
- package/dist/core/runner/prepare-policy-chain.d.ts +5 -0
- package/dist/core/runner/prepare-policy-chain.js +18 -7
- package/dist/core/runner/prepare-prompt-assembly.d.ts +3 -0
- package/dist/core/runner/prepare-prompt-assembly.js +4 -3
- package/dist/core/runner/prepare-suspend-saga.d.ts +4 -1
- package/dist/core/runner/prepare-suspend-saga.js +19 -5
- package/dist/core/runner/prepare-task.d.ts +2 -5
- package/dist/core/runner/prepare-task.js +71 -26
- package/dist/core/runner/prepare-turn-wiring.js +7 -5
- package/dist/core/runner/prepare-workspace-restore.js +59 -28
- package/dist/core/runner/read-root-grant.d.ts +1 -0
- package/dist/core/runner/read-root-grant.js +1 -2
- package/dist/core/runner/resume-admission.d.ts +3 -0
- package/dist/core/runner/resume-admission.js +6 -4
- package/dist/core/runner/resume-apply.js +7 -5
- package/dist/core/runner/resume-claim.d.ts +2 -2
- package/dist/core/runner/resume-claim.js +4 -4
- package/dist/core/runner/resume-policy-outcome.d.ts +1 -1
- package/dist/core/runner/resume-policy-outcome.js +6 -4
- package/dist/core/runner/resume-preflight.d.ts +3 -0
- package/dist/core/runner/resume-preflight.js +10 -3
- package/dist/core/runner/rewind-conversation.js +11 -4
- package/dist/core/runner/rewind-files.js +29 -14
- package/dist/core/runner/rewind-outcome.d.ts +27 -0
- package/dist/core/runner/rewind-outcome.js +14 -0
- 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-identity-wiring.js +2 -0
- package/dist/core/runner/run-leg.js +11 -1
- package/dist/core/runner/run-notification-lane.d.ts +3 -0
- package/dist/core/runner/run-notification-lane.js +2 -2
- package/dist/core/runner/run-settle-and-teardown.d.ts +4 -2
- package/dist/core/runner/run-settle-and-teardown.js +52 -40
- package/dist/core/runner/run-stop-and-final-verify.d.ts +4 -0
- package/dist/core/runner/run-stop-and-final-verify.js +5 -4
- 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 +7 -0
- package/dist/core/runner/runtask.d.ts +7 -4
- package/dist/core/runner/runtask.js +18 -9
- 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.js +2 -2
- 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-rule-policy.js +1 -1
- 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/side-call-account.js +5 -1
- 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 +17 -18
- package/dist/core/runner/terminal-account.js +17 -8
- package/dist/core/runner/terminal-projection.d.ts +3 -2
- package/dist/core/runner/terminal-projection.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/turn-attachments.d.ts +22 -1
- package/dist/core/runner/turn-attachments.js +20 -3
- package/dist/core/runner-deps.d.ts +6 -2
- package/dist/core/secret-env.d.ts +26 -6
- package/dist/core/secret-env.js +6 -6
- 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-checkout.d.ts +3 -0
- package/dist/core/session-checkout.js +8 -3
- package/dist/core/session-policy-store.d.ts +14 -0
- package/dist/core/session-policy-store.js +16 -2
- package/dist/core/session-store.d.ts +18 -1
- package/dist/core/session-store.js +20 -4
- package/dist/core/session.d.ts +36 -4
- package/dist/core/shared-artifact-reads.d.ts +93 -0
- package/dist/core/shared-artifact-reads.js +94 -0
- package/dist/core/skill-grant.js +1 -1
- package/dist/core/skills-directory.d.ts +9 -45
- package/dist/core/skills-directory.js +9 -722
- package/dist/core/spend-account.js +3 -0
- package/dist/core/store-contracts/checkpoint-store-contract.d.ts +22 -4
- package/dist/core/store-contracts/checkpoint-store-contract.js +363 -29
- package/dist/core/store-contracts/file-history-store-contract.d.ts +11 -3
- package/dist/core/store-contracts/file-history-store-contract.js +62 -2
- 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/session-repo-contract.js +18 -0
- package/dist/core/store-contracts/session-store-contract.d.ts +15 -1
- package/dist/core/store-contracts/session-store-contract.js +211 -2
- package/dist/core/store-contracts/workflow-journal-store-contract.js +47 -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-limits.d.ts +15 -0
- package/dist/core/task-notification.d.ts +33 -7
- package/dist/core/task-notification.js +34 -9
- package/dist/core/task-registry-agent.d.ts +1 -1
- package/dist/core/task-registry-agent.js +18 -7
- package/dist/core/task-registry-shared.d.ts +29 -4
- package/dist/core/task-registry-shared.js +7 -0
- package/dist/core/task-registry.d.ts +21 -1
- package/dist/core/task-registry.js +36 -9
- package/dist/core/task-result.d.ts +55 -1
- package/dist/core/task-spec.d.ts +17 -3
- package/dist/core/terminal-cause.d.ts +68 -5
- package/dist/core/tool-catalog-entries.js +1 -1
- package/dist/core/tool-check-reading.js +2 -1
- package/dist/core/tool-errors.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-name-aliases.js +2 -3
- package/dist/core/tool-name-readings.d.ts +4 -0
- package/dist/core/tool-name-readings.js +1 -0
- package/dist/core/tool-policy.d.ts +46 -4
- package/dist/core/tool-policy.js +47 -18
- package/dist/core/tool-result-store.d.ts +0 -24
- package/dist/core/tool-result-store.js +1 -36
- package/dist/core/tool-spec.d.ts +8 -4
- package/dist/core/untrusted-egress.js +2 -2
- package/dist/core/untrusted-text.d.ts +8 -0
- package/dist/core/untrusted-text.js +14 -0
- package/dist/core/user-attachment.d.ts +16 -1
- package/dist/core/user-attachment.js +42 -18
- package/dist/core/wiring-manifest.d.ts +4 -9
- package/dist/core/wiring-manifest.js +1 -1
- package/dist/core/workflow-journal-store.d.ts +55 -8
- package/dist/core/workflow-journal-store.js +34 -10
- package/dist/core/workflow-run-store-contract.js +56 -1
- package/dist/core/workflow-run-store.d.ts +43 -19
- package/dist/core/workflow-run-store.js +17 -2
- package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
- package/dist/engine/execution-env/node-execution-env.js +4 -0
- package/dist/engine/harness/agent-harness.d.ts +10 -5
- package/dist/engine/harness/agent-harness.js +12 -4
- package/dist/engine/harness/types.d.ts +18 -0
- package/dist/engine/llm/tool-turns.d.ts +1 -1
- package/dist/engine/llm/types.d.ts +5 -4
- package/dist/engine/session/memory-repo.d.ts +15 -3
- package/dist/engine/session/memory-repo.js +21 -3
- package/dist/engine/session/memory-storage.d.ts +5 -0
- package/dist/engine/session/memory-storage.js +8 -3
- package/dist/engine/session/repo-utils.d.ts +9 -0
- package/dist/engine/session/repo-utils.js +14 -0
- package/dist/engine/session/storage-base.d.ts +20 -7
- package/dist/engine/session/storage-base.js +13 -1
- package/dist/index.d.ts +39 -21
- package/dist/index.js +32 -17
- package/dist/internal/harness.d.ts +1 -1
- package/dist/internal/harness.js +1 -1
- package/dist/orchestration/run-workflow-tool.d.ts +13 -1
- package/dist/orchestration/run-workflow-tool.js +101 -32
- package/dist/orchestration/workflow-park-adoption.d.ts +309 -92
- package/dist/orchestration/workflow-park-adoption.js +588 -323
- 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 +90 -11
- package/dist/orchestration/workflow-types.js +10 -1
- package/dist/orchestration/workflow.d.ts +30 -4
- package/dist/orchestration/workflow.js +424 -114
- 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 +61 -22
- package/dist/prompt-assembly/catalog/environment.js +2 -2
- package/dist/prompt-assembly/catalog/events.d.ts +16 -0
- package/dist/prompt-assembly/catalog/events.js +2 -0
- package/dist/prompt-assembly/catalog/locales/zh-Hans/core-behavior.js +72 -44
- package/dist/prompt-assembly/catalog/locales/zh-Hans/environment.js +2 -2
- package/dist/prompt-assembly/catalog/locales/zh-Hans/events.js +2 -0
- package/dist/prompt-assembly/catalog/schema.d.ts +5 -1
- package/dist/prompt-assembly/catalog/schema.js +2 -0
- package/dist/prompt-assembly/catalog/sections.js +3 -14
- package/dist/prompt-assembly/event-registry.js +2 -0
- package/dist/prompt-assembly/select.js +1 -0
- package/dist/prompt-assembly/tool-catalog.d.ts +10 -7
- package/dist/prompt-assembly/tool-catalog.js +21 -7
- package/dist/prompt-assembly/types.d.ts +3 -0
- package/dist/prompts/default.d.ts +4 -1
- package/dist/prompts/default.js +6 -0
- package/dist/stores/file/checkpoint-store.d.ts +11 -10
- package/dist/stores/file/checkpoint-store.js +36 -10
- package/dist/stores/file/file-history-store.d.ts +6 -0
- package/dist/stores/file/file-history-store.js +21 -4
- package/dist/stores/file/fs-atomic.d.ts +1 -1
- package/dist/stores/file/index.d.ts +14 -4
- package/dist/stores/file/index.js +21 -5
- package/dist/stores/file/process-anchor.d.ts +9 -1
- package/dist/stores/file/session-policy-store.js +2 -17
- package/dist/stores/file/session-store.d.ts +27 -0
- package/dist/stores/file/session-store.js +81 -9
- package/dist/stores/file/workflow-journal-store.d.ts +14 -4
- package/dist/stores/file/workflow-journal-store.js +32 -24
- package/dist/stores/file/workflow-run-store.d.ts +15 -4
- package/dist/stores/file/workflow-run-store.js +76 -0
- package/dist/tools/artifact/artifact-tool.d.ts +10 -3
- package/dist/tools/artifact/artifact-tool.js +16 -1
- package/dist/tools/fs/bash-program-position.d.ts +10 -4
- package/dist/tools/fs/bash-program-position.js +11 -8
- package/dist/tools/fs/bash-readonly-classifier.d.ts +3 -1
- package/dist/tools/fs/bash-readonly-classifier.js +9 -2
- package/dist/tools/fs/find-actions.d.ts +30 -16
- package/dist/tools/fs/find-actions.js +272 -19
- package/dist/tools/fs/fs-bash.js +8 -5
- package/dist/tools/fs/fs-shared.d.ts +0 -29
- package/dist/tools/fs/fs-shared.js +0 -5
- package/dist/tools/fs/fs-write.js +2 -1
- 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 +6 -0
- package/dist/tools/fs/read-floor.js +5 -1
- 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 +2 -21
- package/dist/tools/fs/removal-targets.js +2 -3
- package/dist/tools/fs/safety.d.ts +37 -1
- package/dist/tools/fs/safety.js +52 -0
- 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-check.js +47 -19
- package/dist/tools/fs/shell-read-establish.js +36 -22
- package/dist/tools/fs/shell-read-judge.d.ts +10 -2
- package/dist/tools/fs/shell-read-judge.js +4 -4
- package/dist/tools/fs/shell-read-plan.d.ts +3 -0
- package/dist/tools/fs/shell-read-plan.js +1 -1
- package/dist/tools/fs/shell-read-workdir.js +3 -2
- package/dist/tools/fs/shell-read-write-targets.d.ts +4 -3
- package/dist/tools/fs/shell-read-write-targets.js +3 -0
- package/package.json +2 -2
- package/test/export-surface.snapshot.json +173 -15
- package/wire-changes/core-stores-sql@7.71.0.json +40 -0
- package/wire-changes/core-stores-sql@7.71.1.json +40 -0
- package/wire-changes/core@7.71.0.json +5827 -0
- package/wire-changes/core@7.71.1.json +118 -0
- package/wire-changes/mods-kernel@7.71.0.json +52 -0
- package/wire-changes/mods-kernel@7.71.1.json +40 -0
- package/wire-changes/primitives@7.71.0.json +473 -0
- package/wire-changes/primitives@7.71.1.json +40 -0
- package/wire-changes/wiki-gate@7.71.0.json +40 -0
- package/wire-changes/wiki-gate@7.71.1.json +40 -0
- package/dist/core/frontmatter-fence.d.ts +0 -10
- package/dist/core/frontmatter-fence.js +0 -6
- package/dist/core/permission-rule-syntax.d.ts +0 -46
- package/dist/core/permission-rule-syntax.js +0 -52
|
@@ -16,11 +16,14 @@ import { ANONYMOUS_SCOPE, callScopeOf, isolationScopeOf } from "../core/isolatio
|
|
|
16
16
|
import { TERMINAL_CAUSE_IS_REPLAYABLE, isTerminalCauseKind } from "../core/terminal-cause.js";
|
|
17
17
|
import { terminalProjection } from "../core/runner/terminal-projection.js";
|
|
18
18
|
import { steeringError } from "../core/runner/steer-admission.js";
|
|
19
|
+
import { answeringOnce } from "../core/runner/delegation-owner.js";
|
|
19
20
|
import { builtinAgentDefinitions } from "../agents/builtin-agents.js";
|
|
20
21
|
import { GENERAL_PURPOSE_SUBAGENT_TYPE, markerFragment } from "../agents/subagent.js";
|
|
21
22
|
import { runnerRoleMap } from "../agents/child-model-seat.js";
|
|
22
23
|
import { namesRoleBase } from "../prompt-assembly/role-base.js";
|
|
23
24
|
import { createSafeNotifier } from "../core/safe-notify.js";
|
|
25
|
+
import { isWorkflowRunId, workflowRunCreationIdOf, WORKFLOW_RUN_ID_CHARACTERS } from "../core/workflow-run-store.js";
|
|
26
|
+
import { treeIdOf } from "./workflow-tree-id.js";
|
|
24
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";
|
|
25
28
|
import { isWorkflowRunActive, closeWorkflowChannel, markWorkflowActive, publishWorkflowEvent, readWorkflowParkedDecisions, registerWorkflowParkDelivery } from "./workflow-observe.js";
|
|
26
29
|
import { isDurablePause, resumeNeverStarted } from "../agents/suspend-guard.js";
|
|
@@ -42,13 +45,14 @@ import { snapshotAndValidateMcpEntries } from "../core/locked-config.js";
|
|
|
42
45
|
import { compileOutputSchema } from "../core/runner/strict-output-schema.js";
|
|
43
46
|
import { callerPlacementSeats } from "../core/runner/child-tree.js";
|
|
44
47
|
import { judgedOwnerSeat } from "../core/runner/delegation-owner.js";
|
|
45
|
-
import { WorkflowBudgetExceededError, WorkflowNestingError, WorkflowAgentBlockedError, WorkflowAgentParkedError, WorkflowAgentSchemaError, WorkflowAgentStalledError, WorkflowMaxAgentsError, WORKFLOW_SPAWN_BLOCKED_ERROR_CODE, WORKFLOW_AGENT_OUTLIVED_RUN_CODE, PARK_NOT_PENDING_STATUSES, WORKFLOW_STORE_WAIT_BOUND_MS,
|
|
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";
|
|
46
49
|
import { memberOutcomeOf, memberRefusalsOf } from "../core/member-outcome.js";
|
|
47
|
-
import {
|
|
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";
|
|
48
51
|
import { WorkflowScriptError } from "./workflow-meta.js";
|
|
49
52
|
import { firstByteLaneKnobMs, STALL_FIRST_BYTE_MS, STALL_FIRST_TOKEN_MS } from "../brain/timeout.js";
|
|
50
53
|
import { asThrownError, codedRefusal, isErrorLike, readMember, thrownIs, thrownName, thrownText } from "../core/thrown-value.js";
|
|
51
54
|
import { bindSettledRun } from "../core/workflow-settled-run.js";
|
|
55
|
+
import { nativeSignalOf } from "../core/native-signal.js";
|
|
52
56
|
import { persistTaskArtifact } from "../core/tool-result-store.js";
|
|
53
57
|
import { formatWorkflowRun, WORKFLOW_RECORD_WHOLE } from "../core/task-registry-shared.js";
|
|
54
58
|
const WORKFLOW_TOOL_NAME = (() => {
|
|
@@ -65,6 +69,7 @@ const MAX_ACTIVITY = 30;
|
|
|
65
69
|
const MAX_REVIEWED_SCHEMA_BYTES = 4096;
|
|
66
70
|
const MAX_REVIEW_REASON_CHARS = 500;
|
|
67
71
|
const MAX_REVIEWED_PROMPT_CHARS = 2_000;
|
|
72
|
+
const MAX_MEMBER_STOPPER_CHARS = 256;
|
|
68
73
|
const MAX_SCHEMA_WALK_DEPTH = 32;
|
|
69
74
|
function isUsableSchema(v) {
|
|
70
75
|
if (v === true)
|
|
@@ -335,6 +340,12 @@ function runStoreUnreadableRefusal(fromRunId, cause) {
|
|
|
335
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);
|
|
336
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" });
|
|
337
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
|
+
}
|
|
338
349
|
const workflowDepthStore = new AsyncLocalStorage();
|
|
339
350
|
function currentWorkflowDepth() {
|
|
340
351
|
return workflowDepthStore.getStore()?.depth ?? 0;
|
|
@@ -593,12 +604,18 @@ export const workflowResumeClaimFallback = {
|
|
|
593
604
|
export function takeWorkflowResumeClaim(store, input) {
|
|
594
605
|
if (store.resumeClaim === undefined)
|
|
595
606
|
return Promise.resolve({ ...workflowResumeClaimFallback.acquire(store, input), fallback: true });
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
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
|
+
});
|
|
602
619
|
}
|
|
603
620
|
export async function releaseWorkflowResumeClaim(store, input, fallback) {
|
|
604
621
|
if (fallback)
|
|
@@ -621,6 +638,12 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
621
638
|
const depth = Math.max(alsDepth, internalDepth ?? 0);
|
|
622
639
|
if (depth >= 1)
|
|
623
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
|
+
}
|
|
624
647
|
if (opts.resumeFromRunId !== undefined && opts.journalStore === undefined) {
|
|
625
648
|
throw new Error("runWorkflow: resumeFromRunId requires a journalStore to load the prior run's journal");
|
|
626
649
|
}
|
|
@@ -646,14 +669,17 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
646
669
|
}
|
|
647
670
|
const scope = seatScope ?? givenScope ?? ANONYMOUS_SCOPE;
|
|
648
671
|
const parkedResume = opts.parkedResume === undefined ? undefined : readWorkflowParkedDecisions(opts.parkedResume, "runWorkflow: parkedResume"), claimHolder = opts.holder;
|
|
672
|
+
const spentAtAdmission = new Set();
|
|
649
673
|
let launchUnkept = false;
|
|
650
|
-
const runId =
|
|
651
|
-
if (
|
|
652
|
-
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`);
|
|
653
677
|
}
|
|
654
678
|
if (opts.resumeFromRunId !== undefined && isWorkflowRunActive(opts.resumeFromRunId)) {
|
|
655
679
|
throw new Error(`startWorkflow: resumeFromRunId "${opts.resumeFromRunId}" is still an active workflow run in this process — stop it before resuming from it`);
|
|
656
680
|
}
|
|
681
|
+
let resumeFrom = opts.resumeFromRunId;
|
|
682
|
+
let resumeAsked = opts.resumeFromRunId !== undefined ? internals?.resumeAsked : undefined;
|
|
657
683
|
const concurrency = normalizeConcurrency(opts.concurrency);
|
|
658
684
|
const agentRegistry = workflowAgentRegistry(opts);
|
|
659
685
|
const holdKeeper = holdKeeperDeclarations(runner);
|
|
@@ -674,12 +700,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
674
700
|
const taskArtifacts = opts.taskArtifacts;
|
|
675
701
|
const cancelController = new AbortController();
|
|
676
702
|
const timeoutController = totalTimeoutMs !== undefined ? new AbortController() : undefined;
|
|
677
|
-
const
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
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
|
+
};
|
|
683
713
|
let timeoutTimer;
|
|
684
714
|
let keeperHold;
|
|
685
715
|
let storeRev = 0;
|
|
@@ -692,16 +722,36 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
692
722
|
let persistEpoch = 0;
|
|
693
723
|
let vouched = true;
|
|
694
724
|
let createAnswer;
|
|
695
|
-
const
|
|
725
|
+
const creationId = randomUUID();
|
|
726
|
+
const ownRow = (row) => row != null && row.id === runId && row.scope === scope && workflowRunCreationIdOf(row) === creationId;
|
|
727
|
+
let endingCreateSent = false;
|
|
696
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
|
+
};
|
|
697
738
|
const row = await s.get(runId);
|
|
698
|
-
if (
|
|
699
|
-
return { ok: false, cause: "not_own" };
|
|
700
|
-
if (row.status
|
|
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);
|
|
701
747
|
return { ok: true };
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
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
|
+
}
|
|
705
755
|
};
|
|
706
756
|
const persist = (mode, given) => {
|
|
707
757
|
if (!store)
|
|
@@ -727,7 +777,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
727
777
|
if (!vouched)
|
|
728
778
|
return await writeOwnRow(store, snapshot);
|
|
729
779
|
snapshot.rev = storeRev;
|
|
730
|
-
const won = await store.update(runId, scope, snapshot, { rev: storeRev });
|
|
780
|
+
const won = await store.update(runId, scope, snapshot, { rev: storeRev, creationId });
|
|
731
781
|
if (won)
|
|
732
782
|
storeRev += 1;
|
|
733
783
|
else
|
|
@@ -751,6 +801,8 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
751
801
|
const run = {
|
|
752
802
|
id: runId,
|
|
753
803
|
scope,
|
|
804
|
+
creationId,
|
|
805
|
+
...(opts.resumeFromRunId === undefined ? { treeId: runId } : {}),
|
|
754
806
|
...(opts.name !== undefined ? { name: opts.name } : {}),
|
|
755
807
|
...(opts.description !== undefined ? { description: opts.description } : {}),
|
|
756
808
|
...(opts.editedFrom !== undefined ? { editedFrom: { name: opts.editedFrom.name, contentHash: opts.editedFrom.contentHash } } : {}),
|
|
@@ -771,6 +823,12 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
771
823
|
startedAt: t0,
|
|
772
824
|
createdAt: t0,
|
|
773
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);
|
|
774
832
|
markWorkflowActive(runId, scope);
|
|
775
833
|
if (timeoutController) {
|
|
776
834
|
timeoutTimer = setTimeout(() => timeoutController.abort(new Error("workflow total timeout")), totalTimeoutMs);
|
|
@@ -803,7 +861,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
803
861
|
return outcome;
|
|
804
862
|
};
|
|
805
863
|
const withMember = (result, member) => ({ ...result, member });
|
|
806
|
-
const lateMember = (rec, result, provenance, facts) =>
|
|
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
|
+
};
|
|
807
869
|
const countAgentFailures = (phase) => run.agents.reduce((n, a) => n + (a.status === "failed" && (phase === undefined || agentPhaseOf.get(a) === phase) ? 1 : 0), 0);
|
|
808
870
|
const phaseFailureExtra = (p) => {
|
|
809
871
|
const n = countAgentFailures(p);
|
|
@@ -821,11 +883,30 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
821
883
|
}
|
|
822
884
|
};
|
|
823
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);
|
|
824
900
|
const closeAbandonedAgents = (endedAt) => {
|
|
825
|
-
const stopper = runStopper();
|
|
826
901
|
for (const a of run.agents) {
|
|
827
902
|
if (a.status === "running") {
|
|
903
|
+
const stopper = stopperOf(a.callKey);
|
|
904
|
+
if (stopper === undefined)
|
|
905
|
+
outlivedRun.add(a.callKey);
|
|
828
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);
|
|
829
910
|
a.endedAt = endedAt;
|
|
830
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 });
|
|
831
912
|
}
|
|
@@ -908,7 +989,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
908
989
|
...(opts.placementRoot !== undefined ? { placementRoot: opts.placementRoot } : {}),
|
|
909
990
|
...(opts.placementTarget !== undefined ? { placementTarget: opts.placementTarget } : {}),
|
|
910
991
|
...(opts.crossBoundaryTree !== undefined ? { crossBoundaryTree: opts.crossBoundaryTree } : {}),
|
|
911
|
-
...(opts.delegationOwner !== undefined ? { delegationOwner: opts.delegationOwner } : {}),
|
|
992
|
+
...(opts.delegationOwner !== undefined ? { delegationOwner: answeringOnce(opts.delegationOwner) } : {}),
|
|
912
993
|
...(opts.originatingSessionId !== undefined ? { parentSessionId: opts.originatingSessionId } : {}),
|
|
913
994
|
};
|
|
914
995
|
const captureFloorSeatsNow = async () => {
|
|
@@ -934,7 +1015,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
934
1015
|
return;
|
|
935
1016
|
const agentType = workflowLaunchTypeWord(asked, agentRegistry);
|
|
936
1017
|
const id = waIdOf(callKey);
|
|
937
|
-
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 });
|
|
938
1019
|
bceEmit({
|
|
939
1020
|
kind: "spawn",
|
|
940
1021
|
taskId: id,
|
|
@@ -1171,32 +1252,33 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1171
1252
|
const memberSeat = (callKey, label) => ({ workflowMember: memberAt(callKey, label) });
|
|
1172
1253
|
const memberStamp = (e, callKey, label) => stampWorkflowMember(e, memberAt(callKey, label));
|
|
1173
1254
|
const storeWithin = (p) => finalizeWithin(timers, p.then((value) => ({ ok: true, value }), () => ({ ok: false })), { ok: false }, true);
|
|
1174
|
-
let
|
|
1175
|
-
const
|
|
1255
|
+
let admissionTree;
|
|
1256
|
+
const treeAtAdmission = (fromRunId) => (admissionTree ??= store === undefined ? Promise.resolve("unreadable") : readWorkflowRunTreeWithin(store, fromRunId, scope, storeWithin));
|
|
1176
1257
|
const endOf = (r) => ({ runId: r.id, status: r.status, ...(r.errorCode !== undefined ? { errorCode: r.errorCode } : {}) });
|
|
1177
1258
|
const continuationThatTook = async (key, fromRunId) => {
|
|
1178
|
-
const
|
|
1179
|
-
if (typeof
|
|
1259
|
+
const tree = await treeAtAdmission(fromRunId);
|
|
1260
|
+
if (typeof tree === "string")
|
|
1180
1261
|
return undefined;
|
|
1181
|
-
const took = runThatDrove(
|
|
1262
|
+
const took = runThatDrove(workflowRunsBelow(tree, fromRunId).filter((r) => r.id !== runId), key.token, key.callKey);
|
|
1182
1263
|
return took === undefined ? undefined : endOf(took);
|
|
1183
1264
|
};
|
|
1184
1265
|
const continuedBeforeOf = async (fromRunId) => {
|
|
1185
|
-
const
|
|
1186
|
-
if (typeof
|
|
1266
|
+
const tree = await treeAtAdmission(fromRunId);
|
|
1267
|
+
if (typeof tree === "string")
|
|
1187
1268
|
return undefined;
|
|
1188
|
-
const earlier =
|
|
1269
|
+
const earlier = workflowRunChildrenIn(tree, fromRunId).filter((r) => r.id !== runId).sort((a, b) => b.startedAt - a.startedAt)[0];
|
|
1189
1270
|
return earlier === undefined ? undefined : endOf(earlier);
|
|
1190
1271
|
};
|
|
1191
1272
|
const PASS_ATTEMPTS = 3;
|
|
1192
1273
|
const passParksFrom = async (from, keys) => {
|
|
1193
1274
|
let open = keys;
|
|
1194
1275
|
for (let attempt = 0; attempt < PASS_ATTEMPTS && open.length > 0 && store !== undefined; attempt++) {
|
|
1195
|
-
const
|
|
1196
|
-
if (typeof
|
|
1276
|
+
const tree = await readWorkflowRunTreeWithin(store, from, scope, storeWithin);
|
|
1277
|
+
if (typeof tree === "string")
|
|
1197
1278
|
return;
|
|
1198
|
-
const
|
|
1199
|
-
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);
|
|
1200
1282
|
const stand = (key) => {
|
|
1201
1283
|
key.parkedBy = runId;
|
|
1202
1284
|
const settled = entryOf(key)?.settledDecisions;
|
|
@@ -1210,16 +1292,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1210
1292
|
const entry = entryOf(key);
|
|
1211
1293
|
if (entry === undefined || entry.passedTo !== undefined)
|
|
1212
1294
|
return false;
|
|
1213
|
-
const holder =
|
|
1295
|
+
const holder = parkHolderAmong(key.token, records);
|
|
1214
1296
|
return holder.kind === "held" && holder.runId === from;
|
|
1215
1297
|
});
|
|
1216
1298
|
if (open.length === 0)
|
|
1217
1299
|
return;
|
|
1218
|
-
const next = structuredClone(
|
|
1300
|
+
const next = structuredClone(named);
|
|
1219
1301
|
for (const p of next.parks ?? [])
|
|
1220
1302
|
if (p.parkedBy === from && open.some((key) => key.token === p.token))
|
|
1221
1303
|
p.passedTo = runId;
|
|
1222
|
-
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" })));
|
|
1223
1305
|
if (won.ok && won.value) {
|
|
1224
1306
|
for (const key of open)
|
|
1225
1307
|
stand(key);
|
|
@@ -1339,7 +1421,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1339
1421
|
wakeParksSettled();
|
|
1340
1422
|
};
|
|
1341
1423
|
};
|
|
1342
|
-
const parkedResumeFor = (token) => parkedResume?.find((d) => d.token === token);
|
|
1424
|
+
const parkedResumeFor = (token) => parkedResume?.find((d) => d.token === token && !spentAtAdmission.has(d));
|
|
1343
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) ` +
|
|
1344
1426
|
(divergence === undefined
|
|
1345
1427
|
? `while no earlier call diverged from the record — the difference is in this call's own inputs (${CALL_INPUTS_THAT_MOVE}). `
|
|
@@ -1359,6 +1441,9 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1359
1441
|
keeperHold?.release();
|
|
1360
1442
|
if (timeoutTimer)
|
|
1361
1443
|
clearTimeout(timeoutTimer);
|
|
1444
|
+
for (const f of hostSignals.values())
|
|
1445
|
+
f.release();
|
|
1446
|
+
hostSignals.clear();
|
|
1362
1447
|
};
|
|
1363
1448
|
const legStart = () => {
|
|
1364
1449
|
inFlightLegs += 1;
|
|
@@ -1424,7 +1509,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1424
1509
|
};
|
|
1425
1510
|
const parkMaterialOf = async (key, ordinal) => {
|
|
1426
1511
|
let entry;
|
|
1427
|
-
if (key.originRunId ===
|
|
1512
|
+
if (key.originRunId === resumeFrom)
|
|
1428
1513
|
entry = replayByOrdinal[ordinal];
|
|
1429
1514
|
else if (journalStore) {
|
|
1430
1515
|
const loaded = await finalizeWithin(timers, new Promise((resolve) => resolve(journalStore.load(key.originRunId, scope)))
|
|
@@ -1535,15 +1620,29 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1535
1620
|
results[at] = takenParkTokens.has(d.token) ? "already_taken" : "not_parked_here";
|
|
1536
1621
|
return;
|
|
1537
1622
|
}
|
|
1538
|
-
const was = d.decisionId === undefined ? undefined : workflowParkDecisionOf(d.token, d.decisionId, [run]);
|
|
1539
|
-
if (was?.kind === "spent") {
|
|
1540
|
-
emitRunLog(`[park] a decision for the parked leg "${w.rec.label.slice(0, 80)}" was not applied — it was already refused${was.code !== undefined ? ` (${withoutToken(was.code, w.key.token)})` : ""}; the park stands and needs a new decision.`);
|
|
1541
|
-
results[at] = "spent";
|
|
1542
|
-
return;
|
|
1543
|
-
}
|
|
1544
1623
|
takeParkWait(w);
|
|
1545
1624
|
taken.push({ at, w, d });
|
|
1546
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
|
+
}
|
|
1547
1646
|
for (const { at, w, d } of taken) {
|
|
1548
1647
|
const ordinal = callKeyOrdinal(w.rec.callKey);
|
|
1549
1648
|
let disposition;
|
|
@@ -1574,6 +1673,83 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1574
1673
|
}
|
|
1575
1674
|
return parkedLeg !== undefined || finalized ? ending() : { kind: "live", results };
|
|
1576
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
|
+
};
|
|
1577
1753
|
const assertChildParkSeat = (s) => {
|
|
1578
1754
|
const seat = s.checkpointStore;
|
|
1579
1755
|
if (seat === undefined || seat === "disabled")
|
|
@@ -1599,10 +1775,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1599
1775
|
});
|
|
1600
1776
|
};
|
|
1601
1777
|
let journalTail = Promise.resolve();
|
|
1778
|
+
let journalSealed = false;
|
|
1602
1779
|
const JOURNAL_DRAIN_MAX_MS = 5_000;
|
|
1603
1780
|
const awaitedAppends = new Map();
|
|
1604
1781
|
const lastAppendByCall = new Map();
|
|
1605
|
-
const trackJournalWrite = (append, callKey) => {
|
|
1782
|
+
const trackJournalWrite = (append, callKey, drainedLate = false) => {
|
|
1606
1783
|
const start = () => {
|
|
1607
1784
|
try {
|
|
1608
1785
|
return Promise.resolve(append());
|
|
@@ -1614,8 +1791,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1614
1791
|
const prior = lastAppendByCall.get(callKey);
|
|
1615
1792
|
const write = prior === undefined ? start() : prior.then(start, start);
|
|
1616
1793
|
lastAppendByCall.set(callKey, write.catch(() => undefined));
|
|
1617
|
-
if (finalized)
|
|
1794
|
+
if (finalized) {
|
|
1795
|
+
if (drainedLate && !journalSealed)
|
|
1796
|
+
journalTail = journalTail.then(() => write).catch(() => undefined);
|
|
1618
1797
|
return Promise.resolve();
|
|
1798
|
+
}
|
|
1619
1799
|
const written = new Promise((resolve, reject) => {
|
|
1620
1800
|
const handle = timers.setTimeout(() => {
|
|
1621
1801
|
awaitedAppends.delete(handle);
|
|
@@ -1648,7 +1828,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1648
1828
|
return result;
|
|
1649
1829
|
return { ...result, terminal: { ...t, message: boundedRedactedSummary(t.message, MAX_TRANSCRIPT_CHARS) } };
|
|
1650
1830
|
};
|
|
1651
|
-
const journalAppend = async (callKey, result, label) => {
|
|
1831
|
+
const journalAppend = async (callKey, result, label, stoppedBy) => {
|
|
1652
1832
|
const dbg = typeof process !== "undefined" && process.env?.SEMA_DEBUG_WORKFLOW_JOURNAL === "1";
|
|
1653
1833
|
const trace = (step) => {
|
|
1654
1834
|
if (dbg)
|
|
@@ -1658,6 +1838,10 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1658
1838
|
trace("SKIP (no journalStore on this run)");
|
|
1659
1839
|
return;
|
|
1660
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
|
+
}
|
|
1661
1845
|
const stored = journalDurableResult(result);
|
|
1662
1846
|
let serialized;
|
|
1663
1847
|
try {
|
|
@@ -1666,6 +1850,19 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1666
1850
|
catch {
|
|
1667
1851
|
serialized = undefined;
|
|
1668
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
|
+
}
|
|
1669
1866
|
if (serialized !== undefined && oversizeJournalResult(serialized)) {
|
|
1670
1867
|
const bytes = Buffer.byteLength(serialized, "utf8");
|
|
1671
1868
|
if (!finalized)
|
|
@@ -1692,6 +1889,24 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1692
1889
|
throw err;
|
|
1693
1890
|
}
|
|
1694
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
|
+
};
|
|
1695
1910
|
const journalAppendParked = async (callKey, paused) => {
|
|
1696
1911
|
if (!journalStore)
|
|
1697
1912
|
return false;
|
|
@@ -1880,7 +2095,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1880
2095
|
return;
|
|
1881
2096
|
if (first.cause === "timeout")
|
|
1882
2097
|
restartPersistTail();
|
|
1883
|
-
if (first.cause === "not_own") {
|
|
2098
|
+
if (first.cause === "not_own" && first.mayAppear !== true) {
|
|
1884
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.`);
|
|
1885
2100
|
afterAnswer.push(() => noOwnRow(ending));
|
|
1886
2101
|
return;
|
|
@@ -1957,7 +2172,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1957
2172
|
tries.state = "written";
|
|
1958
2173
|
return;
|
|
1959
2174
|
}
|
|
1960
|
-
if (last.cause === "not_own") {
|
|
2175
|
+
if (last.cause === "not_own" && last.mayAppear !== true) {
|
|
1961
2176
|
tries.state = "stopped";
|
|
1962
2177
|
noOwnRow(tries.ending);
|
|
1963
2178
|
return;
|
|
@@ -1987,10 +2202,10 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
1987
2202
|
readBackAndTell(tries, last);
|
|
1988
2203
|
};
|
|
1989
2204
|
const readBackAndTell = (tries, answered) => {
|
|
1990
|
-
if (answered.cause === "not_own")
|
|
2205
|
+
if (answered.cause === "not_own" && answered.mayAppear !== true)
|
|
1991
2206
|
return;
|
|
1992
|
-
const last = answered;
|
|
1993
|
-
const cause = answered.cause;
|
|
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;
|
|
1994
2209
|
void answeredWithin(async () => {
|
|
1995
2210
|
const row = await store?.get(runId);
|
|
1996
2211
|
return ownRow(row) ? { read: true, own: true, running: row.status === "running" } : { read: true, own: false, running: false };
|
|
@@ -2339,8 +2554,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2339
2554
|
const s = result.stats;
|
|
2340
2555
|
if (!counted)
|
|
2341
2556
|
accumulateStats(result);
|
|
2342
|
-
const stopper = result.terminal.kind === "failed" ?
|
|
2557
|
+
const stopper = result.terminal.kind === "failed" ? stopperOf(rec.callKey) : undefined;
|
|
2343
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) };
|
|
2344
2562
|
rec.taskStatus = terminalProjection(result.terminal).status;
|
|
2345
2563
|
foldAgentSession(rec, result);
|
|
2346
2564
|
setLegRunId(rec, result);
|
|
@@ -2360,7 +2578,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2360
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 });
|
|
2361
2579
|
void persist("update");
|
|
2362
2580
|
bceTerminal(rec.callKey, rec.status === "completed" ? "completed" : "failed", output, rec.stats);
|
|
2363
|
-
await journalAppend(rec.callKey, result, rec.label);
|
|
2581
|
+
await journalAppend(rec.callKey, result, rec.label, ownStop);
|
|
2364
2582
|
if (schemaUnmet !== undefined)
|
|
2365
2583
|
throw schemaUnmet;
|
|
2366
2584
|
return withMember(result, outcome);
|
|
@@ -2388,6 +2606,9 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2388
2606
|
throw parkedError();
|
|
2389
2607
|
if (drive !== undefined || opts.resumeFromRunId === undefined)
|
|
2390
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 };
|
|
2391
2612
|
const runAgain = () => {
|
|
2392
2613
|
const prior = replayByOrdinal[ordinal];
|
|
2393
2614
|
if (prior?.callKey === callKey && prior.result !== undefined && TERMINAL_CAUSE_IS_REPLAYABLE[prior.result.terminal.kind])
|
|
@@ -2427,9 +2648,9 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2427
2648
|
: `the journaled result was ${cached.result?.terminal?.kind ?? "(no terminal record)"}, not completed`);
|
|
2428
2649
|
return { kind: "live", drive: undefined };
|
|
2429
2650
|
};
|
|
2430
|
-
const replayAgent = async (call, r, agentOpts) => {
|
|
2651
|
+
const replayAgent = async (call, r, agentOpts, stoppedBy) => {
|
|
2431
2652
|
const { label, callKey, groupId, phase, phaseInstance, prompt } = call;
|
|
2432
|
-
const replayFacts = { from: "result", result: r, schemaRequested: Boolean(agentOpts.schema), parked: false };
|
|
2653
|
+
const replayFacts = { from: "result", result: r, schemaRequested: Boolean(agentOpts.schema), parked: false, ...(stoppedBy !== undefined ? { settled: { status: "killed", stoppedBy } } : {}) };
|
|
2433
2654
|
if (finalized)
|
|
2434
2655
|
return lateMember(undefined, r, "replayed", replayFacts);
|
|
2435
2656
|
const rs = r.stats;
|
|
@@ -2473,7 +2694,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2473
2694
|
bceTerminal(callKey, replayRec.status === "completed" ? "completed" : "failed", cachedOutput, replayRec.stats);
|
|
2474
2695
|
accumulateStats(r);
|
|
2475
2696
|
void persist("update");
|
|
2476
|
-
await journalAppend(callKey, r);
|
|
2697
|
+
await journalAppend(callKey, r, undefined, stoppedBy);
|
|
2477
2698
|
if (schemaUnmet !== undefined)
|
|
2478
2699
|
throw schemaUnmet;
|
|
2479
2700
|
return withMember(r, replayOutcome);
|
|
@@ -2488,6 +2709,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2488
2709
|
throw steeringError(`the task has already finished — workflow agent "${label}" was settled on this resume without running`);
|
|
2489
2710
|
},
|
|
2490
2711
|
result: () => settled,
|
|
2712
|
+
stop: () => stopMember(callKey, "parent"),
|
|
2491
2713
|
};
|
|
2492
2714
|
};
|
|
2493
2715
|
const ctx = {
|
|
@@ -2498,15 +2720,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2498
2720
|
emitRunLog(message);
|
|
2499
2721
|
},
|
|
2500
2722
|
async agent(spec, agentOpts = {}) {
|
|
2501
|
-
const
|
|
2723
|
+
const spawnSignal = assertAgentSpawnAllowed("ctx.agent", spec, agentOpts);
|
|
2502
2724
|
const { label, phase, phaseInstance, groupId, inheritedModelSnap, inheritedModelRef, inheritedModelError, inheritedThinkingSnap, callKey, place, prompt, model } = prepareAgentCall(spec, agentOpts);
|
|
2725
|
+
const effectiveSignal = memberSignalOf(callKey, spawnSignal);
|
|
2503
2726
|
const call = { label, callKey, groupId, phase, phaseInstance, prompt };
|
|
2504
2727
|
const arm = resumeArmOf(callKey, place);
|
|
2505
2728
|
const disposition = arm.kind === "dispose" ? arm.d : undefined;
|
|
2506
2729
|
if (disposition?.kind === "settle")
|
|
2507
2730
|
return await settleParkedCall(openDispositionRecord(disposition, call, agentOpts), disposition.result, [], agentOpts);
|
|
2508
2731
|
if (arm.kind === "replay")
|
|
2509
|
-
return await replayAgent(call, arm.result, agentOpts);
|
|
2732
|
+
return await replayAgent(call, arm.result, agentOpts, arm.stoppedBy);
|
|
2510
2733
|
let nextDrive = arm.kind === "live" ? arm.drive : undefined;
|
|
2511
2734
|
let rec;
|
|
2512
2735
|
if (disposition !== undefined) {
|
|
@@ -2609,7 +2832,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2609
2832
|
const attemptSpec = { ...runSpec, ...(attemptSessionId !== undefined ? { sessionId: attemptSessionId } : {}), signal: attemptCtl.signal, ...attemptYield?.spec };
|
|
2610
2833
|
if (attemptSessionId !== undefined && !finalized) {
|
|
2611
2834
|
bceBindSession(callKey, attemptSessionId);
|
|
2612
|
-
if (drive !== undefined || judgedOwnerSeat(
|
|
2835
|
+
if (drive !== undefined || judgedOwnerSeat(opts) === undefined)
|
|
2613
2836
|
verifyAgentSession(rec, attemptSessionId);
|
|
2614
2837
|
else
|
|
2615
2838
|
delete rec.sessionId;
|
|
@@ -2839,7 +3062,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2839
3062
|
rec.attempts = err.attempts;
|
|
2840
3063
|
rec.lastAttemptReason = "stalled";
|
|
2841
3064
|
}
|
|
2842
|
-
const stopper = thrownIs(err, WorkflowBudgetExceededError) ? undefined :
|
|
3065
|
+
const stopper = thrownIs(err, WorkflowBudgetExceededError) ? undefined : stopperOf(callKey);
|
|
2843
3066
|
const thrownOutcome = settleRowOutcome(rec, thrownIs(err, WorkflowBudgetExceededError)
|
|
2844
3067
|
? { from: "refused", budget: true }
|
|
2845
3068
|
: (() => {
|
|
@@ -2854,7 +3077,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2854
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 });
|
|
2855
3078
|
void persist("update");
|
|
2856
3079
|
release();
|
|
2857
|
-
const
|
|
3080
|
+
const thrownLeg = salvaged ?? {
|
|
2858
3081
|
taskId: callKey,
|
|
2859
3082
|
sessionId: "",
|
|
2860
3083
|
result: boundedRedactedSummary(thrownText(err), 500), resultEntryIds: [],
|
|
@@ -2865,10 +3088,15 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2865
3088
|
message: boundedRedactedSummary(thrownText(err), 500),
|
|
2866
3089
|
},
|
|
2867
3090
|
stats: { turns: 0, tokens: 0, costMicroUsd: 0, usageMissing: true },
|
|
2868
|
-
}
|
|
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);
|
|
2869
3095
|
if (!((thrownIs(err, WorkflowBudgetExceededError) || thrownIs(err, WorkflowAgentParkedError)) && rec.startedAt === undefined))
|
|
2870
3096
|
await journaled;
|
|
2871
3097
|
bceTerminal(callKey, "failed", rec.output ?? (thrownText(err)), rec.stats);
|
|
3098
|
+
if (ownStop !== undefined)
|
|
3099
|
+
return withMember(stoppedLeg, thrownOutcome);
|
|
2872
3100
|
}
|
|
2873
3101
|
throw err;
|
|
2874
3102
|
}
|
|
@@ -2895,15 +3123,16 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2895
3123
|
}
|
|
2896
3124
|
},
|
|
2897
3125
|
async agentStream(spec, agentOpts = {}) {
|
|
2898
|
-
const
|
|
3126
|
+
const spawnSignal = assertAgentSpawnAllowed("ctx.agentStream", spec, agentOpts);
|
|
2899
3127
|
const { label, phase, phaseInstance, groupId, inheritedModelSnap, inheritedModelRef, inheritedModelError, inheritedThinkingSnap, callKey, place, prompt, model } = prepareAgentCall(spec, agentOpts);
|
|
3128
|
+
const effectiveSignal = memberSignalOf(callKey, spawnSignal);
|
|
2900
3129
|
const call = { label, callKey, groupId, phase, phaseInstance, prompt };
|
|
2901
3130
|
const arm = resumeArmOf(callKey, place);
|
|
2902
3131
|
const disposition = arm.kind === "dispose" ? arm.d : undefined;
|
|
2903
3132
|
if (disposition?.kind === "settle")
|
|
2904
3133
|
return settledHandle(label, callKey, Promise.resolve(await settleParkedCall(openDispositionRecord(disposition, call, agentOpts), disposition.result, [], agentOpts)));
|
|
2905
3134
|
if (arm.kind === "replay")
|
|
2906
|
-
return settledHandle(label, callKey, replayAgent(call, arm.result, agentOpts));
|
|
3135
|
+
return settledHandle(label, callKey, replayAgent(call, arm.result, agentOpts, arm.stoppedBy));
|
|
2907
3136
|
let rec;
|
|
2908
3137
|
if (disposition !== undefined) {
|
|
2909
3138
|
rec = openDispositionRecord(disposition, call, agentOpts);
|
|
@@ -2935,7 +3164,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2935
3164
|
};
|
|
2936
3165
|
const recordFailed = (facts) => {
|
|
2937
3166
|
if (!finalized) {
|
|
2938
|
-
const stopper =
|
|
3167
|
+
const stopper = stopperOf(callKey);
|
|
2939
3168
|
const outcome = settleRowOutcome(rec, facts ?? (stopper !== undefined ? { from: "ended", status: "killed", stoppedBy: stopper } : { from: "ended", status: "failed", ...(rec.errorCode !== undefined ? { code: rec.errorCode } : {}) }));
|
|
2940
3169
|
rec.endedAt = now();
|
|
2941
3170
|
emit({ type: "agent_end", runId, label, phase, ...(groupId !== undefined ? { groupId } : {}), status: "failed", ...(rec.errorCode !== undefined ? { errorCode: rec.errorCode } : {}), ts: rec.endedAt });
|
|
@@ -2951,8 +3180,21 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
2951
3180
|
};
|
|
2952
3181
|
try {
|
|
2953
3182
|
if (effectiveSignal?.aborted || finalized) {
|
|
2954
|
-
recordFailed();
|
|
3183
|
+
const queuedOutcome = recordFailed();
|
|
2955
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
|
+
}
|
|
2956
3198
|
throw new Error(finalized ? "workflow run already finalized — ctx.agentStream cannot spawn after the run ended" : "workflow aborted");
|
|
2957
3199
|
}
|
|
2958
3200
|
if (parkedLeg !== undefined && drive === undefined) {
|
|
@@ -3091,7 +3333,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3091
3333
|
bceTerminal(callKey, "failed", thrownText(err), undefined);
|
|
3092
3334
|
throw err;
|
|
3093
3335
|
}
|
|
3094
|
-
if ((drive !== undefined || judgedOwnerSeat(
|
|
3336
|
+
if ((drive !== undefined || judgedOwnerSeat(opts) === undefined) && childSessionId !== undefined && !finalized) {
|
|
3095
3337
|
verifyAgentSession(rec, childSessionId);
|
|
3096
3338
|
void persist("update");
|
|
3097
3339
|
}
|
|
@@ -3139,21 +3381,27 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3139
3381
|
if (!finalized && partialSpend !== undefined && (partialSpend.tokens > 0 || partialSpend.turns > 0 || (partialSpend.costMicroUsd ?? 0) > 0)) {
|
|
3140
3382
|
accumulateStats({ stats: partialSpend });
|
|
3141
3383
|
}
|
|
3384
|
+
let failedOutcome;
|
|
3142
3385
|
try {
|
|
3143
|
-
recordFailed();
|
|
3386
|
+
failedOutcome = recordFailed();
|
|
3144
3387
|
}
|
|
3145
3388
|
finally {
|
|
3146
3389
|
releaseLeg();
|
|
3147
3390
|
}
|
|
3148
|
-
|
|
3391
|
+
const thrownLeg = {
|
|
3149
3392
|
taskId: callKey,
|
|
3150
3393
|
sessionId: "",
|
|
3151
3394
|
terminal: { kind: "failed", message: boundedRedactedSummary(thrownText(err), 500) },
|
|
3152
3395
|
result: boundedRedactedSummary(thrownText(err), 500), resultEntryIds: [],
|
|
3153
3396
|
continuesFrom: { none: "unsettled" },
|
|
3154
3397
|
stats: { turns: partialSpend?.turns ?? 0, tokens: partialSpend?.tokens ?? 0, costMicroUsd: partialSpend?.costMicroUsd ?? 0 },
|
|
3155
|
-
}
|
|
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);
|
|
3156
3402
|
bceTerminal(callKey, "failed", thrownText(err), rec.stats);
|
|
3403
|
+
if (ownStop !== undefined && failedOutcome !== undefined)
|
|
3404
|
+
return withMember(stoppedLeg, failedOutcome);
|
|
3157
3405
|
throw err;
|
|
3158
3406
|
}
|
|
3159
3407
|
rollbackUsageBeat();
|
|
@@ -3178,7 +3426,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3178
3426
|
}
|
|
3179
3427
|
})();
|
|
3180
3428
|
completion.catch(() => undefined);
|
|
3181
|
-
return { runId, label, callKey, steer, result: () => completion };
|
|
3429
|
+
return { runId, label, callKey, steer, result: () => completion, stop: () => stopMember(callKey, "parent") };
|
|
3182
3430
|
},
|
|
3183
3431
|
async parallel(thunks, fanOutOpts) {
|
|
3184
3432
|
const list = snapshotFanOutList("parallel", "the thunk list", thunks);
|
|
@@ -3353,7 +3601,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3353
3601
|
if (run.resume === undefined)
|
|
3354
3602
|
return;
|
|
3355
3603
|
for (const entry of parkedResume ?? []) {
|
|
3356
|
-
if (entry.decisionId === undefined)
|
|
3604
|
+
if (entry.decisionId === undefined || spentAtAdmission.has(entry))
|
|
3357
3605
|
continue;
|
|
3358
3606
|
const key = run.parks?.find((p) => p.token === entry.token);
|
|
3359
3607
|
if (key === undefined || run.decisions?.some((d) => d.decisionId === entry.decisionId && d.callKey === key.callKey) === true)
|
|
@@ -3390,44 +3638,97 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3390
3638
|
}
|
|
3391
3639
|
if (opts.resumeFromRunId !== undefined && journalStore) {
|
|
3392
3640
|
const usingFallback = journalStore.resumeClaim === undefined;
|
|
3641
|
+
const named = opts.resumeFromRunId;
|
|
3393
3642
|
let walkThrew;
|
|
3394
3643
|
const walkWithin = (p) => storeWithin(p.catch((err) => ((walkThrew ??= { err }), Promise.reject(err))));
|
|
3395
|
-
const
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
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.`);
|
|
3400
3661
|
if (finalized)
|
|
3401
3662
|
throw new Error("workflow run already finalized — its resume admission takes no claim after the run ended");
|
|
3402
|
-
const verdict = takeWorkflowResumeClaim(journalStore, { sourceRunId:
|
|
3403
|
-
resumeClaim = { sourceRunId:
|
|
3404
|
-
|
|
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
|
+
}
|
|
3405
3672
|
if (!decision.granted) {
|
|
3406
|
-
const
|
|
3407
|
-
const
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
|
|
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.`);
|
|
3684
|
+
}
|
|
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
|
+
}
|
|
3414
3712
|
}
|
|
3415
|
-
|
|
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));
|
|
3416
3717
|
for (const e of entries) {
|
|
3417
3718
|
const ordinal = callKeyOrdinal(e.callKey);
|
|
3418
3719
|
if (e.parked === undefined) {
|
|
3419
|
-
const t = e.result.terminal;
|
|
3720
|
+
const t = (e.result ?? e.stopped?.result)?.terminal;
|
|
3420
3721
|
if (t === null || typeof t !== "object" || !isTerminalCauseKind(t.kind)) {
|
|
3421
|
-
throw new WorkflowJournalIncompatibleError(
|
|
3722
|
+
throw new WorkflowJournalIncompatibleError(from, ordinal);
|
|
3422
3723
|
}
|
|
3423
3724
|
}
|
|
3424
3725
|
replayByOrdinal[ordinal] = e;
|
|
3425
3726
|
}
|
|
3426
|
-
const fromRunId = clampRunIdText(
|
|
3727
|
+
const fromRunId = clampRunIdText(from);
|
|
3427
3728
|
let prior = null;
|
|
3428
3729
|
if (opts.store !== undefined) {
|
|
3429
3730
|
try {
|
|
3430
|
-
prior = await opts.store.get(
|
|
3731
|
+
prior = await opts.store.get(from);
|
|
3431
3732
|
}
|
|
3432
3733
|
catch (err) {
|
|
3433
3734
|
throw runStoreUnreadableRefusal(fromRunId, { err });
|
|
@@ -3436,7 +3737,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3436
3737
|
prior = null;
|
|
3437
3738
|
}
|
|
3438
3739
|
if (opts.store !== undefined && prior === null)
|
|
3439
|
-
throw
|
|
3740
|
+
throw priorRecordMissingRefusal(fromRunId);
|
|
3440
3741
|
if (parkSeat !== undefined && prior !== null && prior.status === "running")
|
|
3441
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" });
|
|
3442
3743
|
if (prior?.resumeAdmissionIncomplete === true)
|
|
@@ -3469,9 +3770,9 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3469
3770
|
for (const [ord, e] of replayByOrdinal.entries()) {
|
|
3470
3771
|
if (e?.parked === undefined)
|
|
3471
3772
|
continue;
|
|
3472
|
-
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 });
|
|
3473
3774
|
const settled = candidates.get(ord);
|
|
3474
|
-
settled.originRunId =
|
|
3775
|
+
settled.originRunId = from;
|
|
3475
3776
|
delete settled.originUnconfirmed;
|
|
3476
3777
|
}
|
|
3477
3778
|
for (const rec of recordParks === undefined && Array.isArray(prior?.agents) ? prior.agents : []) {
|
|
@@ -3479,13 +3780,13 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3479
3780
|
continue;
|
|
3480
3781
|
if (typeof rec.callKey !== "string" || !/^\d+:/.test(rec.callKey))
|
|
3481
3782
|
throw parkBindingBroken(-1, "a parked agent row is malformed or its call key has no ordinal");
|
|
3482
|
-
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 });
|
|
3483
3784
|
}
|
|
3484
3785
|
if (noParksList && candidates.size === 0)
|
|
3485
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)");
|
|
3486
3787
|
const inherited = [];
|
|
3487
3788
|
for (const [ord, key] of [...candidates.entries()].sort((a, b) => a[0] - b[0])) {
|
|
3488
|
-
if (replayByOrdinal[ord]?.result !== undefined)
|
|
3789
|
+
if (replayByOrdinal[ord]?.result !== undefined || replayByOrdinal[ord]?.stopped !== undefined)
|
|
3489
3790
|
continue;
|
|
3490
3791
|
inherited.push(key);
|
|
3491
3792
|
}
|
|
@@ -3498,7 +3799,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3498
3799
|
const seen = placeAtOrdinal.get(ord);
|
|
3499
3800
|
const recordedAt = position === null ? undefined : recordedOrdinalOfPosition.get(position);
|
|
3500
3801
|
if ((seen !== undefined && seen !== position) || (recordedAt !== undefined && recordedAt !== ord))
|
|
3501
|
-
throw new WorkflowJournalIncompatibleError(
|
|
3802
|
+
throw new WorkflowJournalIncompatibleError(from, ord);
|
|
3502
3803
|
placeAtOrdinal.set(ord, position);
|
|
3503
3804
|
recordedOrdinals.add(ord);
|
|
3504
3805
|
marked ||= callKey.includes("@");
|
|
@@ -3545,15 +3846,19 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3545
3846
|
parkedByOrdinal[ord] = truth;
|
|
3546
3847
|
}
|
|
3547
3848
|
}
|
|
3849
|
+
const fromCreationId = prior === null ? null : workflowRunCreationIdOf(prior);
|
|
3850
|
+
const treeOfPrior = store === undefined || prior === null ? undefined : await treeIdOf(store, prior, scope, storeWithin);
|
|
3548
3851
|
if (!finalized) {
|
|
3549
3852
|
for (const key of inherited)
|
|
3550
3853
|
if (key.generation !== undefined)
|
|
3551
3854
|
key.generation += 1;
|
|
3552
3855
|
run.parks = inherited;
|
|
3553
3856
|
delete run.resumeAdmissionIncomplete;
|
|
3554
|
-
run.resume = { fromRunId, journalEntries: entries.length, replayed: 0 };
|
|
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;
|
|
3555
3860
|
}
|
|
3556
|
-
const continuedBefore = await continuedBeforeOf(
|
|
3861
|
+
const continuedBefore = await continuedBeforeOf(from);
|
|
3557
3862
|
workflowSignal.throwIfAborted();
|
|
3558
3863
|
if (continuedBefore !== undefined && run.resume !== undefined)
|
|
3559
3864
|
run.resume = { ...run.resume, continuedBefore };
|
|
@@ -3659,10 +3964,8 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3659
3964
|
closeAbandonedAgents(run.endedAt);
|
|
3660
3965
|
{
|
|
3661
3966
|
const thrownCode = readMember(err, "code");
|
|
3662
|
-
const
|
|
3663
|
-
|
|
3664
|
-
.sort((a, b) => (a.endedAt ?? Number.POSITIVE_INFINITY) - (b.endedAt ?? Number.POSITIVE_INFINITY))[0];
|
|
3665
|
-
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);
|
|
3666
3969
|
if (code !== undefined)
|
|
3667
3970
|
run.errorCode = code;
|
|
3668
3971
|
}
|
|
@@ -3688,6 +3991,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3688
3991
|
latchFinalized();
|
|
3689
3992
|
yieldIntent?.removeEventListener("abort", onYieldIntent);
|
|
3690
3993
|
yieldLegs.clear();
|
|
3994
|
+
journalSealed = true;
|
|
3691
3995
|
await new Promise((resolve) => {
|
|
3692
3996
|
const t = setTimeout(() => {
|
|
3693
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.`);
|
|
@@ -3746,6 +4050,12 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
|
|
|
3746
4050
|
done,
|
|
3747
4051
|
cancel: (reason) => cancelController.abort(reason ? new Error(reason) : undefined),
|
|
3748
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
|
+
},
|
|
3749
4059
|
recordLanded: () => recordLanded.then((o) => o.ok),
|
|
3750
4060
|
};
|
|
3751
4061
|
}
|