@qlairoslabs/acp-client 0.12.0 → 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 -3
- package/CHANGELOG-controller-interface.md +258 -0
- package/CHANGELOG-metering.md +29 -0
- package/CHANGELOG-operation-lifecycle.md +15 -1
- package/CONSUMER_GUIDE.md +847 -7
- 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 +30 -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 +10 -0
- package/src/cli/index.ts +3 -3
- package/src/cli/managed.ts +2 -2
- package/src/client.ts +68 -98
- 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,301 @@
|
|
|
1
|
+
import { RoutineAdmission } from "./routine-guard.ts";
|
|
2
|
+
import { isRoutineSchedule } from "./routine-schedule.ts";
|
|
3
|
+
import { type ReminderNegotiation, type ReminderWireRow, type ReminderWireResult, type ReminderWireList, type ReminderWireOpen } from "./routine-wire.ts";
|
|
4
|
+
import type { AgentConversationId } from "../../agent-ids.ts";
|
|
5
|
+
import type { Logger } from "../../logger.ts";
|
|
6
|
+
import type { HarnessClient } from "../../native-harness/src/client.ts";
|
|
7
|
+
import type { PersistenceBackend, PersistenceScope } from "../../persistence/backend.ts";
|
|
8
|
+
import type { ReminderChange, ReminderPersistence } from "../../persistence/reminders.ts";
|
|
9
|
+
import { codeOf } from "../errors.ts";
|
|
10
|
+
import { defaultReminderLimits } from "./limits.ts";
|
|
11
|
+
import {
|
|
12
|
+
fromWireReminder, negotiatedLimits, routineReminderRequest,
|
|
13
|
+
type ReminderNotification, type WireChange, type WireReminderEvent,
|
|
14
|
+
} from "./wire.ts";
|
|
15
|
+
|
|
16
|
+
const batchLimit = 100;
|
|
17
|
+
const sweepAttempts = 3;
|
|
18
|
+
|
|
19
|
+
export class ReminderSync {
|
|
20
|
+
supported?: boolean;
|
|
21
|
+
readonly routineAdmission = new RoutineAdmission();
|
|
22
|
+
limits = defaultReminderLimits;
|
|
23
|
+
unreconciled = false;
|
|
24
|
+
private sessionId?: string;
|
|
25
|
+
private tail = Promise.resolve();
|
|
26
|
+
private sends = Promise.resolve();
|
|
27
|
+
private readonly fires = new Set<string>();
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
private readonly persistence: PersistenceBackend,
|
|
31
|
+
private readonly repository: ReminderPersistence,
|
|
32
|
+
private readonly log: Logger,
|
|
33
|
+
) {}
|
|
34
|
+
|
|
35
|
+
private transaction<T>(work: (repo: ReminderPersistence, scope: PersistenceScope) => Promise<T>): Promise<T> {
|
|
36
|
+
return this.persistence.reminders
|
|
37
|
+
? this.persistence.transaction(scope => work(scope.reminders!, scope))
|
|
38
|
+
: work(this.repository, this.persistence);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private ordered<T>(work: () => Promise<T>): Promise<T> {
|
|
42
|
+
const next = this.tail.then(work);
|
|
43
|
+
this.tail = next.then(() => {}, () => {});
|
|
44
|
+
return next;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
settled(): Promise<void> { return this.tail; }
|
|
48
|
+
|
|
49
|
+
async initialize(offered: ReminderNegotiation): Promise<void> {
|
|
50
|
+
this.supported = offered.capabilities?.reminders === true;
|
|
51
|
+
this.routineAdmission.initialize(offered.capabilities?.routines, offered.capabilities?.unattendedTurnGuard, this.supported);
|
|
52
|
+
this.limits = negotiatedLimits(offered.reminderLimits, this.routineAdmission.supported);
|
|
53
|
+
await this.repository.setSupported(this.supported);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async stage(include: (change: ReminderChange) => boolean = () => true, originals?: ReminderChange[]): Promise<WireChange[]> {
|
|
57
|
+
if (!this.supported) return [];
|
|
58
|
+
return this.transaction(async repo => {
|
|
59
|
+
const entries = (await repo.list()).flatMap(row => row.changes)
|
|
60
|
+
.filter(change => change.state === "pending" || change.state === "maybe_sent")
|
|
61
|
+
.sort((a, b) => a.stagingOrder - b.stagingOrder);
|
|
62
|
+
const batch: WireChange[] = [];
|
|
63
|
+
let bytes = 0;
|
|
64
|
+
const held = new Set<string>();
|
|
65
|
+
for (const change of entries) {
|
|
66
|
+
if (batch.length === batchLimit) break;
|
|
67
|
+
const id = change.reminder.id;
|
|
68
|
+
if (held.has(id)) continue;
|
|
69
|
+
if (isRoutineSchedule(change.reminder.schedule) && !this.routineAdmission.advertised) {
|
|
70
|
+
await repo.quarantine(id, change.changeId, change.reminder.missedRuns === undefined ? "invalid_local_entry" : "routines_unavailable");
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (!include(change)) {
|
|
74
|
+
held.add(id);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
const wire = change.frozenWire ?? routineReminderRequest(change, this.limits);
|
|
79
|
+
const size = Buffer.byteLength(JSON.stringify(wire)) + 1;
|
|
80
|
+
if (size > 900_000) throw new Error("Reminder entry exceeds startup frame budget");
|
|
81
|
+
if (bytes + size > 900_000) break;
|
|
82
|
+
if (await repo.markMaybeSent(wire.reminderId, wire.changeId, wire)) {
|
|
83
|
+
originals?.push(change);
|
|
84
|
+
batch.push(wire);
|
|
85
|
+
bytes += size;
|
|
86
|
+
}
|
|
87
|
+
} catch (error) {
|
|
88
|
+
this.log.warn("reminder_entry_quarantined", { id: change.reminder.id, error: String(error) });
|
|
89
|
+
await repo.quarantine(change.reminder.id, change.changeId, "invalid_local_entry");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return batch;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async restoreStaged(originals: ReminderChange[]): Promise<void> {
|
|
97
|
+
await this.transaction(async repo => {
|
|
98
|
+
for (const change of originals) await repo.restoreStaged(change);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async rejectedBatch(batch: WireChange[]): Promise<void> {
|
|
103
|
+
// A successful retry isolates the reminder batch. Quarantine it whole.
|
|
104
|
+
this.log.warn("reminder_batch_rejected", { count: batch.length });
|
|
105
|
+
await this.transaction(async repo => {
|
|
106
|
+
for (const entry of batch) await repo.quarantine(entry.reminderId, entry.changeId, "invalid_params");
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async startupRetry(id: string): Promise<WireChange[] | undefined> {
|
|
111
|
+
const retry = (await this.repository.wake()).startupRetry;
|
|
112
|
+
return retry?.sessionId === id ? [...retry.entries] : undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async freezeStartupRetry(sessionId: string, entries: readonly WireChange[], exhausted?: true): Promise<void> {
|
|
116
|
+
await this.repository.setStartupRetry({ sessionId, entries, exhausted });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async replacementAttempted(id: string): Promise<boolean> {
|
|
120
|
+
return (await this.repository.wake()).replacementAttempted === id;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async setReplacementAttempted(id: string | undefined): Promise<void> {
|
|
124
|
+
await this.repository.setReplacementAttempted(id);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async opened(client: HarnessClient, result: ReminderWireOpen, configuredId: string, fresh: boolean): Promise<void> {
|
|
128
|
+
if (!this.supported) return;
|
|
129
|
+
const sessionId = result.sessionId ?? configuredId;
|
|
130
|
+
const wake = await this.repository.wake();
|
|
131
|
+
const saved = wake.reported?.sessionId;
|
|
132
|
+
if (fresh || wake.replacementAttempted === configuredId || ((this.sessionId ?? saved) !== undefined && (this.sessionId ?? saved) !== sessionId)) {
|
|
133
|
+
this.fires.clear();
|
|
134
|
+
await this.repository.replaceSession(sessionId);
|
|
135
|
+
await this.transaction(async repo => {
|
|
136
|
+
for (const receipt of result.reminderChanges ?? []) await repo.markMaybeSent(receipt.reminderId, receipt.changeId);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
this.sessionId = sessionId;
|
|
140
|
+
this.routineAdmission.opened(result);
|
|
141
|
+
await this.ordered(async () => {
|
|
142
|
+
for (const receipt of result.reminderChanges ?? []) await this.recordReceipt(receipt);
|
|
143
|
+
if (result.reminderRevision !== undefined && result.nextDueAt !== undefined) {
|
|
144
|
+
await this.deadline(result.nextDueAt, result.reminderRevision);
|
|
145
|
+
}
|
|
146
|
+
if (result.reminders) await this.sweep(client, undefined, { reminders: result.reminders, next: result.remindersNext });
|
|
147
|
+
if (wake.startupRetry?.sessionId === configuredId) await this.repository.setStartupRetry(undefined);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private async deadline(nextDueAt: string | null, revision: number) {
|
|
152
|
+
if (!this.sessionId) return;
|
|
153
|
+
const result = await this.repository.updateDeadline({
|
|
154
|
+
sessionId: this.sessionId, revision, nextDueAt: nextDueAt === null ? null : Date.parse(nextDueAt),
|
|
155
|
+
});
|
|
156
|
+
if (result === "mismatch") this.log.warn("reminders_due_revision_conflict", { revision, nextDueAt });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private async recordReceipt(receipt: ReminderWireResult) {
|
|
160
|
+
const { reminderId, changeId } = receipt;
|
|
161
|
+
if (receipt.outcome === "blocked") {
|
|
162
|
+
const { reason } = receipt;
|
|
163
|
+
if (reason === "stale" || reason === "conflict") this.log.warn("reminder_receipt_conflict", { reminderId, changeId, reason });
|
|
164
|
+
const blocked = { reason: reason ?? "invalid_state" };
|
|
165
|
+
await this.repository.acknowledge(reminderId, changeId, blocked);
|
|
166
|
+
return blocked;
|
|
167
|
+
}
|
|
168
|
+
const { reminder } = receipt;
|
|
169
|
+
if (!reminder) throw new Error("Applied reminder receipt has no row");
|
|
170
|
+
const journal = (await this.repository.list()).find(row => row.id === reminderId);
|
|
171
|
+
const prior = journal?.changes.find(change => change.changeId === changeId)?.reminder ?? journal?.confirmed;
|
|
172
|
+
const confirmed = fromWireReminder(reminder, prior);
|
|
173
|
+
await this.repository.acknowledge(reminderId, changeId, { confirmed });
|
|
174
|
+
return { confirmed: (await this.repository.list()).find(row => row.id === reminderId)?.confirmed ?? confirmed };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private async storeRows(rows: ReminderWireRow[], seen: Set<string>): Promise<void> {
|
|
178
|
+
await this.transaction(async (repo, scope) => {
|
|
179
|
+
const known = await repo.list();
|
|
180
|
+
for (const row of rows) {
|
|
181
|
+
const conversation = await scope?.conversations.get(row.channel as AgentConversationId);
|
|
182
|
+
if (!conversation || conversation.deletedAt) continue;
|
|
183
|
+
seen.add(row.id);
|
|
184
|
+
const journal = known.find(item => item.id === row.id);
|
|
185
|
+
await repo.observe(fromWireReminder(row, journal?.confirmed ?? journal?.changes.at(-1)?.reminder));
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private async sweep(client: HarnessClient, channel?: string, first?: ReminderWireList): Promise<void> {
|
|
191
|
+
for (let attempt = 0; attempt < sweepAttempts; attempt++) {
|
|
192
|
+
const seen = new Set<string>();
|
|
193
|
+
try {
|
|
194
|
+
let page = attempt === 0 ? first : undefined;
|
|
195
|
+
let after: string | undefined;
|
|
196
|
+
do {
|
|
197
|
+
page ??= await client.listReminders({ ...(channel ? { channel } : {}), ...(after ? { after } : {}) });
|
|
198
|
+
await this.storeRows(page.reminders, seen);
|
|
199
|
+
after = page.next;
|
|
200
|
+
page = undefined;
|
|
201
|
+
} while (after);
|
|
202
|
+
if (!channel) await this.repository.completeSweep(seen);
|
|
203
|
+
this.unreconciled = false;
|
|
204
|
+
return;
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (codeOf(error) !== "invalid_cursor") throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
this.unreconciled = true;
|
|
210
|
+
this.log.warn("reminder_sweep_unreconciled", { channel });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
refresh(client: HarnessClient, channel?: string, id?: string): Promise<void> {
|
|
214
|
+
return this.ordered(async () => {
|
|
215
|
+
if (!this.supported) return;
|
|
216
|
+
if (!id) return this.sweep(client, channel);
|
|
217
|
+
return this.refreshRow(client, channel, id);
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private async refreshRow(client: HarnessClient, channel: string | undefined, id: string): Promise<void> {
|
|
222
|
+
try {
|
|
223
|
+
const { reminder } = await client.getReminder({ id });
|
|
224
|
+
if (reminder.channel === channel) await this.storeRows([reminder], new Set());
|
|
225
|
+
} catch (error) {
|
|
226
|
+
if (codeOf(error) !== "not_found") throw error;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
dispatch(client: HarnessClient, target?: WireChange) {
|
|
231
|
+
const result = this.sends.then(async () => {
|
|
232
|
+
let own: Awaited<ReturnType<ReminderSync["recordReceipt"]>> | undefined;
|
|
233
|
+
for (;;) {
|
|
234
|
+
const batch = await this.stage();
|
|
235
|
+
if (!batch.length) break;
|
|
236
|
+
for (const entry of batch) {
|
|
237
|
+
const send = () => client.changeReminder(entry);
|
|
238
|
+
let receipt: ReminderWireResult | undefined;
|
|
239
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
240
|
+
try { receipt = await send(); break; }
|
|
241
|
+
catch (error) { if (codeOf(error) !== "storage_failure") throw error; }
|
|
242
|
+
}
|
|
243
|
+
if (!receipt) {
|
|
244
|
+
await this.repository.deferStorageFailure(entry.reminderId, entry.changeId);
|
|
245
|
+
this.log.warn("reminder_live_retry_exhausted", { id: entry.reminderId, changeId: entry.changeId });
|
|
246
|
+
return target ? { retryable: true as const } : undefined;
|
|
247
|
+
}
|
|
248
|
+
if (receipt.reminderId !== entry.reminderId || receipt.changeId !== entry.changeId) throw new Error("Mismatched reminder receipt");
|
|
249
|
+
const received = receipt;
|
|
250
|
+
const outcome = await this.ordered(() => this.recordReceipt(received));
|
|
251
|
+
if (entry.reminderId === target?.reminderId && entry.changeId === target.changeId) own = outcome;
|
|
252
|
+
}
|
|
253
|
+
if (own) break;
|
|
254
|
+
}
|
|
255
|
+
if (target && !own) {
|
|
256
|
+
const journal = (await this.repository.list()).find(row => row.id === target.reminderId);
|
|
257
|
+
const terminal = journal?.changes.find(change => change.changeId === target.changeId);
|
|
258
|
+
return terminal?.reason ? { reason: terminal.reason } : journal?.confirmed ? { confirmed: journal.confirmed } : { reason: "not_found" };
|
|
259
|
+
}
|
|
260
|
+
return own;
|
|
261
|
+
});
|
|
262
|
+
this.sends = result.then(() => {}, () => {});
|
|
263
|
+
return result;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
notification(notification: ReminderNotification, emit: (channel: string, event: WireReminderEvent) => void, client?: HarnessClient) {
|
|
267
|
+
void this.ordered(async () => {
|
|
268
|
+
if ("deadline" in notification) return this.deadline(notification.deadline.nextDueAt, notification.deadline.revision);
|
|
269
|
+
const { channel, event } = notification;
|
|
270
|
+
if (event.kind === "reminder_fired" && (this.fires.has(event.occurrenceId) || this.fires.has(event.noticeId))) return;
|
|
271
|
+
const conversation = await this.persistence.conversations.get(channel as AgentConversationId);
|
|
272
|
+
if (!conversation || conversation.deletedAt) return;
|
|
273
|
+
if (event.kind === "routine_disposition" || event.kind === "routine_migration_blocked") {
|
|
274
|
+
emit(channel, event);
|
|
275
|
+
if (client && event.kind === "routine_disposition" && event.reason === "expired") {
|
|
276
|
+
await this.refreshRow(client, channel, event.reminderId);
|
|
277
|
+
}
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (event.kind === "reminder_changed" && event.reminder.channel === channel) await this.storeRows([event.reminder], new Set());
|
|
281
|
+
if (event.kind !== "reminder_changed") {
|
|
282
|
+
await this.transaction(async (repo, scope) => {
|
|
283
|
+
const row = await scope?.conversations.get(channel as AgentConversationId);
|
|
284
|
+
if (!row || row.deletedAt) return;
|
|
285
|
+
const confirmed = (await repo.list()).find(item => item.id === event.reminderId && item.conversationId === channel)?.confirmed;
|
|
286
|
+
if (!confirmed) return;
|
|
287
|
+
const status = event.kind === "reminder_fired" ? "completed" : event.kind === "reminder_expired" ? "expired" : "cancelled";
|
|
288
|
+
const routineOccurrence = event.kind !== "reminder_cancelled" && isRoutineSchedule(confirmed.schedule);
|
|
289
|
+
if (routineOccurrence && event.kind === "reminder_expired") return;
|
|
290
|
+
await repo.observe({ ...confirmed, ...(!routineOccurrence ? { status, nextRunAt: null } : {}), ...(event.kind === "reminder_fired"
|
|
291
|
+
? { lastRunAt: Date.parse(event.firedAt), lastOccurrenceId: event.occurrenceId, noticeId: event.noticeId } : {}) });
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
if (event.kind === "reminder_fired") {
|
|
295
|
+
this.fires.add(event.occurrenceId);
|
|
296
|
+
this.fires.add(event.noticeId);
|
|
297
|
+
}
|
|
298
|
+
emit(channel, event);
|
|
299
|
+
}).catch(error => this.log.warn("reminder_event_failed", { error: String(error) }));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { isRoutineSchedule } from "./routine-schedule.ts";
|
|
2
|
+
import type { ReminderWireChange as WireChange, ReminderWireRow, AdvertisedReminderLimits } from "./routine-wire.ts";
|
|
3
|
+
import { normalizeReminderSchedule } from "./schedule.ts";
|
|
4
|
+
import type {
|
|
5
|
+
ChannelEvent, HarnessClient, ReminderChange as OneOffChange,
|
|
6
|
+
ReminderChangeResult, ReminderSessionEvent,
|
|
7
|
+
} from "../../native-harness/src/client.ts";
|
|
8
|
+
import type { Reminder, ReminderChange } from "../../persistence/reminders.ts";
|
|
9
|
+
import { defaultReminderLimits, type ReminderLimits } from "./limits.ts";
|
|
10
|
+
import { ReminderError } from "./schedule.ts";
|
|
11
|
+
|
|
12
|
+
type HarnessReminderEvent = Extract<ChannelEvent["event"], { type: `reminder_${string}` | `routine_${string}` }>;
|
|
13
|
+
type WithKind<Event extends { type: string }> = Event extends unknown
|
|
14
|
+
? Omit<Event, "type"> & { kind: Event["type"] }
|
|
15
|
+
: never;
|
|
16
|
+
|
|
17
|
+
export type WireReminderEvent = WithKind<Exclude<HarnessReminderEvent, { type: "reminder_changed" }>>
|
|
18
|
+
| { kind: "reminder_changed"; reminder: ReminderWireRow };
|
|
19
|
+
type PublicWireRow<Row> = Row extends unknown ? Omit<Row, "blockedReason"> & { blockedReason?: string } : never;
|
|
20
|
+
// Keep future block reasons representable in the library's public event.
|
|
21
|
+
export type ConsumerReminderEvent = Exclude<WireReminderEvent, { kind: "reminder_changed" }> | (
|
|
22
|
+
Omit<Extract<WireReminderEvent, { kind: "reminder_changed" }>, "reminder"> & {
|
|
23
|
+
reminder: PublicWireRow<ReminderWireRow>;
|
|
24
|
+
}
|
|
25
|
+
);
|
|
26
|
+
export type KnownReminderBlockReason = Extract<ReminderChangeResult, { outcome: "blocked" }>["reason"];
|
|
27
|
+
export type HarnessOpenResult = Awaited<ReturnType<HarnessClient["openSession"]>>;
|
|
28
|
+
export function negotiatedLimits(value: AdvertisedReminderLimits | undefined, routines = false): ReminderLimits {
|
|
29
|
+
const read = (name: keyof AdvertisedReminderLimits, fallback: number) => {
|
|
30
|
+
const limit = value?.[name];
|
|
31
|
+
return typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0 ? limit : fallback;
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
oneShotLeadMs: read("minLeadMs", defaultReminderLimits.oneShotLeadMs),
|
|
35
|
+
repeatIntervalMs: read("minIntervalMs", defaultReminderLimits.repeatIntervalMs),
|
|
36
|
+
perChannel: read("maxActiveRoutinesPerChannel", routines ? 20 : 0),
|
|
37
|
+
maxRoutineCatchUp: read("maxRoutineCatchUp", 10),
|
|
38
|
+
minGraceMs: read("minExpiryGraceMs", defaultReminderLimits.minGraceMs),
|
|
39
|
+
maxGraceMs: read("maxExpiryGraceMs", defaultReminderLimits.maxGraceMs),
|
|
40
|
+
expiryMultiplier: read("expiryMultiplier", defaultReminderLimits.expiryMultiplier),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function reminderRequest(change: ReminderChange, limits = defaultReminderLimits): OneOffChange {
|
|
45
|
+
const { id, conversationId, text, schedule, expiryPolicy, status, policyNames, scheduleAcceptedAt } = change.reminder;
|
|
46
|
+
const includes = (field: NonNullable<ReminderChange["fields"]>[number]) =>
|
|
47
|
+
change.op === "create" || (change.op === "update" && change.fields?.includes(field) === true);
|
|
48
|
+
if (typeof id !== "string" || !id.trim() || !Number.isSafeInteger(change.changeId) || change.changeId < 1) throw new Error("Invalid reminder identity");
|
|
49
|
+
const identity = { reminderId: id, changeId: change.changeId };
|
|
50
|
+
if (change.op === "cancel") return { ...identity, op: "cancel", payload: {} } satisfies OneOffChange;
|
|
51
|
+
if (!("at" in schedule)) throw new ReminderError("routines_unavailable", "Routine reminders are unavailable");
|
|
52
|
+
const anchor = scheduleAcceptedAt ?? change.acceptedAt;
|
|
53
|
+
if (includes("schedule") && (!Number.isSafeInteger(anchor) || !Number.isSafeInteger(schedule.at)
|
|
54
|
+
|| schedule.at - anchor < limits.oneShotLeadMs)) throw new Error("Invalid reminder schedule anchor");
|
|
55
|
+
if (includes("text") && (typeof text !== "string" || !text.trim())) throw new Error("Invalid reminder text");
|
|
56
|
+
if (change.op === "create" && (typeof conversationId !== "string" || !conversationId.trim() || (policyNames !== undefined && (
|
|
57
|
+
!Array.isArray(policyNames) ||
|
|
58
|
+
new Set(policyNames).size !== policyNames.length || policyNames.some(name => typeof name !== "string" || !name.trim())
|
|
59
|
+
)))) throw new Error("Invalid reminder destination or policies");
|
|
60
|
+
if (change.op === "update" && includes("status") && status !== "active" && status !== "paused") throw new Error("Invalid reminder state");
|
|
61
|
+
if (includes("expiry") && !["default", "duration", "unlimited", "unknown"].includes(expiryPolicy?.kind)) throw new Error("Invalid reminder expiry policy");
|
|
62
|
+
const expiresAfter = expiryPolicy.kind === "duration" ? expiryPolicy.milliseconds : expiryPolicy.kind === "unlimited" ? null : undefined;
|
|
63
|
+
if (includes("expiry") && typeof expiresAfter === "number" &&
|
|
64
|
+
(!Number.isSafeInteger(expiresAfter) || expiresAfter < limits.minGraceMs || expiresAfter > limits.maxGraceMs)) {
|
|
65
|
+
throw new Error("Invalid reminder grace");
|
|
66
|
+
}
|
|
67
|
+
const schedulePatch = () => ({ schedule: { at: new Date(schedule.at).toISOString() }, acceptedAt: new Date(anchor).toISOString() });
|
|
68
|
+
const grace = includes("expiry") && expiresAfter !== undefined ? { expiresAfter } : {};
|
|
69
|
+
if (change.op === "create") {
|
|
70
|
+
return { ...identity, op: "create", payload: {
|
|
71
|
+
channel: conversationId, text, ...schedulePatch(), ...grace,
|
|
72
|
+
...(policyNames === undefined ? {} : { policyNames: [...policyNames] }),
|
|
73
|
+
} } satisfies OneOffChange;
|
|
74
|
+
}
|
|
75
|
+
const patch = {
|
|
76
|
+
...(includes("text") ? { text } : {}),
|
|
77
|
+
...(includes("status") && (status === "active" || status === "paused") ? { state: status } : {}),
|
|
78
|
+
...grace,
|
|
79
|
+
};
|
|
80
|
+
if (includes("schedule")) return { ...identity, op: "update", payload: { ...patch, ...schedulePatch() } } satisfies OneOffChange;
|
|
81
|
+
if (Object.keys(patch).length === 0) throw new Error("Empty reminder update");
|
|
82
|
+
return { ...identity, op: "update", payload: patch } satisfies OneOffChange;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function routineReminderRequest(change: ReminderChange, limits = defaultReminderLimits): WireChange {
|
|
86
|
+
const { id: reminderId, conversationId: channel, text, schedule, scheduleAcceptedAt, status, policyNames,
|
|
87
|
+
expiryPolicy, missedRuns, overlap } = change.reminder;
|
|
88
|
+
if (!isRoutineSchedule(schedule) || change.op === "cancel") return reminderRequest(change, limits);
|
|
89
|
+
const identity = { reminderId, changeId: change.changeId };
|
|
90
|
+
if (!reminderId.trim() || !Number.isSafeInteger(change.changeId) || change.changeId < 1) throw new Error("Invalid reminder identity");
|
|
91
|
+
const fields = change.fields ?? [];
|
|
92
|
+
const create = change.op === "create";
|
|
93
|
+
const include = (field: typeof fields[number]) => create || fields.includes(field);
|
|
94
|
+
if (include("text") && !text.trim()) throw new Error("Invalid reminder text");
|
|
95
|
+
if (create && (!channel.trim() || (policyNames && (
|
|
96
|
+
new Set(policyNames).size !== policyNames.length || policyNames.some(name => typeof name !== "string" || !name.trim())
|
|
97
|
+
)))) throw new Error("Invalid reminder destination or policies");
|
|
98
|
+
const anchor = scheduleAcceptedAt ?? change.acceptedAt;
|
|
99
|
+
const schedulePatch = () => {
|
|
100
|
+
normalizeReminderSchedule(schedule, anchor, limits, change.op === "update");
|
|
101
|
+
const bound = schedule.count !== undefined ? { count: schedule.count }
|
|
102
|
+
: schedule.until !== undefined ? { until: new Date(schedule.until).toISOString() } : {};
|
|
103
|
+
const wireSchedule = "every" in schedule
|
|
104
|
+
? { every: schedule.every, startAt: new Date(schedule.startAt).toISOString(), ...bound }
|
|
105
|
+
: { cron: schedule.cron, timezone: schedule.timezone, ...bound };
|
|
106
|
+
return { schedule: wireSchedule, acceptedAt: new Date(anchor).toISOString() };
|
|
107
|
+
};
|
|
108
|
+
const expiresAfter = expiryPolicy.kind === "duration" ? expiryPolicy.milliseconds : expiryPolicy.kind === "unlimited" ? null : undefined;
|
|
109
|
+
if (include("expiry") && typeof expiresAfter === "number" &&
|
|
110
|
+
(!Number.isSafeInteger(expiresAfter) || expiresAfter < limits.minGraceMs || expiresAfter > limits.maxGraceMs)) {
|
|
111
|
+
throw new Error("Invalid reminder grace");
|
|
112
|
+
}
|
|
113
|
+
const options = {
|
|
114
|
+
...(include("expiry") && expiresAfter !== undefined ? { expiresAfter } : {}),
|
|
115
|
+
...(include("missedRuns") && missedRuns !== undefined ? { missedRuns } : {}),
|
|
116
|
+
...(include("overlap") && overlap !== undefined ? { overlap } : {}),
|
|
117
|
+
};
|
|
118
|
+
if (create) return { ...identity, op: "create", payload: {
|
|
119
|
+
channel, text, ...schedulePatch(), ...options,
|
|
120
|
+
...(policyNames ? { policyNames: [...policyNames] } : {}),
|
|
121
|
+
} } satisfies WireChange;
|
|
122
|
+
if (include("status") && status !== "active" && status !== "paused") throw new Error("Invalid routine state");
|
|
123
|
+
const patch = {
|
|
124
|
+
...(include("text") ? { text } : {}),
|
|
125
|
+
...(include("status") && (status === "active" || status === "paused") ? { state: status } : {}),
|
|
126
|
+
...options,
|
|
127
|
+
};
|
|
128
|
+
if (include("schedule")) return { ...identity, op: "update", payload: { ...patch, ...schedulePatch() } } satisfies WireChange;
|
|
129
|
+
if (!Object.keys(patch).length) throw new Error("Empty routine update");
|
|
130
|
+
return { ...identity, op: "update", payload: patch } satisfies WireChange;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type { WireChange };
|
|
134
|
+
|
|
135
|
+
export function fromWireReminder(row: ReminderWireRow, prior?: Reminder): Reminder {
|
|
136
|
+
const { id, channel, text, state, policyNames, createdBy, creatorId, lastRunAt, lastOccurrenceId, noticeId, blockedReason } = row;
|
|
137
|
+
return {
|
|
138
|
+
id, conversationId: channel, text, policyNames, createdBy, creatorId, lastOccurrenceId, noticeId, blockedReason,
|
|
139
|
+
status: state === "done" ? "completed" : state,
|
|
140
|
+
...decodeSchedule(row),
|
|
141
|
+
scheduleAcceptedAt: Date.parse(row.acceptedAt),
|
|
142
|
+
expiryPolicy: prior?.expiryPolicy ?? { kind: "unknown" },
|
|
143
|
+
expiry: row.expiresAt === null ? null : { kind: "absolute", at: Date.parse(row.expiresAt), graceMs: row.expiresAfter! },
|
|
144
|
+
nextRunAt: row.nextRunAt == null ? null : Date.parse(row.nextRunAt),
|
|
145
|
+
...(lastRunAt === undefined ? {} : { lastRunAt: Date.parse(lastRunAt) }),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function decodeSchedule(row: ReminderWireRow): Pick<Reminder, "schedule" | "remainingCount" | "missedRuns" | "overlap" | "timezoneVersion" | "timezoneMigration"> {
|
|
150
|
+
const { schedule, remainingCount, missedRuns, overlap, timezoneVersion, timezoneMigration } = row;
|
|
151
|
+
if (schedule.at !== undefined) return { schedule: { at: Date.parse(schedule.at) } };
|
|
152
|
+
const bound = schedule.count !== undefined ? { count: schedule.count }
|
|
153
|
+
: schedule.until !== undefined ? { until: Date.parse(schedule.until) } : {};
|
|
154
|
+
return {
|
|
155
|
+
schedule: schedule.every !== undefined ? { every: schedule.every, startAt: Date.parse(schedule.startAt), ...bound }
|
|
156
|
+
: { cron: schedule.cron, timezone: schedule.timezone, ...bound },
|
|
157
|
+
remainingCount, missedRuns, overlap, timezoneVersion, timezoneMigration,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export type ReminderNotification =
|
|
162
|
+
| { deadline: Omit<ReminderSessionEvent, "type"> }
|
|
163
|
+
| { channel: string; event: WireReminderEvent };
|
|
164
|
+
|
|
165
|
+
export function reminderNotification(value: unknown): ReminderNotification | undefined {
|
|
166
|
+
const frame = value as { jsonrpc?: string; method?: string; params?: Record<string, unknown> } | null;
|
|
167
|
+
if (frame?.jsonrpc !== "2.0" || !frame.params) return;
|
|
168
|
+
const params = frame.params;
|
|
169
|
+
if (frame.method === "session/event" && params.type === "reminders_due") {
|
|
170
|
+
if (!Number.isSafeInteger(params.revision) || (params.nextDueAt !== null &&
|
|
171
|
+
(typeof params.nextDueAt !== "string" || !Number.isFinite(Date.parse(params.nextDueAt))))) {
|
|
172
|
+
throw new Error("Invalid reminders_due event");
|
|
173
|
+
}
|
|
174
|
+
return { deadline: { nextDueAt: params.nextDueAt as string | null, revision: params.revision as number } };
|
|
175
|
+
}
|
|
176
|
+
if (frame.method !== "channel/event" || typeof params.channel !== "string" || !params.event) return;
|
|
177
|
+
const { type, ...fields } = params.event as { type: string };
|
|
178
|
+
if (!["reminder_changed", "reminder_fired", "reminder_cancelled", "reminder_expired", "routine_disposition", "routine_migration_blocked"].includes(type)) return;
|
|
179
|
+
const fieldsByType: Record<string, readonly string[]> = {
|
|
180
|
+
reminder_fired: ["reminderId", "occurrenceId", "scheduledAt", "firedAt", "noticeId"],
|
|
181
|
+
reminder_cancelled: ["reminderId", "by"],
|
|
182
|
+
reminder_expired: ["reminderId", "occurrenceId", "scheduledAt", "expiredAt"],
|
|
183
|
+
routine_disposition: ["reminderId", "firstScheduledAt", "lastScheduledAt", "reason"],
|
|
184
|
+
routine_migration_blocked: ["reminderId", "fromVersion", "targetVersion", "cause"],
|
|
185
|
+
};
|
|
186
|
+
if (type === "reminder_changed") {
|
|
187
|
+
const row = (fields as { reminder?: ReminderWireRow }).reminder;
|
|
188
|
+
if (!row || typeof row.id !== "string" || row.channel !== params.channel || !(row.schedule && ("at" in row.schedule ? typeof row.schedule.at === "string" : ("every" in row.schedule || "cron" in row.schedule)))) return;
|
|
189
|
+
} else if (fieldsByType[type]!.some(key => typeof (fields as Record<string, unknown>)[key] !== "string")) return;
|
|
190
|
+
const data = fields as Record<string, unknown>;
|
|
191
|
+
if (type === "routine_disposition" && (
|
|
192
|
+
!Number.isSafeInteger(data.count) || Number(data.count) <= 0 ||
|
|
193
|
+
!["missed", "catch_up_limit", "overlap", "expired", "coalesced"].includes(String(data.reason))
|
|
194
|
+
)) return;
|
|
195
|
+
if (type === "routine_migration_blocked" && !["invalid_schedule", "proof_budget"].includes(String(data.cause))) return;
|
|
196
|
+
return { channel: params.channel, event: { ...fields, kind: type } as WireReminderEvent };
|
|
197
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ReminderChange } from "../../native-harness/src/client.ts";
|
|
2
|
+
import type { reminderRequest } from "./wire.ts";
|
|
3
|
+
|
|
4
|
+
type AssignableToWire<T extends ReminderChange> = T;
|
|
5
|
+
type Encoded = AssignableToWire<ReturnType<typeof reminderRequest>>;
|
|
6
|
+
|
|
7
|
+
type Create = Extract<Encoded, { op: "create" }>;
|
|
8
|
+
type MissingAcceptance = Omit<Create, "payload"> & {
|
|
9
|
+
payload: Omit<Create["payload"], "acceptedAt">;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// @ts-expect-error The harness requires the original acceptance instant on create.
|
|
13
|
+
type MustRejectMissingAcceptance = AssignableToWire<MissingAcceptance>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ItemStatus } from "../native-harness/src/client.ts";
|
|
2
|
+
import { codeOf } from "./errors.ts";
|
|
3
|
+
import type { NativeHostRecords } from "./records.ts";
|
|
4
|
+
|
|
5
|
+
export type WithdrawalObservation = { outcome: "withdrawn" } | { outcome: "taken"; turnId: string | undefined };
|
|
6
|
+
|
|
7
|
+
/** An in-flight push can still commit after withdraw returns not_found. */
|
|
8
|
+
export class SubmissionWithdrawal {
|
|
9
|
+
readonly #running = new Map<string, Promise<WithdrawalObservation>>();
|
|
10
|
+
|
|
11
|
+
constructor(
|
|
12
|
+
private readonly records: NativeHostRecords,
|
|
13
|
+
private readonly timeoutMs: number,
|
|
14
|
+
private readonly request: (channel: string, id: string) => Promise<WithdrawalObservation>,
|
|
15
|
+
private readonly lookup: (channel: string, id: string) => Promise<ItemStatus | undefined>,
|
|
16
|
+
private readonly confirmed: (channel: string, id: string) => void,
|
|
17
|
+
) {}
|
|
18
|
+
|
|
19
|
+
async withdraw(channel: string, id: string, acceptance?: Promise<ItemStatus>): Promise<WithdrawalObservation | undefined> {
|
|
20
|
+
const submission = this.records.submission(id);
|
|
21
|
+
if (!submission || submission.channel !== channel) return;
|
|
22
|
+
if (submission.state === "saved") {
|
|
23
|
+
this.confirmed(channel, id);
|
|
24
|
+
return { outcome: "withdrawn" };
|
|
25
|
+
}
|
|
26
|
+
if (!this.records.markWithdrawing) throw new Error("the native submission store cannot record a withdrawal intent");
|
|
27
|
+
this.records.markWithdrawing(id);
|
|
28
|
+
return this.retry(channel, id, acceptance);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
retry(channel: string, id: string, acceptance?: Promise<ItemStatus>, reopened = false): Promise<WithdrawalObservation> {
|
|
32
|
+
const pending = this.#running.get(id);
|
|
33
|
+
if (pending) return reopened ? pending.catch(() => this.retry(channel, id, acceptance)) : pending;
|
|
34
|
+
const request = this.#attempt(channel, id, acceptance).finally(() => this.#running.delete(id));
|
|
35
|
+
this.#running.set(id, request);
|
|
36
|
+
return request;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async #attempt(channel: string, id: string, acceptance?: Promise<ItemStatus>): Promise<WithdrawalObservation> {
|
|
40
|
+
try {
|
|
41
|
+
return await this.request(channel, id);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (codeOf(error) !== "not_found") throw error;
|
|
44
|
+
const item = await this.#findItem(channel, id, acceptance);
|
|
45
|
+
if (!item) throw error;
|
|
46
|
+
if (item.milestone === "withdrawn") {
|
|
47
|
+
this.confirmed(channel, id);
|
|
48
|
+
return { outcome: "withdrawn" };
|
|
49
|
+
}
|
|
50
|
+
return await this.request(channel, id);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async #findItem(channel: string, id: string, acceptance?: Promise<ItemStatus>): Promise<ItemStatus | undefined> {
|
|
55
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
56
|
+
try {
|
|
57
|
+
const accepted = acceptance && await Promise.race([acceptance, new Promise<undefined>(resolve => {
|
|
58
|
+
timer = setTimeout(() => resolve(undefined), this.timeoutMs);
|
|
59
|
+
})]);
|
|
60
|
+
return accepted ?? await this.lookup(channel, id);
|
|
61
|
+
} finally {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { aggregateUsage, type HarnessClient } from "../native-harness/src/client.ts";
|
|
2
|
+
|
|
3
|
+
export async function summarizeModelUsage(client: HarnessClient, channel?: string) {
|
|
4
|
+
const attempts: Parameters<typeof aggregateUsage>[0][number][] = [];
|
|
5
|
+
for (let after: string | undefined; ;) {
|
|
6
|
+
const page = await client.modelCalls({ after });
|
|
7
|
+
for (const call of page.calls) if (channel === undefined || call.channel === channel) attempts.push(...call.attempts);
|
|
8
|
+
if (!page.next) break;
|
|
9
|
+
after = page.next;
|
|
10
|
+
}
|
|
11
|
+
const totals = aggregateUsage(attempts);
|
|
12
|
+
const missing = Object.fromEntries((["inputTokens", "outputTokens", "totalTokens"] as const)
|
|
13
|
+
.map(field => [field, attempts.filter(attempt => attempt.usage?.[field] === undefined).length]));
|
|
14
|
+
return { totals, missing, attempts: attempts.length, partial: Object.values(missing).some(count => count > 0) };
|
|
15
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { WorkerDelivery, WorkerDeliveryRepository, WorkerDeliveryState } from "../persistence/worker-delivery-contract.ts";
|
|
2
|
+
import { codeOf } from "./errors.ts";
|
|
3
|
+
|
|
4
|
+
export class NativeWorkerDelivery {
|
|
5
|
+
private running?: Promise<void>;
|
|
6
|
+
private requested = false;
|
|
7
|
+
|
|
8
|
+
constructor(
|
|
9
|
+
private readonly repository: WorkerDeliveryRepository,
|
|
10
|
+
private readonly available: () => boolean,
|
|
11
|
+
private readonly send: (delivery: WorkerDelivery) => Promise<boolean>,
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
flush(): Promise<void> {
|
|
15
|
+
this.requested = true;
|
|
16
|
+
return this.running ??= this.drain().finally(() => { this.running = undefined; });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async hasWork(): Promise<boolean> {
|
|
20
|
+
for (const state of ["pending", "unstaged"] as const) {
|
|
21
|
+
if ((await this.repository.discoverAssignments({ destinationKind: "native", state, limit: 1 })).assignments.length) return true;
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
private async drain(): Promise<void> {
|
|
27
|
+
while (this.requested && this.available()) {
|
|
28
|
+
this.requested = false;
|
|
29
|
+
for (const state of ["unstaged", "pending"] as const) {
|
|
30
|
+
let after: string | undefined;
|
|
31
|
+
do {
|
|
32
|
+
if (!this.available()) return;
|
|
33
|
+
const page = await this.repository.discoverAssignments({ destinationKind: "native", state, after });
|
|
34
|
+
for (const assignment of page.assignments) {
|
|
35
|
+
if (!this.available()) return;
|
|
36
|
+
if (assignment.state === "unstaged") await this.repository.stage(assignment.binding.assignmentId);
|
|
37
|
+
else await this.deliver(assignment.staged.delivery);
|
|
38
|
+
}
|
|
39
|
+
after = page.next;
|
|
40
|
+
} while (after !== undefined);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private async deliver(delivery: WorkerDelivery): Promise<void> {
|
|
46
|
+
if (delivery.destination.kind !== "native") return;
|
|
47
|
+
let state: Exclude<WorkerDeliveryState, "pending">;
|
|
48
|
+
try {
|
|
49
|
+
if (!await this.send(delivery)) return;
|
|
50
|
+
state = "delivered";
|
|
51
|
+
} catch (error) {
|
|
52
|
+
switch (codeOf(error)) {
|
|
53
|
+
case "invalid_policy": state = "blocked_policy"; break;
|
|
54
|
+
case "not_found":
|
|
55
|
+
case "channel_retired": state = "failed_destination"; break;
|
|
56
|
+
default: return;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
await this.repository.transitionDelivery(delivery.id, { from: "pending", to: state });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Another harness for the world
|