@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,133 @@
|
|
|
1
|
+
import type { ToolDefinition } from "./loop.ts";
|
|
2
|
+
|
|
3
|
+
/** Decision 0021. How a catalog entry can change while the session is open.
|
|
4
|
+
* `fixed`: declared at open; no runtime operation removes it.
|
|
5
|
+
* `revocable`: declared at open; its grant can be revoked and restored, and
|
|
6
|
+
* that choice is stored with the session.
|
|
7
|
+
* `runtime`: enabled and removed by name; the enabled set lives in memory and
|
|
8
|
+
* the consumer supplies it again when it reconnects. */
|
|
9
|
+
export type ToolGroup = "fixed" | "revocable" | "runtime";
|
|
10
|
+
|
|
11
|
+
/** One consumer function offered to the model. Data only: `handler` names an
|
|
12
|
+
* implementation the consumer serves at runtime. Definitions are supplied on
|
|
13
|
+
* every open and never stored. The tool name also identifies policy rules. */
|
|
14
|
+
export interface ToolRegistration extends ToolDefinition {
|
|
15
|
+
handler: string;
|
|
16
|
+
group: ToolGroup;
|
|
17
|
+
/** Execution deadline from dispatch, in milliseconds. Absent: the session
|
|
18
|
+
* default, and without one no wall-clock deadline. */
|
|
19
|
+
deadlineMs?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Supplied with `session/create` and `session/open`. */
|
|
23
|
+
export interface ToolCatalogInput {
|
|
24
|
+
catalog: ToolRegistration[];
|
|
25
|
+
/** Runtime entries enabled from the start. */
|
|
26
|
+
enabled?: string[];
|
|
27
|
+
defaultDeadlineMs?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Availability, reported apart from policy so a consumer can tell why a tool
|
|
31
|
+
* cannot run. A fixed entry is still subject to its handler being served. */
|
|
32
|
+
export interface ToolAvailability {
|
|
33
|
+
name: string;
|
|
34
|
+
group: ToolGroup | "builtin";
|
|
35
|
+
handler?: string;
|
|
36
|
+
available: boolean;
|
|
37
|
+
reason?: "revoked" | "not_enabled" | "handler_missing";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Recorded with a tool result. Absent on results written before decision
|
|
41
|
+
* 0021 and on built-in tools: read as `succeeded`. */
|
|
42
|
+
export interface ToolOutcome {
|
|
43
|
+
/** `skipped`: never dispatched. `interrupted`: the wait ended after
|
|
44
|
+
* dispatch without an authoritative result; the effect is unknown. */
|
|
45
|
+
status: "succeeded" | "failed" | "skipped" | "interrupted";
|
|
46
|
+
/** Stable reason for anything but success, e.g. `policy_denied`,
|
|
47
|
+
* `tool_unavailable`, `invalid_arguments`, `tool_timeout`. */
|
|
48
|
+
code?: string;
|
|
49
|
+
/** The full result is held by its producer; the model saw a preview. */
|
|
50
|
+
reference?: ResultReference;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** An opaque handle to bytes held by the process that produced them. Bound by
|
|
54
|
+
* the harness to the producing session, channel and invocation. The producer
|
|
55
|
+
* owns retention and declares it here. */
|
|
56
|
+
export interface ResultReference {
|
|
57
|
+
resultId: string;
|
|
58
|
+
bytes: number;
|
|
59
|
+
/** `temporary` results can expire (`expiresAt`, UTC) and do not survive the
|
|
60
|
+
* producer's restart unless it says `durable`. */
|
|
61
|
+
retention: "temporary" | "durable";
|
|
62
|
+
expiresAt?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type ToolInvocationState = "requested" | "waiting_for_approval" | "started"
|
|
66
|
+
| "succeeded" | "failed" | "skipped" | "interrupted";
|
|
67
|
+
|
|
68
|
+
/** One requested call, derived from committed records plus, while live, the
|
|
69
|
+
* approval it waits on. `invocationId` is `<turnId>:<toolCallId>`. */
|
|
70
|
+
export interface ToolInvocation {
|
|
71
|
+
invocationId: string;
|
|
72
|
+
channel: string;
|
|
73
|
+
turnId: string;
|
|
74
|
+
/** The provider's ID, which pairs the result with the model response. */
|
|
75
|
+
toolCallId: string;
|
|
76
|
+
tool: string;
|
|
77
|
+
/** The original JSON text. */
|
|
78
|
+
arguments: string;
|
|
79
|
+
state: ToolInvocationState;
|
|
80
|
+
code?: string;
|
|
81
|
+
/** `unknown`: dispatched with no authoritative outcome. The harness never
|
|
82
|
+
* repeats such a call. `none`: it never dispatched. */
|
|
83
|
+
effect?: "none" | "unknown";
|
|
84
|
+
reference?: ResultReference;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** What the turn is doing now, with the ID of the model call, approval request
|
|
88
|
+
* or invocation it concerns. Process state: absent after a reopen until the
|
|
89
|
+
* turn does something. */
|
|
90
|
+
export interface TurnPhase {
|
|
91
|
+
kind: "model" | "approval" | "tool";
|
|
92
|
+
/** UTC time the phase began. */
|
|
93
|
+
since: string;
|
|
94
|
+
id?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** `functions/call` parameters. Sent only after dispatch evidence committed. */
|
|
98
|
+
export interface FunctionCall {
|
|
99
|
+
invocationId: string;
|
|
100
|
+
sessionId: string;
|
|
101
|
+
channel: string;
|
|
102
|
+
turnId: string;
|
|
103
|
+
tool: string;
|
|
104
|
+
handler: string;
|
|
105
|
+
/** Deduplicated configured policy names frozen at authorization, including
|
|
106
|
+
* inherited notice policies. Order grants no precedence. The internal
|
|
107
|
+
* __legacy_allow fallback is omitted. An empty list means none contributed. */
|
|
108
|
+
policyNames: string[];
|
|
109
|
+
/** Parsed and validated against the tool's `parameters`. */
|
|
110
|
+
arguments: Record<string, unknown>;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A handler's answer: structured output inline, or a preview with a reference
|
|
114
|
+
* to bytes it stored itself. An error is a typed failure, not a thrown call. */
|
|
115
|
+
export type FunctionResult =
|
|
116
|
+
| { output: unknown; preview?: never; reference?: never }
|
|
117
|
+
| { output?: never; preview: string; reference: ResultReference };
|
|
118
|
+
|
|
119
|
+
/** `results/read` parameters and result. The harness has already checked that
|
|
120
|
+
* `channel` produced `resultId`; the host serves bytes it holds. */
|
|
121
|
+
export interface ResultRead { resultId: string; invocationId: string; channel: string; offset: number; length: number }
|
|
122
|
+
export interface ResultPage { text: string; eof: boolean; totalBytes: number }
|
|
123
|
+
|
|
124
|
+
/** Runs one authorized catalog call somewhere outside the harness. Resolves
|
|
125
|
+
* with the handler's answer; rejects with `{ code, message }` for a typed
|
|
126
|
+
* error. Aborting `signal` requests cancellation and ends the wait. */
|
|
127
|
+
export interface FunctionExecutor {
|
|
128
|
+
call(request: FunctionCall, signal: AbortSignal): Promise<FunctionResult>;
|
|
129
|
+
read(request: ResultRead, signal: AbortSignal): Promise<ResultPage>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Adjustable defaults (BUSINESS_RULES.md). */
|
|
133
|
+
export interface ToolLimits { inlineBytes: number; previewBytes: number; readBytes: number }
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { ApprovalAnswer, ApprovalCloseReason, ApprovalRequest, ToolDecision } from "../../contracts/config-permissions.ts";
|
|
3
|
+
import type { ToolCall } from "../../contracts/loop.ts";
|
|
4
|
+
import type { ToolOutcome } from "../../contracts/tools.ts";
|
|
5
|
+
|
|
6
|
+
type ClosedCode = ApprovalCloseReason;
|
|
7
|
+
type Answer = { allowed: true } | { allowed: false; content: string };
|
|
8
|
+
type Entry = { request: ApprovalRequest; granted: boolean; closed: boolean; resolve(answer: Answer): void;
|
|
9
|
+
reject(error: unknown): void; recordError?: unknown; close(code: ClosedCode): string; cleanup(): void; clearTimer(): void };
|
|
10
|
+
/** The paired result of a call that was not dispatched. The message tells the
|
|
11
|
+
* model what it can do about it (decision 0021). */
|
|
12
|
+
export const skipped = (code: string, detail?: string) => JSON.stringify({ ok: false, code, message: code === "approval_cancelled_by_suspension"
|
|
13
|
+
? "The tool did not run because the session or channel suspended; after resume request the action again if needed."
|
|
14
|
+
: code === "invalid_arguments" ? `The tool did not run because its arguments are invalid: ${detail ?? "they do not match the tool's schema"}. Correct them and call it again.`
|
|
15
|
+
: code === "tool_unavailable" ? `The tool did not run because it is not available${detail ? ` (${detail})` : ""}. Do not call it again unless it is offered.`
|
|
16
|
+
: `The tool did not run (${code}).` });
|
|
17
|
+
|
|
18
|
+
/** Requests and unused grants belong to one session's active consumer. Close
|
|
19
|
+
* callbacks record the paired result synchronously before lifecycle termination. */
|
|
20
|
+
export function createApprovalService(publish: (request: ApprovalRequest) => void, timeoutMs = 600_000, publishClosed?: (request: ApprovalRequest, reason: ClosedCode | "dispatched") => void) {
|
|
21
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Approval timeout must be positive");
|
|
22
|
+
let consumer = false;
|
|
23
|
+
const pending = new Map<string, Entry>();
|
|
24
|
+
function close(entry: Entry, code: ClosedCode) { if (!entry.closed) entry.close(code); }
|
|
25
|
+
return {
|
|
26
|
+
setConsumer(enabled: boolean) { if (!enabled) this.disconnect(); else consumer = true; },
|
|
27
|
+
disconnect() { consumer = false; for (const entry of [...pending.values()]) close(entry, "approval_disconnected"); },
|
|
28
|
+
/** Decision 0021: the requests still waiting for an answer. */
|
|
29
|
+
waiting(): ApprovalRequest[] { return [...pending.values()].filter(entry => !entry.closed && !entry.granted).map(entry => entry.request); },
|
|
30
|
+
/** Decision 0021: a tool that became unavailable cannot be approved any more.
|
|
31
|
+
* Closes its open requests with the one paired skipped result. An answer
|
|
32
|
+
* already given is caught by the gate's check after approval. */
|
|
33
|
+
closeTool(tool: string) { for (const entry of [...pending.values()]) if (entry.request.tool === tool && !entry.granted) close(entry, "tool_unavailable"); },
|
|
34
|
+
respond(id: string, answer: ApprovalAnswer) {
|
|
35
|
+
const entry = pending.get(id);
|
|
36
|
+
if (!entry || entry.closed || entry.granted || (answer !== "allow_once" && answer !== "deny")) return false;
|
|
37
|
+
if (answer === "deny") { close(entry, "approval_denied"); return true; }
|
|
38
|
+
entry.granted = true; entry.clearTimer(); entry.resolve({ allowed: true }); return true;
|
|
39
|
+
},
|
|
40
|
+
/** Register before publishing, so even a synchronous consumer can answer. */
|
|
41
|
+
request(request: ApprovalRequest, signal: AbortSignal, suspension: AbortSignal, record: (content: string, code: string) => void) {
|
|
42
|
+
if (!consumer) { const content = skipped("approval_unhandled"); record(content, "approval_unhandled"); return { answer: Promise.resolve({ allowed: false as const, content }), consume: () => false, discard: (_code?: ClosedCode) => false, dispatchClosed: () => {}, dispatchFailed: () => {} }; }
|
|
43
|
+
let settle!: (answer: Answer) => void, reject!: (error: unknown) => void;
|
|
44
|
+
const answer = new Promise<Answer>((resolve, fail) => { settle = resolve; reject = fail; });
|
|
45
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
46
|
+
const onSuspend = () => close(entry, "approval_cancelled_by_suspension");
|
|
47
|
+
const onAbort = () => close(entry, signal.reason?.approvalCloseCode === "approval_cancelled_by_stop"
|
|
48
|
+
? "approval_cancelled_by_stop" : "approval_cancelled_by_interrupt");
|
|
49
|
+
const cleanup = () => { clearTimeout(timer); signal.removeEventListener("abort", onAbort); suspension.removeEventListener("abort", onSuspend); pending.delete(request.requestId); };
|
|
50
|
+
let announced = false;
|
|
51
|
+
const announceClose = (reason: ClosedCode | "dispatched") => {
|
|
52
|
+
if (announced) { announced = false; publishClosed?.(request, reason); }
|
|
53
|
+
};
|
|
54
|
+
const entry: Entry = { request, granted: false, closed: false, resolve: settle, reject, cleanup, clearTimer: () => clearTimeout(timer),
|
|
55
|
+
close(code) {
|
|
56
|
+
entry.closed = true; cleanup(); const content = skipped(code);
|
|
57
|
+
try { record(content, code); } catch (error) { entry.recordError = error; reject(error); announceClose(code); return content; }
|
|
58
|
+
settle({ allowed: false, content }); announceClose(code); return content;
|
|
59
|
+
} };
|
|
60
|
+
pending.set(request.requestId, entry);
|
|
61
|
+
signal.addEventListener("abort", onAbort, { once: true }); suspension.addEventListener("abort", onSuspend, { once: true });
|
|
62
|
+
timer = setTimeout(() => close(entry, "approval_timeout"), timeoutMs);
|
|
63
|
+
if (signal.aborted) onAbort(); else if (suspension.aborted) onSuspend(); else { announced = true; publish(request); }
|
|
64
|
+
return { answer, consume() { if (entry.recordError !== undefined) throw entry.recordError; if (entry.closed || !entry.granted) return false; entry.closed = true; cleanup(); return true; },
|
|
65
|
+
dispatchClosed() { announceClose("dispatched"); },
|
|
66
|
+
dispatchFailed() { announceClose("approval_cancelled_by_interrupt"); },
|
|
67
|
+
discard(code: ClosedCode = "approval_cancelled_by_interrupt") {
|
|
68
|
+
if (entry.closed) return false;
|
|
69
|
+
entry.closed = true;
|
|
70
|
+
cleanup();
|
|
71
|
+
announceClose(code);
|
|
72
|
+
return true;
|
|
73
|
+
} };
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Policy is read before authorization from items already taken by this
|
|
79
|
+
* turn. The synchronous span after the final signal checks is the linearization
|
|
80
|
+
* point: durable evidence, invocation, started event, then await the promise. */
|
|
81
|
+
export async function dispatchWithPolicy(options: {
|
|
82
|
+
decide(): ToolDecision; channel: string; turnId: number; call: ToolCall;
|
|
83
|
+
signal: AbortSignal; suspension: AbortSignal; approvals: ReturnType<typeof createApprovalService>;
|
|
84
|
+
/** May resolve with an outcome to record beside the result (decision 0021). */
|
|
85
|
+
execute: import("../../contracts/loop.ts").ExecuteTurnTool;
|
|
86
|
+
recordSkip(content: string, code: string): void; mark(): void; started(): void; beforeDispatch?: () => Promise<void>;
|
|
87
|
+
/** Decision 0021: a reason this call cannot be dispatched (not offered, not
|
|
88
|
+
* available, invalid arguments), or undefined. Read before authorization
|
|
89
|
+
* and again at the dispatch boundary. Policy denial retains precedence. */
|
|
90
|
+
refuse?(): { code: string; detail?: string } | undefined;
|
|
91
|
+
}): Promise<{ content: string; dispatched: boolean; outcome?: ToolOutcome }> {
|
|
92
|
+
const { call, signal, suspension } = options;
|
|
93
|
+
const skip = (code: string, detail?: string) => { const content = skipped(code, detail); options.recordSkip(content, code); return { content, dispatched: false }; };
|
|
94
|
+
signal.throwIfAborted();
|
|
95
|
+
const refused = options.refuse?.();
|
|
96
|
+
const rule = options.decide();
|
|
97
|
+
if (rule === "deny") return skip("policy_denied");
|
|
98
|
+
if (refused) return skip(refused.code, refused.detail);
|
|
99
|
+
let request: ReturnType<typeof options.approvals.request> | undefined;
|
|
100
|
+
if (rule === "ask") {
|
|
101
|
+
if (suspension.aborted) return skip("approval_cancelled_by_suspension");
|
|
102
|
+
request = options.approvals.request({ requestId: randomUUID(), channel: options.channel, turnId: String(options.turnId),
|
|
103
|
+
toolCallId: call.id, tool: call.name, arguments: call.arguments }, signal, suspension, options.recordSkip);
|
|
104
|
+
const answer = await request.answer;
|
|
105
|
+
if (!answer.allowed) return { content: answer.content, dispatched: false };
|
|
106
|
+
}
|
|
107
|
+
try { if (options.beforeDispatch) await options.beforeDispatch(); signal.throwIfAborted(); }
|
|
108
|
+
catch (error) { request?.discard(); throw error; }
|
|
109
|
+
if (rule === "ask" && suspension.aborted) {
|
|
110
|
+
// The signal's listener already recorded the one paired cancellation.
|
|
111
|
+
return { content: skipped("approval_cancelled_by_suspension"), dispatched: false };
|
|
112
|
+
}
|
|
113
|
+
// Revocation or removal before dispatch prevents execution even after an
|
|
114
|
+
// approval was given: the grant is discarded and the one paired result says why.
|
|
115
|
+
const late = options.refuse?.();
|
|
116
|
+
if (late) {
|
|
117
|
+
if (request && !request.discard("tool_unavailable")) return { content: "", dispatched: false };
|
|
118
|
+
return skip(late.code, late.detail);
|
|
119
|
+
}
|
|
120
|
+
if (request && !request.consume()) return { content: "", dispatched: false };
|
|
121
|
+
try { options.mark(); } catch (error) { request?.dispatchFailed(); throw error; }
|
|
122
|
+
let result: ReturnType<typeof options.execute>;
|
|
123
|
+
try { result = options.execute(call, signal); }
|
|
124
|
+
catch (error) { options.started(); request?.dispatchClosed(); throw error; }
|
|
125
|
+
options.started();
|
|
126
|
+
request?.dispatchClosed();
|
|
127
|
+
const settled = await result;
|
|
128
|
+
return typeof settled === "string" ? { content: settled, dispatched: true } : { content: settled.content, dispatched: true, outcome: settled.outcome };
|
|
129
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ManagedConfig, ToolDecision } from "../../contracts/config-permissions.ts";
|
|
2
|
+
|
|
3
|
+
export class PolicyError extends Error {
|
|
4
|
+
readonly code = "invalid_policy";
|
|
5
|
+
constructor(readonly policy: string) { super(`Unknown policy: ${policy}`); }
|
|
6
|
+
}
|
|
7
|
+
export function resolvePolicy(config: ManagedConfig, explicit?: string | null, channel?: string | null): string {
|
|
8
|
+
const selected = explicit ?? channel ?? config.defaultPolicy;
|
|
9
|
+
if (!Object.hasOwn(config.policies, selected)) throw new PolicyError(selected);
|
|
10
|
+
return selected;
|
|
11
|
+
}
|
|
12
|
+
/** A taken input contributes all its policy names; no pending input is passed. */
|
|
13
|
+
export function toolDecision(config: ManagedConfig, references: readonly string[], tool: string): ToolDecision {
|
|
14
|
+
if (!references.length) throw new Error("Cannot authorize a turn without taken-input policies");
|
|
15
|
+
let result: ToolDecision = "allow";
|
|
16
|
+
for (const reference of new Set(references)) {
|
|
17
|
+
if (!Object.hasOwn(config.policies, reference)) throw new PolicyError(reference);
|
|
18
|
+
const policy = config.policies[reference]!;
|
|
19
|
+
const next = Object.hasOwn(policy.tools, tool) ? policy.tools[tool]! : policy.fallback;
|
|
20
|
+
if (next === "deny") return "deny";
|
|
21
|
+
if (next === "ask") result = "ask";
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
/** Stable comparison independent of insertion order. */
|
|
26
|
+
export function policyFingerprint(config: ManagedConfig, references: readonly string[]): string {
|
|
27
|
+
return JSON.stringify([...new Set(references)].sort().map(name => {
|
|
28
|
+
if (!Object.hasOwn(config.policies, name)) throw new PolicyError(name);
|
|
29
|
+
const policy = config.policies[name]!;
|
|
30
|
+
return [name, policy.fallback, Object.keys(policy.tools).sort().map(tool => [tool, policy.tools[tool]])];
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { executeReminderTool, isReminderTool, reminderAction, reminderDefinitions } from "./capabilities/tools/reminders/index.ts";
|
|
2
|
+
import { createReminderRuntime } from "./runtime/reminders.ts";
|
|
3
|
+
import { wallReminderClock } from "./runtime/reminder-timer.ts";
|
|
4
|
+
import type { ReminderSessionEvent } from "./contracts/reminders.ts";
|
|
5
|
+
import { isTimelineTool } from "./util/timeline-tool-names.ts";
|
|
6
|
+
import { runTimelineTool, timelineArgumentsProblem, timelineDefinitions } from "./capabilities/tools/timeline/index.ts";
|
|
7
|
+
import { messagePosition } from "./util/message-position.ts";
|
|
8
|
+
import { executeNotice, notifyChannelDefinition } from "./capabilities/tools/builtin/notify-channel.ts";
|
|
9
|
+
import type { PersistentSession, PersistentSessionOptions } from "./contracts/session.ts";
|
|
10
|
+
import type { SessionAgent, TurnExecutor } from "./contracts/agent.ts";
|
|
11
|
+
import type { EventSink, SessionEventSink } from "./contracts/events.ts";
|
|
12
|
+
import type { SessionStorage } from "./contracts/storage.ts";
|
|
13
|
+
import { createMemoryStorageAdapter } from "./state/storage/memory.ts";
|
|
14
|
+
import { CONTEXT_LIMITS, createSessionContext } from "./capabilities/context/session.ts";
|
|
15
|
+
import { createChannelScheduler } from "./kernel/channels.ts";
|
|
16
|
+
import { runTurn } from "./kernel/loop.ts";
|
|
17
|
+
import { ModelCallError, runModelCall } from "./capabilities/model/runner.ts";
|
|
18
|
+
import { getModelAttempt } from "./capabilities/model/attempt.ts";
|
|
19
|
+
import { createApprovalService, dispatchWithPolicy } from "./governance/permissions/gate.ts";
|
|
20
|
+
import { toolDecision } from "./governance/policy/resolve.ts";
|
|
21
|
+
import type { Message, ToolDefinition } from "./contracts/loop.ts";
|
|
22
|
+
import type { ControlResult, ToolControls } from "./contracts/session.ts";
|
|
23
|
+
import type { FunctionExecutor, ToolAvailability, TurnPhase } from "./contracts/tools.ts";
|
|
24
|
+
import { READ_TOOL_RESULT, createToolCatalog, readToolResultDefinition } from "./capabilities/tools/runtime/catalog.ts";
|
|
25
|
+
import { CallbackLost, TOOL_LIMITS, readResult, runFunction } from "./capabilities/tools/runtime/functions.ts";
|
|
26
|
+
import { findInvocation, invocationId, turnInvocations } from "./capabilities/tools/runtime/invocations.ts";
|
|
27
|
+
import { schemaProblem } from "./util/schema.ts";
|
|
28
|
+
|
|
29
|
+
function fanout<T>() {
|
|
30
|
+
const listeners = new Set<(value: T) => void>();
|
|
31
|
+
return {
|
|
32
|
+
publish(value: T) {
|
|
33
|
+
for (const listener of listeners) {
|
|
34
|
+
try { listener(structuredClone(value)); } catch { /* A consumer cannot fail agent execution. */ }
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
subscribe(listener: (value: T) => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Assemble execution over storage without starting listeners, reading input,
|
|
42
|
+
* requiring keys or running anything: call `start` (or `resume`) to execute.
|
|
43
|
+
* Without `storage` the session lives in memory and ends with the process. */
|
|
44
|
+
export function createSession(options: Omit<PersistentSessionOptions, "storage"> & { storage?: SessionStorage }): PersistentSession {
|
|
45
|
+
let storage = options.storage;
|
|
46
|
+
if (!storage) {
|
|
47
|
+
const opened = createMemoryStorageAdapter().open({ mode: "create", identity: { sessionId: "memory", compatibilityKey: "" }, config: options.config });
|
|
48
|
+
if (!opened.ok) throw new Error(opened.error.message);
|
|
49
|
+
storage = opened.value;
|
|
50
|
+
}
|
|
51
|
+
const store = storage;
|
|
52
|
+
const owner = store.ownerConfig();
|
|
53
|
+
if (!owner.ok) throw new Error(`Cannot read storage owner config (${owner.error.code}): ${owner.error.message}`);
|
|
54
|
+
// Compare by value, ignoring insertion order. Never retain the assertion object:
|
|
55
|
+
// the gate uses only the defensive snapshot returned by the owner.
|
|
56
|
+
const canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item)
|
|
57
|
+
? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
|
|
58
|
+
if (options.config !== undefined && (owner.value === undefined || canonical(options.config) !== canonical(owner.value)))
|
|
59
|
+
throw new Error("Session config does not match the storage owner config");
|
|
60
|
+
if (owner.value !== undefined && options.systemPrompt !== owner.value.system)
|
|
61
|
+
throw new Error("Session system prompt does not match the storage owner config");
|
|
62
|
+
const events = fanout<Parameters<EventSink>[0]>(), lifecycle = fanout<Parameters<SessionEventSink>[0]>(), changes = fanout<void>();
|
|
63
|
+
const read = () => { const view = store.snapshot(); if (!view.ok) throw new Error(view.error.message); return view.value; };
|
|
64
|
+
// Every published event follows a commit, so it is also the moment the
|
|
65
|
+
// timeline projection may have changed.
|
|
66
|
+
const identity = store.readSession();
|
|
67
|
+
if (!identity.ok) throw new Error(identity.error.message);
|
|
68
|
+
const context = createSessionContext(store, identity.value.sessionId, options.systemPrompt, CONTEXT_LIMITS, options.captureContext);
|
|
69
|
+
const limitError = () => Object.assign(new Error("Required inference material exceeds the context budget"), { outcome: "context_limit" });
|
|
70
|
+
const position = (channel: string, seq: string) => messagePosition(identity.value.sessionId, channel, Number(seq));
|
|
71
|
+
const emit: EventSink = value => {
|
|
72
|
+
const { channel, event } = value;
|
|
73
|
+
if ((event.type === "turn_started" || event.type === "turn_took") && event.messages)
|
|
74
|
+
value = { ...value, event: { ...event, messages: event.messages.map(message => ({ ...message, position: position(channel, message.position) })) } };
|
|
75
|
+
changes.publish();
|
|
76
|
+
events.publish(value);
|
|
77
|
+
};
|
|
78
|
+
const config = owner.value ?? { version: 1 as const, system: options.systemPrompt, model: { protocol: "scripted" as const, script: "legacy" },
|
|
79
|
+
defaultPolicy: "__legacy_allow", policies: { __legacy_allow: { fallback: "allow" as const, tools: {} } } };
|
|
80
|
+
// ---- Tools, decision 0021. The catalog's definitions come from the open;
|
|
81
|
+
// the revoked set mirrors storage; the executor belongs to the connection.
|
|
82
|
+
const revoked = options.catalog ? store.readRevokedTools() : undefined;
|
|
83
|
+
if (revoked && !revoked.ok) throw new Error(revoked.error.message);
|
|
84
|
+
if (options.catalog?.catalog.some(tool => isTimelineTool(tool.name) || isReminderTool(tool.name))) throw new Error("Native tool names are reserved");
|
|
85
|
+
const catalog = options.catalog ? createToolCatalog(options.catalog, revoked?.value ?? []) : undefined;
|
|
86
|
+
const limits = { ...TOOL_LIMITS, ...options.toolLimits };
|
|
87
|
+
let executor: FunctionExecutor | undefined;
|
|
88
|
+
/** What each running turn is doing now. Process state, cleared when the turn's run ends. */
|
|
89
|
+
const phases = new Map<number, TurnPhase>();
|
|
90
|
+
const phase = (turnId: number, kind: TurnPhase["kind"], id?: string) => phases.set(turnId, { kind, since: new Date().toISOString(), ...(id === undefined ? {} : { id }) });
|
|
91
|
+
const approvals = createApprovalService(request => {
|
|
92
|
+
phase(Number(request.turnId), "approval", request.requestId);
|
|
93
|
+
emit({ channel: request.channel, event: { type: "approval_requested", ...request } });
|
|
94
|
+
}, options.approvalTimeoutMs, (request, reason) => emit({ channel: request.channel, event: { type: "approval_closed", turnId: request.turnId, requestId: request.requestId, reason } }));
|
|
95
|
+
let agent: SessionAgent;
|
|
96
|
+
const run: TurnExecutor = (turn, port) => {
|
|
97
|
+
const services = options.configureTurn(turn, notice => agent.notify({ ...notice, fromChannelId: turn.channelId, sourceTurnId: turn.turnId }));
|
|
98
|
+
const policySnapshot = () => {
|
|
99
|
+
const read = store.readInferencePolicies(turn.turnId, CONTEXT_LIMITS);
|
|
100
|
+
if (!read.ok) throw new Error(read.error.message);
|
|
101
|
+
if ("code" in read.value) throw limitError();
|
|
102
|
+
return read.value;
|
|
103
|
+
};
|
|
104
|
+
/** The names offered by this turn's latest inference: what a call must match. */
|
|
105
|
+
let offered = new Set<string>();
|
|
106
|
+
/** One snapshot per inference: built-ins and available catalog entries the
|
|
107
|
+
* turn's policy does not deny, the stable group first. The model call runner
|
|
108
|
+
* freezes it, so a retry of the request offers the same list. */
|
|
109
|
+
const offer = (policies: readonly string[]): { tools: ToolDefinition[]; fixedToolCount?: number } => {
|
|
110
|
+
const allowed = <T extends ToolDefinition>(tools: readonly T[]) => tools.filter(tool => toolDecision(config, policies, tool.name) !== "deny");
|
|
111
|
+
const definition = ({ name, description, parameters }: ToolDefinition): ToolDefinition => ({ name, description, parameters });
|
|
112
|
+
const builtins = allowed([...services.tools.filter(tool => tool.name !== "notify_channel" && !isTimelineTool(tool.name) && !isReminderTool(tool.name)), notifyChannelDefinition, ...reminderDefinitions,
|
|
113
|
+
...((owner.value === undefined ? options.timelineTools : config.timelineTools) ? timelineDefinitions : [])]);
|
|
114
|
+
if (!catalog) { offered = new Set(builtins.map(tool => tool.name)); return { tools: [...builtins] }; }
|
|
115
|
+
const available = catalog.offered();
|
|
116
|
+
const fixed = [...builtins, ...allowed(available.fixed).map(definition), ...allowed([readToolResultDefinition])];
|
|
117
|
+
const tools = [...fixed, ...allowed(available.changeable).map(definition)];
|
|
118
|
+
offered = new Set(tools.map(tool => tool.name));
|
|
119
|
+
return { tools, fixedToolCount: fixed.length };
|
|
120
|
+
};
|
|
121
|
+
/** The latest commit of this turn; `failedResult` names the call whose
|
|
122
|
+
* paired result recorded a typed failure (its event reports that commit). */
|
|
123
|
+
let recorded: { seq: number; revision: number; failedResult?: string } | undefined;
|
|
124
|
+
const append = (message: Message) => {
|
|
125
|
+
if (message.role !== "assistant" && message.role !== "tool") throw new Error("Only assistant and tool messages are recorded by a turn");
|
|
126
|
+
const entry = store.appendMessage(turn.turnId, message);
|
|
127
|
+
if (!entry.ok) throw new Error(`${entry.error.code}: ${entry.error.message}`);
|
|
128
|
+
recorded = { seq: entry.value.seq, revision: entry.revision,
|
|
129
|
+
...(message.role === "tool" && message.outcome?.status === "failed" ? { failedResult: message.callId } : {}) };
|
|
130
|
+
changes.publish();
|
|
131
|
+
};
|
|
132
|
+
return runTurn({
|
|
133
|
+
signal: port.signal, drainNotices: port.take, finish: port.finish, checkpoint: port.checkpoint, confirm: port.confirm,
|
|
134
|
+
append,
|
|
135
|
+
dispatchTool(call, execute) {
|
|
136
|
+
const registration = catalog?.get(call.name), reader = !!catalog && call.name === READ_TOOL_RESULT;
|
|
137
|
+
const retrieval = isTimelineTool(call.name), reminder = isReminderTool(call.name);
|
|
138
|
+
const action = reminder ? reminderAction(call.name, JSON.parse(call.arguments)) : undefined;
|
|
139
|
+
const id = invocationId(turn.turnId, call.id);
|
|
140
|
+
let policies: readonly string[];
|
|
141
|
+
return dispatchWithPolicy({ channel: turn.channelId, turnId: turn.turnId, call,
|
|
142
|
+
signal: port.signal, suspension: port.suspensionSignal, approvals, beforeDispatch: options.beforeToolDispatch,
|
|
143
|
+
decide: () => toolDecision(config, policies = policySnapshot(), call.name),
|
|
144
|
+
// Catalog tools and the reader must have been offered by this request,
|
|
145
|
+
// still be available, and carry arguments their definition accepts.
|
|
146
|
+
...(registration || reader || retrieval || reminder ? { refuse: () => {
|
|
147
|
+
if (!offered.has(call.name)) return { code: "tool_unavailable", detail: "it was not offered for this request" };
|
|
148
|
+
if (reminder) return action ? undefined : { code: "invalid_arguments", detail: "Invalid reminder arguments" };
|
|
149
|
+
if (retrieval) {
|
|
150
|
+
const detail = timelineArgumentsProblem(call.name, JSON.parse(call.arguments));
|
|
151
|
+
return detail ? { code: "invalid_arguments", detail } : undefined;
|
|
152
|
+
}
|
|
153
|
+
if (!registration) return undefined;
|
|
154
|
+
const why = catalog!.unavailable(call.name);
|
|
155
|
+
if (why) return { code: "tool_unavailable", detail: why.replace("_", " ") };
|
|
156
|
+
const problem = schemaProblem(registration.parameters, JSON.parse(call.arguments));
|
|
157
|
+
return problem ? { code: "invalid_arguments", detail: problem } : undefined;
|
|
158
|
+
} } : {}),
|
|
159
|
+
execute: reminder ? async () => {
|
|
160
|
+
if (!action) throw new Error("Invalid reminder arguments");
|
|
161
|
+
return executeReminderTool(store, action, turn.channelId, turn.turnId, id, policies, reminderClock.now(),
|
|
162
|
+
(event, revision) => emit({ channel: turn.channelId, event, revision }));
|
|
163
|
+
} : retrieval ? async (_call, signal) => runTimelineTool(store, call.name, JSON.parse(call.arguments), signal) : registration ? (_call, signal) => {
|
|
164
|
+
// Dispatch evidence is committed. From here the effect is the host's.
|
|
165
|
+
if (!executor) throw new CallbackLost("No connection serves this tool's handler");
|
|
166
|
+
return runFunction({ executor, registration, limits, signal: signal ?? port.signal, defaultDeadlineMs: catalog!.defaultDeadlineMs,
|
|
167
|
+
request: { invocationId: id, sessionId: identity.value.sessionId, channel: turn.channelId, turnId: String(turn.turnId),
|
|
168
|
+
tool: call.name, handler: registration.handler, policyNames: policies.filter(name => name !== "__legacy_allow"), arguments: JSON.parse(call.arguments) } });
|
|
169
|
+
} : reader ? (_call, signal) => readResult({ executor, view: read(), channel: turn.channelId, arguments: call.arguments, limits, signal: signal ?? port.signal })
|
|
170
|
+
: call.name === "notify_channel" ? async () => {
|
|
171
|
+
try { return JSON.stringify(executeNotice(JSON.parse(call.arguments), (channelId, text) =>
|
|
172
|
+
agent.notify({ channelId, text, fromChannelId: turn.channelId, sourceTurnId: turn.turnId }))); }
|
|
173
|
+
catch (error) { return JSON.stringify({ ok: false, error: String(error) }); }
|
|
174
|
+
} : execute,
|
|
175
|
+
recordSkip: (content, code) => {
|
|
176
|
+
append({ role: "tool", callId: call.id, content, outcome: { status: "skipped", code } });
|
|
177
|
+
// Built-in tools keep their event stream as it was: a skip is silent.
|
|
178
|
+
if (registration || reader || retrieval || reminder) emit({ channel: turn.channelId, ...(recorded ? { revision: recorded.revision } : {}),
|
|
179
|
+
event: { type: "tool_call", turnId: String(turn.turnId), id: call.id, name: call.name, status: "skipped", output: content, invocationId: id } });
|
|
180
|
+
},
|
|
181
|
+
mark: () => {
|
|
182
|
+
const result = store.markToolDispatched(turn.turnId, call.id); if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
|
|
183
|
+
phase(turn.turnId, "tool", id);
|
|
184
|
+
},
|
|
185
|
+
started: () => emit({ channel: turn.channelId, event: { type: "tool_call", turnId: String(turn.turnId), id: call.id, name: call.name, status: "started", input: call.arguments, invocationId: id } }) });
|
|
186
|
+
},
|
|
187
|
+
emit(event) {
|
|
188
|
+
// Completed messages and results were committed by the append just
|
|
189
|
+
// before; a tool start or failure reports no commit of its own.
|
|
190
|
+
const committed = event.type === "message_completed" || (event.type === "tool_call" && (event.status === "completed" || event.status === "interrupted" || (event.status === "failed" && recorded?.failedResult === event.id)));
|
|
191
|
+
emit({ channel: turn.channelId, ...(committed && recorded ? { revision: recorded.revision } : {}),
|
|
192
|
+
event: { ...event, turnId: String(turn.turnId),
|
|
193
|
+
...(event.type === "tool_call" ? { invocationId: invocationId(turn.turnId, event.id) } : {}),
|
|
194
|
+
...(event.type === "message_completed" && recorded ? { messageId: String(recorded.seq) } : {}) } });
|
|
195
|
+
},
|
|
196
|
+
}, async signal => {
|
|
197
|
+
const built = context.build(turn, offer);
|
|
198
|
+
if (!built.ok) throw limitError();
|
|
199
|
+
const { tools, fixedToolCount, messages, takenItemIds, representedItemIds: itemIds } = built.value;
|
|
200
|
+
phase(turn.turnId, "model");
|
|
201
|
+
const binding = getModelAttempt(services.model);
|
|
202
|
+
let draftId: string | undefined;
|
|
203
|
+
try {
|
|
204
|
+
const result = await runModelCall({ turnId: String(turn.turnId), itemIds, request: { messages, tools, takenItemIds, ...(fixedToolCount === undefined ? {} : { fixedToolCount }) },
|
|
205
|
+
started: callId => {
|
|
206
|
+
phase(turn.turnId, "model", callId);
|
|
207
|
+
try { options.observeModelCall?.(turn.channelId, turn.turnId, callId); } catch { /* best-effort observation */ }
|
|
208
|
+
},
|
|
209
|
+
scripted: binding.scripted, store, attempt: binding.create, signal, settings: binding.settings,
|
|
210
|
+
delta: ({ messageId, text }) => { draftId = messageId; emit({ channel: turn.channelId,
|
|
211
|
+
event: { type: "text_delta", turnId: String(turn.turnId), messageId, text } }); },
|
|
212
|
+
incomplete: ({ messageId, reason }) => emit({ channel: turn.channelId,
|
|
213
|
+
event: { type: "text_incomplete", turnId: String(turn.turnId), messageId, reason } }),
|
|
214
|
+
receipt: (milestone, items, revision) => emit({ channel: turn.channelId, revision,
|
|
215
|
+
event: { type: "items_receipt", turnId: String(turn.turnId), items, milestone } }),
|
|
216
|
+
});
|
|
217
|
+
recorded = { seq: result.entry.seq, revision: result.revision }; changes.publish();
|
|
218
|
+
if (result.response.content) emit({ channel: turn.channelId, revision: result.revision,
|
|
219
|
+
event: { type: "message_completed", turnId: String(turn.turnId), messageId: result.messageId, position: position(turn.channelId, String(result.entry.seq)),
|
|
220
|
+
parts: [{ type: "text", text: result.response.content }] } });
|
|
221
|
+
return result.response;
|
|
222
|
+
} catch (error) {
|
|
223
|
+
// A storage failure can occur after a draft was published but before the
|
|
224
|
+
// runner can write a normal terminal outcome. The draft must still end.
|
|
225
|
+
if (error instanceof ModelCallError && error.message === "script_exhausted") throw Object.assign(new Error(error.message), { outcome: "script_exhausted" });
|
|
226
|
+
if (draftId && !(error instanceof ModelCallError)) emit({ channel: turn.channelId,
|
|
227
|
+
event: { type: "text_incomplete", turnId: String(turn.turnId), messageId: draftId, reason: "failed" } });
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
}, services.executeTool).finally(() => { phases.delete(turn.turnId); });
|
|
231
|
+
};
|
|
232
|
+
const scheduler = createChannelScheduler(store, options.wrapTurn?.(run) ?? run, emit, lifecycle.publish, CONTEXT_LIMITS);
|
|
233
|
+
agent = scheduler.agent;
|
|
234
|
+
/** Status with each running turn's phase, which only this process knows. */
|
|
235
|
+
const status = () => {
|
|
236
|
+
const current = scheduler.status();
|
|
237
|
+
for (const channel of current.channels) {
|
|
238
|
+
const now = channel.activeTurn?.status === "running" ? phases.get(channel.activeTurn.turnId) : undefined;
|
|
239
|
+
if (now) channel.activeTurn = { ...channel.activeTurn!, phase: { ...now } };
|
|
240
|
+
}
|
|
241
|
+
return current;
|
|
242
|
+
};
|
|
243
|
+
const tools = catalog && toolControls();
|
|
244
|
+
function toolControls(): ToolControls {
|
|
245
|
+
const book = catalog!;
|
|
246
|
+
const waiting = () => new Set(approvals.waiting().map(request => invocationId(request.turnId, request.toolCallId)));
|
|
247
|
+
/** A tool that just became unavailable cannot be approved any more. */
|
|
248
|
+
const closeUnavailable = () => { for (const entry of book.entries) if (book.unavailable(entry.name)) approvals.closeTool(entry.name); };
|
|
249
|
+
const change = (name: string, group: "revocable" | "runtime", act: () => number): ControlResult<ToolAvailability> => {
|
|
250
|
+
const entry = book.get(name);
|
|
251
|
+
if (!entry) return { ok: false, error: { code: "not_found", message: `Unknown tool: ${String(name)}` } };
|
|
252
|
+
if (entry.group !== group) return { ok: false, error: { code: "invalid_state", message: `Tool ${name} is ${entry.group}; this operation needs a ${group} tool` } };
|
|
253
|
+
let revision: number;
|
|
254
|
+
try { revision = act(); } catch (error) { return { ok: false, error: { code: "storage_failure", message: String(error) } }; }
|
|
255
|
+
closeUnavailable();
|
|
256
|
+
return { ok: true, value: book.availability(entry), revision };
|
|
257
|
+
};
|
|
258
|
+
const persist = (name: string, revoked: boolean) => {
|
|
259
|
+
const result = store.setToolRevoked(name, revoked);
|
|
260
|
+
if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
|
|
261
|
+
book.setRevoked(result.value);
|
|
262
|
+
return result.revision;
|
|
263
|
+
};
|
|
264
|
+
return {
|
|
265
|
+
list: () => [...book.entries.map(entry => book.availability(entry)), { name: READ_TOOL_RESULT, group: "builtin", available: true }],
|
|
266
|
+
serve(handlers, next) { book.serve(handlers); executor = next; closeUnavailable(); },
|
|
267
|
+
revoke: name => change(name, "revocable", () => persist(name, true)),
|
|
268
|
+
restore: name => change(name, "revocable", () => persist(name, false)),
|
|
269
|
+
enable: name => change(name, "runtime", () => { book.setEnabled(name, true); return read().revision; }),
|
|
270
|
+
remove: name => change(name, "runtime", () => { book.setEnabled(name, false); return read().revision; }),
|
|
271
|
+
invocation: id => findInvocation(read(), id, waiting()),
|
|
272
|
+
invocations: turnId => turnInvocations(read(), turnId, waiting()),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
const reminderClock = options.reminderClock ?? wallReminderClock;
|
|
276
|
+
const reminderWakeEvents = fanout<ReminderSessionEvent>();
|
|
277
|
+
const reminderExecutable = () => {
|
|
278
|
+
if (stopped) return false;
|
|
279
|
+
const result = store.executionCompatible();
|
|
280
|
+
return result.ok && result.value;
|
|
281
|
+
};
|
|
282
|
+
let stopped = false;
|
|
283
|
+
let startupProcessed = false;
|
|
284
|
+
const reminderRuntime = createReminderRuntime(store, reminderClock, reminderExecutable,
|
|
285
|
+
(channel, event, revision) => emit({ channel, event, revision }),
|
|
286
|
+
reminderWakeEvents.publish, scheduler.wakeCommittedChannel);
|
|
287
|
+
const stop = (reason: string) => {
|
|
288
|
+
stopped = true;
|
|
289
|
+
reminderRuntime.stop();
|
|
290
|
+
return scheduler.stop(reason);
|
|
291
|
+
};
|
|
292
|
+
changes.subscribe(() => reminderRuntime.refresh());
|
|
293
|
+
function processStartup() { if (!startupProcessed) { startupProcessed = true; reminderRuntime.process(); } }
|
|
294
|
+
return {
|
|
295
|
+
...(tools ? { tools } : {}),
|
|
296
|
+
reminders: {
|
|
297
|
+
readReminder: id => store.readReminder(id), listReminders: params => store.listReminders(params),
|
|
298
|
+
reminderWake: () => store.reminderWake(), change: change => reminderRuntime.change(change),
|
|
299
|
+
executable: reminderExecutable, processStartup, releaseTimer: reminderRuntime.stop, subscribeWake: reminderWakeEvents.subscribe,
|
|
300
|
+
conditionalStop(windowMs) {
|
|
301
|
+
if (status().execution === "working" || !scheduler.agent.idle() || (approvals.waiting?.().length ?? 0) > 0) return { stopped: false, reason: "busy" };
|
|
302
|
+
const wake = store.reminderWake();
|
|
303
|
+
if (!wake.ok) throw new Error(wake.error.message);
|
|
304
|
+
if (wake.value.nextDueAt !== null && Date.parse(wake.value.nextDueAt) <= reminderClock.now() + windowMs)
|
|
305
|
+
return { stopped: false, reason: "next_due_soon" };
|
|
306
|
+
stop("Stopped by the host");
|
|
307
|
+
return { stopped: true };
|
|
308
|
+
},
|
|
309
|
+
},
|
|
310
|
+
agent, channels: scheduler.channels, approvals, operatorReads: store, readModelCalls: (after, limit) => store.readCalls(after, limit), turnPhase: id => phases.get(id),
|
|
311
|
+
store: { snapshot: () => read().timeline, subscribe: listener => changes.subscribe(listener) },
|
|
312
|
+
snapshot: read, status,
|
|
313
|
+
start() { processStartup(); scheduler.start(); reminderRuntime.start(); },
|
|
314
|
+
suspend: scheduler.suspend, resume: scheduler.resume, stop,
|
|
315
|
+
subscribe: events.subscribe, subscribeSession: lifecycle.subscribe,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
export type { PersistentSession, PersistentSessionOptions } from "./contracts/session.ts";
|