@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
package/src/agent.ts
CHANGED
|
@@ -1,7 +1,19 @@
|
|
|
1
|
+
import { createAgentReminderService, type ReminderService } from "./native/reminders/service.ts";
|
|
2
|
+
import { resolveProviderStart } from "./conversation-startup.ts";
|
|
3
|
+
import { withDelegationTools } from "./orchestrator/native-delegation.ts";
|
|
4
|
+
import { AcpWorkerDelivery } from "./orchestrator/acp-delivery.ts";
|
|
5
|
+
import { DurableWorkerAssignments } from "./orchestrator/durable-assignments.ts";
|
|
6
|
+
import { workerConsumerApi, type WorkerConsumerApi } from "./orchestrator/consumer-api.ts";
|
|
7
|
+
import { Orchestrator } from "./orchestrator/orchestrator.ts";
|
|
8
|
+
import { validateOrchestrator } from "./orchestrator/config.ts";
|
|
9
|
+
import { validatePermissionConsumerConfig } from "./permissions/consumer-config.ts";
|
|
10
|
+
import { inheritPermissionConfig, ownPermissions } from "./permissions/policy.ts";
|
|
1
11
|
import { randomUUID } from "node:crypto";
|
|
2
12
|
import {
|
|
3
13
|
type AgentSessionId,
|
|
4
14
|
} from "./agent-ids.ts";
|
|
15
|
+
import { NativeHarnessHost } from "./native/host.ts";
|
|
16
|
+
import { protectedChannels } from "./agent/native-channel-lifecycle.ts";
|
|
5
17
|
import {
|
|
6
18
|
AgentAdapterRegistry,
|
|
7
19
|
type AgentAdapterRegistration,
|
|
@@ -88,6 +100,7 @@ export type {
|
|
|
88
100
|
CreateAgentConversationConfig,
|
|
89
101
|
OpenAgentConversationConfig,
|
|
90
102
|
OpenOwnedAgentConversationResult,
|
|
103
|
+
ProviderStart,
|
|
91
104
|
} from "./agent/config.ts";
|
|
92
105
|
|
|
93
106
|
/** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
|
|
@@ -97,7 +110,17 @@ export class Agent {
|
|
|
97
110
|
readonly persistence: PersistenceBackend;
|
|
98
111
|
readonly identity: AgentIdentityRuntime;
|
|
99
112
|
readonly adapters: AgentAdapterRegistry;
|
|
113
|
+
/**
|
|
114
|
+
* The shared native harness host, when `harness` is configured: one process and one durable session
|
|
115
|
+
* for every native conversation of this Agent. Null otherwise.
|
|
116
|
+
*/
|
|
117
|
+
readonly nativeHarness: NativeHarnessHost | null;
|
|
118
|
+
readonly reminders: ReminderService;
|
|
100
119
|
readonly conversations: AgentConversationManager;
|
|
120
|
+
/** @internal Delegation routes use this pool. */
|
|
121
|
+
readonly orchestrator?: Orchestrator;
|
|
122
|
+
private readonly acpWorkerDelivery?: AcpWorkerDelivery;
|
|
123
|
+
readonly workers?: WorkerConsumerApi;
|
|
101
124
|
readonly internalInferences?: InternalInferenceManager;
|
|
102
125
|
readonly checkpointing?: ConversationCheckpointCoordinator;
|
|
103
126
|
readonly audit?: AgentAuditRuntime;
|
|
@@ -134,8 +157,23 @@ export class Agent {
|
|
|
134
157
|
) {
|
|
135
158
|
this.media = config.media ?? {};
|
|
136
159
|
this.id = id;
|
|
160
|
+
if (config.orchestrator) validateOrchestrator(config.orchestrator, persistence, resolveConversationRecordCapture(config.capture).message);
|
|
137
161
|
this.persistence = persistence;
|
|
138
162
|
this.adapters = adapters;
|
|
163
|
+
const channels = config.harness ? protectedChannels(persistence) : undefined;
|
|
164
|
+
this.nativeHarness = config.harness
|
|
165
|
+
? new NativeHarnessHost({
|
|
166
|
+
sessionId: id,
|
|
167
|
+
...config.harness,
|
|
168
|
+
...(config.orchestrator ? { functions: withDelegationTools(config.harness.functions, config.orchestrator,
|
|
169
|
+
() => this.orchestrator!, () => this.conversations) } : {}),
|
|
170
|
+
...(config.harness.launcher ?? config.conversationDefaults?.launcher
|
|
171
|
+
? { launcher: config.harness.launcher ?? config.conversationDefaults!.launcher }
|
|
172
|
+
: {}),
|
|
173
|
+
...(config.conversationDefaults?.logger ? { logger: config.conversationDefaults.logger } : {}),
|
|
174
|
+
}, channels, persistence.workerDelivery)
|
|
175
|
+
: null;
|
|
176
|
+
this.reminders = createAgentReminderService(this.nativeHarness, persistence, config.reminders, config.conversationDefaults?.logger);
|
|
139
177
|
this.audit = audit;
|
|
140
178
|
const logger = config.conversationDefaults?.logger ?? noopLogger;
|
|
141
179
|
this.eventBus = new CommittedRecordEventBus({
|
|
@@ -189,6 +227,7 @@ export class Agent {
|
|
|
189
227
|
...(config.conversationPersistence ? { conversationPersistence: config.conversationPersistence } : {}),
|
|
190
228
|
defaults: {
|
|
191
229
|
...config.conversationDefaults,
|
|
230
|
+
...inheritPermissionConfig(config, config.conversationDefaults),
|
|
192
231
|
...(config.operationLifecycle ? { operationLifecycle: config.operationLifecycle } : {}),
|
|
193
232
|
},
|
|
194
233
|
meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
|
|
@@ -203,6 +242,20 @@ export class Agent {
|
|
|
203
242
|
},
|
|
204
243
|
});
|
|
205
244
|
this.conversations = this.manager;
|
|
245
|
+
if (config.orchestrator) {
|
|
246
|
+
const workerOptions = config.orchestrator.workers;
|
|
247
|
+
const adapterId = workerOptions.adapterId ?? config.defaultAdapterId ?? adapters.list()[0]?.id;
|
|
248
|
+
if (!adapterId || adapters.native(adapterId)) throw new Error("orchestrator workers require an ACP adapter");
|
|
249
|
+
adapters.require(adapterId);
|
|
250
|
+
const acpDelivery = this.acpWorkerDelivery = new AcpWorkerDelivery(persistence.workerDelivery!,
|
|
251
|
+
(id, input, stableId) => this.manager.appendAssistantMessage(id, input, stableId), logger);
|
|
252
|
+
const assignments = new DurableWorkerAssignments(persistence, () => acpDelivery.flush(),
|
|
253
|
+
() => this.nativeHarness?.flushWorkerDelivery());
|
|
254
|
+
this.orchestrator = new Orchestrator(persistence.workers!, this.conversations, { ...workerOptions, adapterId,
|
|
255
|
+
defaultPermissions: config.orchestrator.defaults?.workerPermissions }, logger,
|
|
256
|
+
event => this.eventBus.publishWorker(event), assignments, id => this.manager.liveConversation(id));
|
|
257
|
+
this.workers = workerConsumerApi(this.orchestrator);
|
|
258
|
+
}
|
|
206
259
|
if (checkpointing?.enabled) {
|
|
207
260
|
// Checkpoints summarize stored messages, so `metadata` (messages with no text) would checkpoint nothing
|
|
208
261
|
// useful. `none` is allowed: a conversation that stores no messages has nothing to checkpoint, and the
|
|
@@ -316,6 +369,16 @@ export class Agent {
|
|
|
316
369
|
}
|
|
317
370
|
|
|
318
371
|
static async open(config: AgentConfig): Promise<Agent> {
|
|
372
|
+
validatePermissionConsumerConfig(config.conversationDefaults);
|
|
373
|
+
resolveProviderStart(config.conversationDefaults?.providerStart);
|
|
374
|
+
config = {
|
|
375
|
+
...config,
|
|
376
|
+
permissions: ownPermissions(config.permissions),
|
|
377
|
+
conversationDefaults: config.conversationDefaults && {
|
|
378
|
+
...config.conversationDefaults,
|
|
379
|
+
permissions: ownPermissions(config.conversationDefaults.permissions),
|
|
380
|
+
},
|
|
381
|
+
};
|
|
319
382
|
const auditLog = config.auditLog && resolveAgentAuditLogConfig(config.auditLog);
|
|
320
383
|
if (auditLog && config.persistence.kind === "custom") {
|
|
321
384
|
throw new PersistenceCapabilityError("auditOutbox");
|
|
@@ -326,6 +389,9 @@ export class Agent {
|
|
|
326
389
|
const adapters = new AgentAdapterRegistry(registrations);
|
|
327
390
|
if (adapters.list().length === 0) throw new Error("Agent requires at least one adapter");
|
|
328
391
|
if (config.defaultAdapterId) adapters.require(config.defaultAdapterId);
|
|
392
|
+
if (!config.harness && adapters.list().some((registration) => adapters.native(registration.id))) {
|
|
393
|
+
throw new Error("a native adapter requires AgentConfig.harness");
|
|
394
|
+
}
|
|
329
395
|
|
|
330
396
|
let persistence: PersistenceBackend;
|
|
331
397
|
let id: AgentSessionId;
|
|
@@ -378,6 +444,7 @@ export class Agent {
|
|
|
378
444
|
audit,
|
|
379
445
|
);
|
|
380
446
|
await agent.recordAgentAuditObservation("agent_lifecycle", "opened");
|
|
447
|
+
await agent.acpWorkerDelivery?.flush();
|
|
381
448
|
return agent;
|
|
382
449
|
} catch (error) {
|
|
383
450
|
await audit?.close().catch(() => undefined);
|
|
@@ -406,6 +473,8 @@ export class Agent {
|
|
|
406
473
|
async close(): Promise<void> {
|
|
407
474
|
if (this.closed) return;
|
|
408
475
|
this.closed = true;
|
|
476
|
+
this.nativeHarness?.closeReminderSupervisors();
|
|
477
|
+
this.manager.cancelStarts();
|
|
409
478
|
let shutdownError: unknown;
|
|
410
479
|
try {
|
|
411
480
|
this.checkpointing?.close();
|
|
@@ -414,7 +483,11 @@ export class Agent {
|
|
|
414
483
|
this.detachInternalInferenceAudit = undefined;
|
|
415
484
|
await this.auditObservationTail;
|
|
416
485
|
const observationError = this.auditObservationError;
|
|
486
|
+
await this.orchestrator?.close();
|
|
417
487
|
await this.manager.stopAll();
|
|
488
|
+
await this.orchestrator?.waitForCompletions();
|
|
489
|
+
await this.acpWorkerDelivery?.flush();
|
|
490
|
+
await this.nativeHarness?.stop();
|
|
418
491
|
// Every authorized shutdown write has finished; nothing may be observed after this.
|
|
419
492
|
this.eventBus.close();
|
|
420
493
|
await this.recordAgentAuditObservation("agent_lifecycle", "closed");
|
package/src/capabilities.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface Capabilities {
|
|
|
30
30
|
export interface ClientCapabilities {
|
|
31
31
|
fs: { readTextFile: boolean; writeTextFile: boolean };
|
|
32
32
|
terminal: boolean;
|
|
33
|
+
/** Extensions advertised to the agent: the JetBrains AIR session-failure capability (provider-notices.ts). */
|
|
34
|
+
_meta?: Record<string, unknown>;
|
|
33
35
|
}
|
|
34
36
|
|
|
35
37
|
export interface AgentCapabilities {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ProviderSessionReloadUnsupportedError } from "../errors.ts";
|
|
1
2
|
import type { AgentConversationId } from "../agent-ids.ts";
|
|
2
3
|
import type {
|
|
3
4
|
ConversationErrorRecoverability,
|
|
@@ -23,6 +24,8 @@ export function isMissingProviderSessionError(
|
|
|
23
24
|
error: unknown,
|
|
24
25
|
override?: (error: unknown) => boolean,
|
|
25
26
|
): boolean {
|
|
27
|
+
// Our own condition, not a provider's failure: a classifier written for provider errors isn't asked.
|
|
28
|
+
if (error instanceof ProviderSessionReloadUnsupportedError) return true;
|
|
26
29
|
if (override) return override(error);
|
|
27
30
|
const value = error as { code?: unknown; message?: unknown; data?: unknown } | null;
|
|
28
31
|
const message = typeof value?.message === "string" ? value.message : String(error);
|
package/src/cli/index.ts
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
// --wire=FILE : the same as ndjson in FILE (truncated per run) instead of stderr
|
|
26
26
|
|
|
27
27
|
import {
|
|
28
|
-
|
|
28
|
+
HarnessController,
|
|
29
29
|
createConsoleLogger,
|
|
30
30
|
createWireLog,
|
|
31
31
|
type Adapter,
|
|
@@ -116,14 +116,14 @@ async function chat(args: Args): Promise<void> {
|
|
|
116
116
|
displayName: args.adapterName,
|
|
117
117
|
});
|
|
118
118
|
const adapter: Adapter = resolved.adapter;
|
|
119
|
-
const controller = new
|
|
119
|
+
const controller = new HarnessController({
|
|
120
120
|
adapter,
|
|
121
121
|
adapterId: resolved.adapterId,
|
|
122
122
|
mode: args.degraded ? "degraded" : "normal",
|
|
123
123
|
execPrefix: args.execPrefix,
|
|
124
124
|
cwd: args.cwd,
|
|
125
125
|
sessionId: args.sessionId,
|
|
126
|
-
|
|
126
|
+
permissions: { default: args.approve ? "allow" : "ask" },
|
|
127
127
|
logger,
|
|
128
128
|
wire,
|
|
129
129
|
});
|
package/src/cli/managed.ts
CHANGED
|
@@ -139,7 +139,7 @@ export async function runManagedCliCommand(command: ManagedCliCommand, io: Manag
|
|
|
139
139
|
const adapter = resolveCliAdapter(command);
|
|
140
140
|
const pending = command.agentSessionId ? await manager.getSessionMaintenance(command.agentSessionId) : null;
|
|
141
141
|
if (pending && pending.kind !== "creation") throw new ManagedCliUsageError(`session has pending ${pending.kind} maintenance; complete it first`);
|
|
142
|
-
const session = await manager.createAgentSession({ adapter: adapter.adapter, adapterId: adapter.adapterId, ...(command.agentSessionId ? { agentSessionId: command.agentSessionId } : {}), ...(pending ? { creationId: pending.operationId } : {}), ...(command.cwd ? { cwd: command.cwd } : {}), ...(command.title ? { title: command.title } : {}), ...(command.execPrefix.length ? { execPrefix: [...command.execPrefix] } : {}),
|
|
142
|
+
const session = await manager.createAgentSession({ adapter: adapter.adapter, adapterId: adapter.adapterId, ...(command.agentSessionId ? { agentSessionId: command.agentSessionId } : {}), ...(pending ? { creationId: pending.operationId } : {}), ...(command.cwd ? { cwd: command.cwd } : {}), ...(command.title ? { title: command.title } : {}), ...(command.execPrefix.length ? { execPrefix: [...command.execPrefix] } : {}), permissions: { default: command.approve ? "allow" : "ask" }, persistence: { ...(command.transcript !== undefined ? { transcript: command.transcript } : {}), ...(command.auditLogPath ? { auditLog: { path: command.auditLogPath } } : {}) } });
|
|
143
143
|
out(`Created managed agent session ${session.agentSessionId}.\n`); await own(session, command, io); return;
|
|
144
144
|
}
|
|
145
145
|
if (command.kind === "open") {
|
|
@@ -177,7 +177,7 @@ interface Parsed {
|
|
|
177
177
|
}
|
|
178
178
|
const COMMANDS = new Set(["sessions", "info", "checkpoint", "maintenance", "create", "open", "restore", "reconfigure", "delete"]);
|
|
179
179
|
function live(v: Parsed): Live { return { root: v.root, ...(v.adapterId ? { adapterId: v.adapterId } : {}), ...(v.command ? { command: v.command } : {}), ...(v.ptyCommand ? { ptyCommand: v.ptyCommand } : {}), ...(v.displayName ? { displayName: v.displayName } : {}), ...(v.cwd ? { cwd: v.cwd } : {}), execPrefix: v.execPrefix, approve: v.approve, activity: v.activity, repl: v.repl }; }
|
|
180
|
-
function runtime(command: Live, adapter: ReturnType<typeof resolveCliAdapter>) { return { adapter: adapter.adapter, adapterId: adapter.adapterId, ...(command.cwd ? { cwd: command.cwd } : {}), ...(command.execPrefix.length ? { execPrefix: [...command.execPrefix] } : {}),
|
|
180
|
+
function runtime(command: Live, adapter: ReturnType<typeof resolveCliAdapter>) { return { adapter: adapter.adapter, adapterId: adapter.adapterId, ...(command.cwd ? { cwd: command.cwd } : {}), ...(command.execPrefix.length ? { execPrefix: [...command.execPrefix] } : {}), permissions: { default: command.approve ? "allow" as const : "ask" as const } }; }
|
|
181
181
|
function recordedAdapter(command: Live, row: AgentSessionSummary) { if (command.adapterId && command.adapterId !== row.adapterId && !command.command) throw new ManagedCliUsageError(`recorded adapter is ${row.adapterId}; changing adapters requires an explicit continuation strategy`); return resolveCliAdapter({ adapterId: command.adapterId ?? row.adapterId, command: command.command ? [...command.command] : undefined, ptyCommand: command.ptyCommand ? [...command.ptyCommand] : undefined, displayName: command.displayName }); }
|
|
182
182
|
async function own(session: AgentSession, command: Live, io: ManagedCliIo) { try { if (command.repl) io.runSession ? await io.runSession(session, { activity: command.activity }) : await runAgentSessionRepl(session, { activity: command.activity }); } finally { await session.stop(); } }
|
|
183
183
|
function reportOpen(opened: AgentSessionOpenResult, error: (s: string) => void) { error(`Continuation: ${opened.continuation.outcome.kind}; recovery: ${opened.recovery.kind}; configuration: ${opened.configuration.kind}; promptable: ${opened.promptability.promptable}.\n`); opened.repairs.forEach((repair) => error(`Persistence repair: ${JSON.stringify(repair)}\n`)); }
|
package/src/client.ts
CHANGED
|
@@ -9,7 +9,7 @@ import type { OutputListener, ProviderOutput } from "./operations/contracts.ts";
|
|
|
9
9
|
import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
|
10
10
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
11
11
|
import type { Adapter } from "./adapters.ts";
|
|
12
|
-
import { AcpTransport
|
|
12
|
+
import { AcpTransport } from "./transport/acp-transport.ts";
|
|
13
13
|
import { prepareLaunch, type AcpLauncher } from "./launcher.ts";
|
|
14
14
|
import {
|
|
15
15
|
parseCapabilities,
|
|
@@ -23,14 +23,16 @@ import { ResponseAccumulator } from "./response.ts";
|
|
|
23
23
|
import { normalizeTokenUsage } from "./metering/usage.ts";
|
|
24
24
|
import { TerminalRegistry } from "./terminals.ts";
|
|
25
25
|
import { readTextFile, writeTextFile } from "./fs-access.ts";
|
|
26
|
-
import { NotConnectedError } from "./errors.ts";
|
|
26
|
+
import { ConnectionCancelledError, NotConnectedError, ProcessCrashError } from "./errors.ts";
|
|
27
|
+
import { ConnectionAttempts, untilAborted } from "./connection-attempt.ts";
|
|
28
|
+
import { resolveClientHandlers, type ResolvedClientHandlers, type AcpClientHandlers } from "./acp-client-handlers.ts";
|
|
29
|
+
export type { AcpClientHandlers, FilesystemHandlers } from "./acp-client-handlers.ts";
|
|
27
30
|
import { noopLogger, type Logger } from "./logger.ts";
|
|
28
31
|
import type { AgentClient, InterruptOptions } from "./agent-client.ts";
|
|
29
32
|
import type {
|
|
30
33
|
ActivityEvent,
|
|
31
34
|
PromptResult,
|
|
32
35
|
PromptHandlers,
|
|
33
|
-
PermissionRequest,
|
|
34
36
|
PermissionOutcome,
|
|
35
37
|
Attachment,
|
|
36
38
|
SessionListPage,
|
|
@@ -43,8 +45,12 @@ import { resolveParts } from "./media/store.ts";
|
|
|
43
45
|
import { assertPartCapabilities, attachmentParts, partsToAcp } from "./media/acp.ts";
|
|
44
46
|
import { redactMedia } from "./media/redact.ts";
|
|
45
47
|
import type { ClientPrompt } from "./agent-client.ts";
|
|
48
|
+
import { answerPermissionLevel, ownPermissions, permissionLevel, recordingPermissionHandlers, type PermissionPolicyConfig } from "./permissions/policy.ts";
|
|
49
|
+
import { stampAcpPermission } from "./permissions/arrival.ts";
|
|
50
|
+
import { toPermissionRequest } from "./permissions/acp.ts";
|
|
51
|
+
import { AIR_CLIENT_CAPABILITY_META } from "./provider-notices.ts";
|
|
46
52
|
|
|
47
|
-
export interface AcpClientConfig {
|
|
53
|
+
export interface AcpClientConfig extends PermissionPolicyConfig {
|
|
48
54
|
/** How to launch the agent binary. */
|
|
49
55
|
adapter: Adapter;
|
|
50
56
|
/** Runtime-specific launcher for exact ACP/PTY host process preparation. */
|
|
@@ -64,8 +70,6 @@ export interface AcpClientConfig {
|
|
|
64
70
|
sessionId?: string;
|
|
65
71
|
/** Policy when config.sessionId cannot be loaded. Default "new" for compatibility. */
|
|
66
72
|
sessionLoadFailure?: SessionLoadFailure;
|
|
67
|
-
/** Fallback when a prompt has no onPermissionRequest handler. Default "cancel". */
|
|
68
|
-
defaultPermission?: "approve" | "cancel";
|
|
69
73
|
/** Identification sent in initialize. */
|
|
70
74
|
clientInfo?: { name: string; title?: string; version?: string };
|
|
71
75
|
/**
|
|
@@ -90,51 +94,6 @@ export interface AcpClientConfig {
|
|
|
90
94
|
wire?: (entry: WireEntry) => void;
|
|
91
95
|
}
|
|
92
96
|
|
|
93
|
-
export interface FilesystemHandlers {
|
|
94
|
-
readTextFile?: (
|
|
95
|
-
params: schema.ReadTextFileRequest,
|
|
96
|
-
) => Promise<schema.ReadTextFileResponse>;
|
|
97
|
-
writeTextFile?: (
|
|
98
|
-
params: schema.WriteTextFileRequest,
|
|
99
|
-
) => Promise<schema.WriteTextFileResponse>;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export interface AcpClientHandlers {
|
|
103
|
-
terminal?: TerminalHandlers | false;
|
|
104
|
-
filesystem?: FilesystemHandlers | false;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
interface ResolvedClientHandlers {
|
|
108
|
-
terminal: "builtin" | TerminalHandlers | false;
|
|
109
|
-
readTextFile: "builtin" | NonNullable<FilesystemHandlers["readTextFile"]> | false;
|
|
110
|
-
writeTextFile: "builtin" | NonNullable<FilesystemHandlers["writeTextFile"]> | false;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
function resolveClientHandlers(
|
|
114
|
-
handlers: AcpClientHandlers | undefined,
|
|
115
|
-
legacy: ClientCapabilityConfig | undefined,
|
|
116
|
-
): ResolvedClientHandlers {
|
|
117
|
-
const terminal = handlers?.terminal !== undefined
|
|
118
|
-
? handlers.terminal
|
|
119
|
-
: legacy?.terminal === false ? false : "builtin";
|
|
120
|
-
|
|
121
|
-
if (handlers?.filesystem === false) {
|
|
122
|
-
return { terminal, readTextFile: false, writeTextFile: false };
|
|
123
|
-
}
|
|
124
|
-
if (handlers?.filesystem) {
|
|
125
|
-
return {
|
|
126
|
-
terminal,
|
|
127
|
-
readTextFile: handlers.filesystem.readTextFile ?? false,
|
|
128
|
-
writeTextFile: handlers.filesystem.writeTextFile ?? false,
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
return {
|
|
132
|
-
terminal,
|
|
133
|
-
readTextFile: legacy?.fs?.readTextFile === false ? false : "builtin",
|
|
134
|
-
writeTextFile: legacy?.fs?.writeTextFile === false ? false : "builtin",
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
|
|
138
97
|
export interface StartSessionOptions {
|
|
139
98
|
additionalDirectories?: string[];
|
|
140
99
|
/** Resume this session. Defaults to config.sessionId. */
|
|
@@ -200,6 +159,7 @@ interface CommandTransition {
|
|
|
200
159
|
|
|
201
160
|
export class AcpClient implements AgentClient {
|
|
202
161
|
private transport: AcpTransport | null = null;
|
|
162
|
+
private readonly connections = new ConnectionAttempts<Capabilities>();
|
|
203
163
|
private _capabilities: Capabilities | null = null;
|
|
204
164
|
private _configOptions: ConfigOptions = new Map();
|
|
205
165
|
private _availableCommands: readonly InternalSessionCommand[] = Object.freeze([]);
|
|
@@ -251,6 +211,7 @@ export class AcpClient implements AgentClient {
|
|
|
251
211
|
private readonly handlers: ResolvedClientHandlers;
|
|
252
212
|
|
|
253
213
|
constructor(private config: AcpClientConfig) {
|
|
214
|
+
this.config = { ...config, permissions: ownPermissions(config.permissions) };
|
|
254
215
|
this.log = config.logger ?? noopLogger;
|
|
255
216
|
this.handlers = resolveClientHandlers(config.clientHandlers, config.clientCapabilities);
|
|
256
217
|
this.clientCapabilities = {
|
|
@@ -259,6 +220,9 @@ export class AcpClient implements AgentClient {
|
|
|
259
220
|
writeTextFile: this.handlers.writeTextFile !== false,
|
|
260
221
|
},
|
|
261
222
|
terminal: this.handlers.terminal !== false,
|
|
223
|
+
// Ask adapters that speak the AIR extension (codex-acp, claude-agent-acp) to report retries,
|
|
224
|
+
// warnings and failures as typed session failures; read in provider-notices.ts.
|
|
225
|
+
_meta: { ...AIR_CLIENT_CAPABILITY_META },
|
|
262
226
|
};
|
|
263
227
|
}
|
|
264
228
|
|
|
@@ -329,7 +293,6 @@ export class AcpClient implements AgentClient {
|
|
|
329
293
|
get currentSessionId(): string | null {
|
|
330
294
|
return this._sessionId;
|
|
331
295
|
}
|
|
332
|
-
/** True once connect() has spawned + initialized (a session may not exist yet). */
|
|
333
296
|
get isConnected(): boolean {
|
|
334
297
|
return this.transport?.isConnected ?? false;
|
|
335
298
|
}
|
|
@@ -345,10 +308,25 @@ export class AcpClient implements AgentClient {
|
|
|
345
308
|
* create a session — call startSession() (or just prompt(), which lazily starts one),
|
|
346
309
|
* or listSessions() to pick an existing one first.
|
|
347
310
|
*/
|
|
348
|
-
|
|
349
|
-
|
|
311
|
+
connect(): Promise<Capabilities> {
|
|
312
|
+
return this.connections.run("connect", ({ signal }) => this.initialize(signal));
|
|
313
|
+
}
|
|
350
314
|
|
|
351
|
-
|
|
315
|
+
private async initialize(signal: AbortSignal): Promise<Capabilities> {
|
|
316
|
+
await this.stopPromise;
|
|
317
|
+
signal.throwIfAborted();
|
|
318
|
+
if (this.transport?.isConnected) return this.capabilities;
|
|
319
|
+
|
|
320
|
+
const preparing = prepareLaunch("acp", this.config.launcher, this.config);
|
|
321
|
+
const launch = await untilAborted(preparing.then(async prepared => {
|
|
322
|
+
if (signal.aborted) await prepared.dispose?.();
|
|
323
|
+
signal.throwIfAborted();
|
|
324
|
+
return prepared;
|
|
325
|
+
}), signal);
|
|
326
|
+
if (signal.aborted) {
|
|
327
|
+
await launch.dispose?.();
|
|
328
|
+
signal.throwIfAborted();
|
|
329
|
+
}
|
|
352
330
|
const caps = this.clientCapabilities;
|
|
353
331
|
this.terminals = this.handlers.terminal === "builtin"
|
|
354
332
|
? new TerminalRegistry({
|
|
@@ -385,10 +363,12 @@ export class AcpClient implements AgentClient {
|
|
|
385
363
|
this.authStderrSink?.(line);
|
|
386
364
|
},
|
|
387
365
|
onDisconnect: () => {
|
|
366
|
+
if (this.transport !== transport) return;
|
|
388
367
|
this.cancelPendingPermissions();
|
|
389
368
|
this.notifyDisconnected();
|
|
390
369
|
},
|
|
391
370
|
onCrash: (code) => {
|
|
371
|
+
if (this.transport !== transport) return;
|
|
392
372
|
this.cancelPendingPermissions();
|
|
393
373
|
this.terminals?.releaseAll();
|
|
394
374
|
this.terminals = null;
|
|
@@ -402,8 +382,9 @@ export class AcpClient implements AgentClient {
|
|
|
402
382
|
});
|
|
403
383
|
try {
|
|
404
384
|
this.log.info("connect", { command: launch.command });
|
|
405
|
-
await transport.start();
|
|
406
385
|
this.transport = transport;
|
|
386
|
+
await transport.start();
|
|
387
|
+
signal.throwIfAborted();
|
|
407
388
|
|
|
408
389
|
const init = await transport.raceExit(
|
|
409
390
|
transport.initialize({
|
|
@@ -416,6 +397,8 @@ export class AcpClient implements AgentClient {
|
|
|
416
397
|
},
|
|
417
398
|
} as schema.InitializeRequest),
|
|
418
399
|
);
|
|
400
|
+
signal.throwIfAborted();
|
|
401
|
+
transport.throwIfClosed();
|
|
419
402
|
this._capabilities = parseCapabilities(init, caps);
|
|
420
403
|
this.log.info("initialized", {
|
|
421
404
|
agent: this._capabilities.agentInfo?.name,
|
|
@@ -425,7 +408,7 @@ export class AcpClient implements AgentClient {
|
|
|
425
408
|
this.log.debug("initialize_response", { response: init });
|
|
426
409
|
return this._capabilities;
|
|
427
410
|
} catch (error) {
|
|
428
|
-
this.transport = null;
|
|
411
|
+
if (this.transport === transport) this.transport = null;
|
|
429
412
|
await transport.stop().catch((cleanupError) => {
|
|
430
413
|
this.log.warn("launch_cleanup_failed", { error: String(cleanupError) });
|
|
431
414
|
});
|
|
@@ -459,6 +442,7 @@ export class AcpClient implements AgentClient {
|
|
|
459
442
|
sessionId = result.sessionId;
|
|
460
443
|
resumed = result.resumed;
|
|
461
444
|
} catch (err) {
|
|
445
|
+
if (err instanceof ConnectionCancelledError || err instanceof ProcessCrashError) throw err;
|
|
462
446
|
this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
|
|
463
447
|
if (loadFailure === "error") throw err;
|
|
464
448
|
sessionId = await this.newSessionInternal(transport, cwd, mcpServers, additionalDirectories);
|
|
@@ -499,6 +483,7 @@ export class AcpClient implements AgentClient {
|
|
|
499
483
|
mcpServers: options.mcpServers ?? [],
|
|
500
484
|
...this.additionalDirectoriesParam(options.additionalDirectories ?? this.config.additionalDirectories),
|
|
501
485
|
} as schema.LoadSessionRequest);
|
|
486
|
+
if (this.transport !== transport) throw new ConnectionCancelledError();
|
|
502
487
|
} catch (err) {
|
|
503
488
|
this.abortCommandTransition();
|
|
504
489
|
throw err;
|
|
@@ -693,6 +678,7 @@ export class AcpClient implements AgentClient {
|
|
|
693
678
|
mcpServers,
|
|
694
679
|
...this.additionalDirectoriesParam(additionalDirectories),
|
|
695
680
|
} as schema.NewSessionRequest);
|
|
681
|
+
if (this.transport !== transport) throw new ConnectionCancelledError();
|
|
696
682
|
} catch (err) {
|
|
697
683
|
this.abortCommandTransition();
|
|
698
684
|
throw err;
|
|
@@ -721,6 +707,7 @@ export class AcpClient implements AgentClient {
|
|
|
721
707
|
stop(): Promise<void> {
|
|
722
708
|
if (this.stopPromise) return this.stopPromise;
|
|
723
709
|
this.cancelPendingPermissions();
|
|
710
|
+
const connecting = this.connections.cancel();
|
|
724
711
|
const t = this.transport;
|
|
725
712
|
this.transport = null;
|
|
726
713
|
this._sessionId = null;
|
|
@@ -728,8 +715,9 @@ export class AcpClient implements AgentClient {
|
|
|
728
715
|
this.setAvailableCommands([]);
|
|
729
716
|
this.terminals?.releaseAll();
|
|
730
717
|
this.terminals = null;
|
|
731
|
-
|
|
732
|
-
|
|
718
|
+
if (t) this.notifyDisconnected();
|
|
719
|
+
const pending = Promise.all([connecting, t?.stop()]);
|
|
720
|
+
this.stopPromise = pending.then(() => undefined).finally(() => {
|
|
733
721
|
this.stopPromise = null;
|
|
734
722
|
this.log.info("stopped", {});
|
|
735
723
|
});
|
|
@@ -838,6 +826,7 @@ export class AcpClient implements AgentClient {
|
|
|
838
826
|
usage: usage.ok ? usage.usage : null,
|
|
839
827
|
};
|
|
840
828
|
} finally {
|
|
829
|
+
this.cancelPendingPermissions();
|
|
841
830
|
this.active = null;
|
|
842
831
|
}
|
|
843
832
|
}
|
|
@@ -970,9 +959,9 @@ export class AcpClient implements AgentClient {
|
|
|
970
959
|
private async handlePermission(
|
|
971
960
|
params: schema.RequestPermissionRequest,
|
|
972
961
|
): Promise<schema.RequestPermissionResponse> {
|
|
962
|
+
const request = stampAcpPermission(toPermissionRequest(params));
|
|
973
963
|
this.log.debug("permission_request", { request: params });
|
|
974
964
|
const handler = this.active?.handlers?.onPermissionRequest;
|
|
975
|
-
const request = toPermissionRequest(params);
|
|
976
965
|
|
|
977
966
|
const abort = new AbortController();
|
|
978
967
|
let cancel!: () => void;
|
|
@@ -992,7 +981,9 @@ export class AcpClient implements AgentClient {
|
|
|
992
981
|
cancelled,
|
|
993
982
|
Promise.resolve().then(() => {
|
|
994
983
|
if (abort.signal.aborted) return { outcome: "cancelled" as const };
|
|
995
|
-
|
|
984
|
+
if (handler && recordingPermissionHandlers.has(handler)) return handler(request, abort.signal);
|
|
985
|
+
return answerPermissionLevel(permissionLevel(request, this.config), request,
|
|
986
|
+
handler && (() => handler(request, abort.signal)));
|
|
996
987
|
}),
|
|
997
988
|
]);
|
|
998
989
|
} finally {
|
|
@@ -1007,23 +998,6 @@ export class AcpClient implements AgentClient {
|
|
|
1007
998
|
return { outcome: { outcome: "cancelled" } };
|
|
1008
999
|
}
|
|
1009
1000
|
|
|
1010
|
-
private defaultOutcome(request: PermissionRequest): PermissionOutcome {
|
|
1011
|
-
if ((this.config.defaultPermission ?? "cancel") !== "approve") return { outcome: "cancelled" };
|
|
1012
|
-
|
|
1013
|
-
// By KIND, never by position. Agents order their options differently and Claude leads
|
|
1014
|
-
// with reject, so taking `options[0]` auto-REFUSED every call it meant to approve.
|
|
1015
|
-
//
|
|
1016
|
-
// `allow_once` first is deliberate: `allow_always` writes a rule into the agent's own
|
|
1017
|
-
// settings that outlives this session, and an auto-approver must not quietly make
|
|
1018
|
-
// policy on the user's behalf. It is the fallback, never the preference.
|
|
1019
|
-
const allow =
|
|
1020
|
-
request.options.find((o) => o.kind === "allow_once") ??
|
|
1021
|
-
request.options.find((o) => o.kind === "allow_always");
|
|
1022
|
-
|
|
1023
|
-
// Nothing recognizable to approve: refuse rather than guess. Guessing is the bug above.
|
|
1024
|
-
return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
1001
|
private beginCommandTransition(): void {
|
|
1028
1002
|
// Session operations are serialized by their callers. Preserve the last snapshot so
|
|
1029
1003
|
// a failed load/new can roll back without leaving an unrelated empty command palette.
|
|
@@ -1074,19 +1048,3 @@ function sameAvailableCommands(
|
|
|
1074
1048
|
command.input?.hint === other.input?.hint;
|
|
1075
1049
|
});
|
|
1076
1050
|
}
|
|
1077
|
-
|
|
1078
|
-
function toPermissionRequest(
|
|
1079
|
-
params: schema.RequestPermissionRequest,
|
|
1080
|
-
): PermissionRequest {
|
|
1081
|
-
const p = params as Record<string, any>;
|
|
1082
|
-
return {
|
|
1083
|
-
toolCallId: p.toolCall?.toolCallId ?? "",
|
|
1084
|
-
title: p.toolCall?.title,
|
|
1085
|
-
options: (p.options ?? []).map((o: Record<string, any>) => ({
|
|
1086
|
-
optionId: o.optionId,
|
|
1087
|
-
name: o.name,
|
|
1088
|
-
kind: o.kind,
|
|
1089
|
-
})),
|
|
1090
|
-
raw: params,
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { ConnectionCancelledError } from "./errors.ts";
|
|
2
|
+
|
|
3
|
+
export class ConnectionAttempt<Progress = never> {
|
|
4
|
+
private readonly abort = new AbortController();
|
|
5
|
+
private readonly observers = new Set<(event: Progress) => void>();
|
|
6
|
+
private readonly progress: Progress[] = [];
|
|
7
|
+
private cleanup?: () => Promise<void>;
|
|
8
|
+
private cancellation?: ConnectionCancelledError;
|
|
9
|
+
|
|
10
|
+
get signal(): AbortSignal { return this.abort.signal; }
|
|
11
|
+
|
|
12
|
+
throwIfCancelled(): void {
|
|
13
|
+
if (this.cancellation) throw this.cancellation;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
own(cleanup: () => Promise<void>): void {
|
|
17
|
+
this.throwIfCancelled();
|
|
18
|
+
this.cleanup = cleanup;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async cancel(): Promise<void> {
|
|
22
|
+
this.cancellation ??= new ConnectionCancelledError();
|
|
23
|
+
this.abort.abort(this.cancellation);
|
|
24
|
+
await this.cleanup?.();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
observe(observer: (event: Progress) => void): void {
|
|
28
|
+
this.observers.add(observer);
|
|
29
|
+
for (const event of this.progress) {
|
|
30
|
+
if (this.signal.aborted) break;
|
|
31
|
+
observer(event);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
report(event: Progress): void {
|
|
36
|
+
this.progress.push(event);
|
|
37
|
+
for (const observer of [...this.observers]) {
|
|
38
|
+
if (this.signal.aborted) break;
|
|
39
|
+
observer(event);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Equivalent attempts share readiness. An incompatible request cancels and drains the candidate first. */
|
|
45
|
+
export class ConnectionAttempts<T, Progress = never> {
|
|
46
|
+
private active?: { key: string; attempt: ConnectionAttempt<Progress>; result: Promise<T> };
|
|
47
|
+
private teardown = Promise.resolve();
|
|
48
|
+
|
|
49
|
+
run(key: string, work: (attempt: ConnectionAttempt<Progress>) => Promise<T>, observer?: (event: Progress) => void): Promise<T> {
|
|
50
|
+
const active = this.active;
|
|
51
|
+
if (active?.key === key) {
|
|
52
|
+
if (observer) active.attempt.observe(observer);
|
|
53
|
+
return active.result;
|
|
54
|
+
}
|
|
55
|
+
void this.cancel().catch(() => undefined);
|
|
56
|
+
const prior = this.teardown;
|
|
57
|
+
const attempt = new ConnectionAttempt<Progress>();
|
|
58
|
+
if (observer) attempt.observe(observer);
|
|
59
|
+
const result = prior.then(() => {
|
|
60
|
+
attempt.throwIfCancelled();
|
|
61
|
+
return work(attempt);
|
|
62
|
+
}).then(value => {
|
|
63
|
+
attempt.throwIfCancelled();
|
|
64
|
+
return value;
|
|
65
|
+
}, error => {
|
|
66
|
+
// A stopped attempt owns its public outcome, regardless of how the leaf unwinds.
|
|
67
|
+
attempt.throwIfCancelled();
|
|
68
|
+
throw error;
|
|
69
|
+
}).finally(() => {
|
|
70
|
+
if (this.active?.attempt === attempt) this.active = undefined;
|
|
71
|
+
});
|
|
72
|
+
this.active = { key, attempt, result };
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
cancel(): Promise<void> {
|
|
77
|
+
const active = this.active;
|
|
78
|
+
if (!active) return this.teardown;
|
|
79
|
+
this.active = undefined;
|
|
80
|
+
const teardown = Promise.all([this.teardown, active.attempt.cancel()]).then(() => undefined);
|
|
81
|
+
this.teardown = teardown.catch(() => undefined);
|
|
82
|
+
return teardown;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Observe the original promise even if its result loses the race. */
|
|
87
|
+
export function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
const abort = () => reject(signal.reason);
|
|
90
|
+
if (signal.aborted) abort();
|
|
91
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
92
|
+
const release = () => signal.removeEventListener("abort", abort);
|
|
93
|
+
void work.then(value => { release(); resolve(value); }, error => { release(); reject(error); });
|
|
94
|
+
});
|
|
95
|
+
}
|