@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,92 @@
|
|
|
1
|
+
import type { Message, ToolDefinition } from "../../contracts/loop.ts";
|
|
2
|
+
import type { ContextCapture } from "../../contracts/context.ts";
|
|
3
|
+
import type { InspectionStorageReads } from "../../contracts/inspection.ts";
|
|
4
|
+
import type { StorageResult } from "../../contracts/storage.ts";
|
|
5
|
+
import { composeSystemPrompt } from "../../capabilities/context/load-instructions.ts";
|
|
6
|
+
import { buildSharedContext } from "../../capabilities/context/build.ts";
|
|
7
|
+
|
|
8
|
+
interface InspectedInference {
|
|
9
|
+
number: number;
|
|
10
|
+
turnId?: number;
|
|
11
|
+
at: string;
|
|
12
|
+
body: unknown;
|
|
13
|
+
context?: Pick<ContextCapture, "estimatedInputBytes" | "omitted" | "records"> & { revision: number; offeredTools: string[]; modelCallId?: string };
|
|
14
|
+
response?: Extract<Message, { role: "assistant" }> | { omitted: true };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const CAPTURE_LIMIT = 8;
|
|
18
|
+
const CAPTURE_BYTES = 128 * 1024;
|
|
19
|
+
function read<T>(result: StorageResult<T>) {
|
|
20
|
+
if (!result.ok) throw new Error(result.error.message);
|
|
21
|
+
return { ...result.value, revision: result.revision };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Capture state is process-local. A notification marks the requested view
|
|
25
|
+
* dirty. Only HTTP reads request data from storage. */
|
|
26
|
+
export function createInspection(systemPrompt: string, tools: readonly ToolDefinition[],
|
|
27
|
+
reads: InspectionStorageReads, storage: string) {
|
|
28
|
+
const instructions = composeSystemPrompt(systemPrompt);
|
|
29
|
+
const captures = new Map<string, { turnId: number; metadata: NonNullable<InspectedInference["context"]> }>();
|
|
30
|
+
const channels = new Map<string, InspectedInference[]>();
|
|
31
|
+
const listeners = new Set<() => void>();
|
|
32
|
+
let stopped = false;
|
|
33
|
+
const invalidate = () => { for (const listener of listeners) listener(); };
|
|
34
|
+
return {
|
|
35
|
+
invalidate,
|
|
36
|
+
stopped() { stopped = true; invalidate(); },
|
|
37
|
+
status() {
|
|
38
|
+
const { revision, session, channels: status } = read(reads.readInspectionStatus());
|
|
39
|
+
const execution = stopped ? "stopped" : session.lifecycle !== "running" ? session.lifecycle
|
|
40
|
+
: status.some(channel => channel.turn === "running" || (channel.lifecycle === "open" && channel.pending > 0)) ? "working" : "idle";
|
|
41
|
+
return { session: { sessionId: session.sessionId, lifecycle: session.lifecycle, execution, revision, storage },
|
|
42
|
+
channels: status.map(channel => ({ ...channel, running: channel.turn === "running",
|
|
43
|
+
...(channel.unresolved ? { error: `Turn ${channel.unresolved.turnId} ${channel.unresolved.status}: ${channel.unresolved.reason}` } : {}) })) };
|
|
44
|
+
},
|
|
45
|
+
liveContext() {
|
|
46
|
+
const { entries, unfinished, revision } = read(reads.readInspectionPage());
|
|
47
|
+
const selected = entries.filter(entry => "message" in entry).reverse();
|
|
48
|
+
return { revision, entries: selected, tools, base: buildSharedContext(selected, instructions, unfinished) };
|
|
49
|
+
},
|
|
50
|
+
timeline(before?: number) {
|
|
51
|
+
const { entries, next, revision } = read(reads.readInspectionPage(before));
|
|
52
|
+
return { entries, next, revision };
|
|
53
|
+
},
|
|
54
|
+
channel: (id: string) => ({ requests: structuredClone(channels.get(id) ?? []) }),
|
|
55
|
+
modelCalls(id: string) {
|
|
56
|
+
const result = reads.readInspectionCalls(id);
|
|
57
|
+
if (!result.ok) throw new Error(result.error.message);
|
|
58
|
+
return { modelCalls: result.value };
|
|
59
|
+
},
|
|
60
|
+
subscribe(listener: () => void) {
|
|
61
|
+
listeners.add(listener);
|
|
62
|
+
return () => { listeners.delete(listener); };
|
|
63
|
+
},
|
|
64
|
+
capture(value: ContextCapture) {
|
|
65
|
+
const { channelId, turnId, timelineRevision } = value.context;
|
|
66
|
+
captures.set(channelId, { turnId, metadata: { revision: timelineRevision, estimatedInputBytes: value.estimatedInputBytes,
|
|
67
|
+
omitted: value.omitted, records: value.records, offeredTools: value.context.tools.map(tool => tool.name) } });
|
|
68
|
+
},
|
|
69
|
+
modelCall(channelId: string, turnId: number, callId: string) {
|
|
70
|
+
const capture = captures.get(channelId);
|
|
71
|
+
if (capture?.turnId === turnId) capture.metadata.modelCallId = callId;
|
|
72
|
+
},
|
|
73
|
+
request(id: string, body: string, turnId?: number) {
|
|
74
|
+
let requests = channels.get(id);
|
|
75
|
+
if (!requests) { requests = []; channels.set(id, requests); }
|
|
76
|
+
const capture = captures.get(id);
|
|
77
|
+
requests.push({ ...(capture && capture.turnId === turnId ? { context: capture.metadata } : {}),
|
|
78
|
+
number: (requests.at(-1)?.number ?? 0) + 1, turnId, at: new Date().toISOString(),
|
|
79
|
+
body: Buffer.byteLength(body) <= CAPTURE_BYTES ? JSON.parse(body) : { omitted: true } });
|
|
80
|
+
if (requests.length > CAPTURE_LIMIT) requests.shift();
|
|
81
|
+
invalidate();
|
|
82
|
+
},
|
|
83
|
+
response(id: string, message: Extract<Message, { role: "assistant" }>) {
|
|
84
|
+
const request = channels.get(id)?.at(-1);
|
|
85
|
+
if (!request) return;
|
|
86
|
+
request.response = Buffer.byteLength(JSON.stringify(message)) <= CAPTURE_BYTES ? structuredClone(message) : { omitted: true };
|
|
87
|
+
invalidate();
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type Inspection = ReturnType<typeof createInspection>;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { ChannelChangeResult, PendingChannelChange } from "../../contracts/protocol.ts";
|
|
2
|
+
import type { ChannelStatus, ControlResult, PersistentSession } from "../../contracts/session.ts";
|
|
3
|
+
|
|
4
|
+
/** A batch the open must refuse (`invalid_params`, `invalid_policy`) or a
|
|
5
|
+
* transition that failed for a reason the contract gives no outcome for. */
|
|
6
|
+
export class ChannelChangeFault extends Error {
|
|
7
|
+
constructor(readonly code: string, message: string) { super(message); }
|
|
8
|
+
}
|
|
9
|
+
const invalid = (message: string): never => { throw new ChannelChangeFault("invalid_params", message); };
|
|
10
|
+
const FIELDS = ["channel", "changeId", "displayName", "policy", "lifecycle"];
|
|
11
|
+
const NAME_MAX = 200;
|
|
12
|
+
|
|
13
|
+
/** Structural validation of the whole batch (decision 0020). Runs before the
|
|
14
|
+
* session is opened, so a malformed batch touches nothing. Policy names need
|
|
15
|
+
* the open's configuration and are checked by `checkPolicies`. */
|
|
16
|
+
export function parseChannelChanges(raw: unknown): PendingChannelChange[] {
|
|
17
|
+
if (!Array.isArray(raw)) return invalid("channelChanges must be an array");
|
|
18
|
+
const seen = new Set<string>();
|
|
19
|
+
return raw.map((value, index): PendingChannelChange => {
|
|
20
|
+
const at = `channelChanges[${index}]`;
|
|
21
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) invalid(`${at} must be an object`);
|
|
22
|
+
const entry = value as Record<string, unknown>;
|
|
23
|
+
for (const key of Object.keys(entry)) if (!FIELDS.includes(key)) invalid(`${at}: unsupported field ${key}`);
|
|
24
|
+
const word = (name: string) => {
|
|
25
|
+
const field = entry[name];
|
|
26
|
+
if (typeof field !== "string" || !field.trim()) invalid(`${at}.${name} must be a nonempty string`);
|
|
27
|
+
return field as string;
|
|
28
|
+
};
|
|
29
|
+
const channel = word("channel"), changeId = word("changeId");
|
|
30
|
+
if (seen.has(channel)) invalid(`${at}: channel ${channel} appears twice`);
|
|
31
|
+
seen.add(channel);
|
|
32
|
+
const { displayName, policy, lifecycle } = entry;
|
|
33
|
+
// The same bound storage enforces, checked here so no entry can fail
|
|
34
|
+
// validation after an earlier one was applied.
|
|
35
|
+
if (displayName !== undefined && displayName !== null && (typeof displayName !== "string" || !displayName.trim() || displayName.trim().length > NAME_MAX))
|
|
36
|
+
invalid(`${at}.displayName must be null or 1 to ${NAME_MAX} characters`);
|
|
37
|
+
if (policy !== undefined && policy !== null && (typeof policy !== "string" || !policy.trim())) invalid(`${at}.policy must be null or a policy name`);
|
|
38
|
+
if (lifecycle !== undefined && lifecycle !== "open" && lifecycle !== "suspended" && lifecycle !== "retired") invalid(`${at}.lifecycle must be open, suspended or retired`);
|
|
39
|
+
return { channel, changeId,
|
|
40
|
+
...(displayName === undefined ? {} : { displayName: displayName as string | null }),
|
|
41
|
+
...(policy === undefined ? {} : { policy: policy as string | null }),
|
|
42
|
+
...(lifecycle === undefined ? {} : { lifecycle: lifecycle as PendingChannelChange["lifecycle"] }) };
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Unknown policy names reject the whole batch. `policies` is the set the
|
|
47
|
+
* session's configuration defines. */
|
|
48
|
+
export function checkPolicies(batch: readonly PendingChannelChange[], policies: readonly string[]) {
|
|
49
|
+
for (const change of batch)
|
|
50
|
+
if (typeof change.policy === "string" && !policies.includes(change.policy)) throw new ChannelChangeFault("invalid_policy", `Unknown policy: ${change.policy}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Two batches are the same request when they ask for the same thing in the same order. */
|
|
54
|
+
export const sameBatch = (left: readonly PendingChannelChange[], right: readonly PendingChannelChange[]) =>
|
|
55
|
+
JSON.stringify(left.map(canonical)) === JSON.stringify(right.map(canonical));
|
|
56
|
+
const canonical = (change: PendingChannelChange) => [change.channel, change.changeId, change.displayName ?? (change.displayName === null ? null : "\0"),
|
|
57
|
+
change.policy ?? (change.policy === null ? null : "\0"), change.lifecycle ?? "\0"];
|
|
58
|
+
|
|
59
|
+
type Channels = PersistentSession["channels"];
|
|
60
|
+
function done<T>(result: ControlResult<T>): T {
|
|
61
|
+
if (!result.ok) throw new ChannelChangeFault(result.error.code, result.error.message);
|
|
62
|
+
return result.value;
|
|
63
|
+
}
|
|
64
|
+
const applied = (change: PendingChannelChange): ChannelChangeResult => ({ channel: change.channel, changeId: change.changeId, outcome: "applied" });
|
|
65
|
+
const blocked = (change: PendingChannelChange, reason: NonNullable<ChannelChangeResult["reason"]>): ChannelChangeResult =>
|
|
66
|
+
({ channel: change.channel, changeId: change.changeId, outcome: "blocked", reason });
|
|
67
|
+
|
|
68
|
+
/** Apply a validated batch to a session that has NOT been started, reusing the
|
|
69
|
+
* channel controls of decision 0014. Two phases:
|
|
70
|
+
*
|
|
71
|
+
* 1. (awaited) everything except resumes. Suspension returns a promise, but
|
|
72
|
+
* with no running turn it commits at once; nothing else can run meanwhile
|
|
73
|
+
* because the session is not started and no resume has happened yet.
|
|
74
|
+
* 2. (the returned function, synchronous) resumes. The caller holds their
|
|
75
|
+
* committed notifications behind the open response.
|
|
76
|
+
*
|
|
77
|
+
* For each entry the lifecycle step is decided before the name and policy are
|
|
78
|
+
* written, so a blocked entry writes neither. */
|
|
79
|
+
export async function applyChannelChanges(session: Pick<PersistentSession, "channels" | "status" | "operatorReads">, batch: readonly PendingChannelChange[]): Promise<() => ChannelChangeResult[]> {
|
|
80
|
+
const channels: Channels = session.channels;
|
|
81
|
+
const results = new Map<string, ChannelChangeResult>();
|
|
82
|
+
const find = (channel: string) => {
|
|
83
|
+
if (!session.operatorReads) {
|
|
84
|
+
const state = session.status().channels.find(value => value.channelId === channel);
|
|
85
|
+
return state && { ...state, pendingCount: state.pendingItemIds.length };
|
|
86
|
+
}
|
|
87
|
+
const result = session.operatorReads.readChannel(channel);
|
|
88
|
+
if (!result.ok && result.error.code === "not_found") return undefined;
|
|
89
|
+
const state = done(result);
|
|
90
|
+
return { ...state.channel, pendingCount: state.pendingCount, activeTurn: state.activeTurn };
|
|
91
|
+
};
|
|
92
|
+
/** Create the channel with its settings, or edit the fields the entry names. */
|
|
93
|
+
const write = (change: PendingChannelChange, existing: ReturnType<typeof find>) => {
|
|
94
|
+
if (!existing) {
|
|
95
|
+
done(channels.create({ channelId: change.channel, ...(typeof change.displayName === "string" ? { displayName: change.displayName } : {}),
|
|
96
|
+
...(typeof change.policy === "string" ? { policy: change.policy } : {}) }));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (change.displayName === undefined && change.policy === undefined) return;
|
|
100
|
+
// The control replaces the name, so an entry that omits it restates the current one.
|
|
101
|
+
done(channels.edit(change.channel, change.displayName === undefined ? existing.displayName ?? null : change.displayName, change.policy));
|
|
102
|
+
};
|
|
103
|
+
const suspend = async (channel: string) => { done(await channels.suspend(channel)); };
|
|
104
|
+
|
|
105
|
+
for (const change of batch) {
|
|
106
|
+
if (change.lifecycle === "open") continue;
|
|
107
|
+
const existing = find(change.channel);
|
|
108
|
+
if (existing?.lifecycle === "retired") {
|
|
109
|
+
results.set(change.channel, change.lifecycle === "retired" ? applied(change) : blocked(change, "channel_retired"));
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (change.lifecycle === "retired") {
|
|
113
|
+
// Busy is decided before anything is written: pending input or a
|
|
114
|
+
// checkpoint must survive, and must not run, so the channel is suspended
|
|
115
|
+
// instead and the host keeps its deletion pending.
|
|
116
|
+
if (existing && (existing.pendingCount || existing.activeTurn)) {
|
|
117
|
+
await suspend(change.channel);
|
|
118
|
+
results.set(change.channel, blocked(change, "channel_busy"));
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
write(change, existing);
|
|
122
|
+
const retired = channels.delete(change.channel);
|
|
123
|
+
if (!retired.ok && retired.error.code === "channel_busy") {
|
|
124
|
+
await suspend(change.channel);
|
|
125
|
+
results.set(change.channel, blocked(change, "channel_busy"));
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
done(retired);
|
|
129
|
+
} else {
|
|
130
|
+
write(change, existing);
|
|
131
|
+
if (change.lifecycle === "suspended") await suspend(change.channel);
|
|
132
|
+
}
|
|
133
|
+
results.set(change.channel, applied(change));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return () => {
|
|
137
|
+
for (const change of batch) {
|
|
138
|
+
if (change.lifecycle !== "open") continue;
|
|
139
|
+
const existing = find(change.channel);
|
|
140
|
+
if (existing?.lifecycle === "retired") { results.set(change.channel, blocked(change, "channel_retired")); continue; }
|
|
141
|
+
if (existing) {
|
|
142
|
+
const resumed = channels.resume(change.channel);
|
|
143
|
+
// The checkpoint, or a stored policy reference, cannot run under this
|
|
144
|
+
// configuration: storage wrote nothing and the channel stays suspended.
|
|
145
|
+
if (!resumed.ok && resumed.error.code === "incompatible") { results.set(change.channel, blocked(change, "incompatible")); continue; }
|
|
146
|
+
done(resumed);
|
|
147
|
+
}
|
|
148
|
+
write(change, existing);
|
|
149
|
+
results.set(change.channel, applied(change));
|
|
150
|
+
}
|
|
151
|
+
return batch.map(change => results.get(change.channel)!);
|
|
152
|
+
};
|
|
153
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const MAX_FRAME_BYTES = 1024 * 1024;
|
|
2
|
+
|
|
3
|
+
/** Buffer bytes, not strings: a UTF-8 character can span input chunks. */
|
|
4
|
+
export class LineDecoder {
|
|
5
|
+
private parts: Uint8Array[] = [];
|
|
6
|
+
private size = 0;
|
|
7
|
+
constructor(private readonly limit = MAX_FRAME_BYTES) {}
|
|
8
|
+
push(chunk: Uint8Array): string[] {
|
|
9
|
+
const lines: string[] = [];
|
|
10
|
+
let start = 0;
|
|
11
|
+
for (let i = 0; i <= chunk.length; i++) {
|
|
12
|
+
if (i !== chunk.length && chunk[i] !== 10) continue;
|
|
13
|
+
const part = chunk.slice(start, i);
|
|
14
|
+
this.size += part.length;
|
|
15
|
+
if (this.size > this.limit) throw new Error("Protocol frame exceeds size limit");
|
|
16
|
+
if (part.length) this.parts.push(part);
|
|
17
|
+
if (i < chunk.length) {
|
|
18
|
+
const bytes = new Uint8Array(this.size);
|
|
19
|
+
let offset = 0;
|
|
20
|
+
for (const item of this.parts) { bytes.set(item, offset); offset += item.length; }
|
|
21
|
+
const line = new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/\r$/, "");
|
|
22
|
+
this.parts = []; this.size = 0;
|
|
23
|
+
if (line.trim()) lines.push(line);
|
|
24
|
+
}
|
|
25
|
+
start = i + 1;
|
|
26
|
+
}
|
|
27
|
+
return lines;
|
|
28
|
+
}
|
|
29
|
+
finish() { if (this.size) throw new Error("Incomplete protocol frame at EOF"); }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One ordered writer for responses and notifications, with bounded buffering. */
|
|
33
|
+
export class LineWriter {
|
|
34
|
+
private tail: Promise<void> = Promise.resolve();
|
|
35
|
+
private queued = 0;
|
|
36
|
+
constructor(private readonly write: (bytes: Uint8Array) => Promise<void>) {}
|
|
37
|
+
send(message: unknown): Promise<void> {
|
|
38
|
+
const bytes = new TextEncoder().encode(`${JSON.stringify(message)}\n`);
|
|
39
|
+
if (bytes.length - 1 > MAX_FRAME_BYTES || this.queued + bytes.length > 4 * MAX_FRAME_BYTES) throw new Error("Protocol output exceeds buffer limit");
|
|
40
|
+
this.queued += bytes.length;
|
|
41
|
+
const next = this.tail.then(() => this.write(bytes)).finally(() => { this.queued -= bytes.length; });
|
|
42
|
+
this.tail = next;
|
|
43
|
+
void next.catch(() => {});
|
|
44
|
+
return next;
|
|
45
|
+
}
|
|
46
|
+
flush() { return this.tail; }
|
|
47
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { RpcCallbackCancel, RpcCallbackRequest, RpcCallbackResponse } from "../../contracts/protocol.ts";
|
|
2
|
+
import type { PersistentSession } from "../../contracts/session.ts";
|
|
3
|
+
import type { FunctionExecutor, FunctionResult, ResultPage } from "../../contracts/tools.ts";
|
|
4
|
+
import { CallbackFailure, CallbackLost } from "../../capabilities/tools/runtime/functions.ts";
|
|
5
|
+
import { MAX_FRAME_BYTES } from "./framing.ts";
|
|
6
|
+
|
|
7
|
+
/** A refused tool request, with a stable protocol code. */
|
|
8
|
+
export class ToolFault extends Error {
|
|
9
|
+
constructor(readonly code: string, message: string) { super(message); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Requests from the harness to the host over one connection (decision 0021).
|
|
13
|
+
* Each wait is keyed by its own request ID, so answers to concurrent callbacks
|
|
14
|
+
* cannot be confused. A wait is closed by its answer, by cancellation or by
|
|
15
|
+
* the connection going away; an answer for a closed wait is ignored. */
|
|
16
|
+
export function createCallbackBridge(emit: (message: RpcCallbackRequest | RpcCallbackCancel) => void) {
|
|
17
|
+
let nextId = 0, connected = true;
|
|
18
|
+
const waiting = new Map<number, { resolve(value: unknown): void; reject(error: unknown): void }>();
|
|
19
|
+
function ask<T>(method: RpcCallbackRequest["method"], params: any, signal: AbortSignal, cancel?: () => void): Promise<T> {
|
|
20
|
+
if (!connected) return Promise.reject(new CallbackLost("The host connection is closed"));
|
|
21
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
22
|
+
const id = ++nextId, message = { jsonrpc: "2.0" as const, id, method, params } as RpcCallbackRequest;
|
|
23
|
+
// Nothing was sent, so this is a known failure and not an uncertain call.
|
|
24
|
+
if (new TextEncoder().encode(JSON.stringify(message)).length > MAX_FRAME_BYTES - 1024)
|
|
25
|
+
return Promise.reject(new CallbackFailure("request_too_large", "The call's arguments do not fit one protocol frame"));
|
|
26
|
+
return new Promise<T>((resolve, reject) => {
|
|
27
|
+
const close = () => { waiting.delete(id); signal.removeEventListener("abort", aborted); };
|
|
28
|
+
const aborted = () => { close(); try { cancel?.(); } catch { /* The connection may be gone. */ } reject(signal.reason); };
|
|
29
|
+
waiting.set(id, { resolve: value => { close(); resolve(value as T); }, reject: error => { close(); reject(error); } });
|
|
30
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
31
|
+
try { emit(message); } catch (error) { close(); reject(new CallbackLost(String(error))); }
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
const executor: FunctionExecutor = {
|
|
35
|
+
call: (request, signal) => ask<FunctionResult>("functions/call", request, signal, () => emit({ jsonrpc: "2.0", method: "functions/cancel",
|
|
36
|
+
params: { invocationId: request.invocationId, reason: signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? "cancelled") } })),
|
|
37
|
+
read: (request, signal) => ask<ResultPage>("results/read", request, signal),
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
executor,
|
|
41
|
+
/** The host's answer. Unknown, repeated and late IDs are ignored. */
|
|
42
|
+
respond(response: RpcCallbackResponse) {
|
|
43
|
+
const wait = response && Number.isSafeInteger(response.id) ? waiting.get(response.id) : undefined;
|
|
44
|
+
if (!wait) return;
|
|
45
|
+
if ("error" in response && response.error) wait.reject(new CallbackFailure(
|
|
46
|
+
typeof response.error.data?.code === "string" && response.error.data.code ? response.error.data.code : "handler_failed", String(response.error.message ?? "The handler failed")));
|
|
47
|
+
else wait.resolve((response as { result: unknown }).result);
|
|
48
|
+
},
|
|
49
|
+
/** The connection is gone: every open wait ends without an outcome. */
|
|
50
|
+
disconnect() {
|
|
51
|
+
connected = false;
|
|
52
|
+
for (const wait of [...waiting.values()]) wait.reject(new CallbackLost("The host connection closed before the call was answered"));
|
|
53
|
+
},
|
|
54
|
+
outstanding: () => waiting.size,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const TOOL_METHODS = ["session/tools", "tool/revoke", "tool/restore", "tool/enable", "tool/remove", "session/tool-invocation", "session/tool-invocations"];
|
|
59
|
+
export const toolMethods = (): string[] => [...TOOL_METHODS];
|
|
60
|
+
export const isToolMethod = (method: string) => TOOL_METHODS.includes(method);
|
|
61
|
+
|
|
62
|
+
/** The catalog and invocation methods. A session without a catalog has no
|
|
63
|
+
* tools to list or change and no consumer invocations beyond its records. */
|
|
64
|
+
export function toolRequest(session: PersistentSession, method: string, p: Record<string, any>): unknown {
|
|
65
|
+
const only = (names: string[]) => { for (const key of Object.keys(p)) if (!names.includes(key)) throw new ToolFault("invalid_params", `Unsupported field: ${key}`); };
|
|
66
|
+
const word = (value: unknown) => { if (typeof value !== "string" || !value.trim()) throw new ToolFault("invalid_params", "Expected a nonempty string"); return value; };
|
|
67
|
+
const tools = session.tools;
|
|
68
|
+
if (method === "session/tools") { only([]); return { tools: tools?.list() ?? [] }; }
|
|
69
|
+
if (!tools) throw new ToolFault("not_found", "This session has no tool catalog");
|
|
70
|
+
if (method === "session/tool-invocation") {
|
|
71
|
+
only(["invocationId"]);
|
|
72
|
+
const invocation = tools.invocation(word(p.invocationId));
|
|
73
|
+
if (!invocation) throw new ToolFault("not_found", "Unknown invocation");
|
|
74
|
+
return { invocation };
|
|
75
|
+
}
|
|
76
|
+
if (method === "session/tool-invocations") {
|
|
77
|
+
only(["turn"]);
|
|
78
|
+
const raw = word(p.turn), turn = Number(raw);
|
|
79
|
+
if (!Number.isSafeInteger(turn) || turn < 1 || String(turn) !== raw) throw new ToolFault("invalid_params", "Expected a turn ID");
|
|
80
|
+
return { invocations: tools.invocations(turn) };
|
|
81
|
+
}
|
|
82
|
+
only(["name"]);
|
|
83
|
+
const name = word(p.name);
|
|
84
|
+
const result = method === "tool/revoke" ? tools.revoke(name) : method === "tool/restore" ? tools.restore(name) : method === "tool/enable" ? tools.enable(name) : tools.remove(name);
|
|
85
|
+
if (!result.ok) throw new ToolFault(result.error.code, result.error.message);
|
|
86
|
+
return { tool: result.value };
|
|
87
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { ClientTransport, ProtocolEndpoint, RpcCallbackCancel, RpcCallbackRequest, RpcNotification, RpcResponse, RpcSessionNotification } from "../../contracts/protocol.ts";
|
|
2
|
+
type Callback = RpcCallbackRequest | RpcCallbackCancel;
|
|
3
|
+
const isCallback = (message: { method?: string }): message is Callback => message.method === "functions/call" || message.method === "results/read" || message.method === "functions/cancel";
|
|
4
|
+
import { LiveQueue } from "./live-queue.ts";
|
|
5
|
+
|
|
6
|
+
// Match the data boundary stdio imposes: no shared references or functions.
|
|
7
|
+
const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
|
8
|
+
export function createInProcessTransport(endpoint: ProtocolEndpoint): ClientTransport {
|
|
9
|
+
let closed = false;
|
|
10
|
+
const closeListeners = new Set<(error?: Error) => void>();
|
|
11
|
+
const listeners = new Set<(message: RpcResponse | RpcNotification) => void>();
|
|
12
|
+
const sessionListeners = new Set<(message: RpcSessionNotification) => void>();
|
|
13
|
+
const callbackListeners = new Set<(message: Callback) => void>();
|
|
14
|
+
let unsubscribeChannel = () => {}, unsubscribeSession: (() => void) | undefined, unsubscribeCallbacks: (() => void) | undefined;
|
|
15
|
+
function close(error?: Error) {
|
|
16
|
+
if (closed) return;
|
|
17
|
+
closed = true; endpoint.disconnect?.(); unsubscribeChannel(); unsubscribeSession?.(); unsubscribeCallbacks?.();
|
|
18
|
+
listeners.clear(); sessionListeners.clear(); callbackListeners.clear();
|
|
19
|
+
for (const listener of closeListeners) { try { listener(error); } catch { /* Isolate observers. */ } }
|
|
20
|
+
closeListeners.clear();
|
|
21
|
+
}
|
|
22
|
+
function fail(cause: unknown) {
|
|
23
|
+
if (closed) return;
|
|
24
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
25
|
+
close(error);
|
|
26
|
+
// Like stdio's failed writer, a failed connection stops its session; the
|
|
27
|
+
// request is asynchronous but the producer never waits on the consumer.
|
|
28
|
+
void endpoint.request({ jsonrpc: "2.0", id: -1, method: "session/stop", params: {} }).catch(() => {});
|
|
29
|
+
}
|
|
30
|
+
const queue = new LiveQueue(value => new Promise<void>(resolve => queueMicrotask(() => {
|
|
31
|
+
if (!closed) {
|
|
32
|
+
const message = value as RpcResponse | RpcNotification | RpcSessionNotification | Callback;
|
|
33
|
+
if ("method" in message && isCallback(message)) {
|
|
34
|
+
for (const listener of callbackListeners) { try { listener(copy(message)); } catch { /* Isolate observers. */ } }
|
|
35
|
+
} else if ("method" in message && message.method === "session/event") {
|
|
36
|
+
for (const listener of sessionListeners) { try { listener(copy(message)); } catch { /* Isolate observers. */ } }
|
|
37
|
+
} else for (const listener of listeners) { try { listener(copy(message as RpcResponse | RpcNotification)); } catch { /* Isolate observers. */ } }
|
|
38
|
+
}
|
|
39
|
+
resolve();
|
|
40
|
+
})), fail);
|
|
41
|
+
function enqueue(message: RpcResponse | RpcNotification | RpcSessionNotification | Callback) {
|
|
42
|
+
if (closed) return;
|
|
43
|
+
try { queue.send(message); } catch (error) { fail(error); }
|
|
44
|
+
}
|
|
45
|
+
// Notifications and responses use the same bounded queue and preserve order.
|
|
46
|
+
unsubscribeChannel = endpoint.subscribe(enqueue);
|
|
47
|
+
unsubscribeSession = endpoint.subscribeSession?.(enqueue);
|
|
48
|
+
// Callback requests travel in the same queue, so they keep their place among events.
|
|
49
|
+
unsubscribeCallbacks = endpoint.subscribeCallbacks?.(enqueue);
|
|
50
|
+
return {
|
|
51
|
+
send(request) {
|
|
52
|
+
if (closed) throw new Error("Transport closed");
|
|
53
|
+
const captured = copy(request);
|
|
54
|
+
queueMicrotask(() => {
|
|
55
|
+
if (closed) return;
|
|
56
|
+
void endpoint.request(captured).then(enqueue, error => enqueue({ jsonrpc: "2.0", id: captured.id,
|
|
57
|
+
error: { code: -32603, message: String(error), data: { code: "internal_error" } } }));
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
subscribe(listener) { if (closed) throw new Error("Transport closed"); listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
61
|
+
subscribeSession(listener) { if (closed) throw new Error("Transport closed"); sessionListeners.add(listener); return () => { sessionListeners.delete(listener); }; },
|
|
62
|
+
subscribeCallbacks(listener) { if (closed) throw new Error("Transport closed"); callbackListeners.add(listener); return () => { callbackListeners.delete(listener); }; },
|
|
63
|
+
respond(response) { if (closed) return; const captured = copy(response); queueMicrotask(() => { if (!closed) endpoint.respond?.(captured); }); },
|
|
64
|
+
onClose(listener) { if (closed) listener(); else closeListeners.add(listener); return () => { closeListeners.delete(listener); }; },
|
|
65
|
+
close() { close(); },
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { MAX_FRAME_BYTES } from "./framing.ts";
|
|
2
|
+
|
|
3
|
+
/** The queue sits before the existing writer. Producers never await a reader;
|
|
4
|
+
* only deltas may be dropped, and the gap travels before completion. */
|
|
5
|
+
export class LiveQueue {
|
|
6
|
+
private queue: { message: any; bytes: number }[] = [];
|
|
7
|
+
private bytes = 0;
|
|
8
|
+
private running = false;
|
|
9
|
+
private failed: unknown;
|
|
10
|
+
private idle: (() => void)[] = [];
|
|
11
|
+
private dropped = new Set<string>();
|
|
12
|
+
constructor(private readonly write: (message: unknown) => Promise<void>, private readonly fail: (error: unknown) => void, private readonly limit = MAX_FRAME_BYTES) {}
|
|
13
|
+
private size(message: unknown) { return new TextEncoder().encode(JSON.stringify(message)).length + 1; }
|
|
14
|
+
private push(message: any) {
|
|
15
|
+
const bytes = this.size(message);
|
|
16
|
+
if (this.bytes + bytes > this.limit) throw new Error("Protocol live queue exceeds buffer limit");
|
|
17
|
+
this.queue.push({ message, bytes }); this.bytes += bytes;
|
|
18
|
+
}
|
|
19
|
+
send(value: unknown): void {
|
|
20
|
+
if (this.failed) throw this.failed;
|
|
21
|
+
const message = structuredClone(value) as any, event = message?.method === "channel/event" ? message.params?.event : undefined;
|
|
22
|
+
const key = event?.messageId && `${message.params.channel}\u0000${event.turnId}\u0000${event.messageId}`;
|
|
23
|
+
if (event?.type === "text_delta" && key) {
|
|
24
|
+
if (this.dropped.has(key)) return;
|
|
25
|
+
const last = this.queue.at(-1), previous = last?.message?.params?.event;
|
|
26
|
+
if (last && previous?.type === "text_delta" && last.message.params.channel === message.params.channel && previous.turnId === event.turnId && previous.messageId === event.messageId) {
|
|
27
|
+
const merged = structuredClone(last.message); merged.params.event.text += event.text;
|
|
28
|
+
const bytes = this.size(merged);
|
|
29
|
+
if (this.bytes - last.bytes + bytes <= this.limit) { this.bytes += bytes - last.bytes; last.message = merged; last.bytes = bytes; return; }
|
|
30
|
+
}
|
|
31
|
+
if (this.bytes + this.size(message) > this.limit) {
|
|
32
|
+
this.dropped.add(key);
|
|
33
|
+
this.push({ ...message, params: { ...message.params, event: { type: "text_gap", turnId: event.turnId, messageId: event.messageId } } });
|
|
34
|
+
this.drain(); return;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
this.push(message);
|
|
38
|
+
if (key && (event?.type === "message_completed" || event?.type === "text_incomplete")) this.dropped.delete(key);
|
|
39
|
+
this.drain();
|
|
40
|
+
}
|
|
41
|
+
private drain() {
|
|
42
|
+
if (this.running || this.failed) return;
|
|
43
|
+
this.running = true;
|
|
44
|
+
void (async () => {
|
|
45
|
+
try {
|
|
46
|
+
while (this.queue.length) {
|
|
47
|
+
const item = this.queue.shift()!;
|
|
48
|
+
await this.write(item.message); this.bytes -= item.bytes;
|
|
49
|
+
}
|
|
50
|
+
} catch (error) { this.failed = error; this.fail(error); }
|
|
51
|
+
finally { this.running = false; for (const resolve of this.idle.splice(0)) resolve(); }
|
|
52
|
+
})();
|
|
53
|
+
}
|
|
54
|
+
async flush() { while (this.running) await new Promise<void>(resolve => this.idle.push(resolve)); if (this.failed) throw this.failed; }
|
|
55
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { ItemStatus, LoadResult, StatusResult, StoredMessage, TurnStatus } from "../../contracts/protocol.ts";
|
|
2
|
+
import type { SessionStatus } from "../../contracts/session.ts";
|
|
3
|
+
import type { StorageSnapshot, StoredTurn } from "../../contracts/storage.ts";
|
|
4
|
+
import { MAX_FRAME_BYTES } from "./framing.ts";
|
|
5
|
+
|
|
6
|
+
/** Room left in a frame for the JSON-RPC envelope around a result. */
|
|
7
|
+
const BUDGET = MAX_FRAME_BYTES - 1024;
|
|
8
|
+
const size = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).length;
|
|
9
|
+
export class FrameLimit extends Error {}
|
|
10
|
+
|
|
11
|
+
export function turnStatus(turn: StoredTurn): TurnStatus {
|
|
12
|
+
const state = turn.state;
|
|
13
|
+
return { turnId: String(turn.turnId), channel: turn.channelId, items: turn.itemIds, state: state.status,
|
|
14
|
+
...(state.status === "failed" || state.status === "interrupted" ? { reason: state.reason, uncertainCalls: state.uncertainCallIds } : {}) };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function wireStatus(status: SessionStatus, view: Pick<StorageSnapshot, "turns">): StatusResult {
|
|
18
|
+
return { sessionId: status.sessionId, revision: status.revision, lifecycle: status.lifecycle, execution: status.execution,
|
|
19
|
+
channels: status.channels.map(channel => {
|
|
20
|
+
const unresolved = channel.unresolvedInterruption && view.turns.find(turn => turn.turnId === channel.unresolvedInterruption!.turnId);
|
|
21
|
+
return { channel: channel.channelId, pending: channel.pendingItemIds, lifecycle: channel.lifecycle, waitingForResume: channel.waitingForResume,
|
|
22
|
+
...(channel.displayName === undefined ? {} : { displayName: channel.displayName }),
|
|
23
|
+
...(channel.policy === undefined ? {} : { policy: channel.policy }),
|
|
24
|
+
...(channel.activeTurn ? { activeTurn: { turnId: String(channel.activeTurn.turnId), state: channel.activeTurn.status,
|
|
25
|
+
...(channel.activeTurn.phase ? { phase: channel.activeTurn.phase } : {}) } } : {}),
|
|
26
|
+
...(unresolved ? { unresolved: turnStatus(unresolved) } : {}) };
|
|
27
|
+
}) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Committed assistant text after `after`, no newer than `revision`, filled
|
|
31
|
+
* until the count or the frame budget is reached. A page whose own records fit
|
|
32
|
+
* is complete, whatever follows it. Only a request whose first record cannot
|
|
33
|
+
* fit a frame by itself fails: that record is never skipped or truncated. */
|
|
34
|
+
export function pageMessages(view: StorageSnapshot, revision: number, after: number, limit: number, used = 0) {
|
|
35
|
+
const messages: StoredMessage[] = [];
|
|
36
|
+
let nextMessage: string | undefined;
|
|
37
|
+
for (const entry of view.timeline) {
|
|
38
|
+
if (entry.seq <= after || entry.seq > revision || entry.message.role !== "assistant" || !entry.message.content) continue;
|
|
39
|
+
const message: StoredMessage = { messageId: entry.messageId ?? String(entry.seq), channel: entry.channelId, turnId: String(entry.turnId),
|
|
40
|
+
parts: [{ type: "text", text: entry.message.content }] };
|
|
41
|
+
if (size(message) + 1 > BUDGET) { delete (message as { parts?: unknown }).parts; Object.assign(message, { reference: true }); }
|
|
42
|
+
const bytes = size(message) + 1;
|
|
43
|
+
// Count reached, or no room left on this page: an ordinary page break.
|
|
44
|
+
if (messages.length >= limit || used + bytes > BUDGET) { nextMessage = messages.at(-1)?.messageId ?? String(after); break; }
|
|
45
|
+
messages.push(message); used += bytes;
|
|
46
|
+
}
|
|
47
|
+
return { messages, ...(nextMessage === undefined ? {} : { nextMessage }) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One view of one snapshot. Turns and items are not paged, so they must fit. */
|
|
51
|
+
export function loadView(status: SessionStatus, view: StorageSnapshot, limit: number): LoadResult {
|
|
52
|
+
const fixed = {
|
|
53
|
+
status: wireStatus(status, view), turns: view.turns.map(turnStatus),
|
|
54
|
+
items: view.items.map((item): ItemStatus => ({ id: item.itemId, channel: item.channelId, kind: item.kind, sender: item.senderId,
|
|
55
|
+
milestone: item.milestone, ...(item.policy === undefined ? {} : { policy: item.policy }), ...(item.turnId === undefined ? {} : { turnId: String(item.turnId) }) })),
|
|
56
|
+
};
|
|
57
|
+
const used = size(fixed);
|
|
58
|
+
if (used > BUDGET) throw new FrameLimit("Session turns and items do not fit in one protocol frame");
|
|
59
|
+
return { ...fixed, ...pageMessages(view, view.revision, 0, limit, used) };
|
|
60
|
+
}
|