@qlairoslabs/acp-client 0.12.1 → 0.13.0-alpha.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-consumer-fixes.md +17 -10
- package/CHANGELOG-controller-interface.md +258 -0
- package/CHANGELOG-metering.md +29 -0
- package/CHANGELOG-operation-lifecycle.md +15 -1
- package/CONSUMER_GUIDE.md +845 -6
- package/MIGRATION-0.10-to-0.12.md +4 -1
- package/MIGRATION-0.12-to-0.13.md +275 -0
- package/README.md +17 -16
- package/package.json +4 -2
- package/src/acp-client-handlers.ts +48 -0
- package/src/activity.ts +3 -0
- package/src/adapters.ts +25 -0
- package/src/agent/adoption/provider-attachment.ts +33 -0
- package/src/agent/adoption/provider-session-delete.ts +1 -1
- package/src/agent/adoption/provider-sessions.ts +3 -2
- package/src/agent/append-assistant-message.ts +91 -0
- package/src/agent/config.ts +54 -6
- package/src/agent/conversation-manager.ts +94 -158
- package/src/agent/manager-settings.ts +1 -0
- package/src/agent/native-channel-lifecycle.ts +111 -0
- package/src/agent/persisted-lifecycle.ts +44 -4
- package/src/agent/persistence-policy/context.ts +13 -0
- package/src/agent/persistence-policy/resolver.ts +7 -0
- package/src/agent/persistence-policy/types.ts +1 -0
- package/src/agent/record-capture.ts +1 -0
- package/src/agent-adapter-registry.ts +33 -7
- package/src/agent-conversation-contracts.ts +14 -1
- package/src/agent-conversation-errors.ts +8 -0
- package/src/agent-conversation-owner.ts +9 -4
- package/src/agent-session-config.ts +135 -0
- package/src/agent-session.ts +439 -934
- package/src/agent.ts +73 -0
- package/src/capabilities.ts +2 -0
- package/src/checkpointing/recovery.ts +3 -0
- package/src/cli/index.ts +3 -3
- package/src/cli/managed.ts +2 -2
- package/src/client.ts +52 -94
- package/src/connection-attempt.ts +95 -0
- package/src/controller-connection.ts +114 -0
- package/src/controller.ts +156 -148
- package/src/conversation-controller/capabilities.ts +88 -0
- package/src/conversation-controller/contracts.ts +208 -0
- package/src/conversation-controller/factory.ts +39 -0
- package/src/conversation-controller/guards.ts +98 -0
- package/src/conversation-controller/index.ts +20 -0
- package/src/conversation-startup.ts +35 -0
- package/src/conversation-turns/backend-turns.ts +373 -0
- package/src/conversation-turns/clear-operations.ts +37 -0
- package/src/conversation-turns/context.ts +135 -0
- package/src/conversation-turns/index.ts +4 -0
- package/src/conversation-turns/record-helpers.ts +75 -0
- package/src/conversation-turns/recording.ts +235 -0
- package/src/conversation-turns/run-turn.ts +367 -0
- package/src/conversation-turns/turn-run.ts +57 -0
- package/src/errors.ts +41 -0
- package/src/handoff-options.ts +81 -0
- package/src/identity/checkpoint-backed.ts +1 -1
- package/src/index.ts +58 -3
- package/src/internal-inference/coordination/manager.ts +11 -0
- package/src/internal-inference/runtime/harness-runtime.ts +4 -4
- package/src/launcher.ts +35 -2
- package/src/media/parts.ts +5 -0
- package/src/message-status.ts +83 -0
- package/src/metering/engine.ts +39 -64
- package/src/metering/measurement-provenance.ts +36 -0
- package/src/metering/native/durability.ts +115 -0
- package/src/metering/native/ledger.ts +104 -0
- package/src/metering/native/operation.ts +85 -0
- package/src/metering/native/projection.ts +114 -0
- package/src/metering/native/proof.ts +51 -0
- package/src/metering/native/requirements.ts +10 -0
- package/src/metering/native/retirement.ts +92 -0
- package/src/metering/native/source.ts +90 -0
- package/src/metering/record.ts +38 -1
- package/src/metering/state.ts +13 -3
- package/src/native/approvals.ts +169 -0
- package/src/native/capabilities.ts +17 -0
- package/src/native/channel-changes.ts +211 -0
- package/src/native/connection.ts +56 -0
- package/src/native/controller.ts +591 -0
- package/src/native/delegation-sender.ts +26 -0
- package/src/native/errors.ts +35 -0
- package/src/native/functions.ts +156 -0
- package/src/native/host-config.ts +59 -0
- package/src/native/host.ts +909 -0
- package/src/native/item-receipts.ts +15 -0
- package/src/native/metering.ts +12 -0
- package/src/native/records.ts +166 -0
- package/src/native/recovery.ts +186 -0
- package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
- package/src/native/reminders/idle.ts +70 -0
- package/src/native/reminders/limits.ts +19 -0
- package/src/native/reminders/notifications.ts +29 -0
- package/src/native/reminders/reminders.test.ts +553 -0
- package/src/native/reminders/routine-config.typecheck.ts +13 -0
- package/src/native/reminders/routine-guard.ts +66 -0
- package/src/native/reminders/routine-schedule.ts +25 -0
- package/src/native/reminders/routine-wire.ts +21 -0
- package/src/native/reminders/schedule.ts +97 -0
- package/src/native/reminders/service.ts +280 -0
- package/src/native/reminders/supervisor.ts +91 -0
- package/src/native/reminders/sync.ts +301 -0
- package/src/native/reminders/wire.ts +197 -0
- package/src/native/reminders/wire.typecheck.ts +13 -0
- package/src/native/submission-withdrawal.ts +65 -0
- package/src/native/usage.ts +15 -0
- package/src/native/worker-delivery.ts +61 -0
- package/src/native-harness/.res/README.md +1 -0
- package/src/native-harness/.res/architecture/README.md +21 -0
- package/src/native-harness/.res/architecture/context-and-data.md +31 -0
- package/src/native-harness/.res/architecture/execution.md +42 -0
- package/src/native-harness/.res/architecture/overview.md +44 -0
- package/src/native-harness/.res/architecture/persistence.md +56 -0
- package/src/native-harness/.res/architecture/suspend-and-resume.md +45 -0
- package/src/native-harness/.res/architecture/technical-architecture.md +50 -0
- package/src/native-harness/.res/decisions/0001-basic-loop.md +11 -0
- package/src/native-harness/.res/decisions/0002-channel-input.md +17 -0
- package/src/native-harness/.res/decisions/0003-inference-inspection.md +14 -0
- package/src/native-harness/.res/decisions/0004-shared-context.md +21 -0
- package/src/native-harness/.res/decisions/0005-notice-inbox.md +20 -0
- package/src/native-harness/.res/decisions/0006-explicit-notices.md +12 -0
- package/src/native-harness/.res/decisions/0007-channel-output.md +12 -0
- package/src/native-harness/.res/decisions/0008-browser-client.md +16 -0
- package/src/native-harness/.res/decisions/0009-scripted-model.md +18 -0
- package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +19 -0
- package/src/native-harness/.res/decisions/0011-stdio-transport.md +21 -0
- package/src/native-harness/.res/decisions/0012-session-storage-contract.md +37 -0
- package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +64 -0
- package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +73 -0
- package/src/native-harness/.res/decisions/0015-session-file-contract.md +72 -0
- package/src/native-harness/.res/decisions/0016-configuration-permissions.md +159 -0
- package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +69 -0
- package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +78 -0
- package/src/native-harness/.res/decisions/0019-model-execution.md +188 -0
- package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +71 -0
- package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +100 -0
- package/src/native-harness/.res/decisions/0022-operator-controls.md +115 -0
- package/src/native-harness/.res/decisions/0023-long-running-mock.md +82 -0
- package/src/native-harness/.res/decisions/0024-callback-policy-names.md +46 -0
- package/src/native-harness/.res/decisions/0025-external-notices.md +364 -0
- package/src/native-harness/.res/decisions/0026-bounded-context.md +81 -0
- package/src/native-harness/.res/decisions/0027-development-instructions.md +22 -0
- package/src/native-harness/.res/decisions/0028-debug-tools.md +16 -0
- package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +37 -0
- package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +145 -0
- package/src/native-harness/.res/decisions/0031-one-off-reminders.md +173 -0
- package/src/native-harness/.res/docs/11-15.md +148 -0
- package/src/native-harness/.res/docs/BUSINESS_RULES.md +111 -0
- package/src/native-harness/.res/docs/WORK.md +65 -0
- package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +312 -0
- package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +77 -0
- package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +313 -0
- package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +160 -0
- package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +89 -0
- package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +135 -0
- package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +143 -0
- package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +93 -0
- package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +181 -0
- package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +433 -0
- package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +60 -0
- package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +141 -0
- package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +168 -0
- package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +111 -0
- package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +129 -0
- package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +135 -0
- package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +437 -0
- package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +127 -0
- package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +203 -0
- package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +292 -0
- package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +91 -0
- package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +187 -0
- package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +148 -0
- package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +95 -0
- package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +200 -0
- package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +80 -0
- package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +206 -0
- package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +106 -0
- package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +297 -0
- package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +41 -0
- package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +36 -0
- package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +84 -0
- package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +147 -0
- package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +15 -0
- package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +107 -0
- package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +114 -0
- package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +24 -0
- package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +23 -0
- package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +103 -0
- package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +50 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +337 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +76 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +204 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +73 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +64 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +58 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +45 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +108 -0
- package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +169 -0
- package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +128 -0
- package/src/native-harness/.res/marketing-draft.md +22 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/README.md +285 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +19 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +138 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +148 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +172 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +194 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +233 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +249 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +265 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +279 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +293 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +307 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +29 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +317 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +327 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +40 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +59 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +69 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +79 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +89 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +102 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +116 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +49 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +87 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +289 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +221 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +287 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +165 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/state.json +22 -0
- package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +2 -0
- package/src/native-harness/AGENTS.md +70 -0
- package/src/native-harness/ARCHITECTURE.md +249 -0
- package/src/native-harness/README.md +726 -0
- package/src/native-harness/bun.lock +26 -0
- package/src/native-harness/package.json +24 -0
- package/src/native-harness/src/capabilities/context/build.ts +59 -0
- package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
- package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
- package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
- package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
- package/src/native-harness/src/capabilities/context/session.ts +92 -0
- package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
- package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
- package/src/native-harness/src/capabilities/model/runner.ts +116 -0
- package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
- package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
- package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
- package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
- package/src/native-harness/src/capabilities/model/usage.ts +15 -0
- package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
- package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
- package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
- package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
- package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
- package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
- package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
- package/src/native-harness/src/capabilities/tools/reminders/index.ts +75 -0
- package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
- package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
- package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
- package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
- package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
- package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
- package/src/native-harness/src/client.ts +18 -0
- package/src/native-harness/src/contracts/agent.ts +105 -0
- package/src/native-harness/src/contracts/config-permissions.ts +47 -0
- package/src/native-harness/src/contracts/context.ts +112 -0
- package/src/native-harness/src/contracts/events.ts +47 -0
- package/src/native-harness/src/contracts/input-limits.ts +7 -0
- package/src/native-harness/src/contracts/inspection.ts +22 -0
- package/src/native-harness/src/contracts/loop.ts +31 -0
- package/src/native-harness/src/contracts/model-execution.ts +83 -0
- package/src/native-harness/src/contracts/operator-controls.ts +106 -0
- package/src/native-harness/src/contracts/output.ts +13 -0
- package/src/native-harness/src/contracts/protocol.ts +320 -0
- package/src/native-harness/src/contracts/reminders.ts +132 -0
- package/src/native-harness/src/contracts/scenario.ts +42 -0
- package/src/native-harness/src/contracts/session-file.ts +19 -0
- package/src/native-harness/src/contracts/session.ts +184 -0
- package/src/native-harness/src/contracts/storage.ts +596 -0
- package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
- package/src/native-harness/src/contracts/tools.ts +133 -0
- package/src/native-harness/src/governance/permissions/gate.ts +129 -0
- package/src/native-harness/src/governance/policy/resolve.ts +32 -0
- package/src/native-harness/src/index.ts +318 -0
- package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
- package/src/native-harness/src/interfaces/cli/development.ts +145 -0
- package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
- package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
- package/src/native-harness/src/interfaces/cli/main.ts +47 -0
- package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
- package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
- package/src/native-harness/src/interfaces/cli/start.ts +106 -0
- package/src/native-harness/src/interfaces/client.ts +225 -0
- package/src/native-harness/src/interfaces/inspector/index.html +283 -0
- package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
- package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
- package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
- package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
- package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
- package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
- package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
- package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
- package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
- package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
- package/src/native-harness/src/interfaces/protocol/server.ts +517 -0
- package/src/native-harness/src/interfaces/protocol/stdio-client.ts +119 -0
- package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
- package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
- package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
- package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
- package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
- package/src/native-harness/src/kernel/channels.ts +405 -0
- package/src/native-harness/src/kernel/loop.ts +45 -0
- package/src/native-harness/src/runtime/config/development.ts +23 -0
- package/src/native-harness/src/runtime/config/managed.ts +2 -0
- package/src/native-harness/src/runtime/config/paths.ts +27 -0
- package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
- package/src/native-harness/src/runtime/reminder-validation.ts +104 -0
- package/src/native-harness/src/runtime/reminders.ts +66 -0
- package/src/native-harness/src/state/storage/archive.ts +239 -0
- package/src/native-harness/src/state/storage/engine.ts +1013 -0
- package/src/native-harness/src/state/storage/inference.ts +124 -0
- package/src/native-harness/src/state/storage/memory-reminders.ts +78 -0
- package/src/native-harness/src/state/storage/memory.ts +341 -0
- package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
- package/src/native-harness/src/state/storage/reminder-archive.ts +63 -0
- package/src/native-harness/src/state/storage/reminder-change.ts +92 -0
- package/src/native-harness/src/state/storage/reminder-tables.ts +27 -0
- package/src/native-harness/src/state/storage/retrieval.ts +122 -0
- package/src/native-harness/src/state/storage/script-identity.ts +7 -0
- package/src/native-harness/src/state/storage/session-file.ts +85 -0
- package/src/native-harness/src/state/storage/sqlite-reminders.ts +134 -0
- package/src/native-harness/src/state/storage/sqlite.ts +625 -0
- package/src/native-harness/src/testing.ts +190 -0
- package/src/native-harness/src/util/config.ts +58 -0
- package/src/native-harness/src/util/json.ts +41 -0
- package/src/native-harness/src/util/message-position.ts +3 -0
- package/src/native-harness/src/util/reminder-schedule.ts +44 -0
- package/src/native-harness/src/util/schema.ts +40 -0
- package/src/native-harness/src/util/timeline-text.ts +72 -0
- package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
- package/src/native-harness/test/agent.test.ts +130 -0
- package/src/native-harness/test/approval-gate.test.ts +255 -0
- package/src/native-harness/test/approval-protocol.test.ts +94 -0
- package/src/native-harness/test/boundaries.test.ts +18 -0
- package/src/native-harness/test/channel-controls.test.ts +322 -0
- package/src/native-harness/test/client-abort.test.ts +136 -0
- package/src/native-harness/test/config-policy.test.ts +301 -0
- package/src/native-harness/test/conformance/storage.ts +1141 -0
- package/src/native-harness/test/context.test.ts +177 -0
- package/src/native-harness/test/crash.test.ts +187 -0
- package/src/native-harness/test/debug-tools.test.ts +67 -0
- package/src/native-harness/test/development-cli.test.ts +67 -0
- package/src/native-harness/test/development.test.ts +171 -0
- package/src/native-harness/test/dispatch-evidence.test.ts +58 -0
- package/src/native-harness/test/e2e.test.ts +186 -0
- package/src/native-harness/test/external-notices.test.ts +101 -0
- package/src/native-harness/test/fixtures/approval-e2e.jsonl +4 -0
- package/src/native-harness/test/fixtures/crash-scenario.jsonl +5 -0
- package/src/native-harness/test/fixtures/development-lifecycle.jsonl +10 -0
- package/src/native-harness/test/fixtures/echo-scenario.jsonl +3 -0
- package/src/native-harness/test/fixtures/format2-schema.ts +27 -0
- package/src/native-harness/test/fixtures/format3-schema.ts +16 -0
- package/src/native-harness/test/fixtures/hold-scenario.jsonl +4 -0
- package/src/native-harness/test/fixtures/model-e2e.jsonl +3 -0
- package/src/native-harness/test/fixtures/storage-owner.ts +20 -0
- package/src/native-harness/test/format-reply.test.ts +10 -0
- package/src/native-harness/test/helpers/operator-view.ts +41 -0
- package/src/native-harness/test/helpers/scenario.ts +9 -0
- package/src/native-harness/test/helpers/session.ts +38 -0
- package/src/native-harness/test/helpers/stdio.ts +46 -0
- package/src/native-harness/test/inspector.test.ts +77 -0
- package/src/native-harness/test/listeners.test.ts +49 -0
- package/src/native-harness/test/loop.test.ts +88 -0
- package/src/native-harness/test/model-channel-double.test.ts +87 -0
- package/src/native-harness/test/model-crash.test.ts +62 -0
- package/src/native-harness/test/model-delivery-regressions.test.ts +55 -0
- package/src/native-harness/test/model-e2e.test.ts +71 -0
- package/src/native-harness/test/model-final-filter.test.ts +30 -0
- package/src/native-harness/test/model-large-reply.test.ts +28 -0
- package/src/native-harness/test/model-live-queue.test.ts +33 -0
- package/src/native-harness/test/model-runner.test.ts +117 -0
- package/src/native-harness/test/model-storage.test.ts +99 -0
- package/src/native-harness/test/model-stream-adapter.test.ts +26 -0
- package/src/native-harness/test/model-stream-public.test.ts +77 -0
- package/src/native-harness/test/notices.test.ts +64 -0
- package/src/native-harness/test/openrouter-config.test.ts +218 -0
- package/src/native-harness/test/operator-controls.test.ts +132 -0
- package/src/native-harness/test/output.test.ts +44 -0
- package/src/native-harness/test/owner-config.test.ts +64 -0
- package/src/native-harness/test/permissions-e2e.test.ts +68 -0
- package/src/native-harness/test/persistence.test.ts +236 -0
- package/src/native-harness/test/portability.test.ts +337 -0
- package/src/native-harness/test/protocol.test.ts +160 -0
- package/src/native-harness/test/reminder-clock.test.ts +61 -0
- package/src/native-harness/test/reminder-stdio.test.ts +140 -0
- package/src/native-harness/test/reminder-storage.test.ts +124 -0
- package/src/native-harness/test/scenario-jsonl.test.ts +112 -0
- package/src/native-harness/test/scripted.test.ts +92 -0
- package/src/native-harness/test/session-file.test.ts +51 -0
- package/src/native-harness/test/startup-channel-changes.test.ts +256 -0
- package/src/native-harness/test/stdio.test.ts +132 -0
- package/src/native-harness/test/storage-memory.test.ts +4 -0
- package/src/native-harness/test/storage-sqlite.test.ts +420 -0
- package/src/native-harness/test/suspension.test.ts +430 -0
- package/src/native-harness/test/timeline-retrieval.test.ts +211 -0
- package/src/native-harness/test/tools-catalog.test.ts +468 -0
- package/src/native-harness/test/tools-protocol.test.ts +418 -0
- package/src/native-harness/test/transfers.test.ts +94 -0
- package/src/native-harness/test/web-chat.test.ts +35 -0
- package/src/native-harness/tsconfig.json +20 -0
- package/src/observation/agent-event-bus.ts +44 -18
- package/src/observation/index.ts +1 -0
- package/src/operations/contracts.ts +11 -3
- package/src/operations/errors.ts +5 -0
- package/src/operations/stale-policy.ts +1 -1
- package/src/operations/supervisor.ts +34 -10
- package/src/orchestrator/acp-delivery.ts +68 -0
- package/src/orchestrator/assignments.ts +27 -0
- package/src/orchestrator/busy.ts +15 -0
- package/src/orchestrator/config.ts +41 -0
- package/src/orchestrator/consumer-api.ts +24 -0
- package/src/orchestrator/contracts.ts +71 -0
- package/src/orchestrator/durable-assignments.ts +111 -0
- package/src/orchestrator/native-delegation.ts +103 -0
- package/src/orchestrator/orchestrator.ts +318 -0
- package/src/orchestrator/permissions.ts +25 -0
- package/src/orchestrator/policy.ts +44 -0
- package/src/orchestrator/pool.ts +123 -0
- package/src/orchestrator/tool-descriptions.ts +11 -0
- package/src/permissions/acp.ts +18 -0
- package/src/permissions/arrival.ts +13 -0
- package/src/permissions/consumer-config.ts +19 -0
- package/src/permissions/conversation.ts +280 -0
- package/src/permissions/matcher.ts +85 -0
- package/src/permissions/outcome.ts +15 -0
- package/src/permissions/policy.ts +81 -0
- package/src/permissions/request.ts +26 -0
- package/src/persistence/activity-projection.ts +1 -0
- package/src/persistence/backend.ts +34 -1
- package/src/persistence/channels.ts +23 -0
- package/src/persistence/index.ts +4 -0
- package/src/persistence/protocol-method.ts +5 -0
- package/src/persistence/reminder-wake.ts +49 -0
- package/src/persistence/reminders.ts +385 -0
- package/src/persistence/sqlite-backend.ts +84 -6
- package/src/persistence/sqlite-channels.ts +65 -0
- package/src/persistence/sqlite-reminders.ts +85 -0
- package/src/persistence/sqlite-schema.ts +108 -3
- package/src/persistence/sqlite-worker-delivery.ts +374 -0
- package/src/persistence/sqlite-workers.ts +59 -0
- package/src/persistence/worker-delivery-contract.ts +104 -0
- package/src/persistence/worker-terminal-reason.ts +29 -0
- package/src/persistence/workers.ts +19 -0
- package/src/provider-notices.ts +137 -0
- package/src/repl/commands.ts +2 -2
- package/src/steering/combine.ts +3 -1
- package/src/steering/contracts.ts +11 -2
- package/src/steering/controller.ts +3 -2
- package/src/transport/acp-transport.ts +24 -14
- package/src/types.ts +15 -12
- package/src/updates.ts +14 -2
- package/src/wire-log.ts +1 -1
|
@@ -0,0 +1,1013 @@
|
|
|
1
|
+
import { normalizeReminderSchedule, resolveAgentReminder } from "../../util/reminder-schedule.ts";
|
|
2
|
+
import { applyReminderChange } from "./reminder-change.ts";
|
|
3
|
+
import type { OneOffReminder, ReminderChannelEvent } from "../../contracts/reminders.ts";
|
|
4
|
+
import type { ReminderTables } from "./reminder-tables.ts";
|
|
5
|
+
import { searchTimeline, readMessageWindow } from "./retrieval.ts";
|
|
6
|
+
import type { InspectionEntry } from "../../contracts/inspection.ts";
|
|
7
|
+
import type { ContextTurnOutcome } from "../../contracts/context.ts";
|
|
8
|
+
import type { IntakeLimit } from "../../contracts/input-limits.ts";
|
|
9
|
+
import type { OperatorStorageReads } from "../../contracts/operator-controls.ts";
|
|
10
|
+
import type { ModelCallSummary } from "../../contracts/model-execution.ts";
|
|
11
|
+
import type { ManagedConfig } from "../../contracts/config-permissions.ts";
|
|
12
|
+
import { externalNoticeSignature, policyItemSignature, contributingPolicies, fingerprint } from "./policy-metadata.ts";
|
|
13
|
+
import { byteLength, readInference, validReadLimits, type ContextRows } from "./inference.ts";
|
|
14
|
+
import { validateManagedConfig } from "../../util/config.ts";
|
|
15
|
+
import type {
|
|
16
|
+
AcceptItem, ChannelLifecycle, SessionArchive, SessionLifecycle, SessionStorage, StorageErrorCode, StorageResult,
|
|
17
|
+
StorageSnapshot, StoredChannel, StoredItem, StoredSession, StoredTurn, TimelineEntry, TurnTake,
|
|
18
|
+
} from "../../contracts/storage.ts";
|
|
19
|
+
|
|
20
|
+
/** Session-wide scalars. `revision` is also the last allocated global seq. */
|
|
21
|
+
export interface Meta {
|
|
22
|
+
sessionId: string; formatVersion: number; createdAt: string; compatibilityKey: string;
|
|
23
|
+
lifecycle: SessionLifecycle; revision: number; nextTurnId: number; nextItemNumber: number;
|
|
24
|
+
}
|
|
25
|
+
/** A channel as stored; `participantIds` is derived from the timeline. */
|
|
26
|
+
export type ChannelRow = Omit<StoredChannel, "participantIds">;
|
|
27
|
+
/** A turn as stored; `itemIds` is derived from the items linked to it. */
|
|
28
|
+
export type TurnRow = Omit<StoredTurn, "itemIds">;
|
|
29
|
+
|
|
30
|
+
/** Model-call metadata is stored transactionally alongside the logical rows. */
|
|
31
|
+
export interface ModelState {
|
|
32
|
+
nextCall: number;
|
|
33
|
+
calls: ModelCallSummary[];
|
|
34
|
+
itemIds: Record<string, string[]>;
|
|
35
|
+
scriptPositions: Record<string, number>;
|
|
36
|
+
entryIds: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
export const emptyModelState = (): ModelState => ({ nextCall: 1, calls: [], itemIds: {}, scriptPositions: {}, entryIds: {} });
|
|
39
|
+
|
|
40
|
+
/** Row access shared by the memory and SQLite adapters. The engine owns every
|
|
41
|
+
* rule of the storage contract; a backend only stores rows and makes
|
|
42
|
+
* `transaction` atomic (all writes of a throwing callback are undone). */
|
|
43
|
+
export interface Tables extends ContextRows {
|
|
44
|
+
reminders: ReminderTables;
|
|
45
|
+
retrievalCandidates(terms: readonly string[], channel: string | undefined, limit: number): Array<{ seq: number; bytes: number }>;
|
|
46
|
+
retrievalEntry(seq: number): TimelineEntry | undefined;
|
|
47
|
+
retrievalReplyId(id: string): number | undefined;
|
|
48
|
+
readRange(range: Parameters<OperatorStorageReads["readTimeline"]>[0]): TimelineEntry[];
|
|
49
|
+
pendingCount(channel: string): number;
|
|
50
|
+
getModelState(): ModelState | undefined;
|
|
51
|
+
setModelState(state: ModelState, changed?: readonly ModelCallSummary[]): void;
|
|
52
|
+
modelCallPage(after: string | undefined, count: number): ModelCallSummary[];
|
|
53
|
+
/** Decision 0021: sorted names of revoked revocable tools; undefined if never written. */
|
|
54
|
+
getRevokedTools(): string[] | undefined;
|
|
55
|
+
setRevokedTools(names: string[]): void;
|
|
56
|
+
getConfig(): import("../../contracts/session-file.ts").PortableSessionConfig | undefined;
|
|
57
|
+
setConfig(config: import("../../contracts/session-file.ts").PortableSessionConfig): void;
|
|
58
|
+
transaction<T>(run: () => T): T;
|
|
59
|
+
getMeta(): Meta;
|
|
60
|
+
setMeta(meta: Meta): void;
|
|
61
|
+
channel(channelId: string): ChannelRow | undefined;
|
|
62
|
+
/** Insert, or update name/lifecycle of an existing channel (position is kept). */
|
|
63
|
+
putChannel(channel: ChannelRow): void;
|
|
64
|
+
/** In creation order. */
|
|
65
|
+
channels(): ChannelRow[];
|
|
66
|
+
/** Idempotent. */
|
|
67
|
+
addParticipant(participantId: string): void;
|
|
68
|
+
participants(): string[];
|
|
69
|
+
item(itemId: string): StoredItem | undefined;
|
|
70
|
+
/** Insert, or update milestone/turn link of an existing item. */
|
|
71
|
+
putItem(item: StoredItem): void;
|
|
72
|
+
/** Milestone `received` (never `withdrawn`), in acceptedSeq order. */
|
|
73
|
+
pendingItems(channelId: string, limit?: number): StoredItem[];
|
|
74
|
+
/** In take (entrySeq) order. */
|
|
75
|
+
itemsOfTurn(turnId: number): StoredItem[];
|
|
76
|
+
items(): StoredItem[];
|
|
77
|
+
turn(turnId: number): TurnRow | undefined;
|
|
78
|
+
/** Insert, or update state of an existing turn. */
|
|
79
|
+
putTurn(turn: TurnRow): void;
|
|
80
|
+
/** The channel's running or suspended turn. */
|
|
81
|
+
liveTurn(channelId: string): TurnRow | undefined;
|
|
82
|
+
turns(): TurnRow[];
|
|
83
|
+
liveTurns(): TurnRow[];
|
|
84
|
+
latestTurn(channel: string): TurnRow | undefined;
|
|
85
|
+
policyNames(): string[];
|
|
86
|
+
addEntry(entry: TimelineEntry): void;
|
|
87
|
+
entriesOfTurn(turnId: number): TimelineEntry[];
|
|
88
|
+
entries(): TimelineEntry[];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Check persisted names before recovery or config replacement. A changed
|
|
92
|
+
* definition is permitted here; checkpoint compatibility is checked only when
|
|
93
|
+
* that particular checkpoint would actually resume. */
|
|
94
|
+
export function referencesCompatible(tables: Tables, config?: ManagedConfig): boolean {
|
|
95
|
+
if (!config) return true;
|
|
96
|
+
return tables.policyNames().every(name => Object.hasOwn(config.policies, name));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export class Fail extends Error {
|
|
100
|
+
constructor(readonly code: StorageErrorCode, message: string) { super(message); }
|
|
101
|
+
}
|
|
102
|
+
const fail = (code: StorageErrorCode, message: string): never => { throw new Fail(code, message); };
|
|
103
|
+
export function failure<T>(error: unknown): StorageResult<T> {
|
|
104
|
+
return { ok: false, error: error instanceof Fail ? { code: error.code, message: error.message }
|
|
105
|
+
: { code: "storage_failure", message: String(error) } };
|
|
106
|
+
}
|
|
107
|
+
const text = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
|
|
108
|
+
const AUTO = /^auto:(0|[1-9]\d*)$/;
|
|
109
|
+
const RANK = { received: 0, taken: 1, delivered: 2, seen: 3, withdrawn: 4 } as const;
|
|
110
|
+
const NAME_MAX = 200;
|
|
111
|
+
/** A display name as stored: trimmed, 1..200 characters. */
|
|
112
|
+
function cleanName(name: unknown): string {
|
|
113
|
+
if (typeof name !== "string" || !name.trim() || name.trim().length > NAME_MAX)
|
|
114
|
+
fail("invalid_input", `Display name must be 1..${NAME_MAX} characters`);
|
|
115
|
+
return (name as string).trim();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The contract's exact signature; identical for both adapters and archives. */
|
|
119
|
+
export function signatureOf(item: Pick<AcceptItem, "kind" | "channelId" | "senderId" | "sourceChannelId" | "text" | "explicitPolicy" | "externalSource" | "inheritedPolicyNames">): string {
|
|
120
|
+
return item.kind === "external_notice" ? externalNoticeSignature(item.channelId, item.externalSource, item.text, item.inheritedPolicyNames ?? []) : policyItemSignature(item);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Strict JSON data: what survives a JSON round trip unchanged. */
|
|
124
|
+
export function isJson(value: unknown, seen = new Set<object>()): boolean {
|
|
125
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
126
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
127
|
+
if (typeof value !== "object") return false;
|
|
128
|
+
if (seen.has(value)) return false;
|
|
129
|
+
seen.add(value);
|
|
130
|
+
let ok: boolean;
|
|
131
|
+
if (Array.isArray(value)) ok = value.every(entry => isJson(entry, seen));
|
|
132
|
+
else {
|
|
133
|
+
const proto = Object.getPrototypeOf(value);
|
|
134
|
+
ok = (proto === Object.prototype || proto === null) && Object.values(value).every(entry => isJson(entry, seen));
|
|
135
|
+
}
|
|
136
|
+
seen.delete(value);
|
|
137
|
+
return ok;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
type Stored = Extract<TimelineEntry["message"], { role: "assistant" | "tool" }>;
|
|
141
|
+
function checkMessage(message: unknown): Stored {
|
|
142
|
+
if (!isJson(message)) fail("serialization_error", "Message is not plain JSON data");
|
|
143
|
+
const m = message as Record<string, unknown>;
|
|
144
|
+
const keys = Object.keys(m);
|
|
145
|
+
if (m.role === "tool") {
|
|
146
|
+
if (typeof m.content !== "string" || !text(m.callId) || keys.some(key => !["role", "content", "callId", "outcome"].includes(key)))
|
|
147
|
+
fail("invalid_input", "Tool result needs content and callId");
|
|
148
|
+
// Decision 0021: an optional, typed outcome. Checked here so a stored
|
|
149
|
+
// result never claims a status the invocation view cannot interpret.
|
|
150
|
+
if (m.outcome !== undefined) {
|
|
151
|
+
const outcome = m.outcome as Record<string, any>, reference = outcome?.reference;
|
|
152
|
+
if (!outcome || typeof outcome !== "object" || Array.isArray(outcome) || !["succeeded", "failed", "skipped", "interrupted"].includes(outcome.status)
|
|
153
|
+
|| Object.keys(outcome).some(key => !["status", "code", "reference"].includes(key)) || (outcome.code !== undefined && !text(outcome.code))
|
|
154
|
+
|| (reference !== undefined && (!reference || typeof reference !== "object" || !text(reference.resultId) || !Number.isSafeInteger(reference.bytes) || reference.bytes < 0
|
|
155
|
+
|| !["temporary", "durable"].includes(reference.retention) || (reference.expiresAt !== undefined && !text(reference.expiresAt))
|
|
156
|
+
|| Object.keys(reference).some(key => !["resultId", "bytes", "retention", "expiresAt"].includes(key)))))
|
|
157
|
+
fail("invalid_input", "Invalid tool outcome");
|
|
158
|
+
}
|
|
159
|
+
} else if (m.role === "assistant") {
|
|
160
|
+
const calls = m.calls;
|
|
161
|
+
if (!(m.content === null || typeof m.content === "string") || !Array.isArray(calls)
|
|
162
|
+
|| keys.some(key => !["role", "content", "calls", "providerState"].includes(key))
|
|
163
|
+
|| calls.some(call => !call || typeof call !== "object" || !text(call.id) || !text(call.name) || typeof call.arguments !== "string"))
|
|
164
|
+
fail("invalid_input", "Assistant message needs content and well-formed calls");
|
|
165
|
+
} else fail("invalid_input", "Only assistant and tool messages can be appended");
|
|
166
|
+
return message as Stored;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function session(meta: Meta): StoredSession {
|
|
170
|
+
return { sessionId: meta.sessionId, formatVersion: meta.formatVersion === 7 ? 7 : 6, createdAt: meta.createdAt,
|
|
171
|
+
lifecycle: meta.lifecycle, compatibilityKey: meta.compatibilityKey };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function readSnapshot(tables: Tables): StorageSnapshot {
|
|
175
|
+
const meta = tables.getMeta();
|
|
176
|
+
const timeline = tables.entries();
|
|
177
|
+
const spoke = new Map<string, Set<string>>();
|
|
178
|
+
for (const entry of timeline) {
|
|
179
|
+
if (entry.kind !== "participant_message") continue;
|
|
180
|
+
if (!spoke.has(entry.channelId)) spoke.set(entry.channelId, new Set());
|
|
181
|
+
spoke.get(entry.channelId)!.add(entry.from);
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
revision: meta.revision, session: session(meta),
|
|
185
|
+
channels: tables.channels().map(row => ({ channelId: row.channelId, ...(row.displayName === undefined ? {} : { displayName: row.displayName }), ...(row.policy === undefined ? {} : { policy: row.policy }),
|
|
186
|
+
lifecycle: row.lifecycle, participantIds: [...spoke.get(row.channelId) ?? []] })),
|
|
187
|
+
participants: tables.participants().map(participantId => ({ participantId })),
|
|
188
|
+
turns: tables.turns().map(row => ({ ...row, itemIds: tables.itemsOfTurn(row.turnId).map(item => item.itemId) })),
|
|
189
|
+
items: tables.items(), timeline: timeline.map(entry => {
|
|
190
|
+
const id = tables.getModelState()?.entryIds[String(entry.seq)];
|
|
191
|
+
return id ? { ...entry, messageId: id } : entry;
|
|
192
|
+
}),
|
|
193
|
+
modelCalls: tables.getModelState()?.calls ?? [], scriptPositions: tables.getModelState()?.scriptPositions ?? {},
|
|
194
|
+
...(tables.getRevokedTools() === undefined ? {} : { revokedTools: tables.getRevokedTools()! }),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Reopen recovery, one transaction, executes nothing. `upgrade` (format 2 data,
|
|
199
|
+
* decision 0014) runs first in the same transaction, so a failure leaves the
|
|
200
|
+
* data untouched. Interrupted: every running turn, and every checkpointed turn
|
|
201
|
+
* whose channel is not individually `suspended` (a committed channel suspension
|
|
202
|
+
* and its checkpoint survive, in every lifecycle); a clean session suspension
|
|
203
|
+
* keeps all. A `suspending` channel never committed and returns to `open`. A
|
|
204
|
+
* clean state with nothing to change is left unwritten. */
|
|
205
|
+
function refreshReminderWake(tables: Tables, meta: Meta) {
|
|
206
|
+
if (meta.formatVersion !== 7) return;
|
|
207
|
+
const wake = tables.reminders.wake();
|
|
208
|
+
const nextDueAt = meta.lifecycle === "running" ? tables.reminders.eligible(null, 1)[0]?.reminder.nextRunAt ?? null : null;
|
|
209
|
+
if (nextDueAt !== wake.nextDueAt) tables.reminders.setWake({ nextDueAt, reminderRevision: wake.reminderRevision + 1 });
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function recover(tables: Tables, upgrade?: () => void): void {
|
|
213
|
+
tables.transaction(() => {
|
|
214
|
+
if (upgrade) upgrade();
|
|
215
|
+
const meta = tables.getMeta();
|
|
216
|
+
let changed = !!upgrade;
|
|
217
|
+
if (upgrade) meta.formatVersion = 4;
|
|
218
|
+
let abandonedModel = false;
|
|
219
|
+
if (meta.lifecycle !== "suspended") {
|
|
220
|
+
const kept = (turn: TurnRow) => turn.state.status === "suspended"
|
|
221
|
+
&& tables.channel(turn.channelId)?.lifecycle === "suspended";
|
|
222
|
+
const live = tables.liveTurns().filter(turn => !kept(turn));
|
|
223
|
+
abandonedModel = live.some(turn => turn.state.status === "running");
|
|
224
|
+
for (const turn of live) tables.putTurn({ ...turn, state: { status: "interrupted",
|
|
225
|
+
reason: "The owning process exited before this turn finished", uncertainCallIds: uncertain(tables, turn) } });
|
|
226
|
+
const reopened = tables.channels().filter(channel => channel.lifecycle === "suspending");
|
|
227
|
+
for (const channel of reopened) tables.putChannel({ ...channel, lifecycle: "open" });
|
|
228
|
+
if (live.length || reopened.length || meta.lifecycle !== "running") { meta.lifecycle = "running"; changed = true; }
|
|
229
|
+
}
|
|
230
|
+
if (meta.formatVersion < 5) {
|
|
231
|
+
const state = emptyModelState();
|
|
232
|
+
for (const entry of tables.entries()) if (entry.message.role === "assistant")
|
|
233
|
+
Object.defineProperty(state.scriptPositions, entry.channelId, { value: (Object.hasOwn(state.scriptPositions, entry.channelId) ? state.scriptPositions[entry.channelId]! : 0) + 1, writable: true, configurable: true, enumerable: true });
|
|
234
|
+
tables.setModelState(state); meta.formatVersion = 5; changed = true;
|
|
235
|
+
} else if (abandonedModel) {
|
|
236
|
+
const state = tables.getModelState() ?? emptyModelState();
|
|
237
|
+
for (const call of state.calls) if (call.outcome === "running") {
|
|
238
|
+
call.outcome = "interrupted"; call.endedAt = new Date().toISOString();
|
|
239
|
+
for (const attempt of call.attempts) if (attempt.outcome === "running") { attempt.outcome = "interrupted"; attempt.endedAt = call.endedAt; }
|
|
240
|
+
changed = true;
|
|
241
|
+
}
|
|
242
|
+
if (changed) tables.setModelState(state);
|
|
243
|
+
}
|
|
244
|
+
if (meta.formatVersion < 6) { meta.formatVersion = 6; changed = true; }
|
|
245
|
+
refreshReminderWake(tables, meta);
|
|
246
|
+
if (changed) tables.setMeta({ ...meta, revision: meta.revision + 1 });
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function unanswered(tables: Tables, turnId: number): string[] {
|
|
251
|
+
const open: string[] = [];
|
|
252
|
+
for (const entry of tables.entriesOfTurn(turnId)) {
|
|
253
|
+
if (entry.message.role === "assistant") for (const call of entry.message.calls) open.push(call.id);
|
|
254
|
+
else if (entry.message.role === "tool") { const at = open.indexOf(entry.message.callId); if (at >= 0) open.splice(at, 1); }
|
|
255
|
+
}
|
|
256
|
+
return open;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Older states lack dispatch evidence and retain the conservative old rule. */
|
|
260
|
+
function uncertain(tables: Tables, turn: TurnRow): string[] {
|
|
261
|
+
const open = unanswered(tables, turn.turnId);
|
|
262
|
+
if (turn.state.status !== "running" && turn.state.status !== "suspended") return open;
|
|
263
|
+
const marked = turn.state.dispatchedCallIds;
|
|
264
|
+
return marked === undefined ? open : open.filter(id => marked.includes(id));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** The contract over any backend. `ownerKey` is the key passed to this open. */
|
|
268
|
+
export function createEngine(tables: Tables, ownerKey: string, release: () => void, config?: ManagedConfig, incompatibleViewOnly = false): SessionStorage {
|
|
269
|
+
let closed = false;
|
|
270
|
+
// This is the config validated at open, not the separately mutable saved copy.
|
|
271
|
+
const ownerSnapshot = config === undefined ? undefined : structuredClone(config);
|
|
272
|
+
const now = () => new Date().toISOString();
|
|
273
|
+
|
|
274
|
+
function run<T>(work: (meta: Meta) => T, readOnly = false): StorageResult<T> {
|
|
275
|
+
if (closed) return failure(new Fail("closed", "Storage handle is closed"));
|
|
276
|
+
if (incompatibleViewOnly && !readOnly) return failure(new Fail("incompatible", "Stored policy is not available in the open configuration"));
|
|
277
|
+
try {
|
|
278
|
+
return tables.transaction(() => {
|
|
279
|
+
const meta = tables.getMeta(), before = JSON.stringify(meta);
|
|
280
|
+
const value = work(meta);
|
|
281
|
+
if (!readOnly && JSON.stringify(meta) !== before) refreshReminderWake(tables, meta);
|
|
282
|
+
if (JSON.stringify(meta) !== before) tables.setMeta(meta);
|
|
283
|
+
// Results never alias rows a backend may keep in memory.
|
|
284
|
+
return { ok: true as const, value: structuredClone(value), revision: meta.revision };
|
|
285
|
+
});
|
|
286
|
+
} catch (error) { return failure(error); }
|
|
287
|
+
}
|
|
288
|
+
const seq = (meta: Meta) => ++meta.revision;
|
|
289
|
+
const full = (row: TurnRow): StoredTurn => ({ ...row, itemIds: tables.itemsOfTurn(row.turnId).map(item => item.itemId) });
|
|
290
|
+
function running(turnId: number): TurnRow {
|
|
291
|
+
const turn = tables.turn(turnId) ?? fail("not_found", `Unknown turn: ${turnId}`);
|
|
292
|
+
if (turn.state.status !== "running") fail("invalid_state", `Turn ${turnId} is ${turn.state.status}, not running`);
|
|
293
|
+
return turn;
|
|
294
|
+
}
|
|
295
|
+
function boundaryPending(channelId: string, intake?: IntakeLimit, turnId?: number): StoredItem[] {
|
|
296
|
+
if (!intake) return tables.pendingItems(channelId);
|
|
297
|
+
const already = turnId === undefined ? [] : tables.contextInputs(turnId, tables.contextPreviousResponse(turnId), intake.maxTakenItems);
|
|
298
|
+
const slots = intake.maxTakenItems - already.length;
|
|
299
|
+
if (slots <= 0) return [];
|
|
300
|
+
let bytes = intake.maxTakenTextBytes - already.reduce((sum, row) => sum + (row.textBytes ?? 0), 0);
|
|
301
|
+
const selected: StoredItem[] = [];
|
|
302
|
+
for (const item of tables.pendingItems(channelId, slots)) {
|
|
303
|
+
bytes -= byteLength(item.text);
|
|
304
|
+
// A legacy oversized head advances alone and gets a typed build failure.
|
|
305
|
+
if (bytes < 0 && (selected.length || already.length)) break;
|
|
306
|
+
selected.push(item);
|
|
307
|
+
if (bytes < 0) break;
|
|
308
|
+
}
|
|
309
|
+
return selected;
|
|
310
|
+
}
|
|
311
|
+
function take(meta: Meta, turn: TurnRow, pending: StoredItem[]): TurnTake {
|
|
312
|
+
const items: StoredItem[] = [], entries: TimelineEntry[] = [];
|
|
313
|
+
for (const item of pending) {
|
|
314
|
+
const entry: TimelineEntry = { seq: seq(meta), at: now(), channelId: turn.channelId, turnId: turn.turnId,
|
|
315
|
+
from: item.senderId, kind: item.kind, ...(item.sourceChannelId ? { sourceChannelId: item.sourceChannelId } : {}),
|
|
316
|
+
...(item.externalSource !== undefined ? { externalSource: item.externalSource } : {}),
|
|
317
|
+
itemId: item.itemId, message: { role: "user", content: item.kind !== "participant_message" ? item.text
|
|
318
|
+
: `Participant: ${JSON.stringify(item.senderId)}\n\n${item.text}` } };
|
|
319
|
+
tables.addEntry(entry);
|
|
320
|
+
const taken: StoredItem = { ...item, milestone: "taken", turnId: turn.turnId, entrySeq: entry.seq };
|
|
321
|
+
tables.putItem(taken);
|
|
322
|
+
items.push(taken); entries.push(entry);
|
|
323
|
+
}
|
|
324
|
+
return { turn: full(turn), items, entries };
|
|
325
|
+
}
|
|
326
|
+
function interrupt(turn: TurnRow, status: "failed" | "interrupted", reason: string): TurnRow {
|
|
327
|
+
const ended: TurnRow = { ...turn, state: { status, reason, uncertainCallIds: uncertain(tables, turn) } };
|
|
328
|
+
tables.putTurn(ended);
|
|
329
|
+
finishModels(turn.turnId);
|
|
330
|
+
settle(turn.channelId);
|
|
331
|
+
return ended;
|
|
332
|
+
}
|
|
333
|
+
/** The channel's running turn just left `running` (end or checkpoint): a
|
|
334
|
+
* `suspending` channel becomes `suspended` in this same transaction. */
|
|
335
|
+
function settle(channelId: string): void {
|
|
336
|
+
const channel = tables.channel(channelId);
|
|
337
|
+
if (channel?.lifecycle === "suspending") tables.putChannel({ ...channel, lifecycle: "suspended" });
|
|
338
|
+
}
|
|
339
|
+
const channelOf = (channelId: unknown): ChannelRow => {
|
|
340
|
+
const channel = typeof channelId === "string" ? tables.channel(channelId) : undefined;
|
|
341
|
+
if (!channel) return fail("not_found", `Unknown channel: ${String(channelId)}`);
|
|
342
|
+
if (channel.lifecycle === "retired") return fail("channel_retired", `Channel ${channel.channelId} is retired`);
|
|
343
|
+
return channel;
|
|
344
|
+
};
|
|
345
|
+
const view = (channel: ChannelRow): StoredChannel => {
|
|
346
|
+
const spoke = new Set(tables.entries().filter(entry => entry.channelId === channel.channelId && entry.kind === "participant_message").map(entry => entry.from));
|
|
347
|
+
return { ...channel, participantIds: [...spoke] };
|
|
348
|
+
};
|
|
349
|
+
const legacy = "__legacy_allow";
|
|
350
|
+
const activeConfig = ownerSnapshot ?? { version: 1 as const, system: "", model: { protocol: "scripted" as const, script: "legacy" }, defaultPolicy: legacy,
|
|
351
|
+
policies: { [legacy]: { fallback: "allow" as const, tools: {} } } };
|
|
352
|
+
const requireCompatible = () => {
|
|
353
|
+
if (!referencesCompatible(tables, activeConfig)) fail("incompatible", "A stored policy no longer exists");
|
|
354
|
+
};
|
|
355
|
+
const turnFingerprint = (turn: TurnRow) => fingerprint(activeConfig, contributingPolicies(tables.itemsOfTurn(turn.turnId)
|
|
356
|
+
.map(item => item.policy ?? { resolved: legacy, inherited: [] })));
|
|
357
|
+
const compatible = (turn: TurnRow) => {
|
|
358
|
+
try { return turn.compatibilityKey === ownerKey && turn.state.status === "suspended" && turn.state.checkpoint.policyFingerprint === turnFingerprint(turn); }
|
|
359
|
+
catch { return false; }
|
|
360
|
+
};
|
|
361
|
+
const resolve = (explicit?: string | null, channel?: string) => {
|
|
362
|
+
const selected = explicit ?? channel ?? ownerSnapshot?.defaultPolicy ?? legacy;
|
|
363
|
+
if (ownerSnapshot && !Object.hasOwn(ownerSnapshot.policies, selected)) fail("invalid_policy", `Unknown policy: ${selected}`);
|
|
364
|
+
if (!ownerSnapshot && selected !== legacy) fail("invalid_policy", `Unknown policy: ${selected}`);
|
|
365
|
+
return selected;
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
const modelCall = (state: ModelState, id: string) => state.calls.find(call => call.callId === id) ?? fail("not_found", `Unknown model call: ${id}`);
|
|
369
|
+
const activeAttempt = (state: ModelState, id: string, attemptId: string) => {
|
|
370
|
+
const call = modelCall(state, id); running(Number(call.turnId));
|
|
371
|
+
if (call.outcome !== "running") fail("invalid_state", "Model call has ended");
|
|
372
|
+
const attempt = call.attempts.find(value => value.attemptId === attemptId);
|
|
373
|
+
if (!attempt || attempt.outcome !== "running") return fail("invalid_state", "Model attempt has ended or is unknown");
|
|
374
|
+
return { call, attempt };
|
|
375
|
+
};
|
|
376
|
+
const finishModels = (turnId: number) => {
|
|
377
|
+
const state = tables.getModelState() ?? emptyModelState(); const changed: ModelCallSummary[] = [];
|
|
378
|
+
for (const call of state.calls) if (call.turnId === String(turnId) && call.outcome === "running") {
|
|
379
|
+
call.outcome = "interrupted"; call.endedAt = now(); changed.push(call);
|
|
380
|
+
for (const attempt of call.attempts) if (attempt.outcome === "running") { attempt.outcome = "interrupted"; attempt.endedAt = call.endedAt; }
|
|
381
|
+
}
|
|
382
|
+
if (changed.length) tables.setModelState(state, changed);
|
|
383
|
+
};
|
|
384
|
+
const accept = (meta: Meta, input: AcceptItem, maxInputBytes?: number) => {
|
|
385
|
+
const external = input?.kind === "external_notice";
|
|
386
|
+
if (!external) requireCompatible();
|
|
387
|
+
if (external && (!text(input.itemId) || !text(input.channelId) || !text(input.text)
|
|
388
|
+
|| (input.externalSource !== undefined && !text(input.externalSource))
|
|
389
|
+
|| !Array.isArray(input.inheritedPolicyNames) || !Array.from(input.inheritedPolicyNames).every(text)
|
|
390
|
+
|| input.sourceChannelId !== undefined || input.sourceTurnId !== undefined || input.explicitPolicy !== undefined))
|
|
391
|
+
fail("invalid_input", "Invalid external notice");
|
|
392
|
+
const shaped = !!input && typeof input === "object"
|
|
393
|
+
&& [input.kind, input.channelId, input.senderId, input.text].every(value => typeof value === "string")
|
|
394
|
+
&& (input.sourceChannelId === undefined || typeof input.sourceChannelId === "string")
|
|
395
|
+
&& (input.explicitPolicy === undefined || input.explicitPolicy === null || typeof input.explicitPolicy === "string");
|
|
396
|
+
if (shaped && typeof input.itemId === "string") {
|
|
397
|
+
const known = tables.item(input.itemId);
|
|
398
|
+
if (known) {
|
|
399
|
+
if (known.signature !== signatureOf(input)) fail("item_conflict", `Item ID ${input.itemId} already identifies different input`);
|
|
400
|
+
return { item: known, duplicate: true };
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const notice = shaped && input.kind === "channel_notice";
|
|
404
|
+
if (!shaped || !(notice || external || input.kind === "participant_message") || ![input.channelId, input.senderId, input.text].every(text)
|
|
405
|
+
|| (input.itemId !== undefined && !text(input.itemId))
|
|
406
|
+
|| (notice ? !text(input.sourceChannelId) : input.sourceChannelId !== undefined))
|
|
407
|
+
fail("invalid_input", "Item needs kind, channelId, senderId and text; a notice also needs sourceChannelId");
|
|
408
|
+
if (maxInputBytes !== undefined && typeof input?.text === "string" && byteLength(input.text) > maxInputBytes)
|
|
409
|
+
fail("invalid_input", `Input exceeds the ${maxInputBytes}-byte UTF-8 limit`);
|
|
410
|
+
if (external) {
|
|
411
|
+
if (incompatibleViewOnly) fail("incompatible", "Stored policy is not available in the open configuration");
|
|
412
|
+
requireCompatible();
|
|
413
|
+
if (meta.lifecycle !== "running") fail("not_running", `Session is ${meta.lifecycle}; new work is not admitted`);
|
|
414
|
+
const channel = channelOf(input.channelId);
|
|
415
|
+
if (channel.lifecycle !== "open") fail("channel_suspended", `Channel ${channel.channelId} is ${channel.lifecycle}`);
|
|
416
|
+
}
|
|
417
|
+
const target = tables.channel(input.channelId);
|
|
418
|
+
if (notice && input.explicitPolicy != null) fail("invalid_input", "Notices cannot override policy");
|
|
419
|
+
if (notice && ownerSnapshot && input.sourceTurnId === undefined) fail("invalid_input", "A notice needs its executing source turn");
|
|
420
|
+
const resolved = resolve(input.explicitPolicy, target?.policy);
|
|
421
|
+
let inherited: string[] = external ? [...new Set(input.inheritedPolicyNames!)].sort() : [];
|
|
422
|
+
if (external) for (const name of inherited)
|
|
423
|
+
if (name === "__legacy_allow" || !Object.hasOwn(activeConfig.policies, name)) fail("invalid_policy", `Unknown or reserved policy: ${name}`);
|
|
424
|
+
if (notice && input.sourceTurnId !== undefined) {
|
|
425
|
+
const source = tables.turn(input.sourceTurnId);
|
|
426
|
+
if (!source || source.channelId !== input.sourceChannelId || source.state.status !== "running") fail("invalid_input", "Invalid notice source turn");
|
|
427
|
+
inherited = contributingPolicies(tables.itemsOfTurn(input.sourceTurnId).map(item => item.policy ?? { resolved: legacy, inherited: [] }));
|
|
428
|
+
}
|
|
429
|
+
if (notice && !target) fail("not_found", `Unknown channel: ${input.channelId}`);
|
|
430
|
+
if (target?.lifecycle === "retired") fail("channel_retired", `Channel ${input.channelId} is retired`);
|
|
431
|
+
if (meta.lifecycle === "suspended" || (meta.lifecycle === "suspending" && !notice))
|
|
432
|
+
fail("not_running", `Session is ${meta.lifecycle}; new work is not admitted`);
|
|
433
|
+
if (target && target.lifecycle !== "open") fail("channel_suspended", `Channel ${input.channelId} is ${target.lifecycle}; new work is not admitted`);
|
|
434
|
+
let itemId = input.itemId;
|
|
435
|
+
if (itemId === undefined) itemId = `auto:${meta.nextItemNumber++}`;
|
|
436
|
+
else {
|
|
437
|
+
const auto = AUTO.exec(itemId);
|
|
438
|
+
if (auto) {
|
|
439
|
+
const n = Number(auto[1]);
|
|
440
|
+
if (!Number.isSafeInteger(n + 1)) fail("invalid_input", "Reserved item ID is out of range");
|
|
441
|
+
if (n >= meta.nextItemNumber) meta.nextItemNumber = n + 1;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
const item: StoredItem = { itemId, kind: input.kind, channelId: input.channelId, senderId: external ? input.externalSource ?? "host" : input.senderId,
|
|
445
|
+
...(external ? { inheritedPolicyNames: inherited, ...(input.externalSource === undefined ? {} : { externalSource: input.externalSource }) } : {}),
|
|
446
|
+
...(notice ? { sourceChannelId: input.sourceChannelId } : {}), ...(input.explicitPolicy == null ? {} : { explicitPolicy: input.explicitPolicy }), text: input.text,
|
|
447
|
+
signature: signatureOf(input), policy: { ...(input.explicitPolicy == null ? {} : { explicit: input.explicitPolicy }), resolved, inherited },
|
|
448
|
+
acceptedSeq: seq(meta), acceptedAt: now(), milestone: "received" };
|
|
449
|
+
if (!notice && !external) {
|
|
450
|
+
if (!target) tables.putChannel({ channelId: item.channelId, lifecycle: "open" });
|
|
451
|
+
tables.addParticipant(item.senderId);
|
|
452
|
+
}
|
|
453
|
+
tables.putItem(item);
|
|
454
|
+
return { item, duplicate: false };
|
|
455
|
+
};
|
|
456
|
+
const reminders = tables.reminders;
|
|
457
|
+
const activateReminders = (meta: Meta) => {
|
|
458
|
+
if (meta.formatVersion < 7) {
|
|
459
|
+
reminders.activate();
|
|
460
|
+
meta.formatVersion = 7;
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
const putReminder = (meta: Meta, reminder: OneOffReminder, defaultedExpiry?: boolean, original?: string) => {
|
|
464
|
+
activateReminders(meta);
|
|
465
|
+
const existing = reminders.get(reminder.id);
|
|
466
|
+
const revision = seq(meta);
|
|
467
|
+
reminders.put({ sequence: existing?.sequence ?? revision, reminder, defaultedExpiry: defaultedExpiry ?? existing?.defaultedExpiry ?? false, original: existing?.original ?? original });
|
|
468
|
+
};
|
|
469
|
+
const validReminderPolicies = (names: readonly string[]) =>
|
|
470
|
+
names.every(name => name !== legacy && Object.hasOwn(activeConfig.policies, name));
|
|
471
|
+
function unblockReminders(meta: Meta, channelId?: string) {
|
|
472
|
+
const unblocked: OneOffReminder[] = [];
|
|
473
|
+
let after = 0;
|
|
474
|
+
for (;;) {
|
|
475
|
+
const batch = reminders.blocked(channelId, after, 100);
|
|
476
|
+
for (const { reminder } of batch) {
|
|
477
|
+
if (tables.channel(reminder.channel)?.lifecycle !== "open" || !validReminderPolicies(reminder.policyNames)) continue;
|
|
478
|
+
const { blockedReason: _block, ...fields } = reminder;
|
|
479
|
+
const active: OneOffReminder = { ...fields, state: "active", nextRunAt: reminder.schedule.at };
|
|
480
|
+
putReminder(meta, active);
|
|
481
|
+
unblocked.push(active);
|
|
482
|
+
}
|
|
483
|
+
if (batch.length < 100) return unblocked.length ? { unblockedReminders: unblocked } : {};
|
|
484
|
+
after = batch.at(-1)!.sequence;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return {
|
|
488
|
+
startCall: (turnId, itemIds) => run(meta => {
|
|
489
|
+
if (!/^[1-9]\d*$/.test(turnId) || !Number.isSafeInteger(Number(turnId))) fail("invalid_input", "Invalid turn ID");
|
|
490
|
+
const turn = running(Number(turnId));
|
|
491
|
+
if (!Array.isArray(itemIds) || new Set(itemIds).size !== itemIds.length || itemIds.some(id => tables.item(id)?.turnId !== turn.turnId))
|
|
492
|
+
fail("invalid_input", "Model call inputs must be taken items of this turn");
|
|
493
|
+
const state = tables.getModelState() ?? emptyModelState();
|
|
494
|
+
if (state.calls.some(call => call.turnId === turnId && call.outcome === "running")) fail("invalid_state", "Turn already has a running model call");
|
|
495
|
+
const id = String(state.nextCall++), call: ModelCallSummary = { callId: id, turnId, channel: turn.channelId, messageId: `model:${id}`,
|
|
496
|
+
startedAt: now(), outcome: "running", attempts: [] };
|
|
497
|
+
state.calls.push(call); state.itemIds[id] = [...itemIds]; tables.setModelState(state, [call]); seq(meta); return call;
|
|
498
|
+
}),
|
|
499
|
+
startAttempt: (id, scripted) => run(meta => {
|
|
500
|
+
const state = tables.getModelState() ?? emptyModelState(), call = modelCall(state, id); running(Number(call.turnId));
|
|
501
|
+
if (call.outcome !== "running" || call.attempts.length >= 2 || call.attempts.some(a => a.outcome === "running")) fail("invalid_state", "Cannot start another model attempt");
|
|
502
|
+
const ordinal = call.attempts.length, step = Object.hasOwn(state.scriptPositions, call.channel) ? state.scriptPositions[call.channel]! : 0;
|
|
503
|
+
const attempt: ModelCallSummary["attempts"][number] = { attemptId: `${id}:${ordinal}`, ordinal, startedAt: now(), outcome: "running", ...(ordinal ? { retryReason: call.attempts[ordinal - 1]?.outcome } : {}), ...(scripted ? { scriptStep: step } : {}) };
|
|
504
|
+
if (scripted) Object.defineProperty(state.scriptPositions, call.channel, { value: step + 1, writable: true, configurable: true, enumerable: true });
|
|
505
|
+
call.attempts.push(attempt); tables.setModelState(state, [call]); seq(meta); return attempt;
|
|
506
|
+
}),
|
|
507
|
+
confirm: (id, attemptId, milestone) => run(meta => {
|
|
508
|
+
const state = tables.getModelState() ?? emptyModelState(); activeAttempt(state, id, attemptId);
|
|
509
|
+
if (milestone !== "delivered" && milestone !== "seen") fail("invalid_input", "Invalid receipt");
|
|
510
|
+
const advanced = (state.itemIds[id] ?? []).map(itemId => tables.item(itemId)!).filter(item => RANK[item.milestone] < RANK[milestone]);
|
|
511
|
+
for (const item of advanced) tables.putItem({ ...item, milestone });
|
|
512
|
+
if (advanced.length) seq(meta); return advanced.map(item => item.itemId);
|
|
513
|
+
}),
|
|
514
|
+
recordProviderRequestId: (id, attemptId, requestId) => run(meta => {
|
|
515
|
+
const state = tables.getModelState() ?? emptyModelState(), { call, attempt } = activeAttempt(state, id, attemptId);
|
|
516
|
+
if (!text(requestId)) fail("invalid_input", "Invalid provider request ID");
|
|
517
|
+
if (!attempt.providerRequestId) { attempt.providerRequestId = requestId; tables.setModelState(state, [call]); seq(meta); }
|
|
518
|
+
}),
|
|
519
|
+
recordUsage: (id, attemptId, usage) => run(meta => {
|
|
520
|
+
const state = tables.getModelState() ?? emptyModelState(), call = modelCall(state, id);
|
|
521
|
+
const attempt = call.attempts.find(value => value.attemptId === attemptId);
|
|
522
|
+
if (!attempt) return fail("not_found", "Unknown model attempt");
|
|
523
|
+
if (call.outcome !== "running" || attempt.outcome !== "running" || tables.turn(Number(call.turnId))?.state.status !== "running") return;
|
|
524
|
+
if (!usage || typeof usage !== "object" || Object.keys(usage).some(key => !["inputTokens", "outputTokens", "totalTokens"].includes(key))
|
|
525
|
+
|| Object.values(usage).some(value => !Number.isSafeInteger(value) || value < 0)) fail("invalid_input", "Invalid provider usage");
|
|
526
|
+
attempt.usage = structuredClone(usage); tables.setModelState(state, [call]); seq(meta);
|
|
527
|
+
}),
|
|
528
|
+
finishAttempt: (id, attemptId, outcome, requestId) => run(meta => {
|
|
529
|
+
const state = tables.getModelState() ?? emptyModelState(), { call, attempt } = activeAttempt(state, id, attemptId);
|
|
530
|
+
if (!["transient_failure", "invalid_request", "invalid_config", "provider_failure", "incomplete", "output_limit", "timeout", "interrupted"].includes(outcome) || (requestId !== undefined && !text(requestId))) fail("invalid_input", "Invalid attempt outcome or provider ID");
|
|
531
|
+
attempt.outcome = outcome; attempt.endedAt = now(); if (!attempt.providerRequestId && requestId) attempt.providerRequestId = requestId;
|
|
532
|
+
tables.setModelState(state, [call]); seq(meta);
|
|
533
|
+
}),
|
|
534
|
+
commitResponse: (id, attemptId, response, requestId) => run(meta => {
|
|
535
|
+
const state = tables.getModelState() ?? emptyModelState(), { call, attempt } = activeAttempt(state, id, attemptId), turn = running(Number(call.turnId));
|
|
536
|
+
if (requestId !== undefined && !text(requestId)) fail("invalid_input", "Invalid provider request ID");
|
|
537
|
+
if (!response || !((response.stopReason === "complete" && response.calls?.length === 0) || (response.stopReason === "tool_calls" && response.calls?.length > 0))) fail("invalid_input", "Invalid response stop reason");
|
|
538
|
+
const { stopReason: _stopReason, ...raw } = response, message = checkMessage(raw);
|
|
539
|
+
if (message.role !== "assistant") return fail("invalid_input", "Expected assistant response");
|
|
540
|
+
if (unanswered(tables, turn.turnId).length) fail("invalid_state", "Earlier tool calls have no result");
|
|
541
|
+
const used = new Set(tables.entriesOfTurn(turn.turnId).flatMap(entry => entry.message.role === "assistant" ? entry.message.calls.map(c => c.id) : []));
|
|
542
|
+
for (const tool of message.calls) {
|
|
543
|
+
if (used.has(tool.id)) fail("invalid_input", "Duplicate tool call ID"); used.add(tool.id);
|
|
544
|
+
try { const args = JSON.parse(tool.arguments); if (!args || typeof args !== "object" || Array.isArray(args)) fail("invalid_input", "Invalid tool arguments"); }
|
|
545
|
+
catch (error) { if (error instanceof Fail) throw error; fail("invalid_input", "Invalid tool arguments"); }
|
|
546
|
+
}
|
|
547
|
+
if (message.calls.length && turn.state.status === "running" && turn.state.dispatchedCallIds === undefined) tables.putTurn({ ...turn, state: { ...turn.state, dispatchedCallIds: [] } });
|
|
548
|
+
const entry: TimelineEntry = { seq: seq(meta), at: now(), channelId: turn.channelId, turnId: turn.turnId, from: "agent", message };
|
|
549
|
+
tables.addEntry({ ...entry, messageId: call.messageId }); state.entryIds[String(entry.seq)] = call.messageId; call.outcome = "succeeded"; call.endedAt = now();
|
|
550
|
+
attempt.outcome = "succeeded"; attempt.endedAt = call.endedAt; if (!attempt.providerRequestId && requestId) attempt.providerRequestId = requestId;
|
|
551
|
+
tables.setModelState(state, [call]); return { ...entry, messageId: call.messageId };
|
|
552
|
+
}),
|
|
553
|
+
finishCall: (id, outcome) => run(meta => {
|
|
554
|
+
const state = tables.getModelState() ?? emptyModelState(), call = modelCall(state, id); running(Number(call.turnId));
|
|
555
|
+
if (call.outcome !== "running" || call.attempts.some(a => a.outcome === "running")) fail("invalid_state", "Cannot finish model call");
|
|
556
|
+
if (!["failed", "incomplete", "output_limit", "timeout", "interrupted"].includes(outcome)) fail("invalid_input", "Invalid call outcome");
|
|
557
|
+
call.outcome = outcome; call.endedAt = now(); tables.setModelState(state, [call]); seq(meta);
|
|
558
|
+
}),
|
|
559
|
+
readCalls: (after, limit = 100) => run(() => {
|
|
560
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) fail("invalid_input", "Invalid model call page size");
|
|
561
|
+
const rows = tables.modelCallPage(after, limit + 1);
|
|
562
|
+
const calls = rows.slice(0, limit);
|
|
563
|
+
return { calls, ...(rows.length > limit ? { next: calls.at(-1)!.callId } : {}) };
|
|
564
|
+
}, true),
|
|
565
|
+
acceptItem: (input, maxInputBytes) => run(meta => accept(meta, input, maxInputBytes), input?.kind === "external_notice"),
|
|
566
|
+
|
|
567
|
+
changeReminder: (change, wallTime) => run(meta => {
|
|
568
|
+
requireCompatible();
|
|
569
|
+
return applyReminderChange({
|
|
570
|
+
receipt: reminders.receipt, highWater: reminders.highWater, originalCreate: reminders.originalCreate,
|
|
571
|
+
defaultedExpiry: id => reminders.get(id)?.defaultedExpiry ?? false,
|
|
572
|
+
get: id => reminders.get(id)?.reminder, put: (reminder, defaulted, original) => putReminder(meta, reminder, defaulted, original),
|
|
573
|
+
saveReceipt(receipt) { activateReminders(meta); reminders.saveReceipt(receipt); seq(meta); },
|
|
574
|
+
channelStatus: channel => tables.channel(channel)?.lifecycle, validPolicies: validReminderPolicies,
|
|
575
|
+
}, change, wallTime);
|
|
576
|
+
}),
|
|
577
|
+
scheduleAgentReminder: (turnId, invocationId, schedule, body, inherited, grace, wallTime) => run(meta => {
|
|
578
|
+
requireCompatible();
|
|
579
|
+
const turn = running(turnId);
|
|
580
|
+
const id = `agent-reminder:${invocationId}`;
|
|
581
|
+
const existing = reminders.get(id)?.reminder;
|
|
582
|
+
if (existing) return { reminder: existing, created: false };
|
|
583
|
+
const anchor = new Date(wallTime).toISOString();
|
|
584
|
+
const at = resolveAgentReminder(schedule, wallTime);
|
|
585
|
+
const timing = at && normalizeReminderSchedule(at, anchor, grace, wallTime);
|
|
586
|
+
if (!timing) return fail("invalid_input", "Invalid reminder schedule");
|
|
587
|
+
const policyNames = [...new Set(inherited.filter(name => name !== legacy))].sort();
|
|
588
|
+
if (!validReminderPolicies(policyNames)) return fail("invalid_policy", "Unknown reminder policy");
|
|
589
|
+
const creatorId = tables.itemsOfTurn(turnId).find(item => item.kind === "participant_message")?.senderId;
|
|
590
|
+
const reminder: OneOffReminder = { ...timing, id, channel: turn.channelId, createdBy: "agent",
|
|
591
|
+
...(creatorId === undefined ? {} : { creatorId }), policyNames, text: body, state: "active", nextRunAt: timing.schedule.at };
|
|
592
|
+
putReminder(meta, reminder, grace === undefined);
|
|
593
|
+
return { reminder, created: true };
|
|
594
|
+
}),
|
|
595
|
+
cancelAgentReminder: (turnId, id) => run(meta => {
|
|
596
|
+
requireCompatible();
|
|
597
|
+
const turn = running(turnId), reminder = reminders.get(id)?.reminder;
|
|
598
|
+
if (!reminder || reminder.channel !== turn.channelId) return fail("not_found", "Unknown reminder");
|
|
599
|
+
const changed = !["done", "cancelled", "expired"].includes(reminder.state);
|
|
600
|
+
if (changed) putReminder(meta, { ...reminder, state: "cancelled", nextRunAt: null });
|
|
601
|
+
return { id, alreadyQueued: reminder.noticeId !== undefined, changed };
|
|
602
|
+
}),
|
|
603
|
+
readReminder: id => run(() => reminders.get(id)?.reminder, true),
|
|
604
|
+
listReminders: ({ channel, after, limit = 50 }) => run(meta => {
|
|
605
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) fail("invalid_input", "Invalid reminder list limit");
|
|
606
|
+
const revision = reminders.listingRevision();
|
|
607
|
+
const cursor = (position: number) => Buffer.from(JSON.stringify([meta.sessionId, channel ?? null, revision, position])).toString("base64url");
|
|
608
|
+
let position = 0;
|
|
609
|
+
if (after !== undefined) {
|
|
610
|
+
try {
|
|
611
|
+
const parsed = JSON.parse(Buffer.from(after, "base64url").toString());
|
|
612
|
+
position = parsed[3];
|
|
613
|
+
if (!Number.isSafeInteger(position) || position < 1 || cursor(position) !== after) fail("invalid_cursor", "Reminder listing cursor expired");
|
|
614
|
+
} catch { fail("invalid_cursor", "Invalid or stale reminder listing cursor"); }
|
|
615
|
+
}
|
|
616
|
+
const rows = reminders.list(channel, position, limit + 1);
|
|
617
|
+
const page = rows.slice(0, limit);
|
|
618
|
+
return { reminders: page.map(row => row.reminder), ...(rows.length > limit ? { next: cursor(page.at(-1)!.sequence) } : {}) };
|
|
619
|
+
}, true),
|
|
620
|
+
reminderWake: () => run(() => reminders.wake(), true),
|
|
621
|
+
fireDueReminders: wallTime => run(meta => {
|
|
622
|
+
requireCompatible();
|
|
623
|
+
const events: Array<{ channel: string; event: ReminderChannelEvent }> = [];
|
|
624
|
+
if (meta.lifecycle !== "running") return events;
|
|
625
|
+
const firedAt = new Date(wallTime).toISOString();
|
|
626
|
+
for (const { reminder } of reminders.eligible(firedAt, 100)) {
|
|
627
|
+
const { id, channel, schedule } = reminder;
|
|
628
|
+
const scheduledAt = schedule.at, occurrenceId = `reminder:${id}:${scheduledAt}`;
|
|
629
|
+
if (reminder.expiresAt !== null && reminder.expiresAt <= firedAt) {
|
|
630
|
+
putReminder(meta, { ...reminder, state: "expired", nextRunAt: null, lastOccurrenceId: occurrenceId });
|
|
631
|
+
events.push({ channel, event: { type: "reminder_expired", reminderId: id, occurrenceId, scheduledAt, expiredAt: firedAt } });
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
if (!validReminderPolicies(reminder.policyNames)) {
|
|
635
|
+
const blocked: OneOffReminder = { ...reminder, state: "blocked", nextRunAt: null, blockedReason: "invalid_policy" };
|
|
636
|
+
putReminder(meta, blocked);
|
|
637
|
+
events.push({ channel, event: { type: "reminder_changed", reminder: blocked } });
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
const noticeId = `reminder-notice:${id}:${scheduledAt}`;
|
|
641
|
+
accept(meta, { kind: "external_notice", itemId: noticeId, channelId: channel, senderId: `reminder:${id}`,
|
|
642
|
+
externalSource: `reminder:${id}`, text: reminder.text, inheritedPolicyNames: reminder.policyNames });
|
|
643
|
+
putReminder(meta, { ...reminder, state: "done", nextRunAt: null, lastOccurrenceId: occurrenceId, lastRunAt: firedAt, noticeId });
|
|
644
|
+
events.push({ channel, event: { type: "reminder_fired", reminderId: id, occurrenceId, scheduledAt, firedAt, noticeId } });
|
|
645
|
+
}
|
|
646
|
+
return events;
|
|
647
|
+
}),
|
|
648
|
+
|
|
649
|
+
beginTurn: (channelId, intake) => run(meta => {
|
|
650
|
+
requireCompatible();
|
|
651
|
+
if (meta.lifecycle !== "running") fail("not_running", `Session is ${meta.lifecycle}; no turn can begin`);
|
|
652
|
+
const channel = channelOf(channelId);
|
|
653
|
+
if (channel.lifecycle !== "open") fail("channel_suspended", `Channel ${channel.channelId} is ${channel.lifecycle}; no turn can begin`);
|
|
654
|
+
if (tables.liveTurn(channel.channelId)) return null;
|
|
655
|
+
const pending = boundaryPending(channelId, intake);
|
|
656
|
+
if (!pending.length) return null;
|
|
657
|
+
const turn: TurnRow = { turnId: meta.nextTurnId++, channelId, startedSeq: seq(meta), startedAt: now(),
|
|
658
|
+
compatibilityKey: ownerKey, state: { status: "running" } };
|
|
659
|
+
tables.putTurn(turn);
|
|
660
|
+
return take(meta, turn, pending);
|
|
661
|
+
}),
|
|
662
|
+
|
|
663
|
+
takePending: (turnId, intake) => run(meta => {
|
|
664
|
+
const turn = running(turnId);
|
|
665
|
+
if (meta.lifecycle !== "running") fail("not_running", `Session is ${meta.lifecycle}; input stays pending`);
|
|
666
|
+
const channel = channelOf(turn.channelId);
|
|
667
|
+
if (channel.lifecycle !== "open") fail("channel_suspended", `Channel ${channel.channelId} is ${channel.lifecycle}; input stays pending`);
|
|
668
|
+
return take(meta, turn, boundaryPending(turn.channelId, intake, turnId));
|
|
669
|
+
}),
|
|
670
|
+
|
|
671
|
+
appendMessage: (turnId, raw) => run(meta => {
|
|
672
|
+
const turn = running(turnId), message = checkMessage(raw), open = unanswered(tables, turnId);
|
|
673
|
+
if (message.role === "assistant") {
|
|
674
|
+
if (open.length) fail("invalid_state", "Earlier tool calls in this turn have no recorded result");
|
|
675
|
+
const used = new Set<string>();
|
|
676
|
+
for (const entry of tables.entriesOfTurn(turnId))
|
|
677
|
+
if (entry.message.role === "assistant") for (const call of entry.message.calls) used.add(call.id);
|
|
678
|
+
for (const call of message.calls) {
|
|
679
|
+
if (used.has(call.id)) fail("invalid_input", `Duplicate tool call ID: ${call.id}`);
|
|
680
|
+
used.add(call.id);
|
|
681
|
+
}
|
|
682
|
+
if (message.calls.length && turn.state.status === "running" && turn.state.dispatchedCallIds === undefined)
|
|
683
|
+
tables.putTurn({ ...turn, state: { ...turn.state, dispatchedCallIds: [] } });
|
|
684
|
+
} else if (!open.includes(message.callId)) fail("invalid_input", `No unanswered call ${message.callId} in this turn`);
|
|
685
|
+
const entry: TimelineEntry = { seq: seq(meta), at: now(), channelId: turn.channelId, turnId,
|
|
686
|
+
from: message.role === "tool" ? "tool" : "agent", message: structuredClone(message) };
|
|
687
|
+
tables.addEntry(entry);
|
|
688
|
+
return entry;
|
|
689
|
+
}),
|
|
690
|
+
|
|
691
|
+
markToolDispatched: (turnId, callId) => run(meta => {
|
|
692
|
+
const turn = running(turnId);
|
|
693
|
+
const state = turn.state.status === "running" ? turn.state : fail("invalid_state", "Turn is not running");
|
|
694
|
+
if (!text(callId) || !unanswered(tables, turnId).includes(callId)
|
|
695
|
+
|| state.dispatchedCallIds?.includes(callId)) fail("invalid_state", "Call is not an undispatched outstanding call of this turn");
|
|
696
|
+
tables.putTurn({ ...turn, state: { ...state, dispatchedCallIds: [...(state.dispatchedCallIds ?? []), callId] } });
|
|
697
|
+
seq(meta);
|
|
698
|
+
}),
|
|
699
|
+
|
|
700
|
+
confirmReceipts: (turnId, milestone) => run(meta => {
|
|
701
|
+
running(turnId);
|
|
702
|
+
if (milestone !== "delivered" && milestone !== "seen") fail("invalid_input", "Receipt must be delivered or seen");
|
|
703
|
+
const advanced = tables.itemsOfTurn(turnId).filter(item => RANK[item.milestone] < RANK[milestone])
|
|
704
|
+
.map(item => ({ ...item, milestone }));
|
|
705
|
+
for (const item of advanced) tables.putItem(item);
|
|
706
|
+
if (advanced.length) seq(meta);
|
|
707
|
+
return advanced;
|
|
708
|
+
}),
|
|
709
|
+
|
|
710
|
+
finishTurn: (turnId, outcome) => run(meta => {
|
|
711
|
+
const turn = running(turnId);
|
|
712
|
+
if (outcome?.status === "completed") {
|
|
713
|
+
const last = tables.entriesOfTurn(turnId).at(-1)?.message;
|
|
714
|
+
if (!last || last.role !== "assistant" || last.calls.length)
|
|
715
|
+
fail("invalid_state", "Completion needs a final assistant response without tool calls");
|
|
716
|
+
const pending = tables.pendingCount(turn.channelId);
|
|
717
|
+
if (pending) return { finished: false as const, pending };
|
|
718
|
+
const done: TurnRow = { ...turn, state: { status: "completed" } };
|
|
719
|
+
tables.putTurn(done); settle(turn.channelId); seq(meta);
|
|
720
|
+
return { finished: true as const, turn: full(done) };
|
|
721
|
+
}
|
|
722
|
+
if (!outcome || (outcome.status !== "failed" && outcome.status !== "interrupted") || !text(outcome.reason))
|
|
723
|
+
fail("invalid_input", "Outcome must be completed, or failed/interrupted with a reason");
|
|
724
|
+
const ended = interrupt(turn, outcome.status as "failed" | "interrupted", (outcome as { reason: string }).reason);
|
|
725
|
+
seq(meta);
|
|
726
|
+
return { finished: true as const, turn: full(ended) };
|
|
727
|
+
}),
|
|
728
|
+
|
|
729
|
+
checkpointTurn: turnId => run(meta => {
|
|
730
|
+
const turn = running(turnId);
|
|
731
|
+
if (meta.lifecycle !== "suspending" && tables.channel(turn.channelId)?.lifecycle !== "suspending")
|
|
732
|
+
fail("invalid_state", "Checkpoints are saved only while the session or the channel is suspending");
|
|
733
|
+
if (unanswered(tables, turnId).length) fail("invalid_state", "A tool call in this turn has no recorded result");
|
|
734
|
+
const last = tables.entriesOfTurn(turnId).at(-1);
|
|
735
|
+
if (last?.message.role === "assistant" && !last.message.calls.length && !tables.pendingItems(turn.channelId).length)
|
|
736
|
+
fail("invalid_state", "This turn is finished; complete it instead of checkpointing");
|
|
737
|
+
const saved: TurnRow = { ...turn, state: { status: "suspended", ...(turn.state.status === "running" && turn.state.dispatchedCallIds !== undefined ? { dispatchedCallIds: turn.state.dispatchedCallIds } : {}),
|
|
738
|
+
checkpoint: { nextStep: "inference", afterSeq: last?.seq ?? turn.startedSeq, policyFingerprint: turnFingerprint(turn) } } };
|
|
739
|
+
tables.putTurn(saved); settle(turn.channelId); seq(meta);
|
|
740
|
+
return full(saved);
|
|
741
|
+
}),
|
|
742
|
+
|
|
743
|
+
beginSuspend: () => run(meta => {
|
|
744
|
+
if (meta.lifecycle === "running") { meta.lifecycle = "suspending"; seq(meta); }
|
|
745
|
+
return session(meta);
|
|
746
|
+
}),
|
|
747
|
+
|
|
748
|
+
completeSuspend: () => run(meta => {
|
|
749
|
+
if (meta.lifecycle === "suspended") return session(meta);
|
|
750
|
+
if (meta.lifecycle !== "suspending") fail("invalid_state", "Session is not suspending");
|
|
751
|
+
if (tables.turns().some(turn => turn.state.status === "running")) fail("invalid_state", "A turn is still running");
|
|
752
|
+
meta.lifecycle = "suspended"; seq(meta);
|
|
753
|
+
return session(meta);
|
|
754
|
+
}),
|
|
755
|
+
|
|
756
|
+
resume: () => run(meta => {
|
|
757
|
+
requireCompatible();
|
|
758
|
+
if (meta.lifecycle === "running") return { session: session(meta), turns: [], ...unblockReminders(meta) };
|
|
759
|
+
if (meta.lifecycle !== "suspended") fail("invalid_state", "Session is still suspending");
|
|
760
|
+
// Turns of individually suspended (or retired) channels are not ours to resume.
|
|
761
|
+
const saved = tables.turns().filter(turn => turn.state.status === "suspended"
|
|
762
|
+
&& ["open", "suspending"].includes(tables.channel(turn.channelId)?.lifecycle ?? "retired"));
|
|
763
|
+
const foreign = saved.find(turn => !compatible(turn));
|
|
764
|
+
if (foreign) fail("incompatible", `Turn ${foreign.turnId} was checkpointed under a different configuration`);
|
|
765
|
+
const turns = saved.map(turn => { const live: TurnRow = { ...turn, state: { status: "running", ...(turn.state.status === "suspended" && turn.state.dispatchedCallIds !== undefined ? { dispatchedCallIds: turn.state.dispatchedCallIds } : {}) } }; tables.putTurn(live); return full(live); });
|
|
766
|
+
meta.lifecycle = "running"; seq(meta);
|
|
767
|
+
return { session: session(meta), turns, ...unblockReminders(meta) };
|
|
768
|
+
}),
|
|
769
|
+
|
|
770
|
+
interruptActive: reason => run(meta => {
|
|
771
|
+
if (!text(reason)) fail("invalid_input", "Interruption needs a reason");
|
|
772
|
+
if (meta.lifecycle === "suspended") return [];
|
|
773
|
+
const suspending = meta.lifecycle === "suspending";
|
|
774
|
+
const held = (turn: TurnRow) => tables.channel(turn.channelId)?.lifecycle === "suspended";
|
|
775
|
+
// A `suspending` channel never committed: it returns to `open`, not to
|
|
776
|
+
// `suspended`, so settle it only after the turns below have ended.
|
|
777
|
+
const reopened = tables.channels().filter(channel => channel.lifecycle === "suspending");
|
|
778
|
+
for (const channel of reopened) tables.putChannel({ ...channel, lifecycle: "open" });
|
|
779
|
+
const ended = tables.turns().filter(turn => turn.state.status === "running" || (suspending && turn.state.status === "suspended" && !held(turn)))
|
|
780
|
+
.map(turn => full(interrupt(turn, "interrupted", reason)));
|
|
781
|
+
if (suspending) meta.lifecycle = "running";
|
|
782
|
+
if (ended.length || suspending || reopened.length) seq(meta);
|
|
783
|
+
return ended;
|
|
784
|
+
}),
|
|
785
|
+
|
|
786
|
+
setToolRevoked: (name, revoked) => run(meta => {
|
|
787
|
+
if (!text(name) || typeof revoked !== "boolean") fail("invalid_input", "Tool revocation needs a name and a boolean");
|
|
788
|
+
const current = tables.getRevokedTools() ?? [];
|
|
789
|
+
if (current.includes(name) === revoked) return current;
|
|
790
|
+
const next = revoked ? [...current, name].sort() : current.filter(value => value !== name);
|
|
791
|
+
tables.setRevokedTools(next); seq(meta);
|
|
792
|
+
return next;
|
|
793
|
+
}),
|
|
794
|
+
|
|
795
|
+
createChannel: input => run(meta => {
|
|
796
|
+
if (!input || typeof input !== "object" || !text(input.channelId)) fail("invalid_input", "Channel needs a channelId");
|
|
797
|
+
const name = input.displayName === undefined ? undefined : cleanName(input.displayName);
|
|
798
|
+
if (input.policy !== undefined) resolve(input.policy);
|
|
799
|
+
const known = tables.channel(input.channelId);
|
|
800
|
+
if (known?.lifecycle === "retired") fail("channel_retired", `Channel ${input.channelId} is retired`);
|
|
801
|
+
if (known) {
|
|
802
|
+
if (known.displayName !== name || known.policy !== input.policy) fail("already_exists", `Channel ${input.channelId} already exists with different settings`);
|
|
803
|
+
return { channel: view(known), created: false };
|
|
804
|
+
}
|
|
805
|
+
const row: ChannelRow = { channelId: input.channelId, ...(name === undefined ? {} : { displayName: name }), ...(input.policy === undefined ? {} : { policy: input.policy }), lifecycle: "open" };
|
|
806
|
+
tables.putChannel(row); seq(meta);
|
|
807
|
+
return { channel: view(row), created: true };
|
|
808
|
+
}),
|
|
809
|
+
|
|
810
|
+
editChannel: (channelId, displayName, policy) => run(meta => {
|
|
811
|
+
const channel = channelOf(channelId);
|
|
812
|
+
const name = displayName === null ? undefined : cleanName(displayName);
|
|
813
|
+
if (policy != null) resolve(policy);
|
|
814
|
+
const nextPolicy = policy === undefined ? channel.policy : policy ?? undefined;
|
|
815
|
+
if (channel.displayName === name && channel.policy === nextPolicy) return view(channel);
|
|
816
|
+
const { displayName: _old, policy: _previous, ...rest } = channel;
|
|
817
|
+
const row: ChannelRow = { ...rest, ...(name === undefined ? {} : { displayName: name }), ...(nextPolicy === undefined ? {} : { policy: nextPolicy }) };
|
|
818
|
+
tables.putChannel(row); seq(meta);
|
|
819
|
+
return view(row);
|
|
820
|
+
}),
|
|
821
|
+
|
|
822
|
+
beginChannelSuspend: channelId => run(meta => {
|
|
823
|
+
const channel = channelOf(channelId);
|
|
824
|
+
if (channel.lifecycle !== "open") return view(channel);
|
|
825
|
+
// A checkpointed turn is not running: nothing to wait for.
|
|
826
|
+
const row: ChannelRow = { ...channel, lifecycle: tables.liveTurn(channel.channelId)?.state.status === "running" ? "suspending" : "suspended" };
|
|
827
|
+
tables.putChannel(row); seq(meta);
|
|
828
|
+
return view(row);
|
|
829
|
+
}),
|
|
830
|
+
|
|
831
|
+
resumeChannel: channelId => run(meta => {
|
|
832
|
+
requireCompatible();
|
|
833
|
+
const channel = channelOf(channelId);
|
|
834
|
+
if (channel.lifecycle === "open") return { channel: view(channel), ...unblockReminders(meta, channel.channelId) };
|
|
835
|
+
if (channel.lifecycle === "suspending") fail("invalid_state", `Channel ${channel.channelId} is still suspending`);
|
|
836
|
+
const saved = tables.liveTurn(channel.channelId);
|
|
837
|
+
const cont = saved?.state.status === "suspended" && meta.lifecycle === "running" ? saved : undefined;
|
|
838
|
+
if (cont && !compatible(cont))
|
|
839
|
+
fail("incompatible", `Turn ${cont.turnId} was checkpointed under a different configuration`);
|
|
840
|
+
const row: ChannelRow = { ...channel, lifecycle: "open" };
|
|
841
|
+
tables.putChannel(row);
|
|
842
|
+
let turn: StoredTurn | undefined;
|
|
843
|
+
if (cont) { const live: TurnRow = { ...cont, state: { status: "running", ...(cont.state.status === "suspended" && cont.state.dispatchedCallIds !== undefined ? { dispatchedCallIds: cont.state.dispatchedCallIds } : {}) } }; tables.putTurn(live); turn = full(live); }
|
|
844
|
+
seq(meta);
|
|
845
|
+
return { channel: view(row), ...(turn ? { turn } : {}), ...unblockReminders(meta, channel.channelId) };
|
|
846
|
+
}),
|
|
847
|
+
|
|
848
|
+
deleteChannel: channelId => run(meta => {
|
|
849
|
+
const channel = tables.channel(channelId as string) ?? fail("not_found", `Unknown channel: ${String(channelId)}`);
|
|
850
|
+
if (channel.lifecycle === "retired") return view(channel);
|
|
851
|
+
if (tables.liveTurn(channel.channelId)) fail("channel_busy", `Channel ${channel.channelId} has an active or checkpointed turn`);
|
|
852
|
+
if (tables.pendingItems(channel.channelId).length) fail("channel_busy", `Channel ${channel.channelId} has pending input`);
|
|
853
|
+
const row: ChannelRow = { ...channel, lifecycle: "retired" };
|
|
854
|
+
tables.putChannel(row); seq(meta);
|
|
855
|
+
const cancelledReminderIds: string[] = [];
|
|
856
|
+
let after = 0;
|
|
857
|
+
for (;;) {
|
|
858
|
+
const batch = reminders.list(channelId, after, 100);
|
|
859
|
+
for (const { reminder } of batch) {
|
|
860
|
+
if (reminder.state !== "active" && reminder.state !== "paused" && reminder.state !== "blocked") continue;
|
|
861
|
+
putReminder(meta, { ...reminder, state: "cancelled", nextRunAt: null });
|
|
862
|
+
cancelledReminderIds.push(reminder.id);
|
|
863
|
+
}
|
|
864
|
+
if (batch.length < 100) break;
|
|
865
|
+
after = batch.at(-1)!.sequence;
|
|
866
|
+
}
|
|
867
|
+
return cancelledReminderIds.length ? { ...view(row), cancelledReminderIds } : view(row);
|
|
868
|
+
}),
|
|
869
|
+
|
|
870
|
+
withdrawItem: (channelId, itemId) => run(meta => {
|
|
871
|
+
const known = typeof itemId === "string" ? tables.item(itemId) : undefined;
|
|
872
|
+
if (!known || known.channelId !== channelId) fail("not_found", `Unknown item ${String(itemId)} on channel ${String(channelId)}`);
|
|
873
|
+
const item = known!;
|
|
874
|
+
if (item.milestone === "withdrawn") return { outcome: "withdrawn" as const, item, repeated: true };
|
|
875
|
+
if (item.milestone !== "received") return { outcome: "taken" as const, item, turnId: item.turnId! };
|
|
876
|
+
const withdrawn: StoredItem = { ...item, milestone: "withdrawn", withdrawnAt: now() };
|
|
877
|
+
tables.putItem(withdrawn); seq(meta);
|
|
878
|
+
return { outcome: "withdrawn" as const, item: withdrawn, repeated: false };
|
|
879
|
+
}),
|
|
880
|
+
|
|
881
|
+
interruptTurn: (channelId, turnId, reason) => run(meta => {
|
|
882
|
+
if (!text(reason)) fail("invalid_input", "Interruption needs a reason");
|
|
883
|
+
const turn = tables.turn(turnId);
|
|
884
|
+
if (!turn || turn.channelId !== channelId) fail("not_found", `Unknown turn ${String(turnId)} on channel ${String(channelId)}`);
|
|
885
|
+
if (turn!.state.status !== "running") return { interrupted: false as const, turn: full(turn!) };
|
|
886
|
+
const ended = interrupt(turn!, "interrupted", reason); seq(meta);
|
|
887
|
+
return { interrupted: true as const, turn: full(ended) };
|
|
888
|
+
}),
|
|
889
|
+
|
|
890
|
+
ownerConfig: () => run(() => ownerSnapshot, true),
|
|
891
|
+
executionCompatible: () => run(() => !incompatibleViewOnly && referencesCompatible(tables, activeConfig), true),
|
|
892
|
+
importedConfig: () => run(() => tables.getConfig(), true),
|
|
893
|
+
saveConfig: value => run(() => {
|
|
894
|
+
let checked: ManagedConfig;
|
|
895
|
+
try { checked = validateManagedConfig(value); } catch (error) { return fail("invalid_input", String(error)); }
|
|
896
|
+
if (!referencesCompatible(tables, checked)) fail("incompatible", "A stored policy no longer exists");
|
|
897
|
+
tables.setConfig(checked);
|
|
898
|
+
}),
|
|
899
|
+
readExecution: () => run(meta => {
|
|
900
|
+
const channels = tables.channels().map(channel => ({ ...channel, participantIds: [] }));
|
|
901
|
+
const turns = channels.flatMap(({ channelId }) => {
|
|
902
|
+
const active = tables.liveTurn(channelId), last = tables.latestTurn(channelId);
|
|
903
|
+
return [active?.turnId === last?.turnId ? undefined : active, last].flatMap(turn => turn ? [{ ...turn, itemIds: turn.state.status === "failed" || turn.state.status === "interrupted" ? tables.itemsOfTurn(turn.turnId).map(item => item.itemId) : [] }] : []);
|
|
904
|
+
});
|
|
905
|
+
return { revision: meta.revision, session: session(meta), channels, turns,
|
|
906
|
+
items: channels.flatMap(channel => tables.pendingItems(channel.channelId)) };
|
|
907
|
+
}, true),
|
|
908
|
+
readReadyChannels: () => run(meta => ({ lifecycle: meta.lifecycle,
|
|
909
|
+
channels: tables.channels().filter(channel => channel.lifecycle === "open" && tables.pendingCount(channel.channelId) > 0).map(channel => channel.channelId) }), true),
|
|
910
|
+
readRevokedTools: () => run(() => tables.getRevokedTools() ?? [], true),
|
|
911
|
+
readSession: () => run(meta => session(meta), true),
|
|
912
|
+
readChannel: channelId => run(() => {
|
|
913
|
+
const channel = tables.channel(channelId);
|
|
914
|
+
if (!channel) return fail("not_found", "Unknown channel");
|
|
915
|
+
const activeTurn = tables.liveTurn(channelId);
|
|
916
|
+
return { channel, pendingCount: tables.pendingCount(channelId), ...(activeTurn ? { activeTurn } : {}) };
|
|
917
|
+
}, true),
|
|
918
|
+
readTracked: (channelId, itemIds, turnIds) => run(() => {
|
|
919
|
+
if (itemIds.length + turnIds.length > 100) fail("invalid_input", "Too many tracked IDs");
|
|
920
|
+
const items = itemIds.flatMap(id => {
|
|
921
|
+
const item = tables.item(id);
|
|
922
|
+
return item?.channelId === channelId ? [item] : [];
|
|
923
|
+
});
|
|
924
|
+
const turns = turnIds.flatMap(id => {
|
|
925
|
+
const turn = tables.turn(id);
|
|
926
|
+
return turn?.channelId === channelId ? [full(turn)] : [];
|
|
927
|
+
});
|
|
928
|
+
return { items, turns };
|
|
929
|
+
}, true),
|
|
930
|
+
searchTimeline: (input, maxBytes) => run(() => searchTimeline(tables, input, maxBytes), true),
|
|
931
|
+
readMessage: (input, maxBytes) => run(meta => readMessageWindow(tables, meta, input, maxBytes), true),
|
|
932
|
+
readTimeline: range => run(meta => {
|
|
933
|
+
if (!Number.isSafeInteger(range.limit) || range.limit < 1 || range.limit > 100
|
|
934
|
+
|| !Number.isSafeInteger(range.throughRevision) || range.throughRevision < 0 || range.throughRevision > meta.revision)
|
|
935
|
+
fail("invalid_input", "Invalid timeline bounds");
|
|
936
|
+
const rows = tables.readRange(range);
|
|
937
|
+
return { entries: rows.slice(0, range.limit), more: rows.length > range.limit };
|
|
938
|
+
}, true),
|
|
939
|
+
readInspectionStatus: () => run(meta => ({
|
|
940
|
+
session: session(meta),
|
|
941
|
+
channels: tables.channels().map(({ channelId, lifecycle }) => {
|
|
942
|
+
const live = tables.liveTurn(channelId), latest = tables.latestTurn(channelId);
|
|
943
|
+
const state = latest?.state;
|
|
944
|
+
return { id: channelId, lifecycle, pending: tables.pendingCount(channelId),
|
|
945
|
+
...(live ? { turn: live.state.status as "running" | "suspended" } : {}),
|
|
946
|
+
...(latest && (state?.status === "failed" || state?.status === "interrupted")
|
|
947
|
+
? { unresolved: { turnId: latest.turnId, ...state } } : {}) };
|
|
948
|
+
}),
|
|
949
|
+
}), true),
|
|
950
|
+
readInspectionPage: before => run(meta => {
|
|
951
|
+
if (before !== undefined && (!Number.isSafeInteger(before) || before < 1)) fail("invalid_input", "Invalid inspection cursor");
|
|
952
|
+
const pageSize = 40, rows = tables.contextRecent(before ?? Number.MAX_SAFE_INTEGER, pageSize + 1, meta.formatVersion < 6);
|
|
953
|
+
const entries: InspectionEntry[] = [], unfinished: ContextTurnOutcome[] = [], turns = new Set<number>();
|
|
954
|
+
let budget = 64 * 1024;
|
|
955
|
+
for (const row of rows.slice(0, pageSize)) {
|
|
956
|
+
if (row.bytes > budget || row.bytes > 16 * 1024) { entries.push({ seq: row.seq, omitted: true }); continue; }
|
|
957
|
+
budget -= row.bytes;
|
|
958
|
+
const saved = tables.contextEntry(row.seq);
|
|
959
|
+
entries.push(saved);
|
|
960
|
+
turns.add(saved.turnId);
|
|
961
|
+
}
|
|
962
|
+
for (const id of turns) {
|
|
963
|
+
if (!budget) break;
|
|
964
|
+
const outcome = tables.contextUnfinished(id, Math.min(budget, 4096));
|
|
965
|
+
if (outcome) { budget -= outcome.bytes; unfinished.push(outcome.outcome); }
|
|
966
|
+
}
|
|
967
|
+
return { entries, unfinished, ...(rows.length > pageSize ? { next: entries.at(-1)!.seq } : {}) };
|
|
968
|
+
}, true),
|
|
969
|
+
readInspectionCalls: channel => run(() => {
|
|
970
|
+
const calls = tables.getModelState()?.calls ?? [];
|
|
971
|
+
const page: ModelCallSummary[] = [];
|
|
972
|
+
for (let i = calls.length - 1; i >= 0 && page.length < 40; i--) {
|
|
973
|
+
const call = calls[i]!;
|
|
974
|
+
if (call.channel === channel) page.push(call);
|
|
975
|
+
}
|
|
976
|
+
return page;
|
|
977
|
+
}, true),
|
|
978
|
+
readInferencePolicies: (turnId, limits) => run(() => {
|
|
979
|
+
if (!validReadLimits(limits)) fail("invalid_input", "Invalid inference read limits");
|
|
980
|
+
return tables.contextPolicies(turnId, limits.maxReadRecords, limits.maxReadBytes)?.names ?? { code: "context_limit" as const };
|
|
981
|
+
}, true),
|
|
982
|
+
readInferenceContext: input => run(meta => {
|
|
983
|
+
if (meta.formatVersion < 6) fail("incompatible", "Inference reads need a recovered session");
|
|
984
|
+
if (!validReadLimits(input.limits)) fail("invalid_input", "Invalid inference read limits");
|
|
985
|
+
const start = tables.contextTurnStart(input.channelId, input.turnId) ?? fail("not_found", "Turn not found on channel");
|
|
986
|
+
return readInference(tables, input, start);
|
|
987
|
+
}, true),
|
|
988
|
+
snapshot: () => run(() => readSnapshot(tables), true),
|
|
989
|
+
|
|
990
|
+
exportArchive: () => run(meta => {
|
|
991
|
+
const snapshot = readSnapshot(tables);
|
|
992
|
+
if (snapshot.modelCalls.some(call => call.outcome === "running" || call.attempts.some(attempt => attempt.outcome === "running")))
|
|
993
|
+
fail("busy", "A model call or attempt is still running");
|
|
994
|
+
const idle = meta.lifecycle === "running" && !snapshot.turns.some(turn => turn.state.status === "running" || turn.state.status === "suspended")
|
|
995
|
+
&& !snapshot.channels.some(channel => channel.lifecycle === "suspending")
|
|
996
|
+
&& !snapshot.items.some(item => item.milestone === "received");
|
|
997
|
+
if (meta.lifecycle !== "suspended" && !idle) fail("busy", "Export needs an idle or cleanly suspended session");
|
|
998
|
+
const archive: SessionArchive = { format: "harness-session", archiveVersion: meta.formatVersion === 7 ? 6 : 5, exportedAt: now(), snapshot,
|
|
999
|
+
...(meta.formatVersion === 7 ? { reminderState: reminders.archive() } : {}),
|
|
1000
|
+
allocation: { nextTurnId: meta.nextTurnId, nextSeq: meta.revision + 1, nextItemNumber: meta.nextItemNumber } };
|
|
1001
|
+
return archive;
|
|
1002
|
+
}),
|
|
1003
|
+
|
|
1004
|
+
close() {
|
|
1005
|
+
if (closed) return { ok: true, value: undefined, revision: 0 };
|
|
1006
|
+
let revision: number;
|
|
1007
|
+
try { revision = tables.getMeta().revision; release(); }
|
|
1008
|
+
catch (error) { return failure(error); }
|
|
1009
|
+
closed = true;
|
|
1010
|
+
return { ok: true, value: undefined, revision };
|
|
1011
|
+
},
|
|
1012
|
+
};
|
|
1013
|
+
}
|