@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,114 @@
|
|
|
1
|
+
import type { ModelAttemptSummary, ModelCallSummary, ModelUsage } from "../../native-harness/src/client.ts";
|
|
2
|
+
import type { TokenUsage } from "../../types.ts";
|
|
3
|
+
import { isTokenCount } from "../categories.ts";
|
|
4
|
+
import type { ProviderInference } from "../opencode/channel.ts";
|
|
5
|
+
|
|
6
|
+
export interface NativeAttemptEvidence {
|
|
7
|
+
readonly attemptId: string;
|
|
8
|
+
readonly ordinal: number;
|
|
9
|
+
readonly outcome: ModelAttemptSummary["outcome"];
|
|
10
|
+
readonly usage?: Readonly<ModelUsage>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface NativeCallEvidence {
|
|
14
|
+
readonly callId: string;
|
|
15
|
+
readonly channel: string;
|
|
16
|
+
readonly turnId: string;
|
|
17
|
+
readonly outcome: ModelCallSummary["outcome"];
|
|
18
|
+
readonly attempts: readonly NativeAttemptEvidence[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface NativeUsageInference extends ProviderInference {
|
|
22
|
+
/** Empty is the internal representation of unknown, required by the string-only source shape. */
|
|
23
|
+
readonly providerID: "";
|
|
24
|
+
readonly modelID: "";
|
|
25
|
+
readonly callId: string;
|
|
26
|
+
readonly attemptId: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface NativeUsageProjection {
|
|
30
|
+
readonly evidence: readonly NativeCallEvidence[];
|
|
31
|
+
readonly inferences: readonly NativeUsageInference[];
|
|
32
|
+
readonly unmeasured: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const callOutcomes = new Set<ModelCallSummary["outcome"]>([
|
|
36
|
+
"running", "succeeded", "failed", "incomplete", "output_limit", "timeout", "interrupted",
|
|
37
|
+
]);
|
|
38
|
+
const attemptOutcomes = new Set<ModelAttemptSummary["outcome"]>([
|
|
39
|
+
"running", "succeeded", "transient_failure", "invalid_request", "invalid_config", "provider_failure",
|
|
40
|
+
"incomplete", "output_limit", "timeout", "interrupted",
|
|
41
|
+
]);
|
|
42
|
+
const usageFields = ["inputTokens", "outputTokens", "totalTokens"] as const;
|
|
43
|
+
|
|
44
|
+
export function projectNativeUsage(calls: readonly ModelCallSummary[], sessionID: string): NativeUsageProjection {
|
|
45
|
+
const evidence: NativeCallEvidence[] = [];
|
|
46
|
+
const inferences: NativeUsageInference[] = [];
|
|
47
|
+
let unmeasured = 0;
|
|
48
|
+
|
|
49
|
+
for (const call of calls) {
|
|
50
|
+
if (!Array.isArray(call.attempts) || typeof call.messageId !== "string" ||
|
|
51
|
+
!call.messageId || !callOutcomes.has(call.outcome)) {
|
|
52
|
+
throw new Error("Invalid native model-call summary");
|
|
53
|
+
}
|
|
54
|
+
const sealed = isSealedNativeCall(call);
|
|
55
|
+
const attempts: NativeAttemptEvidence[] = [];
|
|
56
|
+
const ids = new Set<string>();
|
|
57
|
+
for (const attempt of call.attempts) {
|
|
58
|
+
if (typeof attempt?.attemptId !== "string" || !attempt.attemptId ||
|
|
59
|
+
ids.has(attempt.attemptId) || attempt.ordinal !== attempts.length) {
|
|
60
|
+
throw new Error("Native usage ledger returned an invalid or repeated attempt ID or ordinal");
|
|
61
|
+
}
|
|
62
|
+
if (!attemptOutcomes.has(attempt.outcome)) throw new Error("Invalid native model-attempt outcome");
|
|
63
|
+
ids.add(attempt.attemptId);
|
|
64
|
+
const usage = copyUsage(attempt.usage);
|
|
65
|
+
attempts.push({
|
|
66
|
+
attemptId: attempt.attemptId, ordinal: attempt.ordinal, outcome: attempt.outcome,
|
|
67
|
+
...(usage === undefined ? {} : { usage }),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const completedAt = timestamp(attempt.endedAt);
|
|
71
|
+
const tokens = completeUsage(usage);
|
|
72
|
+
if (!sealed || attempt.outcome === "running" || completedAt === undefined || tokens === undefined) {
|
|
73
|
+
unmeasured++;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
inferences.push({
|
|
77
|
+
sequence: null, sessionID, messageID: call.messageId, callId: call.callId, attemptId: attempt.attemptId,
|
|
78
|
+
providerID: "", modelID: "", summary: false, completedAt, cost: null, tokens,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (!attempts.length) unmeasured++;
|
|
82
|
+
evidence.push({ callId: call.callId, channel: call.channel, turnId: call.turnId, outcome: call.outcome, attempts });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return { evidence, inferences, unmeasured };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function isSealedNativeCall(call: ModelCallSummary): boolean {
|
|
89
|
+
return call.outcome !== "running" && timestamp(call.endedAt) !== undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function timestamp(value: string | undefined): number | undefined {
|
|
93
|
+
if (typeof value !== "string") return undefined;
|
|
94
|
+
const parsed = Date.parse(value);
|
|
95
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function copyUsage(usage: ModelUsage | undefined): ModelUsage | undefined {
|
|
99
|
+
if (usage === undefined) return undefined;
|
|
100
|
+
if (typeof usage !== "object" || usage === null || Array.isArray(usage)) throw new Error("Invalid native model usage");
|
|
101
|
+
const copy: ModelUsage = {};
|
|
102
|
+
for (const field of usageFields) {
|
|
103
|
+
const value = usage[field];
|
|
104
|
+
if (value === undefined) continue;
|
|
105
|
+
if (!isTokenCount(value)) throw new Error(`Invalid native model usage field "${field}"`);
|
|
106
|
+
copy[field] = value;
|
|
107
|
+
}
|
|
108
|
+
return copy;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function completeUsage(usage: ModelUsage | undefined): TokenUsage | undefined {
|
|
112
|
+
if (usage?.inputTokens === undefined || usage.outputTokens === undefined || usage.totalTokens === undefined) return undefined;
|
|
113
|
+
return { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, totalTokens: usage.totalTokens };
|
|
114
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { OperationMeteringRecord } from "../record.ts";
|
|
2
|
+
import type { MeteringOperationIdentity } from "../../persistence/backend.ts";
|
|
3
|
+
import { accountedNativeAttempts } from "./retirement.ts";
|
|
4
|
+
|
|
5
|
+
export const MAX_NATIVE_PROOF_IDS = 128;
|
|
6
|
+
export const MAX_NATIVE_PROOF_BYTES = 32 * 1024;
|
|
7
|
+
const MAX_ENCODED_ID_BYTES = 96;
|
|
8
|
+
|
|
9
|
+
type NativeProof = Pick<MeteringOperationIdentity, "nativeAccountedAttemptIds" | "nativeAccountedAttemptCount" |
|
|
10
|
+
"nativeAccountedAttemptsTruncated" | "unaccountedEarlierCalls" | "unaccountedEarlierSummary">;
|
|
11
|
+
|
|
12
|
+
function boundedId(id: string): boolean {
|
|
13
|
+
return id.length <= MAX_ENCODED_ID_BYTES && Buffer.byteLength(JSON.stringify(id)) <= MAX_ENCODED_ID_BYTES;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function serializeNativeMeteringProof(record: OperationMeteringRecord): string | null {
|
|
17
|
+
if (!record.nativeUsage) return null;
|
|
18
|
+
const accounted = accountedNativeAttempts(record);
|
|
19
|
+
const ids = accounted?.slice(0, MAX_NATIVE_PROOF_IDS).filter(boundedId);
|
|
20
|
+
const retained: NativeProof = {
|
|
21
|
+
nativeAccountedAttemptIds: ids,
|
|
22
|
+
...(accounted && ids?.length !== accounted.length ? {
|
|
23
|
+
nativeAccountedAttemptCount: accounted.length, nativeAccountedAttemptsTruncated: true,
|
|
24
|
+
} : {}),
|
|
25
|
+
};
|
|
26
|
+
const earlier = record.nativeUsage.unaccountedEarlierCalls;
|
|
27
|
+
if (!earlier?.length) return JSON.stringify(retained);
|
|
28
|
+
|
|
29
|
+
if (earlier.length <= MAX_NATIVE_PROOF_IDS && earlier.every(call =>
|
|
30
|
+
boundedId(call.callId) && boundedId(call.turnId) && call.attemptIds.length <= MAX_NATIVE_PROOF_IDS &&
|
|
31
|
+
call.attemptIds.every(boundedId) && (call.reason?.length ?? 0) <= 160)) {
|
|
32
|
+
const full = JSON.stringify({ ...retained, unaccountedEarlierCalls: earlier });
|
|
33
|
+
if (Buffer.byteLength(full) <= MAX_NATIVE_PROOF_BYTES) return full;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let attemptCount = 0, unmeasured = 0, measuredCalls = 0;
|
|
37
|
+
const tokens = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
38
|
+
for (const call of earlier) {
|
|
39
|
+
attemptCount += call.attemptCount;
|
|
40
|
+
unmeasured += call.unmeasured;
|
|
41
|
+
if (!call.tokens) continue;
|
|
42
|
+
measuredCalls++;
|
|
43
|
+
tokens.inputTokens += call.tokens.inputTokens;
|
|
44
|
+
tokens.outputTokens += call.tokens.outputTokens;
|
|
45
|
+
tokens.totalTokens += call.tokens.totalTokens;
|
|
46
|
+
}
|
|
47
|
+
return JSON.stringify({ ...retained, unaccountedEarlierSummary: {
|
|
48
|
+
truncated: true, callCount: earlier.length, attemptCount, unmeasured,
|
|
49
|
+
...(measuredCalls ? { tokens } : {}),
|
|
50
|
+
} });
|
|
51
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { MeteringPreflightError, type MeteringEnforcement } from "../record.ts";
|
|
2
|
+
|
|
3
|
+
/** The current ledger lacks the sealed accounting and provider evidence required for certification. */
|
|
4
|
+
export function requireNativeMeteringCapability(enforcement: MeteringEnforcement | undefined): void {
|
|
5
|
+
if (enforcement === "billing_required") {
|
|
6
|
+
throw new MeteringPreflightError(
|
|
7
|
+
"billing_required for the native adapter kind requires the native-harness@1 sealed per-turn accounting capability",
|
|
8
|
+
);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { NativeEarlierCallEvidence, OperationMeteringRecord } from "../record.ts";
|
|
2
|
+
import type { TokenUsage } from "../../types.ts";
|
|
3
|
+
import type { ModelCallSummary } from "../../native-harness/src/client.ts";
|
|
4
|
+
import { isSealedNativeCall, projectNativeUsage, type NativeUsageInference } from "./projection.ts";
|
|
5
|
+
import type { UnallocatedUsageAccrual } from "../state.ts";
|
|
6
|
+
import type { NativeAttemptReceipt, NativeTurnMetering, NativeTurnRead } from "./source.ts";
|
|
7
|
+
|
|
8
|
+
export function sumNativeTokens(inferences: readonly NativeUsageInference[]): TokenUsage {
|
|
9
|
+
const sum = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
10
|
+
for (const { tokens } of inferences) {
|
|
11
|
+
sum.inputTokens += tokens.inputTokens;
|
|
12
|
+
sum.outputTokens += tokens.outputTokens;
|
|
13
|
+
sum.totalTokens += tokens.totalTokens;
|
|
14
|
+
}
|
|
15
|
+
return sum;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Only publish observations within the retired prefix. The record and cursor commit together. */
|
|
19
|
+
interface NativeRetirement {
|
|
20
|
+
readonly through?: string;
|
|
21
|
+
readonly earlier: readonly NativeEarlierCallEvidence[];
|
|
22
|
+
readonly unallocated: readonly UnallocatedUsageAccrual[];
|
|
23
|
+
readonly pendingEarlier: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function evaluateNativeRetirement(
|
|
27
|
+
turn: NativeTurnMetering,
|
|
28
|
+
read: NativeTurnRead,
|
|
29
|
+
currentTerminal: boolean,
|
|
30
|
+
): Promise<NativeRetirement> {
|
|
31
|
+
const prefix = read.prefix ?? [];
|
|
32
|
+
const earlierIds = [...new Set(prefix.filter(call => call.turnId !== turn.turnId).map(call => call.turnId))];
|
|
33
|
+
// One bounded reconcile read per close. A later close can continue past this batch.
|
|
34
|
+
const terminal = earlierIds.length
|
|
35
|
+
? await turn.terminalEarlierTurns?.(earlierIds.slice(0, 100)).catch(() => undefined)
|
|
36
|
+
: undefined;
|
|
37
|
+
const prior = new Map<string, NativeAttemptReceipt | null | undefined>();
|
|
38
|
+
const earlier: NativeEarlierCallEvidence[] = [];
|
|
39
|
+
const unallocated: UnallocatedUsageAccrual[] = [];
|
|
40
|
+
let through: string | undefined;
|
|
41
|
+
|
|
42
|
+
for (const call of prefix) {
|
|
43
|
+
if (call.turnId === turn.turnId) {
|
|
44
|
+
if (!currentTerminal || read.unmeasured || !read.inferences.length) break;
|
|
45
|
+
} else {
|
|
46
|
+
if (!terminal?.has(call.turnId)) return { through, earlier, unallocated, pendingEarlier: true };
|
|
47
|
+
if (!prior.has(call.turnId)) prior.set(call.turnId, await turn.accountedAttempts?.(call.turnId));
|
|
48
|
+
const observed = earlierEvidence(call, prior.get(call.turnId));
|
|
49
|
+
if (observed) {
|
|
50
|
+
earlier.push(observed.evidence);
|
|
51
|
+
unallocated.push(...observed.newlyKnown.map(({ tokens }) => ({
|
|
52
|
+
usage: tokens, ratedCost: null, reason: "unaccounted usage of an earlier turn",
|
|
53
|
+
})));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
through = call.callId;
|
|
57
|
+
}
|
|
58
|
+
return { through, earlier, unallocated, pendingEarlier: false };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Retained records from before explicit attempt proofs can attest only complete measurements. */
|
|
62
|
+
export function accountedNativeAttempts(record: OperationMeteringRecord): readonly string[] | undefined {
|
|
63
|
+
const evidence = record.nativeUsage;
|
|
64
|
+
if (!evidence) return undefined;
|
|
65
|
+
if (evidence.accountedAttemptIds) return evidence.accountedAttemptIds;
|
|
66
|
+
if (record.usage.status !== "metered") return [];
|
|
67
|
+
return evidence.status === "observed" && evidence.unmeasured === 0
|
|
68
|
+
? evidence.calls.flatMap(call => call.attempts.map(attempt => attempt.attemptId))
|
|
69
|
+
: undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function earlierEvidence(call: ModelCallSummary, accounted: NativeAttemptReceipt | null | undefined) {
|
|
73
|
+
const already = new Set(accounted?.ids ?? []);
|
|
74
|
+
const attemptIds = call.attempts.filter(attempt => !already.has(attempt.attemptId)).map(attempt => attempt.attemptId);
|
|
75
|
+
const { inferences } = projectNativeUsage([call], "");
|
|
76
|
+
const uncertain = accounted === undefined || accounted?.truncated;
|
|
77
|
+
const newlyKnown = uncertain ? [] : inferences.filter(inference => !already.has(inference.attemptId));
|
|
78
|
+
const sealed = isSealedNativeCall(call);
|
|
79
|
+
const unmeasured = Math.max(sealed && call.attempts.length ? 0 : 1, attemptIds.length - newlyKnown.length);
|
|
80
|
+
if (!attemptIds.length && !unmeasured) return undefined;
|
|
81
|
+
return {
|
|
82
|
+
newlyKnown,
|
|
83
|
+
evidence: {
|
|
84
|
+
callId: call.callId, turnId: call.turnId, attemptIds, attemptCount: attemptIds.length, unmeasured,
|
|
85
|
+
...(newlyKnown.length ? { tokens: sumNativeTokens(newlyKnown) } : {}),
|
|
86
|
+
...(!sealed ? { reason: "the earlier turn ended with an unsealed model call" }
|
|
87
|
+
: accounted?.truncated ? { reason: "the earlier operation's retained accounting proof was truncated" }
|
|
88
|
+
: accounted === undefined ? { reason: "the earlier operation's retained accounting proof is unavailable" }
|
|
89
|
+
: unmeasured ? { reason: "some earlier model-call attempts could not be measured" } : {}),
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { ModelCallSummary } from "../../native-harness/src/client.ts";
|
|
2
|
+
import type { InferenceSource } from "../engine.ts";
|
|
3
|
+
import type { NativeLedgerPosition, NativeUsageLedger } from "./ledger.ts";
|
|
4
|
+
import { projectNativeUsage, type NativeCallEvidence, type NativeUsageInference } from "./projection.ts";
|
|
5
|
+
|
|
6
|
+
export interface NativeTurnUsage {
|
|
7
|
+
readonly calls: readonly NativeCallEvidence[];
|
|
8
|
+
/** An observation for reconciliation. It is not an accounting acknowledgement. */
|
|
9
|
+
readonly lastSeenCallId?: string;
|
|
10
|
+
readonly unmeasured: number;
|
|
11
|
+
readonly prefix?: readonly ModelCallSummary[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const UNVERIFIED_NATIVE_SOURCE = "native-harness-unverified";
|
|
15
|
+
|
|
16
|
+
export interface NativeTurnRead extends NativeTurnUsage {
|
|
17
|
+
readonly inferences: readonly NativeUsageInference[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface NativeAttemptReceipt {
|
|
21
|
+
readonly ids: readonly string[];
|
|
22
|
+
readonly truncated?: true;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface NativeTurnMetering {
|
|
26
|
+
readonly turnId: string;
|
|
27
|
+
readonly isTerminal?: () => boolean;
|
|
28
|
+
readonly terminalEarlierTurns?: (turnIds: readonly string[]) => Promise<ReadonlySet<string>>;
|
|
29
|
+
/** Null means no operation exists; undefined means its accounting cannot be established. */
|
|
30
|
+
readonly accountedAttempts?: (turnId: string) => Promise<NativeAttemptReceipt | null | undefined>;
|
|
31
|
+
read(position?: NativeLedgerPosition): Promise<NativeTurnRead>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Stages one explicitly owned turn before the engine's synchronous drain. */
|
|
35
|
+
export class NativeInferenceSource implements InferenceSource {
|
|
36
|
+
readonly certificationId = UNVERIFIED_NATIVE_SOURCE;
|
|
37
|
+
readonly sessionKey: string;
|
|
38
|
+
#queue = Promise.resolve();
|
|
39
|
+
#current: NativeTurnUsage | undefined;
|
|
40
|
+
#ready: readonly NativeUsageInference[] = [];
|
|
41
|
+
|
|
42
|
+
constructor(
|
|
43
|
+
agentId: string,
|
|
44
|
+
private readonly channel: string,
|
|
45
|
+
private readonly ledger: NativeUsageLedger,
|
|
46
|
+
) {
|
|
47
|
+
this.sessionKey = `${agentId}/${channel}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
pullTurn(turnId: string, position?: NativeLedgerPosition): Promise<NativeTurnUsage> {
|
|
51
|
+
return this.#enqueue(() => this.#pull(turnId, position));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Keep pull and drain in the same queued operation, even if a second close is waiting. */
|
|
55
|
+
readTurn(turnId: string, position?: NativeLedgerPosition): Promise<NativeTurnRead> {
|
|
56
|
+
return this.#enqueue(async () => {
|
|
57
|
+
const evidence = await this.#pull(turnId, position);
|
|
58
|
+
return { ...evidence, inferences: this.drain(this.sessionKey) };
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
#enqueue<T>(work: () => Promise<T>): Promise<T> {
|
|
63
|
+
const result = this.#queue.then(work);
|
|
64
|
+
this.#queue = result.then(() => undefined, () => undefined);
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async #pull(turnId: string, position?: NativeLedgerPosition): Promise<NativeTurnUsage> {
|
|
69
|
+
this.#ready = [];
|
|
70
|
+
this.#current = undefined;
|
|
71
|
+
const { calls, lastSeenCallId, prefix } = await this.ledger.readTurn(this.channel, turnId, position);
|
|
72
|
+
const { evidence, inferences, unmeasured } = projectNativeUsage(calls, this.sessionKey);
|
|
73
|
+
this.#current = { calls: evidence, lastSeenCallId, unmeasured, prefix };
|
|
74
|
+
this.#ready = inferences;
|
|
75
|
+
return this.#current;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
isHealthy(): boolean { return this.#current !== undefined; }
|
|
79
|
+
|
|
80
|
+
drain(internalSessionId: string | null): readonly NativeUsageInference[] {
|
|
81
|
+
if (internalSessionId !== this.sessionKey) return [];
|
|
82
|
+
const ready = this.#ready;
|
|
83
|
+
this.#ready = [];
|
|
84
|
+
return ready;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
outstandingReports(internalSessionId: string | null): number {
|
|
88
|
+
return internalSessionId === this.sessionKey ? this.#current?.unmeasured ?? 0 : 0;
|
|
89
|
+
}
|
|
90
|
+
}
|
package/src/metering/record.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { Money } from "./money.ts";
|
|
|
15
15
|
import type { AttributableUsage } from "./rating.ts";
|
|
16
16
|
import type { AgentSessionMeteringState, StateRestoration } from "./state.ts";
|
|
17
17
|
import type { PricingConfiguration } from "./pricing.ts";
|
|
18
|
+
import type { NativeCallEvidence } from "./native/projection.ts";
|
|
18
19
|
import type { InferenceSource } from "./engine.ts";
|
|
19
20
|
|
|
20
21
|
export type MeteredOperationKind =
|
|
@@ -32,6 +33,8 @@ export type OperationOutcome = "completed" | "cancelled" | "error";
|
|
|
32
33
|
export type MeteringUsageResult =
|
|
33
34
|
| {
|
|
34
35
|
readonly status: "metered";
|
|
36
|
+
/** Why the reported value is a lower bound when some usage could not be measured. */
|
|
37
|
+
readonly reason?: string;
|
|
35
38
|
readonly reportedCumulative: TokenUsage;
|
|
36
39
|
readonly attributable: AttributableUsage;
|
|
37
40
|
}
|
|
@@ -63,7 +66,7 @@ export interface ProviderIdentitySnapshot {
|
|
|
63
66
|
* traffic bypassed it. Network isolation is a deployment property, not a library claim.
|
|
64
67
|
*/
|
|
65
68
|
export interface MeteringProvenance {
|
|
66
|
-
readonly source: "certified" | "acp_usage" | "none";
|
|
69
|
+
readonly source: "certified" | "native_ledger" | "acp_usage" | "none";
|
|
67
70
|
readonly measurement: "provider_normalized" | "acp_derived" | "unavailable";
|
|
68
71
|
readonly routing: "observed" | "unknown";
|
|
69
72
|
readonly attribution: "complete" | "partial" | "unavailable";
|
|
@@ -101,6 +104,39 @@ export type CostReconciliation =
|
|
|
101
104
|
readonly reason: string;
|
|
102
105
|
};
|
|
103
106
|
|
|
107
|
+
/** Evidence from the native harness ledger for this operation's wire turn. */
|
|
108
|
+
export interface NativeEarlierCallEvidence {
|
|
109
|
+
readonly callId: string;
|
|
110
|
+
readonly turnId: string;
|
|
111
|
+
readonly attemptIds: readonly string[];
|
|
112
|
+
readonly attemptCount: number;
|
|
113
|
+
readonly unmeasured: number;
|
|
114
|
+
/** Known usage excluded from this operation and from its attributable totals. */
|
|
115
|
+
readonly tokens?: TokenUsage;
|
|
116
|
+
readonly reason?: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Compact evidence when the operation index cannot retain all earlier call detail. */
|
|
120
|
+
export interface NativeEarlierCallSummary {
|
|
121
|
+
readonly truncated: true;
|
|
122
|
+
readonly callCount: number;
|
|
123
|
+
readonly attemptCount: number;
|
|
124
|
+
readonly unmeasured: number;
|
|
125
|
+
readonly tokens?: TokenUsage;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type NativeOperationUsage = {
|
|
129
|
+
readonly channel: string;
|
|
130
|
+
readonly turnId: string | null;
|
|
131
|
+
readonly accountedAttemptIds?: readonly string[];
|
|
132
|
+
readonly unaccountedEarlierCalls?: readonly NativeEarlierCallEvidence[];
|
|
133
|
+
readonly unaccountedEarlierSummary?: NativeEarlierCallSummary;
|
|
134
|
+
readonly earlierEvidencePending?: true;
|
|
135
|
+
} & (
|
|
136
|
+
| { readonly status: "observed"; readonly calls: readonly NativeCallEvidence[]; readonly unmeasured: number }
|
|
137
|
+
| { readonly status: "unavailable"; readonly reason: string }
|
|
138
|
+
);
|
|
139
|
+
|
|
104
140
|
export interface OperationMeteringRecord {
|
|
105
141
|
readonly operationId: string;
|
|
106
142
|
readonly operationKind: MeteredOperationKind;
|
|
@@ -114,6 +150,7 @@ export interface OperationMeteringRecord {
|
|
|
114
150
|
readonly provenance: MeteringProvenance;
|
|
115
151
|
|
|
116
152
|
readonly usage: MeteringUsageResult;
|
|
153
|
+
readonly nativeUsage?: NativeOperationUsage;
|
|
117
154
|
readonly pricingStatus: MeteringPricingStatus;
|
|
118
155
|
readonly pricingFailureReason?: string;
|
|
119
156
|
/** Latest observation received by completion; not guaranteed to include this operation. */
|
package/src/metering/state.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// mentioning cache. Coverage distinguishes a category nobody could measure from one the
|
|
11
11
|
// model simply does not use.
|
|
12
12
|
|
|
13
|
+
import type { OperationMeteringRecord } from "./record.ts";
|
|
13
14
|
import type { TokenUsage } from "../types.ts";
|
|
14
15
|
import {
|
|
15
16
|
CATEGORY_FIELD,
|
|
@@ -40,7 +41,7 @@ export interface UsageCategoryTotal {
|
|
|
40
41
|
readonly attributedOperationCount: number;
|
|
41
42
|
/** Operations explicitly known not to use this category. */
|
|
42
43
|
readonly notApplicableOperationCount: number;
|
|
43
|
-
/** Applicable/unknown operations for which this category
|
|
44
|
+
/** Applicable/unknown operations for which this category was partly or wholly unavailable. */
|
|
44
45
|
readonly unavailableOperationCount: number;
|
|
45
46
|
readonly coverage: CategoryCoverage;
|
|
46
47
|
}
|
|
@@ -93,6 +94,10 @@ export interface AgentSessionMeteringState {
|
|
|
93
94
|
readonly ratedCosts: MoneyTotal;
|
|
94
95
|
readonly unallocatedUsage: UnallocatedUsageState;
|
|
95
96
|
readonly activeBaseline: MeteringBaseline | null;
|
|
97
|
+
/** The last sealed, accounted native call in this channel's ledger prefix. */
|
|
98
|
+
readonly nativeCursor?: { readonly channelKey: string; readonly after: string };
|
|
99
|
+
/** Durable recovery slot. The operation commit clears it with the same transaction. */
|
|
100
|
+
readonly pendingNativeMetering?: OperationMeteringRecord;
|
|
96
101
|
}
|
|
97
102
|
|
|
98
103
|
/**
|
|
@@ -177,6 +182,8 @@ export interface OperationAccrual {
|
|
|
177
182
|
/** Applicability from the resolved policy; unknown when no policy was resolved. */
|
|
178
183
|
readonly applicability: Readonly<Record<TokenCategory, CategoryApplicability>> | null;
|
|
179
184
|
readonly baseline: MeteringBaseline | null;
|
|
185
|
+
/** Known usage covers only part of this operation. */
|
|
186
|
+
readonly partial?: boolean;
|
|
180
187
|
/** Usage observed but belonging to no operation — never merged into totals. */
|
|
181
188
|
readonly unallocated?: readonly UnallocatedUsageAccrual[];
|
|
182
189
|
}
|
|
@@ -198,7 +205,7 @@ export function accrueOperation(
|
|
|
198
205
|
const nextAggregate = {
|
|
199
206
|
knownTokens: aggregate.knownTokens + (attributable?.totalTokens ?? 0),
|
|
200
207
|
attributedOperationCount: aggregate.attributedOperationCount + (measured ? 1 : 0),
|
|
201
|
-
unavailableOperationCount: aggregate.unavailableOperationCount + (measured ?
|
|
208
|
+
unavailableOperationCount: aggregate.unavailableOperationCount + (!measured || accrual.partial ? 1 : 0),
|
|
202
209
|
};
|
|
203
210
|
|
|
204
211
|
const categoryTotals: Record<string, UsageCategoryTotal> = {};
|
|
@@ -216,7 +223,7 @@ export function accrueOperation(
|
|
|
216
223
|
notApplicableOperationCount:
|
|
217
224
|
current.notApplicableOperationCount + (value === undefined && notApplicable ? 1 : 0),
|
|
218
225
|
unavailableOperationCount:
|
|
219
|
-
current.unavailableOperationCount + (value === undefined
|
|
226
|
+
current.unavailableOperationCount + (!notApplicable && (value === undefined || accrual.partial) ? 1 : 0),
|
|
220
227
|
};
|
|
221
228
|
categoryTotals[key] = Object.freeze({ ...next, coverage: deriveCoverage(next) });
|
|
222
229
|
}
|
|
@@ -374,6 +381,9 @@ function isStructurallyValid(state: AgentSessionMeteringState): boolean {
|
|
|
374
381
|
if (!isCategoryTotal(totals[key])) return false;
|
|
375
382
|
}
|
|
376
383
|
if (!isMoneyTotal(state.ratedCosts)) return false;
|
|
384
|
+
const cursor = state.nativeCursor;
|
|
385
|
+
if (cursor !== undefined && (typeof cursor?.channelKey !== "string" || !cursor.channelKey ||
|
|
386
|
+
typeof cursor.after !== "string" || !cursor.after)) return false;
|
|
377
387
|
|
|
378
388
|
const unallocated = state.unallocatedUsage as unknown as Record<string, unknown> | undefined;
|
|
379
389
|
if (!unallocated || !isTokenCount(unallocated.recordCount) || !isMoneyTotal(unallocated.ratedCosts)) {
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { permissionArrival } from "../permissions/arrival.ts";
|
|
2
|
+
import type { ChannelEvent } from "../native-harness/src/client.ts";
|
|
3
|
+
import type { Logger } from "../logger.ts";
|
|
4
|
+
import { cancelledPermission, nativeConversationStopping, nativePermissionRequests, refuseNativeOnClose, type NativePermission, type PermissionResolution } from "../permissions/conversation.ts";
|
|
5
|
+
import { recordingPermissionHandlers } from "../permissions/policy.ts";
|
|
6
|
+
import type { PermissionRequest, PromptHandlers } from "../types.ts";
|
|
7
|
+
import type { NativeApprovalRequest, NativeApprovalResponder } from "./host.ts";
|
|
8
|
+
|
|
9
|
+
type ApprovalEvent = Extract<ChannelEvent["event"], { type: "approval_requested" }>;
|
|
10
|
+
type CloseEvent = Extract<ChannelEvent["event"], { type: "approval_closed" }>;
|
|
11
|
+
type SendApproval = (decision: "allow_once" | "deny") => Promise<boolean>;
|
|
12
|
+
const allow = { outcome: "selected", optionId: "allow_once" } as const;
|
|
13
|
+
const deny = { outcome: "selected", optionId: "deny" } as const;
|
|
14
|
+
|
|
15
|
+
class Approval implements NativePermission {
|
|
16
|
+
readonly arrival = permissionArrival();
|
|
17
|
+
readonly resolution: Promise<PermissionResolution>;
|
|
18
|
+
private resolve!: (result: PermissionResolution) => void;
|
|
19
|
+
private readonly abort = new AbortController();
|
|
20
|
+
private inFlight = false;
|
|
21
|
+
private observedAnswer?: PermissionResolution;
|
|
22
|
+
private started = false;
|
|
23
|
+
|
|
24
|
+
constructor(
|
|
25
|
+
readonly request: NativeApprovalRequest,
|
|
26
|
+
readonly hostHandled: boolean,
|
|
27
|
+
private readonly send: SendApproval,
|
|
28
|
+
) {
|
|
29
|
+
this.resolution = new Promise(resolve => { this.resolve = resolve; });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
get signal(): AbortSignal { return this.abort.signal; }
|
|
33
|
+
get settled(): boolean { return this.abort.signal.aborted; }
|
|
34
|
+
get hasWireOutcome(): boolean { return this.settled || this.observedAnswer !== undefined; }
|
|
35
|
+
|
|
36
|
+
start(responder: NativeApprovalResponder, log: Logger): void {
|
|
37
|
+
if (this.started) return;
|
|
38
|
+
this.started = true;
|
|
39
|
+
void Promise.resolve().then(() => {
|
|
40
|
+
if (!this.abort.signal.aborted) {
|
|
41
|
+
return responder(this.request, decision => this.answer({ outcome: decision === "allow_once" ? allow : deny, by: "handler" }), this.abort.signal);
|
|
42
|
+
}
|
|
43
|
+
}).catch(error => log.warn("native_approval_responder_failed", { requestId: this.request.requestId, error: String(error) }));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async answer(resolution: PermissionResolution): Promise<boolean> {
|
|
47
|
+
if (this.inFlight || this.abort.signal.aborted) return false;
|
|
48
|
+
this.inFlight = true;
|
|
49
|
+
const decision = resolution.outcome.outcome === "selected" && resolution.outcome.optionId === "allow_once" ? allow : deny;
|
|
50
|
+
try {
|
|
51
|
+
const accepted = await this.send(decision.optionId);
|
|
52
|
+
if (this.abort.signal.aborted) return false;
|
|
53
|
+
this.finish(accepted ? { ...resolution, outcome: decision } : this.observedAnswer ?? cancelledPermission);
|
|
54
|
+
return accepted;
|
|
55
|
+
} finally {
|
|
56
|
+
if (!this.abort.signal.aborted) this.finish(this.observedAnswer ?? cancelledPermission);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
closed(reason: CloseEvent["reason"]): void {
|
|
61
|
+
if (reason === "approval_denied" || reason === "dispatched") {
|
|
62
|
+
// The harness can emit the effect before replying to approval/respond.
|
|
63
|
+
this.observedAnswer = { outcome: reason === "dispatched" ? allow : deny, by: "consumer" };
|
|
64
|
+
if (!this.inFlight) this.finish(this.observedAnswer);
|
|
65
|
+
} else if (reason === "approval_timeout") {
|
|
66
|
+
this.finish({ outcome: deny, by: "timeout" });
|
|
67
|
+
} else {
|
|
68
|
+
this.finish(cancelledPermission);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
endTurn(): void {
|
|
73
|
+
if (!this.inFlight || !this.observedAnswer) this.finish(cancelledPermission);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
finish(result: PermissionResolution): void {
|
|
77
|
+
if (this.abort.signal.aborted) return;
|
|
78
|
+
this.abort.abort();
|
|
79
|
+
this.resolve(result);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Attach the same ticket to live and observed copies. Held events keep their ticket after turn cleanup. */
|
|
84
|
+
export class NativeApprovals {
|
|
85
|
+
private readonly active = new Map<string, Approval>();
|
|
86
|
+
get busy(): boolean { return [...this.active.values()].some(ticket => !ticket.settled); }
|
|
87
|
+
private readonly events = new WeakMap<ApprovalEvent, Approval>();
|
|
88
|
+
|
|
89
|
+
constructor(private readonly responder: NativeApprovalResponder | undefined, private readonly log: Logger) {}
|
|
90
|
+
|
|
91
|
+
observe(channel: string, event: ApprovalEvent, send: SendApproval): void {
|
|
92
|
+
let ticket = this.events.get(event) ?? this.active.get(event.requestId);
|
|
93
|
+
if (!ticket) {
|
|
94
|
+
const { type: _type, ...request } = event;
|
|
95
|
+
ticket = new Approval({ ...request, channel }, this.responder !== undefined, send);
|
|
96
|
+
this.active.set(event.requestId, ticket);
|
|
97
|
+
}
|
|
98
|
+
this.events.set(event, ticket);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
start(event: ApprovalEvent): void {
|
|
102
|
+
if (this.responder) this.events.get(event)?.start(this.responder, this.log);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
ticket(event: ApprovalEvent): NativePermission | undefined { return this.events.get(event); }
|
|
106
|
+
|
|
107
|
+
closed(event: CloseEvent): void { this.active.get(event.requestId)?.closed(event.reason); }
|
|
108
|
+
|
|
109
|
+
end(channel: string, turnId: string): void {
|
|
110
|
+
for (const [id, ticket] of this.active) {
|
|
111
|
+
if (ticket.request.channel !== channel || ticket.request.turnId !== turnId) continue;
|
|
112
|
+
this.active.delete(id);
|
|
113
|
+
ticket.endTurn();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
disconnected(): void {
|
|
118
|
+
for (const ticket of this.active.values()) ticket.finish(cancelledPermission);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
stop(): void {
|
|
122
|
+
this.disconnected();
|
|
123
|
+
this.active.clear();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const APPROVAL_OPTIONS: PermissionRequest["options"] = [
|
|
128
|
+
{ optionId: "allow_once", name: "Allow once", kind: "allow_once" },
|
|
129
|
+
{ optionId: "deny", name: "Deny", kind: "reject_once" },
|
|
130
|
+
];
|
|
131
|
+
|
|
132
|
+
export async function runNativeApproval(
|
|
133
|
+
ticket: NativePermission, event: ApprovalEvent, handlers: PromptHandlers, cancelled: AbortSignal, log: Logger,
|
|
134
|
+
): Promise<void> {
|
|
135
|
+
const request: PermissionRequest = {
|
|
136
|
+
toolCallId: event.toolCallId, title: event.tool, options: APPROVAL_OPTIONS.map(option => ({ ...option })),
|
|
137
|
+
tool: { name: event.tool, rawInput: event.arguments }, raw: event,
|
|
138
|
+
};
|
|
139
|
+
nativePermissionRequests.set(request, ticket);
|
|
140
|
+
const handler = handlers.onPermissionRequest;
|
|
141
|
+
const recording = handler && recordingPermissionHandlers.has(handler) ? handler : undefined;
|
|
142
|
+
const close = () => refuseNativeOnClose(ticket, cancelled.reason === nativeConversationStopping, () => log);
|
|
143
|
+
if (!recording) {
|
|
144
|
+
if (cancelled.aborted) close();
|
|
145
|
+
else cancelled.addEventListener("abort", close, { once: true });
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
if (recording) {
|
|
149
|
+
await recording(request, cancelled);
|
|
150
|
+
} else if (ticket.hostHandled) {
|
|
151
|
+
await ticket.resolution;
|
|
152
|
+
} else if (!cancelled.aborted) {
|
|
153
|
+
const signal = AbortSignal.any([cancelled, ticket.signal]);
|
|
154
|
+
if (signal.aborted) return;
|
|
155
|
+
const answer = handler ? await Promise.race([
|
|
156
|
+
Promise.resolve().then(() => handler.call(handlers, request, signal)),
|
|
157
|
+
ticket.resolution.then(result => result.outcome),
|
|
158
|
+
]) : deny;
|
|
159
|
+
if (!signal.aborted) await ticket.answer({ outcome: answer, by: handler ? "handler" : "default" });
|
|
160
|
+
}
|
|
161
|
+
} catch (error) {
|
|
162
|
+
log.warn("native_approval_handler_failed", { requestId: event.requestId, error: String(error) });
|
|
163
|
+
if (!ticket.hostHandled && !cancelled.aborted && !recording) {
|
|
164
|
+
await ticket.answer({ outcome: deny, by: "handler" }).catch(() => false);
|
|
165
|
+
}
|
|
166
|
+
} finally {
|
|
167
|
+
cancelled.removeEventListener("abort", close);
|
|
168
|
+
}
|
|
169
|
+
}
|