@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,625 @@
|
|
|
1
|
+
import { sqliteReminderTables } from "./sqlite-reminders.ts";
|
|
2
|
+
import { historicalCandidate, historicalRetrievalProjection, encodedTimelineToken, retrievalMessage, timelineBytes, timelineIndexText } from "../../util/timeline-text.ts";
|
|
3
|
+
import type { ModelCallSummary } from "../../contracts/model-execution.ts";
|
|
4
|
+
import { entryOverhead, type ContextRow } from "./inference.ts";
|
|
5
|
+
import { checkScriptIdentity } from "./script-identity.ts";
|
|
6
|
+
import { Database } from "bun:sqlite";
|
|
7
|
+
import { existsSync, linkSync, rmSync } from "node:fs";
|
|
8
|
+
import type { PortableSessionConfig } from "../../contracts/session-file.ts";
|
|
9
|
+
import type { SessionStorageAdapter, StorageResult, StoredItem, TimelineEntry } from "../../contracts/storage.ts";
|
|
10
|
+
import { Fail, createEngine, failure, recover, referencesCompatible, type ChannelRow, type Meta, type Tables, type TurnRow } from "./engine.ts";
|
|
11
|
+
import { archiveMeta, restoreArchive, storedSession, validateArchive, validateSessionPayload } from "./archive.ts";
|
|
12
|
+
import { legacyItemSignature, policyItemSignature } from "./policy-metadata.ts";
|
|
13
|
+
import { validateManagedConfig } from "../../util/config.ts";
|
|
14
|
+
|
|
15
|
+
/** Query keys are typed columns; structured payloads are JSON text. The partial
|
|
16
|
+
* unique index is the durable form of "one live turn per channel". */
|
|
17
|
+
const SCHEMA = `
|
|
18
|
+
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;
|
|
19
|
+
CREATE TABLE channels (channel_id TEXT PRIMARY KEY, position INTEGER NOT NULL,
|
|
20
|
+
display_name TEXT, policy TEXT,
|
|
21
|
+
lifecycle TEXT NOT NULL DEFAULT 'open' CHECK (lifecycle IN ('open','suspending','suspended','retired')));
|
|
22
|
+
CREATE TABLE participants (participant_id TEXT PRIMARY KEY, position INTEGER NOT NULL);
|
|
23
|
+
CREATE TABLE turns (
|
|
24
|
+
turn_id INTEGER PRIMARY KEY, channel_id TEXT NOT NULL REFERENCES channels(channel_id),
|
|
25
|
+
started_seq INTEGER NOT NULL, started_at TEXT NOT NULL, compatibility_key TEXT NOT NULL,
|
|
26
|
+
status TEXT NOT NULL CHECK (status IN ('running','suspended','completed','failed','interrupted')),
|
|
27
|
+
state TEXT NOT NULL);
|
|
28
|
+
CREATE UNIQUE INDEX one_live_turn ON turns(channel_id) WHERE status IN ('running','suspended');
|
|
29
|
+
CREATE TABLE entries (
|
|
30
|
+
seq INTEGER PRIMARY KEY, at TEXT NOT NULL, channel_id TEXT NOT NULL REFERENCES channels(channel_id),
|
|
31
|
+
turn_id INTEGER NOT NULL REFERENCES turns(turn_id), sender TEXT NOT NULL, kind TEXT,
|
|
32
|
+
source_channel_id TEXT, item_id TEXT, message TEXT NOT NULL, external_source TEXT);
|
|
33
|
+
CREATE INDEX entries_by_turn ON entries(turn_id, seq);
|
|
34
|
+
CREATE TABLE items (
|
|
35
|
+
item_id TEXT PRIMARY KEY, kind TEXT NOT NULL, channel_id TEXT NOT NULL REFERENCES channels(channel_id),
|
|
36
|
+
sender_id TEXT NOT NULL, source_channel_id TEXT, text TEXT NOT NULL, signature TEXT NOT NULL,
|
|
37
|
+
accepted_seq INTEGER NOT NULL UNIQUE, accepted_at TEXT NOT NULL,
|
|
38
|
+
milestone TEXT NOT NULL CHECK (milestone IN ('received','taken','delivered','seen','withdrawn')),
|
|
39
|
+
turn_id INTEGER REFERENCES turns(turn_id), entry_seq INTEGER REFERENCES entries(seq),
|
|
40
|
+
withdrawn_at TEXT, policy_metadata TEXT NOT NULL, external_source TEXT,
|
|
41
|
+
CHECK ((milestone IN ('received','withdrawn')) = (turn_id IS NULL)),
|
|
42
|
+
CHECK ((milestone = 'withdrawn') = (withdrawn_at IS NOT NULL)));
|
|
43
|
+
CREATE INDEX items_pending ON items(channel_id, accepted_seq) WHERE milestone = 'received';
|
|
44
|
+
CREATE INDEX items_by_turn ON items(turn_id, entry_seq);
|
|
45
|
+
`;
|
|
46
|
+
|
|
47
|
+
/** Format 2 (persistence revision) to 3, run inside the recovery transaction by
|
|
48
|
+
* `recover`, so any failure rolls everything back and leaves format 2 intact.
|
|
49
|
+
* Channels gain a name and a lifecycle (existing ones are `open`); `items` is
|
|
50
|
+
* rebuilt because SQLite cannot alter its CHECK constraints. */
|
|
51
|
+
function upgradeFromFormat2(db: Database): void {
|
|
52
|
+
db.exec(`
|
|
53
|
+
ALTER TABLE channels ADD COLUMN display_name TEXT;
|
|
54
|
+
ALTER TABLE channels ADD COLUMN lifecycle TEXT NOT NULL DEFAULT 'open' CHECK (lifecycle IN ('open','suspending','suspended','retired'));
|
|
55
|
+
DROP INDEX items_pending; DROP INDEX items_by_turn;
|
|
56
|
+
ALTER TABLE items RENAME TO items_v2;
|
|
57
|
+
CREATE TABLE items (
|
|
58
|
+
item_id TEXT PRIMARY KEY, kind TEXT NOT NULL, channel_id TEXT NOT NULL REFERENCES channels(channel_id),
|
|
59
|
+
sender_id TEXT NOT NULL, source_channel_id TEXT, text TEXT NOT NULL, signature TEXT NOT NULL,
|
|
60
|
+
accepted_seq INTEGER NOT NULL UNIQUE, accepted_at TEXT NOT NULL,
|
|
61
|
+
milestone TEXT NOT NULL CHECK (milestone IN ('received','taken','delivered','seen','withdrawn')),
|
|
62
|
+
turn_id INTEGER REFERENCES turns(turn_id), entry_seq INTEGER REFERENCES entries(seq),
|
|
63
|
+
withdrawn_at TEXT,
|
|
64
|
+
CHECK ((milestone IN ('received','withdrawn')) = (turn_id IS NULL)),
|
|
65
|
+
CHECK ((milestone = 'withdrawn') = (withdrawn_at IS NOT NULL)));
|
|
66
|
+
INSERT INTO items SELECT item_id, kind, channel_id, sender_id, source_channel_id, text, signature, accepted_seq, accepted_at,
|
|
67
|
+
milestone, turn_id, entry_seq, NULL FROM items_v2;
|
|
68
|
+
DROP TABLE items_v2;
|
|
69
|
+
CREATE INDEX items_pending ON items(channel_id, accepted_seq) WHERE milestone = 'received';
|
|
70
|
+
CREATE INDEX items_by_turn ON items(turn_id, entry_seq);`);
|
|
71
|
+
}
|
|
72
|
+
/** Rewrite legacy identities before the new policy-aware engine can read them.
|
|
73
|
+
* The caller owns the recovery transaction, so a bad signature rolls back the
|
|
74
|
+
* schema and all row updates together. */
|
|
75
|
+
function upgradeFromFormat3(db: Database): void {
|
|
76
|
+
db.exec("ALTER TABLE channels ADD COLUMN policy TEXT; ALTER TABLE items ADD COLUMN policy_metadata TEXT");
|
|
77
|
+
const rows = db.query<Row, []>("SELECT * FROM items").all();
|
|
78
|
+
const update = db.query("UPDATE items SET signature = ?, policy_metadata = ? WHERE item_id = ?");
|
|
79
|
+
for (const row of rows) {
|
|
80
|
+
const input = { kind: row.kind, channelId: row.channel_id, senderId: row.sender_id,
|
|
81
|
+
...(row.source_channel_id === null ? {} : { sourceChannelId: row.source_channel_id }), text: row.text };
|
|
82
|
+
if (row.signature !== legacyItemSignature(input)) throw new Fail("incompatible", `Invalid legacy item signature: ${row.item_id}`);
|
|
83
|
+
update.run(policyItemSignature(input), JSON.stringify({ resolved: "__legacy_allow", inherited: [] }), row.item_id);
|
|
84
|
+
}
|
|
85
|
+
const turns = db.query<Row, []>("SELECT turn_id, state FROM turns WHERE status = 'suspended'").all();
|
|
86
|
+
const updateTurn = db.query("UPDATE turns SET state = ? WHERE turn_id = ?");
|
|
87
|
+
for (const turn of turns) {
|
|
88
|
+
const state = JSON.parse(turn.state); state.checkpoint.policyFingerprint = JSON.stringify([["__legacy_allow", "allow", []]]);
|
|
89
|
+
updateTurn.run(JSON.stringify(state), turn.turn_id);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function addExternalSource(db: Database): void {
|
|
93
|
+
db.exec("ALTER TABLE items ADD COLUMN external_source TEXT; ALTER TABLE entries ADD COLUMN external_source TEXT");
|
|
94
|
+
}
|
|
95
|
+
const NUMERIC: (keyof Meta)[] = ["formatVersion", "revision", "nextTurnId", "nextItemNumber"];
|
|
96
|
+
const KEYS: (keyof Meta)[] = ["sessionId", "createdAt", "compatibilityKey", "lifecycle", ...NUMERIC];
|
|
97
|
+
|
|
98
|
+
type Row = Record<string, any>;
|
|
99
|
+
const item = (row: Row): StoredItem => ({
|
|
100
|
+
itemId: row.item_id, kind: row.kind, channelId: row.channel_id, senderId: row.sender_id,
|
|
101
|
+
...(row.source_channel_id === null ? {} : { sourceChannelId: row.source_channel_id }), text: row.text,
|
|
102
|
+
...(row.external_source == null ? {} : { externalSource: row.external_source }),
|
|
103
|
+
...(row.kind === "external_notice" ? { inheritedPolicyNames: JSON.parse(row.policy_metadata).inherited } : {}),
|
|
104
|
+
signature: row.signature, acceptedSeq: row.accepted_seq, acceptedAt: row.accepted_at, milestone: row.milestone,
|
|
105
|
+
policy: JSON.parse(row.policy_metadata),
|
|
106
|
+
...(JSON.parse(row.policy_metadata).explicit === undefined ? {} : { explicitPolicy: JSON.parse(row.policy_metadata).explicit }),
|
|
107
|
+
...(row.withdrawn_at === null ? {} : { withdrawnAt: row.withdrawn_at }),
|
|
108
|
+
...(row.turn_id === null ? {} : { turnId: row.turn_id, entrySeq: row.entry_seq }) });
|
|
109
|
+
const channel = (row: Row): ChannelRow => ({ channelId: row.channel_id,
|
|
110
|
+
...(row.display_name === null ? {} : { displayName: row.display_name }), ...(row.policy === null ? {} : { policy: row.policy }), lifecycle: row.lifecycle });
|
|
111
|
+
const turn = (row: Row): TurnRow => ({ turnId: row.turn_id, channelId: row.channel_id, startedSeq: row.started_seq,
|
|
112
|
+
startedAt: row.started_at, compatibilityKey: row.compatibility_key, state: JSON.parse(row.state) });
|
|
113
|
+
const entry = (row: Row): TimelineEntry => ({ seq: row.seq, at: row.at, channelId: row.channel_id, turnId: row.turn_id, from: row.sender,
|
|
114
|
+
...(row.external_source == null ? {} : { externalSource: row.external_source }),
|
|
115
|
+
...(row.kind === null ? {} : { kind: row.kind }), ...(row.source_channel_id === null ? {} : { sourceChannelId: row.source_channel_id }),
|
|
116
|
+
...(row.item_id === null ? {} : { itemId: row.item_id }), ...(typeof row.reply_id === "string" ? { messageId: row.reply_id } : {}), message: JSON.parse(row.message) });
|
|
117
|
+
|
|
118
|
+
const ASSISTANT = "json_extract(message, '$.role') = 'assistant'";
|
|
119
|
+
const REPLY = `${ASSISTANT} AND length(json_extract(message, '$.content')) > 0`;
|
|
120
|
+
const CONTEXT_BYTES = `${entryOverhead} + octet_length(message) + octet_length(at) +
|
|
121
|
+
octet_length(e.channel_id) + octet_length(sender) + coalesce(octet_length(kind), 0) +
|
|
122
|
+
coalesce(octet_length(source_channel_id), 0) + coalesce(octet_length(item_id), 0) +
|
|
123
|
+
coalesce(octet_length(external_source), 0) + coalesce(
|
|
124
|
+
(SELECT octet_length(message_id) FROM entry_reply_ids WHERE seq = e.seq), 0)`;
|
|
125
|
+
const contextHeader = (kind: string, legacy = false) =>
|
|
126
|
+
`e.seq, ${legacy ? CONTEXT_BYTES.replace("coalesce(octet_length(external_source), 0)", "0") : CONTEXT_BYTES} AS bytes, ${kind} AS kind`;
|
|
127
|
+
const historyHeader = () => contextHeader("'other'").replace("octet_length(message)",
|
|
128
|
+
"coalesce((SELECT octet_length(message) FROM retrieval_history_projection WHERE seq = e.seq), octet_length(e.message))");
|
|
129
|
+
const contextRow = (row: Row): ContextRow => ({ seq: row.seq, bytes: row.bytes, kind: row.kind, ...(row.text_bytes === undefined ? {} : { textBytes: row.text_bytes }) });
|
|
130
|
+
const CHAT = `kind = 'participant_message' OR (${REPLY})`;
|
|
131
|
+
const installReadIndexes = (db: Database) => db.exec(`
|
|
132
|
+
CREATE INDEX IF NOT EXISTS turns_by_channel ON turns(channel_id, turn_id);
|
|
133
|
+
CREATE INDEX IF NOT EXISTS entries_conversation ON entries(channel_id, seq) WHERE ${CHAT};
|
|
134
|
+
CREATE INDEX IF NOT EXISTS entries_context_inputs ON entries(turn_id, seq) WHERE item_id IS NOT NULL;
|
|
135
|
+
CREATE INDEX IF NOT EXISTS entries_context_assistants ON entries(turn_id, seq) WHERE ${ASSISTANT};
|
|
136
|
+
CREATE INDEX IF NOT EXISTS entries_replies ON entries(turn_id, seq) WHERE ${REPLY};
|
|
137
|
+
CREATE TABLE IF NOT EXISTS entry_reply_ids (seq INTEGER PRIMARY KEY REFERENCES entries(seq), message_id TEXT NOT NULL);
|
|
138
|
+
INSERT OR IGNORE INTO meta VALUES ('replyIdsDirty', '1');
|
|
139
|
+
CREATE TRIGGER IF NOT EXISTS reply_ids_legacy_insert AFTER INSERT ON meta WHEN NEW.key = 'modelState'
|
|
140
|
+
BEGIN UPDATE meta SET value = '1' WHERE key = 'replyIdsDirty'; END;
|
|
141
|
+
CREATE TRIGGER IF NOT EXISTS reply_ids_legacy_update AFTER UPDATE OF value ON meta WHEN NEW.key = 'modelState'
|
|
142
|
+
BEGIN UPDATE meta SET value = '1' WHERE key = 'replyIdsDirty'; END;
|
|
143
|
+
`);
|
|
144
|
+
|
|
145
|
+
// Projection version is in the key so a future tokenizer can rebuild without
|
|
146
|
+
// changing the canonical session or archive format.
|
|
147
|
+
function refreshRetrieval(db: Database, entries: () => TimelineEntry[]): void {
|
|
148
|
+
db.exec(`
|
|
149
|
+
INSERT OR IGNORE INTO meta VALUES ('timelineRetrievalV1Dirty', '1');
|
|
150
|
+
UPDATE meta SET value = '1' WHERE key = 'timelineRetrievalV1Dirty'
|
|
151
|
+
AND (NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name = 'timeline_retrieval_v1')
|
|
152
|
+
OR NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name = 'retrieval_history_candidates'));
|
|
153
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS timeline_retrieval_v1 USING fts5(tokens, channel UNINDEXED, bytes UNINDEXED, tokenize = ascii);
|
|
154
|
+
CREATE TABLE IF NOT EXISTS retrieval_history_projection (seq INTEGER PRIMARY KEY, message TEXT NOT NULL);
|
|
155
|
+
CREATE TABLE IF NOT EXISTS retrieval_history_candidates (seq INTEGER PRIMARY KEY, channel_id TEXT NOT NULL);
|
|
156
|
+
CREATE TABLE IF NOT EXISTS retrieval_history_calls (turn_id INTEGER NOT NULL, call_id TEXT NOT NULL, PRIMARY KEY(turn_id, call_id)) WITHOUT ROWID;
|
|
157
|
+
CREATE INDEX IF NOT EXISTS reverse_entry_reply_ids ON entry_reply_ids(message_id);
|
|
158
|
+
CREATE TRIGGER IF NOT EXISTS timeline_retrieval_insert AFTER INSERT ON entries
|
|
159
|
+
BEGIN UPDATE meta SET value = '1' WHERE key = 'timelineRetrievalV1Dirty'; END;
|
|
160
|
+
CREATE TRIGGER IF NOT EXISTS timeline_retrieval_update AFTER UPDATE ON entries
|
|
161
|
+
BEGIN UPDATE meta SET value = '1' WHERE key = 'timelineRetrievalV1Dirty'; END;
|
|
162
|
+
CREATE TRIGGER IF NOT EXISTS timeline_retrieval_delete AFTER DELETE ON entries
|
|
163
|
+
BEGIN UPDATE meta SET value = '1' WHERE key = 'timelineRetrievalV1Dirty'; END;
|
|
164
|
+
`);
|
|
165
|
+
const dirty = db.prepare("SELECT value FROM meta WHERE key = 'timelineRetrievalV1Dirty'");
|
|
166
|
+
try { if ((dirty.get() as { value: string }).value === "0") return; }
|
|
167
|
+
finally { dirty.finalize(); }
|
|
168
|
+
db.exec("DELETE FROM timeline_retrieval_v1; DELETE FROM retrieval_history_projection; DELETE FROM retrieval_history_candidates; DELETE FROM retrieval_history_calls");
|
|
169
|
+
const insert = db.prepare("INSERT INTO timeline_retrieval_v1(rowid, tokens, channel, bytes) VALUES (?, ?, ?, ?)");
|
|
170
|
+
const history = db.prepare("INSERT INTO retrieval_history_projection VALUES (?, ?)");
|
|
171
|
+
const candidate = db.prepare("INSERT INTO retrieval_history_candidates VALUES (?, ?)");
|
|
172
|
+
const register = db.prepare("INSERT OR IGNORE INTO retrieval_history_calls VALUES (?, ?)");
|
|
173
|
+
const contains = db.prepare("SELECT 1 FROM retrieval_history_calls WHERE turn_id = ? AND call_id = ?");
|
|
174
|
+
try {
|
|
175
|
+
for (const entry of entries()) {
|
|
176
|
+
if (historicalCandidate(entry.message, id => register.run(entry.turnId, id), id => !!contains.get(entry.turnId, id)))
|
|
177
|
+
candidate.run(entry.seq, entry.channelId);
|
|
178
|
+
const message = retrievalMessage(entry);
|
|
179
|
+
if (message) {
|
|
180
|
+
insert.run(message.seq, timelineIndexText(message.text), message.channel, timelineBytes(message.text));
|
|
181
|
+
const projected = historicalRetrievalProjection(entry.message);
|
|
182
|
+
if (projected !== entry.message) history.run(entry.seq, JSON.stringify(projected));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
} finally { insert.finalize(); history.finalize(); candidate.finalize(); register.finalize(); contains.finalize(); }
|
|
186
|
+
db.exec("UPDATE meta SET value = '0' WHERE key = 'timelineRetrievalV1Dirty'");
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const rebuildModelCalls = (db: Database) => db.exec(`
|
|
190
|
+
DELETE FROM model_call_pages;
|
|
191
|
+
INSERT INTO model_call_pages
|
|
192
|
+
SELECT CAST(json_extract(call.value, '$.callId') AS INTEGER), call.value
|
|
193
|
+
FROM meta, json_each(meta.value, '$.calls') AS call WHERE meta.key = 'modelState';
|
|
194
|
+
UPDATE meta SET value = '0' WHERE key = 'modelCallPagesDirty';
|
|
195
|
+
`);
|
|
196
|
+
|
|
197
|
+
function refreshModelCalls(db: Database): void {
|
|
198
|
+
db.exec(`
|
|
199
|
+
INSERT OR IGNORE INTO meta VALUES ('modelCallPagesDirty', '1');
|
|
200
|
+
UPDATE meta SET value = '1' WHERE key = 'modelCallPagesDirty'
|
|
201
|
+
AND NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name = 'model_call_pages');
|
|
202
|
+
CREATE TABLE IF NOT EXISTS model_call_pages (call_number INTEGER PRIMARY KEY, summary TEXT NOT NULL);
|
|
203
|
+
CREATE TRIGGER IF NOT EXISTS model_calls_legacy_insert AFTER INSERT ON meta WHEN NEW.key = 'modelState'
|
|
204
|
+
BEGIN UPDATE meta SET value = '1' WHERE key = 'modelCallPagesDirty'; END;
|
|
205
|
+
CREATE TRIGGER IF NOT EXISTS model_calls_legacy_update AFTER UPDATE OF value ON meta WHEN NEW.key = 'modelState'
|
|
206
|
+
BEGIN UPDATE meta SET value = '1' WHERE key = 'modelCallPagesDirty'; END;
|
|
207
|
+
`);
|
|
208
|
+
const dirty = db.prepare("SELECT value FROM meta WHERE key = 'modelCallPagesDirty'");
|
|
209
|
+
try { if ((dirty.get() as { value: string }).value === "1") rebuildModelCalls(db); }
|
|
210
|
+
finally { dirty.finalize(); }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Older writers keep the blob authoritative. Rebuild only on upgrade or when
|
|
214
|
+
// one of those writers changed it, under the same transaction as recovery.
|
|
215
|
+
function refreshReplyIds(db: Database): void {
|
|
216
|
+
installReadIndexes(db);
|
|
217
|
+
const dirty = db.prepare("SELECT 1 FROM meta WHERE key = 'replyIdsDirty' AND value = '1'");
|
|
218
|
+
try { if (!dirty.get()) return; } finally { dirty.finalize(); }
|
|
219
|
+
db.exec(`
|
|
220
|
+
DELETE FROM entry_reply_ids;
|
|
221
|
+
INSERT INTO entry_reply_ids
|
|
222
|
+
SELECT CAST(ids.key AS INTEGER), ids.value FROM meta, json_each(meta.value, '$.entryIds') AS ids
|
|
223
|
+
WHERE meta.key = 'modelState';
|
|
224
|
+
UPDATE meta SET value = '0' WHERE key = 'replyIdsDirty';
|
|
225
|
+
`);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Backfill once under the owner transaction. Triggers keep the projection
|
|
229
|
+
* current even when an older format-6 writer subsequently takes input. */
|
|
230
|
+
function installContextPolicyIndex(db: Database): void {
|
|
231
|
+
const exists = db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'context_turn_policies'");
|
|
232
|
+
try { if (exists.get()) return; } finally { exists.finalize(); }
|
|
233
|
+
const project = `
|
|
234
|
+
INSERT INTO context_turn_policies
|
|
235
|
+
SELECT NEW.turn_id, coalesce(json_extract(NEW.policy_metadata, '$.resolved'), '__legacy_allow')
|
|
236
|
+
UNION ALL SELECT NEW.turn_id, value FROM json_each(NEW.policy_metadata, '$.inherited') WHERE true
|
|
237
|
+
ON CONFLICT(turn_id, name) DO NOTHING;`;
|
|
238
|
+
db.exec(`
|
|
239
|
+
CREATE TABLE context_turn_policies (
|
|
240
|
+
turn_id INTEGER NOT NULL REFERENCES turns(turn_id), name TEXT NOT NULL, PRIMARY KEY (turn_id, name)
|
|
241
|
+
) WITHOUT ROWID;
|
|
242
|
+
INSERT OR IGNORE INTO context_turn_policies
|
|
243
|
+
SELECT turn_id, coalesce(json_extract(policy_metadata, '$.resolved'), '__legacy_allow') FROM items WHERE turn_id IS NOT NULL
|
|
244
|
+
UNION ALL SELECT turn_id, value FROM items, json_each(items.policy_metadata, '$.inherited') WHERE turn_id IS NOT NULL;
|
|
245
|
+
CREATE TRIGGER context_policy_insert AFTER INSERT ON items WHEN NEW.turn_id IS NOT NULL
|
|
246
|
+
BEGIN ${project} END;
|
|
247
|
+
CREATE TRIGGER context_policy_take AFTER UPDATE OF turn_id ON items WHEN OLD.turn_id IS NULL AND NEW.turn_id IS NOT NULL
|
|
248
|
+
BEGIN ${project} END;
|
|
249
|
+
`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function sqliteTables(db: Database): Tables & { dispose(): void } {
|
|
253
|
+
// Prepared on first use: statements for tables a format 2 file does not have
|
|
254
|
+
// yet must not be compiled before the upgrade runs.
|
|
255
|
+
const finalizers: (() => void)[] = [];
|
|
256
|
+
const q = (sql: string) => {
|
|
257
|
+
let statement: ReturnType<Database["query"]> | undefined;
|
|
258
|
+
const prepared = () => {
|
|
259
|
+
if (!statement) { statement = db.query<Row, any[]>(sql); const current = statement; finalizers.push(() => current.finalize()); }
|
|
260
|
+
return statement;
|
|
261
|
+
};
|
|
262
|
+
return { get: (...args: any[]) => prepared().get(...args) as Row | null, all: (...args: any[]) => prepared().all(...args) as Row[],
|
|
263
|
+
run: (...args: any[]) => { prepared().run(...args); } };
|
|
264
|
+
};
|
|
265
|
+
const s = {
|
|
266
|
+
retrievalDirty: q("SELECT value FROM meta WHERE key = 'timelineRetrievalV1Dirty'"),
|
|
267
|
+
retrievalReplyDirty: q("SELECT value FROM meta WHERE key = 'replyIdsDirty'"),
|
|
268
|
+
retrievalClean: q("UPDATE meta SET value = '0' WHERE key = 'timelineRetrievalV1Dirty'"),
|
|
269
|
+
retrievalAll: q("SELECT rowid AS seq, bytes FROM timeline_retrieval_v1 WHERE timeline_retrieval_v1 MATCH ? ORDER BY rowid DESC LIMIT ?"),
|
|
270
|
+
retrievalChannel: q("SELECT rowid AS seq, bytes FROM timeline_retrieval_v1 WHERE timeline_retrieval_v1 MATCH ? AND channel = ? ORDER BY rowid DESC LIMIT ?"),
|
|
271
|
+
retrievalReverse: q("SELECT seq FROM entry_reply_ids WHERE message_id = ?"),
|
|
272
|
+
historicalCandidate: q("INSERT INTO retrieval_history_candidates VALUES (?, ?)"),
|
|
273
|
+
historicalRegister: q("INSERT OR IGNORE INTO retrieval_history_calls VALUES (?, ?)"),
|
|
274
|
+
historicalContains: q("SELECT 1 FROM retrieval_history_calls WHERE turn_id = ? AND call_id = ?"),
|
|
275
|
+
historicalInsert: q("INSERT INTO retrieval_history_projection VALUES (?, ?)"),
|
|
276
|
+
historicalEntry: q(`SELECT e.seq, e.at, e.channel_id, e.turn_id, e.sender, e.kind, e.source_channel_id, e.item_id, e.external_source,
|
|
277
|
+
coalesce((SELECT message FROM retrieval_history_projection WHERE seq = e.seq), e.message) AS message,
|
|
278
|
+
(SELECT message_id FROM entry_reply_ids WHERE seq = e.seq) AS reply_id FROM entries AS e WHERE e.seq = ?`),
|
|
279
|
+
retrievalInsert: q("INSERT INTO timeline_retrieval_v1(rowid, tokens, channel, bytes) VALUES (?, ?, ?, ?)"),
|
|
280
|
+
modelCallPagesDirty: q("SELECT value FROM meta WHERE key = 'modelCallPagesDirty'"),
|
|
281
|
+
callCursor: q("SELECT call_number FROM model_call_pages WHERE call_number = ?"),
|
|
282
|
+
callPage: q("SELECT summary FROM model_call_pages WHERE call_number > ? ORDER BY call_number LIMIT ?"),
|
|
283
|
+
putCallPage: q(`INSERT INTO model_call_pages VALUES (?, ?)
|
|
284
|
+
ON CONFLICT(call_number) DO UPDATE SET summary = excluded.summary`),
|
|
285
|
+
markCallPagesClean: q("UPDATE meta SET value = '0' WHERE key = 'modelCallPagesDirty'"),
|
|
286
|
+
contextTurnStart: q("SELECT started_seq FROM turns WHERE turn_id = ? AND channel_id = ?"),
|
|
287
|
+
contextTrigger: q(`SELECT ${contextHeader("'input'")}, (SELECT octet_length(text) FROM items WHERE items.item_id = e.item_id) AS text_bytes FROM entries AS e
|
|
288
|
+
WHERE turn_id = ? AND item_id IS NOT NULL ORDER BY seq LIMIT 1`),
|
|
289
|
+
contextPreviousResponse: q(`SELECT seq FROM entries WHERE turn_id = ? AND ${ASSISTANT} ORDER BY seq DESC LIMIT 1`),
|
|
290
|
+
contextInputs: q(`SELECT ${contextHeader("'input'")}, (SELECT octet_length(text) FROM items WHERE items.item_id = e.item_id) AS text_bytes FROM entries AS e
|
|
291
|
+
WHERE turn_id = ? AND item_id IS NOT NULL AND seq > ? ORDER BY seq LIMIT ?`),
|
|
292
|
+
contextActive: q(`SELECT ${contextHeader(`CASE WHEN item_id IS NOT NULL THEN 'input'
|
|
293
|
+
WHEN EXISTS (SELECT 1 FROM entries AS a INDEXED BY entries_context_assistants
|
|
294
|
+
WHERE a.turn_id = e.turn_id AND a.seq = e.seq AND ${ASSISTANT}) THEN 'assistant' ELSE 'other' END`)}
|
|
295
|
+
FROM entries AS e WHERE turn_id = ? ORDER BY seq DESC LIMIT ?`),
|
|
296
|
+
contextLocal: q(`SELECT ${historyHeader()} FROM entries AS e
|
|
297
|
+
WHERE channel_id = ? AND seq < ? AND (${CHAT}) ORDER BY seq DESC LIMIT ?`),
|
|
298
|
+
contextRecent: q(`SELECT ${contextHeader("'other'")} FROM entries AS e WHERE seq < ? ORDER BY seq DESC LIMIT ?`),
|
|
299
|
+
contextRecentLegacy: q(`SELECT ${contextHeader("'other'", true)} FROM entries AS e WHERE seq < ? ORDER BY seq DESC LIMIT ?`),
|
|
300
|
+
contextShared: q(`WITH recent AS MATERIALIZED (
|
|
301
|
+
SELECT seq, channel_id FROM retrieval_history_candidates ORDER BY seq DESC LIMIT ?)
|
|
302
|
+
SELECT ${historyHeader()} FROM recent JOIN entries AS e ON e.seq = recent.seq
|
|
303
|
+
WHERE recent.channel_id <> ? AND EXISTS (
|
|
304
|
+
SELECT 1 FROM entries AS c INDEXED BY entries_conversation
|
|
305
|
+
WHERE c.channel_id = recent.channel_id AND c.seq = recent.seq AND (${CHAT}))
|
|
306
|
+
ORDER BY e.seq DESC`),
|
|
307
|
+
contextPolicySize: q(`SELECT count(*) AS count, coalesce(sum(bytes), 0) AS bytes FROM (
|
|
308
|
+
SELECT octet_length(name) + 1 AS bytes FROM context_turn_policies WHERE turn_id = ? LIMIT ?
|
|
309
|
+
)`),
|
|
310
|
+
contextPolicies: q("SELECT name FROM context_turn_policies WHERE turn_id = ? ORDER BY name LIMIT ?"),
|
|
311
|
+
contextUnfinishedSize: q(`SELECT ${entryOverhead} + octet_length(channel_id) + octet_length(state) AS bytes
|
|
312
|
+
FROM turns WHERE turn_id = ? AND status IN ('failed', 'interrupted')`),
|
|
313
|
+
contextUnfinished: q("SELECT channel_id, state FROM turns WHERE turn_id = ?"),
|
|
314
|
+
contextEntry: q(`SELECT *, (SELECT message_id FROM entry_reply_ids WHERE seq = e.seq) AS reply_id
|
|
315
|
+
FROM entries AS e WHERE e.seq = ?`),
|
|
316
|
+
pendingCount: q("SELECT count(*) AS n FROM items WHERE channel_id = ? AND milestone = 'received'"),
|
|
317
|
+
latestTurn: q("SELECT * FROM turns WHERE channel_id = ? ORDER BY turn_id DESC LIMIT 1"),
|
|
318
|
+
liveTurns: q("SELECT * FROM turns WHERE status IN ('running','suspended') ORDER BY turn_id"),
|
|
319
|
+
policyNames: q(`
|
|
320
|
+
SELECT policy AS name FROM channels WHERE policy IS NOT NULL
|
|
321
|
+
UNION SELECT coalesce(json_extract(policy_metadata, '$.resolved'), '__legacy_allow') FROM items
|
|
322
|
+
UNION SELECT inherited.value FROM items, json_each(items.policy_metadata, '$.inherited') AS inherited
|
|
323
|
+
`),
|
|
324
|
+
|
|
325
|
+
meta: q(`SELECT key, value FROM meta WHERE key IN (${KEYS.map(() => "?").join(", ")})`), modelState: q("SELECT value FROM meta WHERE key = 'modelState'"), revoked: q("SELECT value FROM meta WHERE key = 'revokedTools'"), config: q("SELECT value FROM meta WHERE key = 'importedConfig'"), setMeta: q("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"),
|
|
326
|
+
channel: q("SELECT * FROM channels WHERE channel_id = ?"),
|
|
327
|
+
addChannel: q("INSERT OR IGNORE INTO channels (channel_id, position) VALUES (?, (SELECT COUNT(*) FROM channels))"),
|
|
328
|
+
putChannel: q("UPDATE channels SET display_name = ?, lifecycle = ?, policy = ? WHERE channel_id = ?"),
|
|
329
|
+
channels: q("SELECT * FROM channels ORDER BY position"),
|
|
330
|
+
addParticipant: q("INSERT OR IGNORE INTO participants VALUES (?, (SELECT COUNT(*) FROM participants))"),
|
|
331
|
+
participants: q("SELECT participant_id FROM participants ORDER BY position"),
|
|
332
|
+
item: q("SELECT * FROM items WHERE item_id = ?"),
|
|
333
|
+
putItem: q(`INSERT INTO items (item_id, kind, channel_id, sender_id, source_channel_id, text, signature, accepted_seq, accepted_at, milestone, turn_id, entry_seq, withdrawn_at, policy_metadata, external_source) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
334
|
+
ON CONFLICT(item_id) DO UPDATE SET milestone = excluded.milestone, turn_id = excluded.turn_id, entry_seq = excluded.entry_seq,
|
|
335
|
+
withdrawn_at = excluded.withdrawn_at, signature = excluded.signature, policy_metadata = excluded.policy_metadata`),
|
|
336
|
+
pending: q("SELECT * FROM items WHERE channel_id = ? AND milestone = 'received' ORDER BY accepted_seq LIMIT ?"),
|
|
337
|
+
ofTurn: q("SELECT * FROM items WHERE turn_id = ? ORDER BY entry_seq"), items: q("SELECT * FROM items ORDER BY accepted_seq"),
|
|
338
|
+
turn: q("SELECT * FROM turns WHERE turn_id = ?"),
|
|
339
|
+
putTurn: q(`INSERT INTO turns VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
340
|
+
ON CONFLICT(turn_id) DO UPDATE SET status = excluded.status, state = excluded.state`),
|
|
341
|
+
live: q("SELECT * FROM turns WHERE channel_id = ? AND status IN ('running','suspended')"), turns: q("SELECT * FROM turns ORDER BY turn_id"),
|
|
342
|
+
markReplyIdsClean: q("UPDATE meta SET value = '0' WHERE key = 'replyIdsDirty'"),
|
|
343
|
+
addReplyId: q("INSERT INTO entry_reply_ids VALUES (?, ?)"),
|
|
344
|
+
addEntry: q("INSERT INTO entries (seq, at, channel_id, turn_id, sender, kind, source_channel_id, item_id, message, external_source) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
|
|
345
|
+
entriesOf: q("SELECT * FROM entries WHERE turn_id = ? ORDER BY seq"), entries: q("SELECT * FROM entries ORDER BY seq"),
|
|
346
|
+
};
|
|
347
|
+
let depth = 0;
|
|
348
|
+
const retrievalReady = () => {
|
|
349
|
+
if (s.retrievalDirty.get()?.value !== "0" || s.retrievalReplyDirty.get()?.value !== "0") {
|
|
350
|
+
throw new Fail("storage_failure", "Timeline retrieval projection requires reopen");
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
return {
|
|
354
|
+
reminders: sqliteReminderTables(db),
|
|
355
|
+
contextTurnStart: (channelId, turnId) => s.contextTurnStart.get(turnId, channelId)?.started_seq,
|
|
356
|
+
contextTrigger(turnId) {
|
|
357
|
+
const row = s.contextTrigger.get(turnId);
|
|
358
|
+
return row ? contextRow(row) : undefined;
|
|
359
|
+
},
|
|
360
|
+
contextPreviousResponse: turnId => s.contextPreviousResponse.get(turnId)?.seq ?? 0,
|
|
361
|
+
contextInputs: (turnId, after, limit) => s.contextInputs.all(turnId, after, limit).map(contextRow),
|
|
362
|
+
contextActive: (turnId, limit) => s.contextActive.all(turnId, limit).map(contextRow),
|
|
363
|
+
contextLocal: (channelId, start, limit) => s.contextLocal.all(channelId, start, limit).map(contextRow),
|
|
364
|
+
contextRecent: (before, limit, legacy) => (legacy ? s.contextRecentLegacy : s.contextRecent).all(before, limit).map(contextRow),
|
|
365
|
+
contextShared: (channelId, limit) => s.contextShared.all(limit, channelId).map(contextRow),
|
|
366
|
+
contextPolicies(turnId, limit, budget) {
|
|
367
|
+
const { count, bytes } = s.contextPolicySize.get(turnId, limit + 1)!;
|
|
368
|
+
if (count > limit || bytes > budget) return undefined;
|
|
369
|
+
return { names: s.contextPolicies.all(turnId, count).map(row => String(row.name)).sort(), bytes };
|
|
370
|
+
},
|
|
371
|
+
contextUnfinished(turnId, budget) {
|
|
372
|
+
const size = s.contextUnfinishedSize.get(turnId);
|
|
373
|
+
if (!size || size.bytes > budget) return undefined;
|
|
374
|
+
const row = s.contextUnfinished.get(turnId)!;
|
|
375
|
+
return { outcome: { turnId, channelId: row.channel_id, state: JSON.parse(row.state) }, bytes: size.bytes };
|
|
376
|
+
},
|
|
377
|
+
contextEntry: seq => entry(s.contextEntry.get(seq)!),
|
|
378
|
+
contextHistoricalEntry: seq => entry(s.historicalEntry.get(seq)!),
|
|
379
|
+
pendingCount(id) {
|
|
380
|
+
return Number(s.pendingCount.get(id)?.n ?? 0);
|
|
381
|
+
},
|
|
382
|
+
readRange(range) {
|
|
383
|
+
const older = range.direction === "older";
|
|
384
|
+
const order = older ? "DESC" : "ASC";
|
|
385
|
+
const read = (filter: string, params: (string | number)[]) => {
|
|
386
|
+
const statement = db.prepare<Row, (string | number)[]>(`
|
|
387
|
+
SELECT *, (SELECT message_id FROM entry_reply_ids WHERE entry_reply_ids.seq = entries.seq) AS reply_id FROM entries WHERE (${filter}) AND seq <= ? AND seq ${older ? "<" : ">"} ?
|
|
388
|
+
ORDER BY seq ${order} LIMIT ?
|
|
389
|
+
`);
|
|
390
|
+
try { return statement.all(...params, range.throughRevision, range.exclusiveSeq ?? (older ? Number.MAX_SAFE_INTEGER : 0), range.limit + 1).map(entry); } finally { statement.finalize(); }
|
|
391
|
+
};
|
|
392
|
+
if (range.kind === "conversation") return read(`channel_id = ? AND (${CHAT})`, [range.channel!]);
|
|
393
|
+
if (range.kind === "replies") return (range.turnIds ?? []).flatMap(id => read(`turn_id = ? AND channel_id = ? AND ${REPLY}`, [id, range.channel!]))
|
|
394
|
+
.sort((a, b) => older ? b.seq - a.seq : a.seq - b.seq).slice(0, range.limit + 1);
|
|
395
|
+
return read("1", []);
|
|
396
|
+
},
|
|
397
|
+
retrievalCandidates(terms, channel, limit) {
|
|
398
|
+
retrievalReady();
|
|
399
|
+
const query = terms.map(encodedTimelineToken).join(" AND ");
|
|
400
|
+
const rows = channel === undefined ? s.retrievalAll.all(query, limit) : s.retrievalChannel.all(query, channel, limit);
|
|
401
|
+
return rows.map(row => ({ seq: row.seq, bytes: row.bytes }));
|
|
402
|
+
},
|
|
403
|
+
retrievalEntry(seq) {
|
|
404
|
+
retrievalReady();
|
|
405
|
+
const row = s.contextEntry.get(seq);
|
|
406
|
+
return row ? entry(row) : undefined;
|
|
407
|
+
},
|
|
408
|
+
retrievalReplyId(id) { retrievalReady(); return s.retrievalReverse.get(id)?.seq; },
|
|
409
|
+
dispose() { for (const finalize of finalizers.splice(0)) finalize(); },
|
|
410
|
+
getModelState() { const row = s.modelState.get(); return row ? JSON.parse(row.value) : undefined; },
|
|
411
|
+
setModelState(state, changed) {
|
|
412
|
+
const canPatch = changed !== undefined && s.modelCallPagesDirty.get()?.value === "0";
|
|
413
|
+
s.setMeta.run("modelState", JSON.stringify(state));
|
|
414
|
+
s.markReplyIdsClean.run();
|
|
415
|
+
if (canPatch) {
|
|
416
|
+
for (const call of changed) s.putCallPage.run(Number(call.callId), JSON.stringify(call));
|
|
417
|
+
s.markCallPagesClean.run();
|
|
418
|
+
} else rebuildModelCalls(db);
|
|
419
|
+
},
|
|
420
|
+
modelCallPage(after, count) {
|
|
421
|
+
if (s.modelCallPagesDirty.get()?.value !== "0") throw new Fail("storage_failure", "Model call page projection requires reopen");
|
|
422
|
+
const cursor = after === undefined ? 0 : Number(after);
|
|
423
|
+
if (after !== undefined && (!Number.isSafeInteger(cursor) || String(cursor) !== after || !s.callCursor.get(cursor))) {
|
|
424
|
+
throw new Fail("not_found", "Unknown model call cursor");
|
|
425
|
+
}
|
|
426
|
+
return s.callPage.all(cursor, count).map(row => JSON.parse(row.summary) as ModelCallSummary);
|
|
427
|
+
},
|
|
428
|
+
// A meta key, like the model state: no schema or format change (decision 0021).
|
|
429
|
+
getRevokedTools() { const row = s.revoked.get(); return row ? JSON.parse(row.value) : undefined; },
|
|
430
|
+
setRevokedTools(names) { s.setMeta.run("revokedTools", JSON.stringify(names)); },
|
|
431
|
+
getConfig() { const row = s.config.get(); return row ? JSON.parse(row.value) : undefined; },
|
|
432
|
+
setConfig(config) { s.setMeta.run("importedConfig", JSON.stringify(config)); },
|
|
433
|
+
// Short and synchronous: nothing awaits between BEGIN and COMMIT.
|
|
434
|
+
transaction(run) {
|
|
435
|
+
if (depth) return run();
|
|
436
|
+
db.exec("BEGIN IMMEDIATE"); depth++;
|
|
437
|
+
try { const value = run(); db.exec("COMMIT"); return value; }
|
|
438
|
+
catch (error) { db.exec("ROLLBACK"); throw error; }
|
|
439
|
+
finally { depth--; }
|
|
440
|
+
},
|
|
441
|
+
getMeta() {
|
|
442
|
+
const meta: Row = {};
|
|
443
|
+
for (const row of s.meta.all(...KEYS)) meta[row.key] = NUMERIC.includes(row.key) ? Number(row.value) : row.value;
|
|
444
|
+
return meta as Meta;
|
|
445
|
+
},
|
|
446
|
+
setMeta(meta) { for (const key of KEYS) s.setMeta.run(key, String(meta[key])); },
|
|
447
|
+
channel(id) { const row = s.channel.get(id); return row ? channel(row) : undefined; },
|
|
448
|
+
putChannel(c) { s.addChannel.run(c.channelId); s.putChannel.run(c.displayName ?? null, c.lifecycle, c.policy ?? null, c.channelId); },
|
|
449
|
+
channels: () => s.channels.all().map(channel),
|
|
450
|
+
addParticipant(id) { s.addParticipant.run(id); },
|
|
451
|
+
participants: () => s.participants.all().map(row => row.participant_id),
|
|
452
|
+
item(id) { const row = s.item.get(id); return row ? item(row) : undefined; },
|
|
453
|
+
putItem(i) { s.putItem.run(i.itemId, i.kind, i.channelId, i.senderId, i.sourceChannelId ?? null, i.text, i.signature,
|
|
454
|
+
i.acceptedSeq, i.acceptedAt, i.milestone, i.turnId ?? null, i.entrySeq ?? null, i.withdrawnAt ?? null, JSON.stringify(i.policy ?? { resolved: "__legacy_allow", inherited: [] }), i.externalSource ?? null); },
|
|
455
|
+
pendingItems: (channelId, limit) => s.pending.all(channelId, limit ?? -1).map(item),
|
|
456
|
+
itemsOfTurn: turnId => s.ofTurn.all(turnId).map(item),
|
|
457
|
+
items: () => s.items.all().map(item),
|
|
458
|
+
turn(id) { const row = s.turn.get(id); return row ? turn(row) : undefined; },
|
|
459
|
+
putTurn(t) { s.putTurn.run(t.turnId, t.channelId, t.startedSeq, t.startedAt, t.compatibilityKey, t.state.status, JSON.stringify(t.state)); },
|
|
460
|
+
liveTurn(channelId) { const row = s.live.get(channelId); return row ? turn(row) : undefined; },
|
|
461
|
+
turns: () => s.turns.all().map(turn),
|
|
462
|
+
latestTurn(id) {
|
|
463
|
+
const row = s.latestTurn.get(id);
|
|
464
|
+
return row ? turn(row) : undefined;
|
|
465
|
+
},
|
|
466
|
+
liveTurns: () => s.liveTurns.all().map(turn),
|
|
467
|
+
policyNames: () => s.policyNames.all().map(row => String(row.name)),
|
|
468
|
+
|
|
469
|
+
addEntry(e) { const clean = s.retrievalDirty.get()?.value === "0"; s.addEntry.run(e.seq, e.at, e.channelId, e.turnId, e.from, e.kind ?? null, e.sourceChannelId ?? null,
|
|
470
|
+
e.itemId ?? null, JSON.stringify(e.message), e.externalSource ?? null);
|
|
471
|
+
if (e.messageId !== undefined) s.addReplyId.run(e.seq, e.messageId);
|
|
472
|
+
if (clean) {
|
|
473
|
+
if (historicalCandidate(e.message, id => s.historicalRegister.run(e.turnId, id), id => !!s.historicalContains.get(e.turnId, id)))
|
|
474
|
+
s.historicalCandidate.run(e.seq, e.channelId);
|
|
475
|
+
const projected = retrievalMessage(e);
|
|
476
|
+
if (projected) {
|
|
477
|
+
s.retrievalInsert.run(e.seq, timelineIndexText(projected.text), e.channelId, timelineBytes(projected.text));
|
|
478
|
+
const historical = historicalRetrievalProjection(e.message);
|
|
479
|
+
if (historical !== e.message) s.historicalInsert.run(e.seq, JSON.stringify(historical));
|
|
480
|
+
}
|
|
481
|
+
s.retrievalClean.run();
|
|
482
|
+
}
|
|
483
|
+
},
|
|
484
|
+
entriesOfTurn: turnId => s.entriesOf.all(turnId).map(entry),
|
|
485
|
+
entries: () => s.entries.all().map(entry),
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Build a complete database beside the destination, then publish it with a
|
|
490
|
+
* hard link, which fails if the destination exists. A crash leaves either no
|
|
491
|
+
* session or a whole one, never a partial file at `path`. */
|
|
492
|
+
function publish(path: string, meta: Meta, fill?: (tables: Tables) => void): void {
|
|
493
|
+
if (existsSync(path)) throw new Fail("already_exists", `A session already exists at ${path}`);
|
|
494
|
+
const draft = `${path}.draft-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
495
|
+
try {
|
|
496
|
+
const db = new Database(draft, { readwrite: true, create: true });
|
|
497
|
+
try {
|
|
498
|
+
db.exec("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
|
|
499
|
+
db.exec(SCHEMA);
|
|
500
|
+
installReadIndexes(db);
|
|
501
|
+
const tables = sqliteTables(db);
|
|
502
|
+
try { tables.transaction(() => { tables.setMeta(meta); installContextPolicyIndex(db); refreshModelCalls(db); fill?.(tables); refreshReplyIds(db); refreshRetrieval(db, tables.entries); }); }
|
|
503
|
+
finally { tables.dispose(); }
|
|
504
|
+
} finally { db.close(); }
|
|
505
|
+
try { linkSync(draft, path); }
|
|
506
|
+
catch (error) {
|
|
507
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new Fail("already_exists", `A session already exists at ${path}`);
|
|
508
|
+
throw error;
|
|
509
|
+
}
|
|
510
|
+
} finally { rmSync(draft, { force: true }); rmSync(`${draft}-journal`, { force: true }); }
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
interface SavedSessionHeader { sessionId: string; config: PortableSessionConfig | undefined }
|
|
514
|
+
|
|
515
|
+
/** One SQLite file holds one session. Ownership is SQLite's exclusive file
|
|
516
|
+
* lock, held from open to close: a second handle, in this or any process,
|
|
517
|
+
* fails immediately, and the operating system releases it if the owner dies. */
|
|
518
|
+
export function createSqliteStorageAdapter(path: string): SessionStorageAdapter & {
|
|
519
|
+
/** Inspect the saved identity and config without taking session ownership. */
|
|
520
|
+
readSavedHeader(): StorageResult<SavedSessionHeader>;
|
|
521
|
+
} {
|
|
522
|
+
const readSavedHeader = (): StorageResult<SavedSessionHeader> => {
|
|
523
|
+
let db: Database | undefined;
|
|
524
|
+
try {
|
|
525
|
+
if (!existsSync(path)) throw new Fail("not_found", `No session exists at ${path}`);
|
|
526
|
+
db = new Database(path, { readonly: true }); db.exec("PRAGMA busy_timeout=0");
|
|
527
|
+
const rows = db.query<{ key: string; value: string }, []>("SELECT key, value FROM meta WHERE key IN ('importedConfig', 'revision', 'sessionId')").all();
|
|
528
|
+
const raw = rows.find(row => row.key === "importedConfig")?.value;
|
|
529
|
+
const sessionId = rows.find(row => row.key === "sessionId")?.value;
|
|
530
|
+
if (!sessionId?.trim()) throw new Fail("incompatible", "No saved session ID");
|
|
531
|
+
return { ok: true, value: { sessionId, config: raw === undefined ? undefined : JSON.parse(raw) }, revision: Number(rows.find(row => row.key === "revision")?.value ?? 0) };
|
|
532
|
+
} catch (error) {
|
|
533
|
+
const code = (error as { code?: string }).code;
|
|
534
|
+
if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") return failure(new Fail("owner_conflict", "Session storage already has an owner"));
|
|
535
|
+
return failure(error);
|
|
536
|
+
} finally { db?.close(); }
|
|
537
|
+
};
|
|
538
|
+
return {
|
|
539
|
+
readSavedHeader,
|
|
540
|
+
readSavedConfig() {
|
|
541
|
+
const result = readSavedHeader();
|
|
542
|
+
return result.ok ? { ...result, value: result.value.config } : result;
|
|
543
|
+
},
|
|
544
|
+
importSessionFile(payload, options) {
|
|
545
|
+
try {
|
|
546
|
+
const { archive, config } = validateSessionPayload(payload);
|
|
547
|
+
if (options?.sessionId !== undefined && (typeof options.sessionId !== "string" || !options.sessionId.trim())) throw new Fail("invalid_input", "sessionId must be a nonempty string");
|
|
548
|
+
const meta = archiveMeta(archive, options?.sessionId);
|
|
549
|
+
publish(path, meta, tables => { restoreArchive(tables, archive); tables.setConfig(config); });
|
|
550
|
+
return { ok: true, value: storedSession(meta), revision: meta.revision };
|
|
551
|
+
} catch (error) { return failure(error); }
|
|
552
|
+
},
|
|
553
|
+
open(options) {
|
|
554
|
+
let db: Database | undefined;
|
|
555
|
+
try {
|
|
556
|
+
const identity = options?.identity;
|
|
557
|
+
if (!identity || typeof identity.sessionId !== "string" || !identity.sessionId.trim() || typeof identity.compatibilityKey !== "string"
|
|
558
|
+
|| (options.mode !== "create" && options.mode !== "open")) throw new Fail("invalid_input", "Open needs a mode, sessionId and compatibilityKey");
|
|
559
|
+
let config; try { config = options.config === undefined ? undefined : validateManagedConfig(options.config); } catch (error) { throw new Fail("invalid_input", String(error)); }
|
|
560
|
+
if (options.mode === "create") checkScriptIdentity(identity.compatibilityKey, options.requiredScriptDigest);
|
|
561
|
+
if (options.mode === "create") publish(path, { sessionId: identity.sessionId, formatVersion: 6, createdAt: new Date().toISOString(),
|
|
562
|
+
compatibilityKey: identity.compatibilityKey, lifecycle: "running", revision: 0, nextTurnId: 1, nextItemNumber: 1 });
|
|
563
|
+
else if (!existsSync(path)) throw new Fail("not_found", `No session exists at ${path}`);
|
|
564
|
+
db = new Database(path, { readwrite: true, create: false });
|
|
565
|
+
// Take the lock first, then validate, and only then let recovery write.
|
|
566
|
+
db.exec("PRAGMA busy_timeout=0; PRAGMA locking_mode=EXCLUSIVE; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
|
|
567
|
+
db.exec("BEGIN EXCLUSIVE");
|
|
568
|
+
let meta: Meta;
|
|
569
|
+
const inspect = sqliteTables(db);
|
|
570
|
+
try {
|
|
571
|
+
try { meta = inspect.getMeta(); }
|
|
572
|
+
catch { throw new Fail("incompatible", "File is not a readable harness session"); }
|
|
573
|
+
if (meta.formatVersion !== 2 && meta.formatVersion !== 3 && meta.formatVersion !== 4 && meta.formatVersion !== 5 && meta.formatVersion !== 6 && meta.formatVersion !== 7) throw new Fail("incompatible", `Unsupported storage format: ${meta.formatVersion}`);
|
|
574
|
+
if (meta.formatVersion === 7 && db.query<{ count: number }, []>(`SELECT COUNT(*) AS count FROM sqlite_schema
|
|
575
|
+
WHERE type = 'table' AND name IN ('reminder_rows','reminder_receipts','reminder_creates','reminder_metadata')`).get()?.count !== 4)
|
|
576
|
+
throw new Fail("incompatible", "Format 7 is missing reminder storage");
|
|
577
|
+
if (meta.sessionId !== identity.sessionId) throw new Fail("incompatible", "File holds a different session");
|
|
578
|
+
checkScriptIdentity(meta.compatibilityKey, options.requiredScriptDigest);
|
|
579
|
+
} finally { inspect.dispose(); db.exec("ROLLBACK"); }
|
|
580
|
+
// An old format has only the implicit legacy policy. If the candidate
|
|
581
|
+
// lacks it, build an in-memory inspection view without changing the
|
|
582
|
+
// owned file or running recovery. Every mutation on that view is fenced.
|
|
583
|
+
const legacyNeedsPolicy = meta.formatVersion < 4 && config && !Object.hasOwn(config.policies, "__legacy_allow")
|
|
584
|
+
&& Number(db.query<{ count: number }, []>("SELECT COUNT(*) AS count FROM items").get()?.count ?? 0) > 0;
|
|
585
|
+
if (legacyNeedsPolicy) {
|
|
586
|
+
const owner = db, clone = Database.deserialize(owner.serialize());
|
|
587
|
+
try {
|
|
588
|
+
const view = sqliteTables(clone);
|
|
589
|
+
view.transaction(() => { if (meta.formatVersion === 2) upgradeFromFormat2(clone); upgradeFromFormat3(clone); addExternalSource(clone);
|
|
590
|
+
view.setMeta({ ...view.getMeta(), formatVersion: 4 }); refreshReplyIds(clone); refreshModelCalls(clone); refreshRetrieval(clone, view.entries); });
|
|
591
|
+
return { ok: true, value: createEngine(view, identity.compatibilityKey, () => { view.dispose(); clone.close(true); owner.close(true); }, config, true), revision: meta.revision };
|
|
592
|
+
} catch (error) { clone.close(); throw error; }
|
|
593
|
+
}
|
|
594
|
+
const tables = sqliteTables(db), owner = db;
|
|
595
|
+
tables.transaction(() => {
|
|
596
|
+
refreshReplyIds(owner);
|
|
597
|
+
refreshModelCalls(owner);
|
|
598
|
+
const compatible = meta.formatVersion < 4 || referencesCompatible(tables, config);
|
|
599
|
+
if (meta.formatVersion >= 4 && meta.formatVersion < 6 && compatible) addExternalSource(owner);
|
|
600
|
+
if (compatible)
|
|
601
|
+
recover(tables, meta.formatVersion < 4 ? () => { if (meta.formatVersion === 2) upgradeFromFormat2(owner); upgradeFromFormat3(owner); addExternalSource(owner); } : undefined);
|
|
602
|
+
if (tables.getMeta().formatVersion >= 6) installContextPolicyIndex(owner);
|
|
603
|
+
refreshRetrieval(owner, tables.entries);
|
|
604
|
+
});
|
|
605
|
+
return { ok: true, value: createEngine(tables, identity.compatibilityKey, () => { tables.dispose(); owner.close(true); }, config), revision: tables.getMeta().revision };
|
|
606
|
+
} catch (error) {
|
|
607
|
+
try { db?.close(); } catch { /* The original failure is the one to report. */ }
|
|
608
|
+
const code = (error as { code?: string }).code;
|
|
609
|
+
if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") return failure(new Fail("owner_conflict", "Session storage already has an owner"));
|
|
610
|
+
if (code === "SQLITE_NOTADB" || code === "SQLITE_CORRUPT") return failure(new Fail("incompatible", "File is not a readable harness session"));
|
|
611
|
+
return failure(error);
|
|
612
|
+
}
|
|
613
|
+
},
|
|
614
|
+
importArchive(raw, options) {
|
|
615
|
+
try {
|
|
616
|
+
const archive = validateArchive(raw);
|
|
617
|
+
if (options?.sessionId !== undefined && (typeof options.sessionId !== "string" || !options.sessionId.trim()))
|
|
618
|
+
throw new Fail("invalid_input", "sessionId must be a nonempty string");
|
|
619
|
+
const meta = archiveMeta(archive, options?.sessionId);
|
|
620
|
+
publish(path, meta, tables => restoreArchive(tables, archive));
|
|
621
|
+
return { ok: true, value: storedSession(meta), revision: meta.revision };
|
|
622
|
+
} catch (error) { return failure(error); }
|
|
623
|
+
},
|
|
624
|
+
};
|
|
625
|
+
}
|