@sema-agent/core 7.72.0 → 7.74.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 +565 -0
- package/dist/agents/inherited-tool-pool.d.ts +26 -1
- package/dist/agents/inherited-tool-pool.js +46 -2
- package/dist/agents/list-agents-tool.js +1 -1
- package/dist/agents/parked-resume-drive.d.ts +10 -0
- package/dist/agents/parked-resume-drive.js +9 -0
- package/dist/agents/retain-ledger.d.ts +3 -0
- package/dist/agents/retain-ledger.js +3 -3
- package/dist/agents/send-message-tool.js +5 -4
- package/dist/agents/send-user-message-tool.d.ts +12 -0
- package/dist/agents/send-user-message-tool.js +67 -0
- package/dist/agents/subagent-steps.d.ts +9 -0
- package/dist/agents/subagent-steps.js +38 -0
- package/dist/agents/subagent.d.ts +2 -0
- package/dist/agents/subagent.js +43 -12
- package/dist/agents/verify.js +23 -8
- package/dist/agents/yield-adoption.js +3 -1
- package/dist/brain/anthropic.d.ts +42 -1
- package/dist/brain/anthropic.js +68 -13
- package/dist/brain/failover.d.ts +5 -0
- package/dist/brain/failover.js +51 -22
- package/dist/brain/model-lane.d.ts +12 -3
- package/dist/brain/model-lane.js +5 -5
- package/dist/brain/open-responses.js +7 -8
- package/dist/brain/openai.js +31 -24
- package/dist/brain/route-adjudicator.d.ts +33 -4
- package/dist/brain/route-adjudicator.js +49 -12
- package/dist/brain/stream-engine.js +166 -156
- package/dist/brain/stream-shared.d.ts +4 -3
- package/dist/brain/stream-shared.js +2 -2
- package/dist/core/actions-digest.d.ts +43 -0
- package/dist/core/actions-digest.js +22 -0
- package/dist/core/allow-entry.js +4 -4
- package/dist/core/ask-class.d.ts +2 -2
- package/dist/core/ask-headline.d.ts +1 -1
- package/dist/core/ask-origin.d.ts +44 -4
- package/dist/core/ask-origin.js +29 -10
- package/dist/core/auto-mode.d.ts +7 -9
- package/dist/core/auto-mode.js +114 -8
- package/dist/core/background-agent-store.d.ts +1 -0
- package/dist/core/background-agent-store.js +49 -8
- package/dist/core/checkpoint-features.d.ts +3 -2
- package/dist/core/checkpoint-features.js +1 -1
- package/dist/core/checkpoint-rekey.d.ts +1 -1
- package/dist/core/checkpoint-rekey.js +6 -1
- package/dist/core/checkpoint-requirements.d.ts +23 -3
- package/dist/core/checkpoint-requirements.js +5 -1
- package/dist/core/checkpoint-row-verdict.d.ts +1 -1
- package/dist/core/checkpoint-row-verdict.js +9 -3
- package/dist/core/checkpoint-store.d.ts +26 -2
- package/dist/core/checkpoint-store.js +9 -2
- package/dist/core/child-clamp-seats.d.ts +15 -0
- package/dist/core/child-clamp-seats.js +15 -0
- package/dist/core/config-refusal-codes.d.ts +1 -1
- package/dist/core/config-refusal-codes.js +1 -0
- package/dist/core/cron.js +9 -1
- package/dist/core/delegation-frames.d.ts +1 -0
- package/dist/core/delegation-frames.js +1 -1
- package/dist/core/deployment-shape.d.ts +7 -0
- package/dist/core/deployment-shape.js +19 -0
- package/dist/core/engine-capabilities.d.ts +13 -1
- package/dist/core/engine-capabilities.js +1 -1
- package/dist/core/engine-notice.d.ts +41 -28
- package/dist/core/engine-version.js +1 -1
- package/dist/core/entries-not-applied.d.ts +19 -7
- package/dist/core/entries-not-applied.js +33 -1
- package/dist/core/gate-fold.js +5 -4
- package/dist/core/gate-lanes.js +8 -12
- package/dist/core/gate-outcome.d.ts +8 -2
- package/dist/core/gate-outcome.js +10 -3
- package/dist/core/governance-codes.d.ts +14 -2
- package/dist/core/governance-codes.js +22 -6
- package/dist/core/hook-condition.d.ts +37 -0
- package/dist/core/hook-condition.js +567 -0
- package/dist/core/hooks.d.ts +5 -0
- package/dist/core/hooks.js +1 -0
- package/dist/core/host-instance.d.ts +23 -0
- package/dist/core/host-instance.js +69 -0
- package/dist/core/instruction-preview.d.ts +63 -0
- package/dist/core/instruction-preview.js +406 -0
- package/dist/core/leg-budget.d.ts +26 -0
- package/dist/core/leg-budget.js +9 -0
- package/dist/core/leg-identity.d.ts +51 -1
- package/dist/core/leg-identity.js +45 -2
- package/dist/core/manager-launch-check.d.ts +48 -0
- package/dist/core/manager-launch-check.js +64 -0
- package/dist/core/mcp-call-meta.d.ts +2 -2
- package/dist/core/mcp-injection-drop.d.ts +20 -10
- package/dist/core/mcp-injection-drop.js +9 -3
- package/dist/core/mcp-server-spec.d.ts +2 -1
- package/dist/core/member-outcome.d.ts +3 -2
- package/dist/core/member-outcome.js +1 -1
- package/dist/core/memory-engine/deletion-record.d.ts +46 -0
- package/dist/core/memory-engine/deletion-record.js +96 -0
- package/dist/core/memory-engine/engine.js +24 -16
- package/dist/core/memory-engine/file-backend.js +7 -5
- package/dist/core/memory-engine/projection-ledger.d.ts +1 -1
- package/dist/core/memory-engine/projection-ledger.js +1 -1
- package/dist/core/memory-engine/scope-contract.d.ts +18 -13
- package/dist/core/memory-engine/scope-contract.js +18 -18
- package/dist/core/memory-engine/sync-client.js +26 -6
- package/dist/core/memory-engine/sync.d.ts +20 -2
- package/dist/core/memory-engine/sync.js +18 -17
- package/dist/core/mode-policy.d.ts +25 -6
- package/dist/core/mode-policy.js +33 -8
- package/dist/core/model-seat.d.ts +8 -5
- package/dist/core/model-shell.d.ts +129 -0
- package/dist/core/model-shell.js +249 -0
- package/dist/core/mods/kernel/digest.d.ts +4 -0
- package/dist/core/mods/kernel/digest.js +5 -0
- package/dist/core/mods/kernel/dispatch.d.ts +3 -0
- package/dist/core/mods/kernel/dispatch.js +15 -6
- package/dist/core/mods/kernel/events.d.ts +21 -5
- package/dist/core/mods/kernel/events.js +19 -10
- package/dist/core/mods/kernel/hash-mirror.d.ts +1 -0
- package/dist/core/mods/kernel/hash-mirror.js +55 -0
- package/dist/core/mods/kernel/index.d.ts +1 -0
- package/dist/core/mods/kernel/index.js +1 -0
- package/dist/core/mods/kernel/package-reader.d.ts +48 -0
- package/dist/core/mods/kernel/package-reader.js +149 -0
- package/dist/core/mods/kernel/site-rules.d.ts +4 -0
- package/dist/core/mods/kernel/site-rules.js +13 -0
- package/dist/core/mods/package.d.ts +7 -3
- package/dist/core/mods/package.js +47 -80
- package/dist/core/own-property-receipt.js +11 -4
- package/dist/core/parent-spec-seat.d.ts +13 -11
- package/dist/core/parent-spec-seat.js +13 -9
- package/dist/core/peer-seat.js +3 -3
- package/dist/core/peer-task-store.d.ts +365 -0
- package/dist/core/peer-task-store.js +682 -0
- package/dist/core/permission-rule-consent.js +6 -11
- package/dist/core/permission-rule-model.d.ts +27 -0
- package/dist/core/permission-rule-model.js +33 -5
- package/dist/core/permission-rule-org.js +13 -3
- package/dist/core/permission-rule-provider.d.ts +35 -33
- package/dist/core/permission-rule-provider.js +38 -295
- package/dist/core/permission-rule-store.d.ts +181 -8
- package/dist/core/permission-rule-store.js +420 -17
- package/dist/core/permission-rule-sync.js +15 -1
- package/dist/core/permission-rules.js +4 -1
- package/dist/core/project-seat.d.ts +55 -0
- package/dist/core/project-seat.js +96 -0
- package/dist/core/protocol-http-auth.d.ts +3 -2
- package/dist/core/protocol-http-auth.js +26 -18
- package/dist/core/remote-env.d.ts +4 -4
- package/dist/core/retain-seat.d.ts +42 -0
- package/dist/core/retain-seat.js +76 -0
- package/dist/core/retired-keys.js +1 -0
- package/dist/core/rewind-refusal-codes.d.ts +8 -0
- package/dist/core/rewind-refusal-codes.js +12 -0
- package/dist/core/roles.d.ts +2 -2
- package/dist/core/roles.js +15 -1
- package/dist/core/rule-offer-read.d.ts +1 -1
- package/dist/core/rule-offer-read.js +32 -4
- package/dist/core/rule-store-fault.d.ts +9 -7
- package/dist/core/rule-store-fault.js +8 -3
- package/dist/core/run-ledger-seat.d.ts +66 -0
- package/dist/core/run-ledger-seat.js +70 -0
- package/dist/core/run-ledger.d.ts +332 -0
- package/dist/core/run-ledger.js +550 -0
- package/dist/core/runner/checkpoint-scope.d.ts +14 -3
- package/dist/core/runner/checkpoint-scope.js +16 -6
- package/dist/core/runner/compact-session.js +1 -1
- package/dist/core/runner/construction-doors.js +8 -0
- package/dist/core/runner/contracts.d.ts +21 -5
- package/dist/core/runner/cross-boundary-lane.d.ts +8 -1
- package/dist/core/runner/cross-boundary-lane.js +4 -0
- package/dist/core/runner/delegation-owner.d.ts +30 -0
- package/dist/core/runner/delegation-owner.js +20 -4
- package/dist/core/runner/finish-reason-seat.js +4 -2
- package/dist/core/runner/gate-exit.d.ts +7 -0
- package/dist/core/runner/gate-exit.js +2 -1
- package/dist/core/runner/leg-frame.js +3 -0
- package/dist/core/runner/model-lane-seat.d.ts +3 -0
- package/dist/core/runner/model-lane-seat.js +4 -0
- package/dist/core/runner/nested-memory-lane.d.ts +22 -5
- package/dist/core/runner/nested-memory-lane.js +91 -30
- package/dist/core/runner/person-path-rows.d.ts +27 -16
- package/dist/core/runner/person-path-rows.js +93 -15
- package/dist/core/runner/prepare-caps-and-workflow.js +98 -88
- package/dist/core/runner/prepare-config-doors.d.ts +1 -0
- package/dist/core/runner/prepare-config-doors.js +13 -7
- package/dist/core/runner/prepare-context-lane.js +1 -0
- package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
- package/dist/core/runner/prepare-delegation-surface.js +6 -0
- package/dist/core/runner/prepare-execution-env.d.ts +3 -3
- package/dist/core/runner/prepare-gate-stations.d.ts +6 -0
- package/dist/core/runner/prepare-gate-stations.js +3 -1
- package/dist/core/runner/prepare-hands-readface.d.ts +5 -2
- package/dist/core/runner/prepare-hands-readface.js +15 -3
- package/dist/core/runner/prepare-inherited-gate.d.ts +6 -3
- package/dist/core/runner/prepare-inherited-gate.js +13 -5
- package/dist/core/runner/prepare-offload-wrappers.js +1 -1
- package/dist/core/runner/prepare-run-refs.d.ts +1 -1
- package/dist/core/runner/prepare-run-refs.js +3 -2
- package/dist/core/runner/prepare-suspend-saga.d.ts +6 -2
- package/dist/core/runner/prepare-suspend-saga.js +4 -2
- package/dist/core/runner/prepare-task.js +42 -30
- package/dist/core/runner/prepare-turn-wiring.d.ts +4 -3
- package/dist/core/runner/prepare-turn-wiring.js +2 -1
- package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
- package/dist/core/runner/prepare-wiring-manifest.js +8 -6
- package/dist/core/runner/resume-apply.js +11 -5
- package/dist/core/runner/resume-policy-outcome.js +5 -2
- package/dist/core/runner/resume-review-outcome.d.ts +3 -0
- package/dist/core/runner/resume-review-outcome.js +24 -1
- package/dist/core/runner/role-seat-defaulted.d.ts +3 -3
- package/dist/core/runner/role-seat-defaulted.js +1 -1
- package/dist/core/runner/rule-store-unreadable-notice.d.ts +1 -1
- package/dist/core/runner/rule-store-unreadable-notice.js +3 -3
- package/dist/core/runner/run-harness-handlers.js +4 -1
- package/dist/core/runner/run-identity-wiring.js +3 -2
- package/dist/core/runner/run-leg.js +5 -2
- package/dist/core/runner/run-notification-lane.js +20 -1
- package/dist/core/runner/run-settle-and-teardown.js +21 -12
- package/dist/core/runner/run-stop-and-final-verify.js +6 -0
- package/dist/core/runner/run-telemetry-and-budget-seats.js +1 -1
- package/dist/core/runner/runtask.d.ts +6 -2
- package/dist/core/runner/runtask.js +21 -9
- package/dist/core/runner/shell-env-withheld.d.ts +6 -4
- package/dist/core/runner/shell-env-withheld.js +25 -3
- package/dist/core/runner/stop-tail-notice.d.ts +10 -2
- package/dist/core/runner/stop-tail-notice.js +9 -2
- package/dist/core/runner/stream-settle-backstop.d.ts +1 -0
- package/dist/core/runner/stream-settle-backstop.js +1 -0
- package/dist/core/runner/sub-agent-deny-lists.js +9 -5
- package/dist/core/runner/task-start-doors.js +6 -3
- package/dist/core/runner/terminal-account.d.ts +6 -1
- package/dist/core/runner/terminal-account.js +16 -1
- package/dist/core/runner/tool-end-body.d.ts +1 -1
- package/dist/core/runner/tool-not-executed.d.ts +27 -8
- package/dist/core/runner/tool-not-executed.js +22 -11
- package/dist/core/runner/unreadable-person-rows.d.ts +2 -1
- package/dist/core/runner/write-protection-station.d.ts +1 -1
- package/dist/core/runner/write-protection-station.js +1 -1
- package/dist/core/runner-deps.d.ts +17 -10
- package/dist/core/secret-env.d.ts +61 -37
- package/dist/core/secret-env.js +49 -49
- package/dist/core/session-checkout.d.ts +3 -0
- package/dist/core/session-checkout.js +1 -0
- package/dist/core/session-store.d.ts +12 -6
- package/dist/core/session-store.js +26 -6
- package/dist/core/session.d.ts +31 -8
- package/dist/core/shell-read-silence.d.ts +40 -2
- package/dist/core/shell-read-silence.js +23 -4
- package/dist/core/store-contracts/checkpoint-store-contract.js +10 -0
- package/dist/core/store-contracts/peer-task-store-contract.d.ts +21 -0
- package/dist/core/store-contracts/peer-task-store-contract.js +516 -0
- package/dist/core/store-contracts/session-store-contract.d.ts +15 -2
- package/dist/core/store-contracts/session-store-contract.js +87 -3
- package/dist/core/store-contracts/workflow-journal-store-contract.d.ts +19 -1
- package/dist/core/store-contracts/workflow-journal-store-contract.js +89 -1
- package/dist/core/task-event.d.ts +14 -7
- package/dist/core/task-notification.d.ts +96 -10
- package/dist/core/task-notification.js +135 -6
- package/dist/core/task-registry-agent.d.ts +1 -0
- package/dist/core/task-registry-agent.js +1 -1
- package/dist/core/task-registry-shared.d.ts +12 -1
- package/dist/core/task-registry-shared.js +3 -1
- package/dist/core/task-registry-workflow.d.ts +1 -1
- package/dist/core/task-registry-workflow.js +9 -1
- package/dist/core/task-registry.d.ts +40 -2
- package/dist/core/task-registry.js +80 -15
- package/dist/core/task-result.d.ts +18 -3
- package/dist/core/task-spec-members.d.ts +3 -1
- package/dist/core/task-spec-members.js +19 -3
- package/dist/core/task-spec.d.ts +48 -22
- package/dist/core/tool-catalog-entries.js +2 -0
- package/dist/core/tool-gate-phase.d.ts +6 -3
- package/dist/core/tool-gate-phase.js +1 -0
- package/dist/core/tool-mount-facts.d.ts +8 -4
- package/dist/core/tool-mount-facts.js +7 -2
- package/dist/core/tool-mount-plan.d.ts +3 -1
- package/dist/core/tool-mount-plan.js +10 -3
- package/dist/core/tool-mount-static.d.ts +1 -1
- package/dist/core/tool-mount-static.js +4 -2
- package/dist/core/tool-result-store.d.ts +56 -3
- package/dist/core/tool-result-store.js +219 -25
- package/dist/core/tool-spec.d.ts +9 -2
- package/dist/core/trace.d.ts +3 -3
- package/dist/core/user-attachment.d.ts +5 -1
- package/dist/core/user-attachment.js +14 -7
- package/dist/core/wiring-manifest.d.ts +26 -20
- package/dist/core/wiring-manifest.js +7 -3
- package/dist/core/workflow-journal-store.d.ts +53 -10
- package/dist/core/workflow-journal-store.js +27 -4
- package/dist/core/workflow-run-store-contract.js +16 -0
- package/dist/core/workflow-run-store.d.ts +9 -7
- package/dist/core/workflow-run-store.js +4 -1
- package/dist/engine/execution-env/node-execution-env.d.ts +75 -1
- package/dist/engine/execution-env/node-execution-env.js +227 -13
- package/dist/engine/harness/types.d.ts +49 -1
- package/dist/engine/harness/types.js +10 -0
- package/dist/engine/llm/types.d.ts +13 -7
- package/dist/engine/llm/validation.d.ts +8 -1
- package/dist/engine/llm/validation.js +31 -2
- package/dist/engine/lsp/node-lsp-manager.js +2 -1
- package/dist/engine/session/import-validate.js +6 -1
- package/dist/engine/session/session.d.ts +15 -2
- package/dist/engine/session/session.js +34 -4
- package/dist/host-env.d.ts +10 -0
- package/dist/host-env.js +1 -0
- package/dist/index.d.ts +28 -9
- package/dist/index.js +22 -6
- package/dist/internal/harness-types.d.ts +1 -1
- package/dist/orchestration/goal.js +1 -1
- package/dist/orchestration/run-workflow-tool.js +40 -32
- package/dist/orchestration/workflow-park-adoption.d.ts +51 -12
- package/dist/orchestration/workflow-park-adoption.js +47 -12
- package/dist/orchestration/workflow-primitives.js +10 -1
- package/dist/orchestration/workflow-script-runner.d.ts +2 -2
- package/dist/orchestration/workflow-stop.d.ts +128 -0
- package/dist/orchestration/workflow-stop.js +156 -0
- package/dist/orchestration/workflow.d.ts +31 -7
- package/dist/orchestration/workflow.js +119 -57
- package/dist/prompts/manager-recipe.d.ts +18 -0
- package/dist/prompts/manager-recipe.js +24 -0
- package/dist/shell/lex.d.ts +2 -2
- package/dist/shell/lex.js +1 -1
- package/dist/stores/file/permission-rule-store.d.ts +3 -1
- package/dist/stores/file/permission-rule-store.js +0 -1
- package/dist/stores/file/workflow-journal-store.d.ts +16 -3
- package/dist/stores/file/workflow-journal-store.js +93 -5
- package/dist/stores/file/workflow-run-store.d.ts +1 -1
- package/dist/tools/fs/bash-model-shell.d.ts +23 -0
- package/dist/tools/fs/bash-model-shell.js +25 -0
- package/dist/tools/fs/bash-readonly-classifier.d.ts +6 -0
- package/dist/tools/fs/bash-readonly-classifier.js +3 -0
- package/dist/tools/fs/file-write-check.js +9 -3
- package/dist/tools/fs/fs-bash.js +13 -11
- package/dist/tools/fs/index.d.ts +8 -7
- package/dist/tools/fs/index.js +4 -4
- package/dist/tools/fs/read-deny-home.d.ts +1 -1
- package/dist/tools/fs/read-deny-home.js +5 -5
- package/dist/tools/fs/read-deny.d.ts +33 -8
- package/dist/tools/fs/read-deny.js +114 -25
- package/dist/tools/fs/safety.d.ts +4 -1
- package/dist/tools/fs/safety.js +4 -2
- package/dist/tools/fs/shell-read-argv.js +1 -0
- package/dist/tools/fs/shell-read-check.d.ts +9 -2
- package/dist/tools/fs/shell-read-check.js +134 -22
- package/dist/tools/fs/shell-read-establish.d.ts +9 -0
- package/dist/tools/fs/shell-read-establish.js +21 -11
- package/dist/tools/fs/shell-read-judge.d.ts +13 -1
- package/dist/tools/fs/shell-read-judge.js +26 -7
- package/dist/tools/fs/shell-read-plan.d.ts +7 -3
- package/dist/tools/fs/shell-read-plan.js +8 -5
- package/dist/tools/fs/shell-read-word.d.ts +8 -0
- package/dist/tools/fs/shell-read-word.js +13 -4
- package/dist/tools/fs/shell-read-write-targets.js +17 -9
- package/dist/tools/monitor.js +12 -8
- package/dist/tools/scheduler-tools.d.ts +1 -0
- package/dist/tools/scheduler-tools.js +5 -2
- package/package.json +3 -2
- package/test/export-surface.snapshot.json +192 -3
- package/wire-changes/answers/core-stores-sql@7.73.0.json +28 -0
- package/wire-changes/answers/core-stores-sql@7.74.0.json +7 -0
- package/wire-changes/answers/core@7.73.0.json +216 -0
- package/wire-changes/answers/core@7.74.0.json +68 -0
- package/wire-changes/answers/mods-kernel@7.73.0.json +7 -0
- package/wire-changes/answers/mods-kernel@7.74.0.json +21 -0
- package/wire-changes/answers/primitives@7.73.0.json +12 -0
- package/wire-changes/answers/primitives@7.74.0.json +7 -0
- package/wire-changes/answers/wiki-gate@7.73.0.json +7 -0
- package/wire-changes/answers/wiki-gate@7.74.0.json +8 -0
- package/wire-changes/core-stores-sql@7.73.0.json +326 -0
- package/wire-changes/core-stores-sql@7.74.0.json +143 -0
- package/wire-changes/core@7.73.0.json +6480 -0
- package/wire-changes/core@7.74.0.json +2210 -0
- package/wire-changes/mods-kernel@7.73.0.json +147 -0
- package/wire-changes/mods-kernel@7.74.0.json +421 -0
- package/wire-changes/primitives@7.73.0.json +227 -0
- package/wire-changes/primitives@7.74.0.json +174 -0
- package/wire-changes/wiki-gate@7.73.0.json +145 -0
- package/wire-changes/wiki-gate@7.74.0.json +145 -0
package/dist/agents/verify.js
CHANGED
|
@@ -15,6 +15,7 @@ import { chargeFirstLeg, compositionAccount, compositionExhausted, laterLegTurns
|
|
|
15
15
|
import { recipeContinuationLeg } from "../core/input-author.js";
|
|
16
16
|
import { readIndependence, verifierIsImplementerNotice } from "./verifier-independence.js";
|
|
17
17
|
import { withOpeningObjective } from "../core/task-spec-members.js";
|
|
18
|
+
import { screenProjectSeat } from "../core/project-seat.js";
|
|
18
19
|
import { withLegIdentity } from "./leg-label.js";
|
|
19
20
|
export const VERIFICATION_PROMPT = `You are a verification specialist. Your job is NOT to confirm the implementation works — it is to try to BREAK it.
|
|
20
21
|
|
|
@@ -115,9 +116,21 @@ function verifierObjective(originalObjective, impl, evidence) {
|
|
|
115
116
|
return parts.join("\n\n");
|
|
116
117
|
}
|
|
117
118
|
export async function verifyCompleted(runner, result, specBase, objective, config, internals) {
|
|
118
|
-
return verifyCompletedPlaced(runner, result, specBase, objective, config, internals, compositionPlacement(internals, identityMembersOf(specBase)), compositionAccount(specBase, internals?.spendParent));
|
|
119
|
+
return verifyCompletedPlaced(runner, result, specBase, objective, config, internals, compositionPlacement(internals, identityMembersOf(specBase)), compositionAccount(specBase, internals?.spendParent), gateProject(specBase).project);
|
|
119
120
|
}
|
|
120
|
-
|
|
121
|
+
function gateProject(spec) {
|
|
122
|
+
let screened;
|
|
123
|
+
try {
|
|
124
|
+
screened = screenProjectSeat(Reflect.get(spec, "project"));
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return { spec };
|
|
128
|
+
}
|
|
129
|
+
if (!screened.ok || screened.seat === undefined)
|
|
130
|
+
return { spec };
|
|
131
|
+
return { spec: Object.create(spec, { project: { value: screened.seat, enumerable: true } }), project: screened.seat };
|
|
132
|
+
}
|
|
133
|
+
async function verifyCompletedPlaced(runner, result, specBase, objective, config, internals, placement, composition, project) {
|
|
121
134
|
refuseUnhonorableInternals(internals, "door");
|
|
122
135
|
if (result.terminal.kind !== "completed") {
|
|
123
136
|
return { ...result, verification: { verdict: "unverified", unverifiedReason: "impl_incomplete", rounds: 0, findings: [] } };
|
|
@@ -208,7 +221,7 @@ async function verifyCompletedPlaced(runner, result, specBase, objective, config
|
|
|
208
221
|
...(specBase.clientContext !== undefined ? { clientContext: { ...specBase.clientContext } } : {}),
|
|
209
222
|
...(specBase.promptLean !== undefined ? { promptLean: specBase.promptLean } : {}),
|
|
210
223
|
...(specBase.promptLocale !== undefined ? { promptLocale: specBase.promptLocale } : {}),
|
|
211
|
-
...(
|
|
224
|
+
...(project !== undefined ? { project } : {}),
|
|
212
225
|
signal: specBase.signal,
|
|
213
226
|
}, projectContextSeat);
|
|
214
227
|
const v = await runner.runTask(verifierSpec, withLegIdentity(verifierLegInternals(round), { kind: "verifier", round }, internals));
|
|
@@ -308,7 +321,7 @@ async function verifyCompletedPlaced(runner, result, specBase, objective, config
|
|
|
308
321
|
const { blockReadsOutsideRoots: _readBlockOffTheResult, ...withoutReadBlock } = turns.spec ?? specBase;
|
|
309
322
|
const { sandbox: _sandboxOffTheResult, ...continuedConfig } = withoutReadBlock;
|
|
310
323
|
const fixLegSpec = {
|
|
311
|
-
...placement.laterIdentity(withOpeningObjective({ ...continuedConfig, ...continuedSandbox() }, fixObjective(outcome.findings), current.sessionId)),
|
|
324
|
+
...placement.laterIdentity(withOpeningObjective({ ...continuedConfig, ...continuedSandbox(), ...(project !== undefined ? { project } : {}) }, fixObjective(outcome.findings), current.sessionId)),
|
|
312
325
|
...childClampSeats({
|
|
313
326
|
...clampSourceOf(specBase),
|
|
314
327
|
readFace: foldedRootsFace ? "roots" : specBase.readFace,
|
|
@@ -335,23 +348,25 @@ export async function runWithVerification(runner, implSpec, config = {}, interna
|
|
|
335
348
|
refuseUnhonorableInternals(internals, "door");
|
|
336
349
|
const placement = compositionPlacement(internals, identityMembersOf(implSpec));
|
|
337
350
|
const composition = compositionAccount(implSpec, internals?.spendParent);
|
|
338
|
-
const
|
|
351
|
+
const gate = gateProject(implSpec);
|
|
352
|
+
const result = await runner.runTask(gate.spec, withLegIdentity(onComposition(placement.firstLeg, composition), IMPL_LEG, internals));
|
|
339
353
|
if (isDurablePause(result.terminal)) {
|
|
340
354
|
return { ...mapNestedSuspend(result, GATE_RESUME_ENTRY), verification: { verdict: "unverified", unverifiedReason: pauseFamily(result.terminal), rounds: 0, findings: [] } };
|
|
341
355
|
}
|
|
342
356
|
refuseUnhonorableInternals(internals, "before_leg");
|
|
343
|
-
return verifyCompletedPlaced(runner, result, implSpec, implSpec.objective, config, internals, placement, composition);
|
|
357
|
+
return verifyCompletedPlaced(runner, result, implSpec, implSpec.objective, config, internals, placement, composition, gate.project);
|
|
344
358
|
}
|
|
345
359
|
export async function resumeWithVerification(runner, token, outcome, taskConfig, objective, config = {}, internals) {
|
|
346
360
|
refuseUnhonorableInternals(internals, "door");
|
|
347
361
|
const placement = compositionPlacement(internals, identityMembersOf(taskConfig));
|
|
348
362
|
const composition = compositionAccount(taskConfig, internals?.spendParent);
|
|
349
|
-
const
|
|
363
|
+
const gate = gateProject(taskConfig);
|
|
364
|
+
const result = await runner.resume(token, outcome, gate.spec, withLegIdentity(onComposition(placement.firstLeg, composition), IMPL_LEG, internals, "resumeStream"));
|
|
350
365
|
if (isDurablePause(result.terminal)) {
|
|
351
366
|
return { ...mapNestedSuspend(result, GATE_RESUME_ENTRY), verification: { verdict: "unverified", unverifiedReason: pauseFamily(result.terminal), rounds: 0, findings: [] } };
|
|
352
367
|
}
|
|
353
368
|
refuseUnhonorableInternals(internals, "before_leg");
|
|
354
|
-
return verifyCompletedPlaced(runner, result, taskConfig, objective, config, internals, placement, composition);
|
|
369
|
+
return verifyCompletedPlaced(runner, result, taskConfig, objective, config, internals, placement, composition, gate.project);
|
|
355
370
|
}
|
|
356
371
|
export async function runDeveloperTask(runner, spec, config = {}, internals) {
|
|
357
372
|
const implSpec = namesRoleBase(spec) ? spec : { ...spec, promptRole: "code" };
|
|
@@ -53,7 +53,9 @@ async function adoptYieldedAgents(bag, execute, enrich, leg) {
|
|
|
53
53
|
continue;
|
|
54
54
|
}
|
|
55
55
|
try {
|
|
56
|
-
const
|
|
56
|
+
const ownerGate = ctx.inheritedGateForChildren?.();
|
|
57
|
+
const ownerMode = ownerGate?.permissionModeCeiling?.current ?? ownerGate?.permissionMode;
|
|
58
|
+
const out = await execute({ description: row.description ?? "yielded agent", prompt: "continue", run_in_background: true, ...(row.agentType !== undefined ? { subagent_type: row.agentType } : {}), name: row.name, ...(row.model !== undefined ? { model: row.model } : {}) }, enrich({ toolCallId: `yield-drive-${ticket.claimId}`, reviveClaim: { row: { ...structuredClone(ticket.row), parkClaimId: ticket.claimId }, rev: ticket.reservedRev, parkedResume: { ticket, outcome: { gate: "resource_limit", decision: "continue" }, ...(ownerMode !== undefined ? { inheritedGate: { permissionMode: ownerMode } } : {}) } } }));
|
|
57
59
|
if (typeof out === "object" && out !== null && out.isError === true)
|
|
58
60
|
throw new Error(inlineUntrusted(JSON.stringify(out.content ?? ""), 300));
|
|
59
61
|
adopted.push(row.handle);
|
|
@@ -4,7 +4,7 @@ import { type StreamEngineConfig } from "./stream-engine.js";
|
|
|
4
4
|
export interface AnthropicBrainConfig extends StreamEngineConfig, Pick<RoutePairingConfig, "requireCredential"> {
|
|
5
5
|
/** Base URL of the Anthropic(-compatible) API. Default {@link ANTHROPIC_DEFAULT_BASE_URL}. Overridden by model.baseUrl. */
|
|
6
6
|
baseUrl?: string;
|
|
7
|
-
/** API key (`x-api-key`). Overridden by per-call options.apiKey / getApiKeyAndHeaders. */
|
|
7
|
+
/** API key (`x-api-key`; a subscription token, head `sk-ant-oat`, rides as `Authorization: Bearer` while no header bag fills that seat). Overridden by per-call options.apiKey / getApiKeyAndHeaders. */
|
|
8
8
|
apiKey?: string;
|
|
9
9
|
/** `anthropic-version` header. Default `2023-06-01`. */
|
|
10
10
|
version?: string;
|
|
@@ -43,6 +43,47 @@ export interface AnthropicBrainConfig extends StreamEngineConfig, Pick<RoutePair
|
|
|
43
43
|
* names the Anthropic API's own root — the {@link fable5Model} preset, a host's disclosure of where a default request
|
|
44
44
|
* lands — reads this one spelling. */
|
|
45
45
|
export declare const ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com";
|
|
46
|
+
/** What {@link anthropicCredentialHeadersOf} answers for an Anthropic request: which header carries the API key (when one is supplied) and which `anthropic-beta` token the outgoing credential asks for (when any). */
|
|
47
|
+
export interface AnthropicCredentialHeaders {
|
|
48
|
+
readonly key?: {
|
|
49
|
+
readonly header: "authorization" | "x-api-key";
|
|
50
|
+
readonly value: string;
|
|
51
|
+
};
|
|
52
|
+
readonly beta?: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The one pure judge on the Anthropic lane that answers with the same two rules the adapter applies to its own request
|
|
56
|
+
* (`anthropicKeyHeaderOf` and `credentialBetaOf`, over `BEARER_CREDENTIAL_BETAS`) — exported for a host that builds its own
|
|
57
|
+
* direct request to the same provider — over the same pair the adapter reads: the key and the header bag are first read as
|
|
58
|
+
* the route law reads them (`keyCarriedBy`, `dropBlankCredentialHeaders`: those two functions are the law's, read here and
|
|
59
|
+
* not copied).
|
|
60
|
+
*
|
|
61
|
+
* Two normalizations, then two rules (the head is written into the value by the provider that minted it; no header name,
|
|
62
|
+
* source or host word is read beside it):
|
|
63
|
+
* - **Blank is nothing.** A key that is blank (the empty string or white space only; `keyCarriedBy`) is no key, and a credential
|
|
64
|
+
* header whose value is blank (`Authorization: ""`; `dropBlankCredentialHeaders`) is dropped from the copy of the bag
|
|
65
|
+
* before anything reads it — so it holds no seat and asks for no beta.
|
|
66
|
+
* - **Key header (`key`).** Present when `apiKey` is a string that is not blank (`keyCarriedBy`): `authorization` (as
|
|
67
|
+
* `Bearer <apiKey>`) for a key whose head is a row of `BEARER_CREDENTIAL_BETAS` when that seat is empty on the headers; else
|
|
68
|
+
* `x-api-key` (value `<apiKey>`). A credential a header bag put in `Authorization` is the host's and stays as it is (the
|
|
69
|
+
* documented dual-auth shape).
|
|
70
|
+
* - **Credential beta (`beta`).** Read on the headers as they would go out (a null-prototype shallow copy of the given headers
|
|
71
|
+
* without its blank credential headers, with `key` written into its header, replacing any spelling of that header name):
|
|
72
|
+
* exactly one header whose name folds to `authorization`, its value read as the transport sends it (`httpTrimmed`), its
|
|
73
|
+
* scheme `Bearer` in any letter case, its credentials part opening with a row's head, letter case as written. Two spellings
|
|
74
|
+
* of that name (comma-joined on the wire) or another scheme ask for nothing.
|
|
75
|
+
*
|
|
76
|
+
* For plain data inputs (own enumerable data properties, header values that are strings) it performs no I/O, reads no
|
|
77
|
+
* environment, does not mutate its input and does not throw. A header value that is not a string is outside that: it is copied
|
|
78
|
+
* as it is and the blank-credential reading does not judge it. A header bag with an own `__proto__` member that holds an object
|
|
79
|
+
* is outside the agreement with the adapter too: the adapter's merge (`mergeHeaders`) assigns it through the prototype setter,
|
|
80
|
+
* this judge copies it as a plain member. What it does NOT answer: it does not send, does not validate the key, and does not
|
|
81
|
+
* read `Proxy-Authorization`. `key.value` contains the credential itself — do not log the result.
|
|
82
|
+
*/
|
|
83
|
+
export declare function anthropicCredentialHeadersOf(input: {
|
|
84
|
+
apiKey?: string;
|
|
85
|
+
headers?: Readonly<Record<string, string>>;
|
|
86
|
+
}): AnthropicCredentialHeaders;
|
|
46
87
|
/**
|
|
47
88
|
* Create a Brain for the Anthropic Messages API (`/v1/messages`) with **prompt caching** and
|
|
48
89
|
* **extended-thinking replay**. Translates the unified Context into an Anthropic request and the
|
package/dist/brain/anthropic.js
CHANGED
|
@@ -8,8 +8,9 @@ import { admitToolCallId, providerResultIds, providerToolCallId, responseToolCal
|
|
|
8
8
|
import { emitBrainTelemetry } from "./status-sink.js";
|
|
9
9
|
import { DOCUMENT_OMITTED, errorResultMediaNote, IMAGE_OMITTED_NO_VISION, imageWithholdOf, reportImagesWithheld, sendableImages } from "./media-degrade.js";
|
|
10
10
|
import { ANTHROPIC_RESERVED, OUTPUT_CAP_KEYS, applyExtraBody, declaredRequestValues, effectiveOutputCap, headerBagOnce, headerListEntries, lockHeader, mergeHeaders, takeHeaderSpellings } from "./request-params.js";
|
|
11
|
-
import { admitRouteRequest, applyRouteCredentialHeaders, assertServableRequestRoot, brainConfigSnapshot, createBrainRouteJudge, joinRequestUrl, resolveRequestRootOf, resolveRouteCredential } from "./route-adjudicator.js";
|
|
11
|
+
import { admitRouteRequest, applyRouteCredentialHeaders, assertServableRequestRoot, brainConfigSnapshot, createBrainRouteJudge, dropBlankCredentialHeaders, joinRequestUrl, keyCarriedBy, resolveRequestRootOf, resolveRouteCredential } from "./route-adjudicator.js";
|
|
12
12
|
import { requestRouteOf } from "./request-route.js";
|
|
13
|
+
import { authSchemeCredentials, httpTrimmed } from "../core/protocol-http-auth.js";
|
|
13
14
|
import { NAMES_AS_WRITTEN, judgeInBandError, resolveProviderDialect, endpointToolNames } from "./provider-dialect.js";
|
|
14
15
|
import { applyReasoningToRequest, mergeReasoningHeaders } from "./reasoning-request.js";
|
|
15
16
|
import { applyFastModeToRequest, fastModeRouteOf, observeFastMode, requestSpeedOf } from "./fast-mode.js";
|
|
@@ -318,6 +319,50 @@ function readEvent(raw) {
|
|
|
318
319
|
}
|
|
319
320
|
export const ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com";
|
|
320
321
|
const ANTHROPIC_KEY_HEADER = "x-api-key";
|
|
322
|
+
const BEARER_CREDENTIAL_BETAS = Object.freeze([Object.freeze({ head: "sk-ant-oat", beta: "oauth-2025-04-20" })]);
|
|
323
|
+
const bearerCredentialRowOf = (credential) => BEARER_CREDENTIAL_BETAS.find((row) => credential.startsWith(row.head));
|
|
324
|
+
function anthropicKeyHeaderOf(apiKey, headers) {
|
|
325
|
+
const seatTaken = Object.keys(headers).some((name) => name.toLowerCase() === "authorization");
|
|
326
|
+
return !seatTaken && bearerCredentialRowOf(apiKey) !== undefined ? "authorization" : ANTHROPIC_KEY_HEADER;
|
|
327
|
+
}
|
|
328
|
+
function credentialBetaOf(headers) {
|
|
329
|
+
const carried = Object.entries(headers).filter(([name]) => name.toLowerCase() === "authorization");
|
|
330
|
+
if (carried.length !== 1 || typeof carried[0][1] !== "string")
|
|
331
|
+
return undefined;
|
|
332
|
+
const value = httpTrimmed(carried[0][1]);
|
|
333
|
+
const credentials = authSchemeCredentials(value);
|
|
334
|
+
if (credentials === undefined || value.slice(0, value.length - credentials.length).trim().toLowerCase() !== "bearer")
|
|
335
|
+
return undefined;
|
|
336
|
+
const row = bearerCredentialRowOf(credentials);
|
|
337
|
+
return row === undefined ? undefined : { "anthropic-beta": row.beta };
|
|
338
|
+
}
|
|
339
|
+
export function anthropicCredentialHeadersOf(input) {
|
|
340
|
+
const rawKey = input.apiKey;
|
|
341
|
+
const rawHeaders = input.headers;
|
|
342
|
+
const given = rawHeaders !== undefined && rawHeaders !== null && typeof rawHeaders === "object" ? Object.entries(rawHeaders) : [];
|
|
343
|
+
const stringValued = Object.create(null);
|
|
344
|
+
for (const [name, value] of given)
|
|
345
|
+
if (typeof value === "string")
|
|
346
|
+
stringValued[name] = value;
|
|
347
|
+
dropBlankCredentialHeaders(stringValued);
|
|
348
|
+
const outgoing = Object.create(null);
|
|
349
|
+
for (const [name, value] of given)
|
|
350
|
+
if (typeof value === "string" ? name in stringValued : true)
|
|
351
|
+
outgoing[name] = value;
|
|
352
|
+
const apiKey = typeof rawKey === "string" ? keyCarriedBy(rawKey) : undefined;
|
|
353
|
+
let key;
|
|
354
|
+
if (apiKey !== undefined) {
|
|
355
|
+
const header = anthropicKeyHeaderOf(apiKey, outgoing);
|
|
356
|
+
const value = header === ANTHROPIC_KEY_HEADER ? apiKey : `Bearer ${apiKey}`;
|
|
357
|
+
key = { header, value };
|
|
358
|
+
lockHeader(outgoing, header, value);
|
|
359
|
+
}
|
|
360
|
+
const beta = credentialBetaOf(outgoing)?.["anthropic-beta"];
|
|
361
|
+
return {
|
|
362
|
+
...(key !== undefined ? { key } : {}),
|
|
363
|
+
...(beta !== undefined ? { beta } : {}),
|
|
364
|
+
};
|
|
365
|
+
}
|
|
321
366
|
export function createAnthropicBrain(given = {}) {
|
|
322
367
|
const config = brainConfigSnapshot(given, "createAnthropicBrain config");
|
|
323
368
|
assertServableRequestRoot(config.baseUrl, "config.baseUrl");
|
|
@@ -411,8 +456,13 @@ export function createAnthropicBrain(given = {}) {
|
|
|
411
456
|
mergeReasoningHeaders(headers, fastHeaders);
|
|
412
457
|
lockHeader(headers, "content-type", "application/json");
|
|
413
458
|
lockHeader(headers, "anthropic-version", config.version ?? "2023-06-01");
|
|
414
|
-
if (apiKey !== undefined)
|
|
415
|
-
|
|
459
|
+
if (apiKey !== undefined) {
|
|
460
|
+
const keyHeader = anthropicKeyHeaderOf(apiKey, headers);
|
|
461
|
+
lockHeader(headers, keyHeader, keyHeader === ANTHROPIC_KEY_HEADER ? apiKey : `Bearer ${apiKey}`);
|
|
462
|
+
}
|
|
463
|
+
const credentialBeta = credentialBetaOf(headers);
|
|
464
|
+
if (credentialBeta !== undefined)
|
|
465
|
+
mergeReasoningHeaders(headers, credentialBeta);
|
|
416
466
|
const builtThinkingRequested = reasoningBody.thinking !== undefined;
|
|
417
467
|
const builtMaxTokens = reasoningBody.max_tokens;
|
|
418
468
|
const builtMaxTokensLane = overrides?.maxOutputTokens !== undefined
|
|
@@ -468,7 +518,6 @@ export function createAnthropicBrain(given = {}) {
|
|
|
468
518
|
let degenTextBlock;
|
|
469
519
|
const rep = createRepetitionPoll();
|
|
470
520
|
let lastDegenCheck = 0;
|
|
471
|
-
let lastDegenCheckThinking = 0;
|
|
472
521
|
const detectRep = config.detectRepetition !== false;
|
|
473
522
|
let messageStopped = false;
|
|
474
523
|
const afterEnd = createStreamEndLedger(ctrl.providerWords);
|
|
@@ -612,7 +661,7 @@ export function createAnthropicBrain(given = {}) {
|
|
|
612
661
|
}
|
|
613
662
|
switch (evt.kind) {
|
|
614
663
|
case "message_start": {
|
|
615
|
-
noteResponseModel(partial, evt.model, model.id);
|
|
664
|
+
noteResponseModel(partial, evt.model, model.id, ctrl.providerWords);
|
|
616
665
|
const u = evt.usage;
|
|
617
666
|
if (u) {
|
|
618
667
|
usageRaw.input_tokens = u.input_tokens;
|
|
@@ -643,10 +692,10 @@ export function createAnthropicBrain(given = {}) {
|
|
|
643
692
|
if (cb.signature)
|
|
644
693
|
acc.startSignature = cb.signature;
|
|
645
694
|
}
|
|
646
|
-
acc.pb = { type: "thinking", thinking: "" };
|
|
647
|
-
partial.content = [acc.pb];
|
|
648
|
-
out.push({ type: "thinking_start", contentIndex: idx, partial: { ...partial } });
|
|
649
695
|
if (acc.text !== "") {
|
|
696
|
+
acc.pb = { type: "thinking", thinking: "" };
|
|
697
|
+
partial.content = [acc.pb];
|
|
698
|
+
out.push({ type: "thinking_start", contentIndex: idx, partial: { ...partial } });
|
|
650
699
|
acc.pb.thinking = acc.text;
|
|
651
700
|
out.push({ type: "thinking_delta", contentIndex: idx, delta: acc.text, partial: { ...partial } });
|
|
652
701
|
}
|
|
@@ -694,12 +743,17 @@ export function createAnthropicBrain(given = {}) {
|
|
|
694
743
|
}
|
|
695
744
|
else if (d.type === "thinking_delta" && d.thinking) {
|
|
696
745
|
acc.startSignature = undefined;
|
|
746
|
+
if (!acc.pb) {
|
|
747
|
+
acc.pb = { type: "thinking", thinking: "" };
|
|
748
|
+
partial.content = [acc.pb];
|
|
749
|
+
out.push({ type: "thinking_start", contentIndex: idx, partial: { ...partial } });
|
|
750
|
+
}
|
|
697
751
|
acc.text += d.thinking;
|
|
698
|
-
if (acc.pb
|
|
752
|
+
if (acc.pb.type === "thinking")
|
|
699
753
|
acc.pb.thinking = acc.text;
|
|
700
754
|
out.push({ type: "thinking_delta", contentIndex: idx, delta: d.thinking, partial: { ...partial } });
|
|
701
|
-
if (detectRep && !degenerate && acc.text.length -
|
|
702
|
-
|
|
755
|
+
if (detectRep && !degenerate && acc.text.length - (acc.lastDegenCheck ?? 0) >= 64) {
|
|
756
|
+
acc.lastDegenCheck = acc.text.length;
|
|
703
757
|
if (rep.poll(acc.text)) {
|
|
704
758
|
degenerate = true;
|
|
705
759
|
ctrl.cancel();
|
|
@@ -720,7 +774,8 @@ export function createAnthropicBrain(given = {}) {
|
|
|
720
774
|
if (acc)
|
|
721
775
|
acc.stopped = true;
|
|
722
776
|
if (acc?.type === "thinking") {
|
|
723
|
-
|
|
777
|
+
if (acc.pb)
|
|
778
|
+
out.push({ type: "thinking_end", contentIndex: idx, content: acc.text, partial: { ...partial } });
|
|
724
779
|
}
|
|
725
780
|
else if (acc?.type === "text") {
|
|
726
781
|
out.push({ type: "text_end", contentIndex: idx, content: acc.text, partial: { ...partial } });
|
|
@@ -783,7 +838,7 @@ export function createAnthropicBrain(given = {}) {
|
|
|
783
838
|
},
|
|
784
839
|
sealForRetry() {
|
|
785
840
|
for (const [idx, acc] of [...blocks.entries()].sort((a, b) => a[0] - b[0])) {
|
|
786
|
-
if (acc.type === "thinking" && !acc.stopped) {
|
|
841
|
+
if (acc.type === "thinking" && !acc.stopped && acc.pb) {
|
|
787
842
|
acc.stopped = true;
|
|
788
843
|
out.push({ type: "thinking_end", contentIndex: idx, content: acc.text, partial: { ...partial } });
|
|
789
844
|
}
|
package/dist/brain/failover.d.ts
CHANGED
|
@@ -17,6 +17,11 @@ import type { Brain } from "../core/types.js";
|
|
|
17
17
|
* Every gateway moved off is listed on the answer (the model lane's left-behind list: `leftEntriesOf` / `carryLeftBehind`), with the
|
|
18
18
|
* usage its own message reported — what a failed attempt cost is billed, at the request's model.
|
|
19
19
|
*
|
|
20
|
+
* Each leg is asked before it is sent ({@link legRefusal}), on both faces and on the pass-through: a leg whose own judgment does
|
|
21
|
+
* not go ahead (it refuses, throws, or answers no verdict) is not called — never handed the request or its per-call credential.
|
|
22
|
+
* That is a clean failure of that leg before anything went out: the walk moves on; the last leg's (or the pass-through's) refusal
|
|
23
|
+
* is the answer; a leg not sent is not among the requests left behind.
|
|
24
|
+
*
|
|
20
25
|
* Each underlying brain keeps its own retry policy (e.g. `createOpenAIBrain({ maxRetries })`);
|
|
21
26
|
* failover is the cross-gateway layer on top.
|
|
22
27
|
*/
|
package/dist/brain/failover.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
|
-
import { createAssistantMessageEventStream } from "../internal/llm.js";
|
|
1
|
+
import { createAssistantMessageEventStream, } from "../internal/llm.js";
|
|
2
2
|
import { abortLikeName, extractErrorCode } from "./errors.js";
|
|
3
3
|
import { emitBrainTelemetry } from "./status-sink.js";
|
|
4
|
-
import { carriesContent, carryLeftBehind, errorMessageOf, gateReadingOf, leftEntriesOf, passthroughStream, terminalMessage, terminalOf, } from "./model-lane.js";
|
|
4
|
+
import { carriesContent, carryLeftBehind, errorMessageOf, gateReadingOf, identityOf, leftEntriesOf, passthroughStream, refusalErrorOf, terminalMessage, terminalOf, } from "./model-lane.js";
|
|
5
5
|
import { completeOf } from "./brain-faces.js";
|
|
6
|
+
import { readRouteJudgment, sayableModelId, settleUnread } from "./route-adjudicator.js";
|
|
6
7
|
import { GATEWAY_HOP_GATE } from "../core/model-fallbacks.js";
|
|
8
|
+
function legRefusal(leg, model, options) {
|
|
9
|
+
const refusal = readRouteJudgment(() => leg.adjudicateRoute?.(model, identityOf(options)), model);
|
|
10
|
+
return refusal === undefined ? undefined : errorMessageOf(model, refusalErrorOf(sayableModelId(model), refusal), options?.signal?.aborted === true, false);
|
|
11
|
+
}
|
|
7
12
|
export function createFailoverBrain(brains) {
|
|
8
13
|
if (brains.length === 0) {
|
|
9
14
|
throw new Error("createFailoverBrain: need at least one brain");
|
|
@@ -20,7 +25,18 @@ export function createFailoverBrain(brains) {
|
|
|
20
25
|
};
|
|
21
26
|
const stream = (model, context, options) => {
|
|
22
27
|
if (options?.resilience?.allowFailover === false) {
|
|
23
|
-
|
|
28
|
+
const primary = brains[0];
|
|
29
|
+
const askedPrimary = {
|
|
30
|
+
stream: (m, c, o) => {
|
|
31
|
+
const refused = legRefusal(primary, m, o);
|
|
32
|
+
if (refused === undefined)
|
|
33
|
+
return primary.stream(m, c, o);
|
|
34
|
+
const answered = createAssistantMessageEventStream();
|
|
35
|
+
answered.push(terminalOf(refused));
|
|
36
|
+
return answered;
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
return passthroughStream(askedPrimary, model, context, options);
|
|
24
40
|
}
|
|
25
41
|
const out = createAssistantMessageEventStream();
|
|
26
42
|
void (async () => {
|
|
@@ -29,31 +45,39 @@ export function createFailoverBrain(brains) {
|
|
|
29
45
|
try {
|
|
30
46
|
for (const [i, brain] of brains.entries()) {
|
|
31
47
|
const isLast = i === brains.length - 1;
|
|
32
|
-
const inner = await brain.stream(model, context, options);
|
|
33
48
|
let sawContent = false;
|
|
34
49
|
let heldStart;
|
|
35
50
|
let terminal;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
51
|
+
let message;
|
|
52
|
+
const refused = legRefusal(brain, model, options);
|
|
53
|
+
if (refused !== undefined) {
|
|
54
|
+
message = refused;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
const inner = await brain.stream(model, context, options);
|
|
58
|
+
for await (const ev of inner) {
|
|
59
|
+
if (ev.type === "done" || ev.type === "error") {
|
|
60
|
+
terminal = ev;
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
if (ev.type === "start" && !sawContent) {
|
|
64
|
+
heldStart = ev;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (!sawContent) {
|
|
68
|
+
sawContent = true;
|
|
69
|
+
if (heldStart)
|
|
70
|
+
out.push(heldStart);
|
|
71
|
+
}
|
|
72
|
+
out.push(ev);
|
|
49
73
|
}
|
|
50
|
-
|
|
74
|
+
message = await inner.result();
|
|
51
75
|
}
|
|
52
|
-
const message = await inner.result();
|
|
53
76
|
const cleanUpfrontFailure = !sawContent && gateReadingOf(message, i, false, options?.signal?.aborted === true, GATEWAY_HOP_GATE) !== undefined;
|
|
54
77
|
if (cleanUpfrontFailure && !isLast) {
|
|
55
78
|
lastFailedCode = extractErrorCode(message.errorMessage);
|
|
56
|
-
|
|
79
|
+
if (refused === undefined)
|
|
80
|
+
left.push(...leftEntriesOf(message, model.id));
|
|
57
81
|
continue;
|
|
58
82
|
}
|
|
59
83
|
reportServed(i, lastFailedCode);
|
|
@@ -80,8 +104,11 @@ export function createFailoverBrain(brains) {
|
|
|
80
104
|
const left = [];
|
|
81
105
|
for (let i = 0;; i++) {
|
|
82
106
|
let message;
|
|
107
|
+
let refused;
|
|
83
108
|
try {
|
|
84
|
-
|
|
109
|
+
const leg = brains[i];
|
|
110
|
+
refused = legRefusal(leg, model, options);
|
|
111
|
+
message = refused ?? (await completeOf(leg)(model, context, options));
|
|
85
112
|
}
|
|
86
113
|
catch (e) {
|
|
87
114
|
const shell = errorMessageOf(model, e, options?.signal?.aborted === true || abortLikeName(e) !== undefined);
|
|
@@ -91,7 +118,8 @@ export function createFailoverBrain(brains) {
|
|
|
91
118
|
const cleanUpfrontFailure = !carriesContent(message) && gateReadingOf(message, i, false, options?.signal?.aborted === true, GATEWAY_HOP_GATE) !== undefined;
|
|
92
119
|
if (cleanUpfrontFailure && i < span - 1) {
|
|
93
120
|
lastFailedCode = extractErrorCode(message.errorMessage);
|
|
94
|
-
|
|
121
|
+
if (refused === undefined)
|
|
122
|
+
left.push(...leftEntriesOf(message, model.id));
|
|
95
123
|
continue;
|
|
96
124
|
}
|
|
97
125
|
reportServed(i, lastFailedCode);
|
|
@@ -106,6 +134,7 @@ export function createFailoverBrain(brains) {
|
|
|
106
134
|
let verdict;
|
|
107
135
|
try {
|
|
108
136
|
verdict = b.adjudicateRoute?.(model, perModelAuth);
|
|
137
|
+
settleUnread(verdict);
|
|
109
138
|
}
|
|
110
139
|
catch (e) {
|
|
111
140
|
firstRefusal ??= { threw: e };
|
|
@@ -45,9 +45,10 @@
|
|
|
45
45
|
* every attempt is billed once, at its own model's price ({@link servedReadingOf}). The answer's own `usage` stays the answer's
|
|
46
46
|
* (the context reading of the next request is that message's).
|
|
47
47
|
*/
|
|
48
|
-
import { type AssistantMessage, type AssistantMessageDiagnostic, type AssistantMessageEvent, type Model, type Usage } from "../internal/llm.js";
|
|
48
|
+
import { type AssistantMessage, type AssistantMessageDiagnostic, type AssistantMessageEvent, type Model, type PerModelAuth, type SimpleStreamOptions, type Usage } from "../internal/llm.js";
|
|
49
49
|
import type { Brain } from "../core/types.js";
|
|
50
|
-
import {
|
|
50
|
+
import { BrainError } from "./errors.js";
|
|
51
|
+
import { ROUTE_JUDGMENT_FAILED, type JudgedRefusal } from "./route-adjudicator.js";
|
|
51
52
|
import { type DegradeReason, type HopGate, type ReceivedModelFallbackPolicy } from "../core/model-fallbacks.js";
|
|
52
53
|
export { DEGRADE_REASONS, type DegradeReason } from "../core/model-fallbacks.js";
|
|
53
54
|
/** The `type` of the marker diagnostic a walked request's answer carries. */
|
|
@@ -158,7 +159,8 @@ export declare function servedReadingOf(requested: Model, msg: {
|
|
|
158
159
|
/**
|
|
159
160
|
* The terminal for a request whose Brain threw (or whose stream broke its protocol) instead of answering: the request was handed
|
|
160
161
|
* to the Brain, so what it cost is unknown — the usage is a lower bound (`usageMissing`), never a known zero. A request refused
|
|
161
|
-
* before it was dispatched (`sent: false`) cost nothing: its zero usage is a known zero.
|
|
162
|
+
* before it was dispatched (`sent: false`) cost nothing: its zero usage is a known zero. The model's id is read once, guarded
|
|
163
|
+
* ({@link sayableModelId}): an error terminal is minted for a model whose id will not read too.
|
|
162
164
|
*/
|
|
163
165
|
export declare function errorMessageOf(model: Model, e: unknown, aborted: boolean, sent?: boolean): AssistantMessage;
|
|
164
166
|
/** The terminal event of a message: an error frame for an error / aborted message, else `done`. */
|
|
@@ -178,6 +180,13 @@ export declare function carriesContent(msg: AssistantMessage): boolean;
|
|
|
178
180
|
* guess).
|
|
179
181
|
*/
|
|
180
182
|
export declare function gateReadingOf(msg: AssistantMessage, hop: number, expired: boolean, callerAborted: boolean, gate: HopGate): DegradeReason | "next" | undefined;
|
|
183
|
+
/** The per-call answer a hop is dispatched with, as the judgment is handed it — the whole {@link PerModelAuth} the request carries
|
|
184
|
+
* (its header bag already a copy read once: by the answer's one reader, `askPerModelAuth`, and in the main loop by the merge with
|
|
185
|
+
* the run's own bag):
|
|
186
|
+
* the options' `apiKey`, `headers`, `credentialOrigin` and the engine's `credentialOriginUnsettled` mark (none for a later hop —
|
|
187
|
+
* {@link hopOptionsOf} drops them); `undefined` when there is none. The judgment judges the request the Brain would build from it. */
|
|
188
|
+
export declare function identityOf(options: SimpleStreamOptions | undefined): PerModelAuth | undefined;
|
|
189
|
+
export declare function refusalErrorOf(id: string, refusal: JudgedRefusal): BrainError;
|
|
181
190
|
/**
|
|
182
191
|
* The model lane over a deployment Brain and a received fallback policy — one Brain per (Brain, policy) pair, so every read of
|
|
183
192
|
* the seat answers the same object. A request whose model has no chain is judged, then the inner Brain's own call (its route
|
package/dist/brain/model-lane.js
CHANGED
|
@@ -6,7 +6,7 @@ import { armBrainCallDeadline } from "./timeout.js";
|
|
|
6
6
|
import { isExactCount, reasoningTokensOf } from "./usage-reasoning.js";
|
|
7
7
|
import { markRefusedBeforeAnyStream, wasRefusedBeforeAnyStream } from "./usage-reading.js";
|
|
8
8
|
import { readElements, readMember, readMemberOrUnreadable, thrownText } from "../core/thrown-value.js";
|
|
9
|
-
import { readRouteJudgment, routeRefusalError, ROUTE_JUDGMENT_FAILED } from "./route-adjudicator.js";
|
|
9
|
+
import { readRouteJudgment, routeRefusalError, ROUTE_JUDGMENT_FAILED, sayableModelId } from "./route-adjudicator.js";
|
|
10
10
|
import { requestModelOf } from "../core/model-receipt.js";
|
|
11
11
|
import { isSpendRefusal } from "./spend-meter.js";
|
|
12
12
|
import { ANY_HOP_FAILURE, DEFAULT_MODEL_FALLBACK_POLICY, hopGateAdmits, isDegradeReason, modelFallbackChainOf, } from "../core/model-fallbacks.js";
|
|
@@ -174,7 +174,7 @@ export function errorMessageOf(model, e, aborted, sent = true) {
|
|
|
174
174
|
content: [{ type: "text", text: "" }],
|
|
175
175
|
api: model.api,
|
|
176
176
|
provider: model.provider,
|
|
177
|
-
model: model
|
|
177
|
+
model: sayableModelId(model),
|
|
178
178
|
stopReason: aborted ? "aborted" : "error",
|
|
179
179
|
errorMessage: thrownText(e),
|
|
180
180
|
usage: ZERO_USAGE,
|
|
@@ -240,7 +240,7 @@ export function gateReadingOf(msg, hop, expired, callerAborted, gate) {
|
|
|
240
240
|
}
|
|
241
241
|
return hopGateAdmits(gate, reason) ? reason : undefined;
|
|
242
242
|
}
|
|
243
|
-
function identityOf(options) {
|
|
243
|
+
export function identityOf(options) {
|
|
244
244
|
const { apiKey, headers, credentialOrigin, credentialOriginUnsettled } = options ?? {};
|
|
245
245
|
const auth = {
|
|
246
246
|
...(apiKey !== undefined ? { apiKey } : {}),
|
|
@@ -255,7 +255,7 @@ function judgedHop(inner, hop, options, dispatch) {
|
|
|
255
255
|
const cancelled = () => options?.signal?.aborted === true;
|
|
256
256
|
if (cancelled())
|
|
257
257
|
return { model };
|
|
258
|
-
const refusal = readRouteJudgment(() => inner.adjudicateRoute?.(model, identityOf(options), { hop: dispatch }), hop
|
|
258
|
+
const refusal = readRouteJudgment(() => inner.adjudicateRoute?.(model, identityOf(options), { hop: dispatch }), hop);
|
|
259
259
|
if (refusal === undefined || cancelled())
|
|
260
260
|
return { model };
|
|
261
261
|
const { code, fixHint } = refusal;
|
|
@@ -267,7 +267,7 @@ function refusalMessageOf(requested, refused) {
|
|
|
267
267
|
function cancelledMessageOf(requested, options) {
|
|
268
268
|
return errorMessageOf(requested, options?.signal?.reason ?? "aborted", true, false);
|
|
269
269
|
}
|
|
270
|
-
function refusalErrorOf(id, refusal) {
|
|
270
|
+
export function refusalErrorOf(id, refusal) {
|
|
271
271
|
if (refusal.verdict !== undefined)
|
|
272
272
|
return routeRefusalError(refusal.verdict);
|
|
273
273
|
if (refusal.code === ROUTE_JUDGMENT_FAILED && refusal.fixHint !== undefined)
|
|
@@ -326,7 +326,6 @@ export function createOpenResponsesBrain(given = {}) {
|
|
|
326
326
|
let degenItem;
|
|
327
327
|
const rep = createRepetitionPoll();
|
|
328
328
|
let lastDegenCheckText = 0;
|
|
329
|
-
let lastDegenCheckReasoning = 0;
|
|
330
329
|
const detectRep = config.detectRepetition !== false;
|
|
331
330
|
let malformedFrames = 0;
|
|
332
331
|
let malformedSample;
|
|
@@ -371,8 +370,8 @@ export function createOpenResponsesBrain(given = {}) {
|
|
|
371
370
|
acc.block.thinking = acc.text;
|
|
372
371
|
partial.content = [acc.block];
|
|
373
372
|
out.push({ type: "thinking_delta", contentIndex: index, delta, partial: { ...partial } });
|
|
374
|
-
if (detectRep && !degenerate && acc.text.length -
|
|
375
|
-
|
|
373
|
+
if (detectRep && !degenerate && acc.text.length - (acc.lastDegenCheck ?? 0) >= DEGENERATE_POLL_CHARS) {
|
|
374
|
+
acc.lastDegenCheck = acc.text.length;
|
|
376
375
|
if (rep.poll(acc.text)) {
|
|
377
376
|
degenerate = true;
|
|
378
377
|
degenFace = "reasoning";
|
|
@@ -413,7 +412,7 @@ export function createOpenResponsesBrain(given = {}) {
|
|
|
413
412
|
return;
|
|
414
413
|
acc.closed = true;
|
|
415
414
|
if (acc.kind === "reasoning") {
|
|
416
|
-
if (acc.block)
|
|
415
|
+
if (acc.block?.type === "thinking")
|
|
417
416
|
out.push({ type: "thinking_end", contentIndex: index, content: acc.text, partial: { ...partial } });
|
|
418
417
|
}
|
|
419
418
|
else if (acc.kind === "message") {
|
|
@@ -436,7 +435,7 @@ export function createOpenResponsesBrain(given = {}) {
|
|
|
436
435
|
if (env) {
|
|
437
436
|
if (env.id !== undefined)
|
|
438
437
|
responseId = env.id;
|
|
439
|
-
noteResponseModel(partial, env.model, model.id);
|
|
438
|
+
noteResponseModel(partial, env.model, model.id, ctrl.providerWords);
|
|
440
439
|
auditEcho(env);
|
|
441
440
|
}
|
|
442
441
|
return;
|
|
@@ -577,11 +576,11 @@ export function createOpenResponsesBrain(given = {}) {
|
|
|
577
576
|
usageRaw = env.usage;
|
|
578
577
|
if (env?.id !== undefined)
|
|
579
578
|
responseId = env.id;
|
|
580
|
-
noteResponseModel(partial, env?.model, model.id);
|
|
579
|
+
noteResponseModel(partial, env?.model, model.id, ctrl.providerWords);
|
|
581
580
|
return;
|
|
582
581
|
}
|
|
583
582
|
case "response.failed": {
|
|
584
|
-
noteResponseModel(partial, frame.response?.model, model.id);
|
|
583
|
+
noteResponseModel(partial, frame.response?.model, model.id, ctrl.providerWords);
|
|
585
584
|
const err = frame.response?.error;
|
|
586
585
|
if (err !== undefined && err !== null)
|
|
587
586
|
ctrl.inBandFrame(err);
|
|
@@ -612,7 +611,7 @@ export function createOpenResponsesBrain(given = {}) {
|
|
|
612
611
|
for (const [index, acc] of [...items.entries()].sort((a, b) => a[0] - b[0])) {
|
|
613
612
|
if (acc.kind === "reasoning" && !acc.closed) {
|
|
614
613
|
acc.closed = true;
|
|
615
|
-
if (acc.block)
|
|
614
|
+
if (acc.block?.type === "thinking")
|
|
616
615
|
out.push({ type: "thinking_end", contentIndex: index, content: acc.text, partial: { ...partial } });
|
|
617
616
|
}
|
|
618
617
|
}
|