@qlairoslabs/acp-client 0.12.1 → 0.13.1-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.
Files changed (288) hide show
  1. package/CHANGELOG-consumer-fixes.md +17 -10
  2. package/CHANGELOG-controller-interface.md +258 -0
  3. package/CHANGELOG-metering.md +29 -0
  4. package/CHANGELOG-operation-lifecycle.md +15 -1
  5. package/CONSUMER_GUIDE.md +984 -6
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +288 -0
  8. package/README.md +17 -16
  9. package/package.json +11 -2
  10. package/src/acp-client-handlers.ts +48 -0
  11. package/src/activity.ts +3 -0
  12. package/src/adapters.ts +25 -0
  13. package/src/agent/adoption/provider-attachment.ts +33 -0
  14. package/src/agent/adoption/provider-session-delete.ts +1 -1
  15. package/src/agent/adoption/provider-sessions.ts +3 -2
  16. package/src/agent/append-assistant-message.ts +91 -0
  17. package/src/agent/config.ts +54 -6
  18. package/src/agent/conversation-manager.ts +95 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/native-operations.ts +39 -0
  22. package/src/agent/persisted-lifecycle.ts +44 -4
  23. package/src/agent/persistence-policy/context.ts +13 -0
  24. package/src/agent/persistence-policy/resolver.ts +7 -0
  25. package/src/agent/persistence-policy/types.ts +1 -0
  26. package/src/agent/record-capture.ts +1 -0
  27. package/src/agent-adapter-registry.ts +33 -7
  28. package/src/agent-conversation-contracts.ts +14 -1
  29. package/src/agent-conversation-errors.ts +8 -0
  30. package/src/agent-conversation-owner.ts +9 -4
  31. package/src/agent-session-config.ts +137 -0
  32. package/src/agent-session.ts +440 -934
  33. package/src/agent.ts +168 -0
  34. package/src/capabilities.ts +2 -0
  35. package/src/checkpointing/recovery.ts +3 -0
  36. package/src/cli/index.ts +3 -3
  37. package/src/cli/managed.ts +2 -2
  38. package/src/client.ts +56 -96
  39. package/src/connection-attempt.ts +95 -0
  40. package/src/controller-connection.ts +115 -0
  41. package/src/controller.ts +158 -148
  42. package/src/conversation-controller/capabilities.ts +88 -0
  43. package/src/conversation-controller/contracts.ts +208 -0
  44. package/src/conversation-controller/factory.ts +39 -0
  45. package/src/conversation-controller/guards.ts +98 -0
  46. package/src/conversation-controller/index.ts +20 -0
  47. package/src/conversation-startup.ts +35 -0
  48. package/src/conversation-turns/backend-turns.ts +373 -0
  49. package/src/conversation-turns/clear-operations.ts +37 -0
  50. package/src/conversation-turns/context.ts +135 -0
  51. package/src/conversation-turns/index.ts +4 -0
  52. package/src/conversation-turns/record-helpers.ts +75 -0
  53. package/src/conversation-turns/recording.ts +235 -0
  54. package/src/conversation-turns/run-turn.ts +367 -0
  55. package/src/conversation-turns/turn-run.ts +57 -0
  56. package/src/errors.ts +41 -0
  57. package/src/handoff-options.ts +81 -0
  58. package/src/identity/checkpoint-backed.ts +1 -1
  59. package/src/index.ts +59 -3
  60. package/src/internal-inference/coordination/manager.ts +11 -0
  61. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  62. package/src/launcher.ts +37 -2
  63. package/src/media/parts.ts +5 -0
  64. package/src/message-status.ts +83 -0
  65. package/src/metering/engine.ts +39 -64
  66. package/src/metering/measurement-provenance.ts +36 -0
  67. package/src/metering/native/durability.ts +115 -0
  68. package/src/metering/native/ledger.ts +104 -0
  69. package/src/metering/native/operation.ts +85 -0
  70. package/src/metering/native/projection.ts +114 -0
  71. package/src/metering/native/proof.ts +51 -0
  72. package/src/metering/native/requirements.ts +10 -0
  73. package/src/metering/native/retirement.ts +92 -0
  74. package/src/metering/native/source.ts +90 -0
  75. package/src/metering/record.ts +38 -1
  76. package/src/metering/state.ts +13 -3
  77. package/src/native/approvals.ts +186 -0
  78. package/src/native/capabilities.ts +17 -0
  79. package/src/native/channel-changes.ts +211 -0
  80. package/src/native/connection.ts +56 -0
  81. package/src/native/controller.ts +592 -0
  82. package/src/native/delegation-sender.ts +26 -0
  83. package/src/native/errors.ts +35 -0
  84. package/src/native/functions.ts +156 -0
  85. package/src/native/host-config.ts +59 -0
  86. package/src/native/host.ts +978 -0
  87. package/src/native/item-receipts.ts +15 -0
  88. package/src/native/metering.ts +12 -0
  89. package/src/native/records.ts +166 -0
  90. package/src/native/recovery.ts +186 -0
  91. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  92. package/src/native/reminders/idle.ts +70 -0
  93. package/src/native/reminders/limits.ts +19 -0
  94. package/src/native/reminders/notifications.ts +29 -0
  95. package/src/native/reminders/routine-guard.ts +66 -0
  96. package/src/native/reminders/routine-schedule.ts +25 -0
  97. package/src/native/reminders/routine-wire.ts +21 -0
  98. package/src/native/reminders/schedule.ts +97 -0
  99. package/src/native/reminders/service.ts +280 -0
  100. package/src/native/reminders/supervisor.ts +91 -0
  101. package/src/native/reminders/sync.ts +301 -0
  102. package/src/native/reminders/wire.ts +197 -0
  103. package/src/native/submission-withdrawal.ts +65 -0
  104. package/src/native/usage.ts +15 -0
  105. package/src/native/worker-delivery.ts +61 -0
  106. package/src/native-harness/README.md +726 -0
  107. package/src/native-harness/package.json +24 -0
  108. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  109. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  110. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  111. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  112. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  113. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  114. package/src/native-harness/src/capabilities/context/session.ts +93 -0
  115. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  116. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  117. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  118. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  119. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  120. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  121. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  122. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  123. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  124. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  125. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  126. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  127. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  128. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  129. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  130. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  131. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  132. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  133. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  134. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  135. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  136. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  137. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  138. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  139. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  140. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  141. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  142. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  143. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  144. package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
  145. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  146. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  147. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  148. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  149. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  150. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  151. package/src/native-harness/src/client.ts +18 -0
  152. package/src/native-harness/src/contracts/agent.ts +105 -0
  153. package/src/native-harness/src/contracts/config-permissions.ts +49 -0
  154. package/src/native-harness/src/contracts/context.ts +112 -0
  155. package/src/native-harness/src/contracts/events.ts +47 -0
  156. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  157. package/src/native-harness/src/contracts/inspection.ts +22 -0
  158. package/src/native-harness/src/contracts/loop.ts +31 -0
  159. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  160. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  161. package/src/native-harness/src/contracts/output.ts +13 -0
  162. package/src/native-harness/src/contracts/protocol.ts +320 -0
  163. package/src/native-harness/src/contracts/reminders.ts +134 -0
  164. package/src/native-harness/src/contracts/routines.ts +20 -0
  165. package/src/native-harness/src/contracts/scenario.ts +42 -0
  166. package/src/native-harness/src/contracts/session-file.ts +20 -0
  167. package/src/native-harness/src/contracts/session.ts +184 -0
  168. package/src/native-harness/src/contracts/storage.ts +597 -0
  169. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  170. package/src/native-harness/src/contracts/tools.ts +133 -0
  171. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  172. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  173. package/src/native-harness/src/index.ts +322 -0
  174. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  175. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  176. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  177. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  178. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  179. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  180. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  181. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  182. package/src/native-harness/src/interfaces/client.ts +225 -0
  183. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  184. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  185. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  186. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  187. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  188. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  189. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  190. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  191. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  192. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  193. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  194. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  195. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  196. package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
  197. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
  198. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  199. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  200. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  201. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  202. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  203. package/src/native-harness/src/kernel/channels.ts +409 -0
  204. package/src/native-harness/src/kernel/loop.ts +45 -0
  205. package/src/native-harness/src/runtime/config/development.ts +23 -0
  206. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  207. package/src/native-harness/src/runtime/config/paths.ts +33 -0
  208. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  209. package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
  210. package/src/native-harness/src/runtime/reminders.ts +66 -0
  211. package/src/native-harness/src/state/storage/archive.ts +257 -0
  212. package/src/native-harness/src/state/storage/engine.ts +1204 -0
  213. package/src/native-harness/src/state/storage/inference.ts +124 -0
  214. package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
  215. package/src/native-harness/src/state/storage/memory.ts +354 -0
  216. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  217. package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
  218. package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
  219. package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
  220. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  221. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  222. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  223. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  224. package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
  225. package/src/native-harness/src/state/storage/sqlite.ts +632 -0
  226. package/src/native-harness/src/testing.ts +190 -0
  227. package/src/native-harness/src/util/config.ts +66 -0
  228. package/src/native-harness/src/util/intake.ts +7 -0
  229. package/src/native-harness/src/util/json.ts +41 -0
  230. package/src/native-harness/src/util/message-position.ts +3 -0
  231. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  232. package/src/native-harness/src/util/schema.ts +40 -0
  233. package/src/native-harness/src/util/timeline-text.ts +72 -0
  234. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  235. package/src/native-harness/tsconfig.json +20 -0
  236. package/src/observation/agent-event-bus.ts +44 -18
  237. package/src/observation/index.ts +1 -0
  238. package/src/operations/contracts.ts +11 -3
  239. package/src/operations/errors.ts +5 -0
  240. package/src/operations/stale-policy.ts +1 -1
  241. package/src/operations/supervisor.ts +34 -10
  242. package/src/orchestrator/acp-delivery.ts +68 -0
  243. package/src/orchestrator/assignments.ts +27 -0
  244. package/src/orchestrator/busy.ts +15 -0
  245. package/src/orchestrator/config.ts +41 -0
  246. package/src/orchestrator/consumer-api.ts +24 -0
  247. package/src/orchestrator/contracts.ts +71 -0
  248. package/src/orchestrator/durable-assignments.ts +111 -0
  249. package/src/orchestrator/native-delegation.ts +103 -0
  250. package/src/orchestrator/orchestrator.ts +318 -0
  251. package/src/orchestrator/permissions.ts +28 -0
  252. package/src/orchestrator/policy.ts +44 -0
  253. package/src/orchestrator/pool.ts +123 -0
  254. package/src/orchestrator/tool-descriptions.ts +11 -0
  255. package/src/permissions/acp.ts +18 -0
  256. package/src/permissions/arrival.ts +13 -0
  257. package/src/permissions/consumer-config.ts +19 -0
  258. package/src/permissions/conversation.ts +288 -0
  259. package/src/permissions/matcher.ts +87 -0
  260. package/src/permissions/outcome.ts +26 -0
  261. package/src/permissions/policy.ts +86 -0
  262. package/src/permissions/request.ts +26 -0
  263. package/src/persistence/activity-projection.ts +1 -0
  264. package/src/persistence/backend.ts +34 -1
  265. package/src/persistence/channels.ts +23 -0
  266. package/src/persistence/index.ts +4 -0
  267. package/src/persistence/protocol-method.ts +5 -0
  268. package/src/persistence/reminder-wake.ts +49 -0
  269. package/src/persistence/reminders.ts +385 -0
  270. package/src/persistence/sqlite-backend.ts +84 -6
  271. package/src/persistence/sqlite-channels.ts +65 -0
  272. package/src/persistence/sqlite-reminders.ts +85 -0
  273. package/src/persistence/sqlite-schema.ts +108 -3
  274. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  275. package/src/persistence/sqlite-workers.ts +59 -0
  276. package/src/persistence/worker-delivery-contract.ts +104 -0
  277. package/src/persistence/worker-terminal-reason.ts +29 -0
  278. package/src/persistence/workers.ts +19 -0
  279. package/src/provider-notices.ts +137 -0
  280. package/src/repl/commands.ts +2 -2
  281. package/src/steering/combine.ts +3 -1
  282. package/src/steering/contracts.ts +11 -2
  283. package/src/steering/controller.ts +3 -2
  284. package/src/terminals.ts +9 -6
  285. package/src/transport/acp-transport.ts +24 -14
  286. package/src/types.ts +15 -12
  287. package/src/updates.ts +14 -2
  288. package/src/wire-log.ts +1 -1
@@ -2,7 +2,7 @@
2
2
  // outside (its stage and timestamps) and what the provider is observed to send while it runs.
3
3
  // Spec: .res/somelogs.md/9-22+/10-17-SPEC-operation-lifecycle.md.
4
4
 
5
- import type { ActivityEvent } from "../types.ts";
5
+ import type { ActivityEvent, PromptResult } from "../types.ts";
6
6
 
7
7
  /**
8
8
  * Anything the provider sent for a session: a `session/update`, or a request from the agent to the
@@ -14,6 +14,14 @@ export type ProviderOutput =
14
14
 
15
15
  export type OutputListener = (output: ProviderOutput) => void;
16
16
 
17
+ /** The narrow view of a provider the supervisor needs: one request, started by `prompt()`. */
18
+ export interface SupervisedProvider {
19
+ prompt(): Promise<PromptResult>;
20
+ subscribeOutput(listener: OutputListener): () => void;
21
+ cancel(): void;
22
+ forceStop(): Promise<void>;
23
+ }
24
+
17
25
  /** What a running operation is waiting on. */
18
26
  export type OperationStage = "waiting" | "streaming" | "tool_running" | "awaiting_permission" | "cancelling";
19
27
 
@@ -47,9 +55,9 @@ export interface OperationActivity {
47
55
 
48
56
  /** When an operation counts as stale. `false` disables a condition. */
49
57
  export interface StaleLimits {
50
- /** No output at all since the request was sent. Default 120 000. */
58
+ /** No output at all since the request was sent. Default 600 000 (10 minutes). */
51
59
  readonly firstOutputMs?: number | false;
52
- /** No output since the last one, with no tool or permission explaining it. Default 180 000. */
60
+ /** No output since the last one, with no tool or permission explaining it. Default 900 000 (15 minutes). */
53
61
  readonly nextOutputMs?: number | false;
54
62
  /** One tool running longer than this. Off by default. */
55
63
  readonly toolMs?: number | false;
@@ -14,6 +14,11 @@ export class OperationStalledError extends Error {
14
14
  followedBy?: readonly string[];
15
15
  metering?: OperationMeteringRecord;
16
16
  cancel?: "acknowledged" | "forced";
17
+ /**
18
+ * The provider's last notice before the stall, when it was retrying or warning (a 429, say): the
19
+ * likely cause, which the recorded error names instead of a bare "stopped producing output".
20
+ */
21
+ notice?: { readonly title: string; readonly category: string; readonly code?: string };
17
22
 
18
23
  constructor(readonly operationId: string, readonly phase: StallPhase) {
19
24
  super(`Provider operation stalled (${phase}).`);
@@ -3,7 +3,7 @@ import type { OperationActivity, StaleLimits } from "./contracts.ts";
3
3
  /** Whether anything had arrived when the operation went stale. */
4
4
  export type StallPhase = "no_response" | "incomplete_response";
5
5
 
6
- export const DEFAULT_STALE_LIMITS = Object.freeze({ firstOutputMs: 120_000, nextOutputMs: 180_000 });
6
+ export const DEFAULT_STALE_LIMITS = Object.freeze({ firstOutputMs: 600_000, nextOutputMs: 900_000 });
7
7
 
8
8
  export interface StaleDecision {
9
9
  readonly deadline: number;
@@ -10,21 +10,15 @@ import type {
10
10
  CancelOutcome,
11
11
  CancelReason,
12
12
  OperationActivity,
13
- OutputListener,
14
13
  ProviderOutput,
15
14
  StaleLimits,
16
15
  SupervisedOperationKind,
16
+ SupervisedProvider,
17
17
  } from "./contracts.ts";
18
18
  import { ToolTracker } from "./activity-tracker.ts";
19
19
  import { realTimers, type Timers } from "./timers.ts";
20
20
 
21
- /** The narrow view of a provider the supervisor needs. */
22
- export interface SupervisedProvider {
23
- prompt(): Promise<PromptResult>;
24
- subscribeOutput(listener: OutputListener): () => void;
25
- cancel(): void;
26
- forceStop(): Promise<void>;
27
- }
21
+ export type { SupervisedProvider } from "./contracts.ts";
28
22
 
29
23
  export interface SupervisorOptions {
30
24
  readonly operationId: string;
@@ -35,6 +29,12 @@ export interface SupervisorOptions {
35
29
  readonly cancelGraceMs?: number;
36
30
  readonly timers?: Timers;
37
31
  readonly limits?: StaleLimits;
32
+ /**
33
+ * Whether the provider is replaying output the backend already produced (a held turn that is not `live`). Read each
34
+ * time a stall deadline is reached, not once: a replaying turn is never stalled, and one that has become live since
35
+ * gets its stall deadline back (a controller-interface turn is not live while its held output replays).
36
+ */
37
+ readonly isReplaying?: () => boolean;
38
38
  readonly onStageChanged?: (activity: OperationActivity) => void;
39
39
  /** The last running tool settled. */
40
40
  readonly onToolBoundary?: () => void;
@@ -58,6 +58,7 @@ export class OperationSupervisor {
58
58
  private readonly timers: Timers;
59
59
  private readonly startedAt: number;
60
60
  private lastOutputAt: number | null = null;
61
+ private lastNotice?: { title: string; category: string; code?: string };
61
62
  private permissions = 0;
62
63
  private cancellation?: { reason: CancelReason; requestedAt: number };
63
64
  private stage: OperationActivity["stage"] = "waiting";
@@ -67,6 +68,8 @@ export class OperationSupervisor {
67
68
  private finished = false;
68
69
  private started = false;
69
70
  private forced = false;
71
+ /** The last time a stall deadline was skipped because the provider was replaying: silence counts from then. */
72
+ private replayCheckedAt: number | null = null;
70
73
  private finishForced?: (result: PromptResult) => void;
71
74
 
72
75
  constructor(private readonly provider: SupervisedProvider, private readonly options: SupervisorOptions) {
@@ -155,7 +158,9 @@ export class OperationSupervisor {
155
158
  }
156
159
 
157
160
  private stalled(): OperationStalledError {
158
- return this.markCancel(new OperationStalledError(this.options.operationId, this.stallPhase!));
161
+ const error = new OperationStalledError(this.options.operationId, this.stallPhase!);
162
+ if (this.lastNotice) error.notice = this.lastNotice;
163
+ return this.markCancel(error);
159
164
  }
160
165
 
161
166
  private markCancel(error: OperationStalledError): OperationStalledError {
@@ -180,6 +185,14 @@ export class OperationSupervisor {
180
185
  this.lastOutputAt = this.timers.now();
181
186
  if (output.kind === "permission_started") this.permissions++;
182
187
  if (output.kind === "permission_ended") this.permissions = Math.max(0, this.permissions - 1);
188
+ // A retry or warning in progress is remembered until real output follows, to name a stall's cause.
189
+ if (output.kind === "update" && output.activity?.kind === "provider_notice") {
190
+ const notice = output.activity;
191
+ this.lastNotice = notice.severity === "error" ? undefined
192
+ : { title: notice.title, category: notice.category, ...(notice.code ? { code: notice.code } : {}) };
193
+ } else if (output.kind === "update") {
194
+ this.lastNotice = undefined;
195
+ }
183
196
  if (output.kind === "update" && output.activity) {
184
197
  const settled = this.tools.observe(output.activity, this.lastOutputAt);
185
198
  if (settled && !this.tools.inFlight) this.options.onToolBoundary?.();
@@ -191,9 +204,20 @@ export class OperationSupervisor {
191
204
  private armStaleTimer(): void {
192
205
  this.timers.clearTimeout(this.staleHandle);
193
206
  const limits = this.options.limits ?? {};
194
- const decision = stalePolicy(this.activity, this.permissions, this.tools.oldestStartedAt, limits, this.timers.now());
207
+ // Silence is counted from the last skipped deadline too, so a turn that stopped replaying gets a full interval.
208
+ const floor = this.replayCheckedAt ?? 0;
209
+ const activity = this.activity;
210
+ const counted = this.replayCheckedAt === null ? activity : { ...activity, startedAt: Math.max(activity.startedAt, floor), lastOutputAt: activity.lastOutputAt === null ? null : Math.max(activity.lastOutputAt, floor) };
211
+ const oldestTool = this.tools.oldestStartedAt;
212
+ const decision = stalePolicy(counted, this.permissions, oldestTool === null ? null : Math.max(oldestTool, floor), limits, this.timers.now());
195
213
  if (!decision || this.finished) return;
196
214
  this.staleHandle = this.timers.setTimeout(() => {
215
+ if (this.options.isReplaying?.()) {
216
+ // Still replaying held output: no stall now; look again after another interval.
217
+ this.replayCheckedAt = this.timers.now();
218
+ this.armStaleTimer();
219
+ return;
220
+ }
197
221
  this.stallPhase = decision.phase;
198
222
  this.cancel("stalled");
199
223
  }, Math.max(0, decision.deadline - this.timers.now()));
@@ -0,0 +1,68 @@
1
+ import { isAgentConversationId, type AgentConversationId } from "../agent-ids.ts";
2
+ import { AppendDestinationUnavailableError } from "../agent/append-assistant-message.ts";
3
+ import type { Logger } from "../logger.ts";
4
+ import type { AppendAssistantMessageInput } from "../out-of-band-messages.ts";
5
+ import type { StagedWorkerAssignment, WorkerDeliveryRepository } from "../persistence/worker-delivery-contract.ts";
6
+ import { REFUSED_STEER_REASONS } from "../persistence/worker-terminal-reason.ts";
7
+
8
+ export class AcpWorkerDelivery {
9
+ private tail = Promise.resolve();
10
+
11
+ constructor(
12
+ private readonly repository: WorkerDeliveryRepository,
13
+ private readonly append: (id: AgentConversationId, input: AppendAssistantMessageInput, stableId: string) => Promise<unknown>,
14
+ private readonly log: Logger,
15
+ ) {}
16
+
17
+ flush(): Promise<void> {
18
+ this.tail = this.tail.then(() => this.drain()).catch(error => {
19
+ this.log.warn("acp_worker_delivery_failed", { error: String(error) });
20
+ });
21
+ return this.tail;
22
+ }
23
+
24
+ private async drain(): Promise<void> {
25
+ for (const state of ["unstaged", "pending"] as const) {
26
+ let after: string | undefined;
27
+ do {
28
+ const page = await this.repository.discoverAssignments({ destinationKind: "acp", state, after });
29
+ for (const entry of page.assignments) {
30
+ if (entry.state === "pending") await this.deliver(entry.staged);
31
+ else await this.repository.stage(entry.binding.assignmentId);
32
+ }
33
+ after = page.next;
34
+ } while (after !== undefined);
35
+ }
36
+ }
37
+
38
+ private async deliver({ delivery, outcome }: StagedWorkerAssignment): Promise<void> {
39
+ if (delivery.destination.kind !== "acp") return;
40
+ const target = delivery.destination.id;
41
+ const reason = "reason" in outcome ? outcome.reason : undefined;
42
+ const cause = reason === REFUSED_STEER_REASONS.conflict ? "conflict"
43
+ : reason === REFUSED_STEER_REASONS.hook_error ? "hook_error" : undefined;
44
+ let state: "delivered" | "failed_destination";
45
+ try {
46
+ if (!isAgentConversationId(target)) throw new AppendDestinationUnavailableError("invalid ACP destination");
47
+ await this.append(target, {
48
+ text: delivery.text,
49
+ consumerMetadata: {
50
+ kind: outcome.kind === "result" ? "worker_reply" : "worker_failed",
51
+ sender: delivery.source,
52
+ ...(outcome.kind === "result" ? {} : {
53
+ errorKind: outcome.kind,
54
+ ...(cause ? { reason: "refused", cause } : reason ? { reason } : {}),
55
+ }),
56
+ },
57
+ }, delivery.id);
58
+ state = "delivered";
59
+ } catch (error) {
60
+ if (!(error instanceof AppendDestinationUnavailableError)) {
61
+ this.log.warn("acp_worker_append_unconfirmed", { deliveryId: delivery.id, error: String(error) });
62
+ return;
63
+ }
64
+ state = "failed_destination";
65
+ }
66
+ await this.repository.transitionDelivery(delivery.id, { from: "pending", to: state });
67
+ }
68
+ }
@@ -0,0 +1,27 @@
1
+ import type { AgentConversationId } from "../agent-ids.ts";
2
+ import type { WorkerRow } from "../persistence/workers.ts";
3
+ import type { StagedWorkerAssignment } from "../persistence/worker-delivery-contract.ts";
4
+ import type { WorkerConversationActor } from "./contracts.ts";
5
+
6
+ export interface RunningAssignment {
7
+ readonly id: string;
8
+ readonly destination?: AgentConversationId;
9
+ }
10
+
11
+ export type AssignmentPlan =
12
+ | { readonly kind: "start"; readonly assignment: RunningAssignment }
13
+ | { readonly kind: "continue"; readonly previous: RunningAssignment; readonly assignment: RunningAssignment }
14
+ | { readonly kind: "replace"; readonly previous: RunningAssignment; readonly assignment: RunningAssignment };
15
+
16
+ export type RefusedSteerCause = "conflict" | "hook_error";
17
+ export type RefusedSteer = { readonly actor: WorkerConversationActor; readonly cause: RefusedSteerCause };
18
+
19
+ /** The assignment implementation is supplied separately. The pool only knows the dispatch boundary. */
20
+ export interface WorkerAssignmentPort {
21
+ beforeDispatch(row: WorkerRow, plan: AssignmentPlan, messageId: string, policyNames: readonly string[], actor?: WorkerConversationActor): Promise<RunningAssignment | void>;
22
+ refuse?(row: WorkerRow, plan: AssignmentPlan, refusal: RefusedSteer): Promise<void>;
23
+ settled?(): Promise<void>;
24
+ latestOutcome?(row: WorkerRow): Promise<StagedWorkerAssignment | undefined>;
25
+ latestResult?(row: WorkerRow): Promise<StagedWorkerAssignment | undefined>;
26
+ retryDelivery?(row: WorkerRow): Promise<void>;
27
+ }
@@ -0,0 +1,15 @@
1
+ import type { AssignmentPlan, RunningAssignment } from "./assignments.ts";
2
+ import type { SendWorkerInput, WorkerActor } from "./contracts.ts";
3
+
4
+ export function planAssignment(
5
+ actor: WorkerActor, input: SendWorkerInput, running?: RunningAssignment,
6
+ ): AssignmentPlan | undefined {
7
+ const destination = actor.kind === "conversation" ? actor.conversationId : undefined;
8
+ const fresh = () => ({ id: actor.kind === "conversation" ? actor.invocationId : crypto.randomUUID(), destination });
9
+ if (!running) return { kind: "start", assignment: fresh() };
10
+ if (destination !== running.destination && !input.redirect) return;
11
+ if (input.assignment === "new" || (!running.destination && destination)) {
12
+ return { kind: "replace", previous: running, assignment: fresh() };
13
+ }
14
+ return { kind: "continue", previous: running, assignment: { ...running, destination } };
15
+ }
@@ -0,0 +1,41 @@
1
+ import type { DelegationPolicy } from "./contracts.ts";
2
+ import type { PermissionSettings } from "../permissions/matcher.ts";
3
+ import { PersistenceCapabilityError } from "../persistence/backend.ts";
4
+ import type { PersistenceBackend, RecordCaptureLevel } from "../persistence/backend.ts";
5
+
6
+ export interface OrchestratorConfig {
7
+ /** Each entry corresponds to a configured native harness policy name. */
8
+ readonly policies?: Readonly<Record<string, {
9
+ readonly delegation: DelegationPolicy;
10
+ readonly workerPermissions?: PermissionSettings;
11
+ }>>;
12
+ /** Forwarded requests retain owner options only when every contributing name is listed here. */
13
+ readonly ownerPolicies?: readonly string[];
14
+ readonly defaults?: {
15
+ readonly delegation?: DelegationPolicy;
16
+ /** Worker policy for consumer work and callbacks with no contributing policies. */
17
+ readonly workerPermissions?: PermissionSettings;
18
+ };
19
+ readonly workers: {
20
+ readonly adapterId?: string;
21
+ readonly cwd?: string;
22
+ readonly limit: number;
23
+ /** Time idle before stopping the provider process. Defaults to ten minutes. */
24
+ readonly idleStopMs?: number | false;
25
+ };
26
+ }
27
+
28
+ export function validateOrchestrator(
29
+ config: OrchestratorConfig, persistence: PersistenceBackend, messageCapture: RecordCaptureLevel,
30
+ ): void {
31
+ if (!persistence.capabilities.workers || !persistence.workers) throw new PersistenceCapabilityError("workers");
32
+ if (!persistence.capabilities.workerDelivery || !persistence.workerDelivery) throw new PersistenceCapabilityError("workerDelivery");
33
+ if (messageCapture !== "content") throw new Error('orchestrator requires message capture "content"');
34
+ if (!Number.isSafeInteger(config.workers.limit) || config.workers.limit < 1) {
35
+ throw new RangeError("orchestrator worker limit must be a positive integer");
36
+ }
37
+ const idle = config.workers.idleStopMs;
38
+ if (idle !== undefined && idle !== false && (!Number.isInteger(idle) || idle < 0 || idle > 2_147_483_647)) {
39
+ throw new RangeError("orchestrator worker idleStopMs must be a non-negative timer delay or false");
40
+ }
41
+ }
@@ -0,0 +1,24 @@
1
+ import type { DeleteConversationResult } from "../agent/config.ts";
2
+ import type { WorkerSummary } from "./contracts.ts";
3
+ import type { Orchestrator } from "./orchestrator.ts";
4
+
5
+ export interface WorkerConsumerApi {
6
+ list(): Promise<readonly WorkerSummary[]>;
7
+ check(handle: string): Promise<WorkerSummary>;
8
+ /** Explicitly retry the worker's newest policy-blocked delivery. */
9
+ retryDelivery(handle: string): Promise<void>;
10
+ stop(handle: string): Promise<void>;
11
+ /** Removes the worker locally and reports the provider cleanup outcome. */
12
+ delete(handle: string): Promise<DeleteConversationResult>;
13
+ }
14
+
15
+ export function workerConsumerApi(orchestrator: Orchestrator): WorkerConsumerApi {
16
+ const consumer = { kind: "consumer" } as const;
17
+ return Object.freeze({
18
+ list: () => orchestrator.list(consumer),
19
+ check: (handle: string) => orchestrator.check(consumer, handle),
20
+ retryDelivery: (handle: string) => orchestrator.retryDelivery(handle),
21
+ async stop(handle: string) { await orchestrator.stop(consumer, handle); },
22
+ delete: (handle: string) => orchestrator.drop(consumer, handle),
23
+ });
24
+ }
@@ -0,0 +1,71 @@
1
+ import type { PermissionSettings } from "../permissions/matcher.ts";
2
+ import type { AgentConversationId } from "../agent-ids.ts";
3
+ import type { OperationActivity } from "../operations/contracts.ts";
4
+ import type { WorkerRow } from "../persistence/workers.ts";
5
+ import type { WorkerAssignmentOutcome, WorkerDeliveryState } from "../persistence/worker-delivery-contract.ts";
6
+
7
+ export interface DelegationPolicy {
8
+ readonly use: boolean;
9
+ readonly scope: "none" | "all";
10
+ readonly redirect: boolean;
11
+ readonly maxOpen?: number;
12
+ }
13
+
14
+ export type WorkerActor = { readonly kind: "consumer" } | WorkerConversationActor;
15
+
16
+ export interface WorkerConversationActor {
17
+ readonly kind: "conversation";
18
+ readonly conversationId: AgentConversationId;
19
+ readonly sender: string;
20
+ readonly invocationId: string;
21
+ /** Native callbacks identify their destination even for rows created before controller kinds. */
22
+ readonly destinationKind?: "native" | "acp";
23
+ readonly policyNames: readonly string[];
24
+ readonly policy: DelegationPolicy;
25
+ readonly workerPermissions: readonly PermissionSettings[];
26
+ /** A trusted caller can attest owner authority independently of policy names. */
27
+ readonly isOwner?: boolean;
28
+ }
29
+
30
+ export interface WorkerInput {
31
+ readonly text: string;
32
+ readonly about?: string;
33
+ }
34
+
35
+ export interface SendWorkerInput extends WorkerInput {
36
+ readonly redirect?: boolean;
37
+ readonly assignment?: "new";
38
+ }
39
+
40
+ export interface WorkerSummary extends WorkerRow {
41
+ readonly state: "offline" | "idle" | "busy";
42
+ readonly operation?: OperationActivity;
43
+ readonly sender?: string;
44
+ readonly busyMs?: number;
45
+ readonly latestOutcome?: WorkerAssignmentOutcome;
46
+ /** Delivery state of the latest staged assignment. */
47
+ readonly deliveryState?: WorkerDeliveryState;
48
+ /** The last successful result, when the most recent outcome is a dispatch refusal. */
49
+ readonly latestResult?: Extract<WorkerAssignmentOutcome, { kind: "result" }>;
50
+ }
51
+
52
+ export type OpenWorkerResult = { readonly status: "sent"; readonly handle: string } |
53
+ { readonly status: "no_worker_free"; readonly workers: readonly WorkerSummary[] };
54
+
55
+ export type SendWorkerResult = { readonly status: "sent" | "steered" } |
56
+ { readonly status: "busy"; readonly worker: WorkerSummary } |
57
+ { readonly status: "no_worker_free"; readonly workers: readonly WorkerSummary[] };
58
+
59
+ interface WorkerEventIdentity {
60
+ readonly handle: string;
61
+ readonly conversationId: AgentConversationId;
62
+ readonly openedBy: WorkerRow["openedBy"];
63
+ readonly lastConversation?: AgentConversationId;
64
+ }
65
+
66
+ export type WorkerEvent = WorkerEventIdentity & (
67
+ | { readonly kind: "worker_opened" | "worker_busy" | "worker_idle" | "worker_replied" | "worker_reloaded" | "worker_dropped" }
68
+ | { readonly kind: "worker_redirected"; readonly previousConversation?: AgentConversationId }
69
+ | { readonly kind: "worker_failed"; readonly reason: string; readonly cause?: "conflict" | "hook_error"; readonly destination?: AgentConversationId }
70
+ | { readonly kind: "worker_stopped"; readonly reason: "eviction" | "requested" | "idle" }
71
+ );
@@ -0,0 +1,111 @@
1
+ import type { PersistenceBackend, PersistenceScope } from "../persistence/backend.ts";
2
+ import type { AgentConversationId } from "../agent-ids.ts";
3
+ import type { WorkerAssignmentReservation, WorkerDestination } from "../persistence/worker-delivery-contract.ts";
4
+ import type { WorkerRow } from "../persistence/workers.ts";
5
+ import type { AssignmentPlan, RefusedSteer, RunningAssignment, WorkerAssignmentPort } from "./assignments.ts";
6
+ import { REFUSED_STEER_REASONS } from "../persistence/worker-terminal-reason.ts";
7
+ import type { WorkerConversationActor } from "./contracts.ts";
8
+
9
+ export class WorkerAssignmentConflict extends Error {
10
+ constructor() { super("worker assignment conflict"); }
11
+ }
12
+
13
+ export class DurableWorkerAssignments implements WorkerAssignmentPort {
14
+ constructor(
15
+ private readonly persistence: PersistenceBackend,
16
+ private readonly flushAcp: () => Promise<void>,
17
+ private readonly flushNative: () => Promise<void> | undefined,
18
+ ) {}
19
+
20
+ async beforeDispatch(
21
+ row: WorkerRow, plan: AssignmentPlan, messageId: string, policyNames: readonly string[], actor?: WorkerConversationActor,
22
+ ): Promise<RunningAssignment | void> {
23
+ const target = plan.assignment.destination;
24
+ if (!target) return;
25
+ const accepted = await this.persistence.transaction(async scope => {
26
+ const repository = scope.workerDelivery!;
27
+ const destination = await this.destination(scope, target, actor?.destinationKind);
28
+ const binding = this.binding(row, plan.assignment.id, messageId, destination, policyNames);
29
+ // A local consumer's work has no delivery destination and therefore no predecessor binding.
30
+ if (plan.kind === "start" || !plan.previous.destination) {
31
+ if (await repository.reserve(binding) !== "reserved") throw new WorkerAssignmentConflict();
32
+ return false;
33
+ }
34
+ const old = await repository.readBinding(plan.previous.id);
35
+ if (!old || old.workerConversationId !== row.conversationId) throw new WorkerAssignmentConflict();
36
+ if (plan.kind === "continue" && old.finalRecordId && actor) {
37
+ const result = await repository.replaceAssignment(old.assignmentId, old.messageId, { ...binding, assignmentId: actor.invocationId });
38
+ if (result.kind !== "old_settled" || result.reservation !== "reserved") throw new WorkerAssignmentConflict();
39
+ return { id: actor.invocationId, destination: target };
40
+ }
41
+ if (plan.kind === "replace") {
42
+ const result = await repository.replaceAssignment(old.assignmentId, old.messageId, binding);
43
+ if (result.kind === "conflict" || result.reservation !== "reserved") throw new WorkerAssignmentConflict();
44
+ return result.kind === "replaced";
45
+ }
46
+ if (await repository.continueAssignment(old.assignmentId, old.messageId, messageId) !== "continued"
47
+ || !await repository.addContributingPolicies(old.assignmentId, policyNames)
48
+ || (old.destination.id !== destination.id && !await repository.redirect(old.assignmentId, destination))) {
49
+ throw new WorkerAssignmentConflict();
50
+ }
51
+ return false;
52
+ });
53
+ if (accepted === true) void this.flushNative();
54
+ if (plan.kind === "replace") void this.flushAcp();
55
+ if (typeof accepted === "object") return accepted;
56
+ }
57
+
58
+ async refuse(row: WorkerRow, plan: AssignmentPlan, { actor, cause }: RefusedSteer): Promise<void> {
59
+ await this.persistence.transaction(async scope => {
60
+ const repository = scope.workerDelivery!;
61
+ const old = plan.kind === "start" ? undefined : await repository.readBinding(plan.previous.id);
62
+ if (old?.workerConversationId === row.conversationId) {
63
+ await repository.closeContinuation(old.assignmentId, old.messageId, {
64
+ kind: "interrupted", reason: "worker interrupted by steering", possiblePartialEffects: true,
65
+ });
66
+ }
67
+ const destination = await this.destination(scope, actor.conversationId, actor.destinationKind);
68
+ // The refusal is a separate notice. Its synthetic cause never reaches the worker and cannot
69
+ // take over the predecessor's binding or reuse a conflicting replacement invocation ID.
70
+ const id = `refused-steer:${actor.invocationId}`;
71
+ const reserved = await repository.reserve(this.binding(row, id, id, destination, actor.policyNames));
72
+ if (reserved === "conflict") throw new WorkerAssignmentConflict();
73
+ if (reserved === "reserved") await repository.recordFailure(row.conversationId, id, [id], {
74
+ kind: "failed",
75
+ reason: REFUSED_STEER_REASONS[cause],
76
+ possiblePartialEffects: false,
77
+ });
78
+ });
79
+ void this.flushNative();
80
+ }
81
+
82
+ async settled(): Promise<void> {
83
+ await Promise.all([this.flushAcp(), this.flushNative()]);
84
+ }
85
+
86
+ latestOutcome(row: WorkerRow) { return this.persistence.workerDelivery!.latestOutcome(row.conversationId); }
87
+ latestResult(row: WorkerRow) { return this.persistence.workerDelivery!.latestOutcome(row.conversationId, "result"); }
88
+
89
+ async retryDelivery(row: WorkerRow): Promise<void> {
90
+ const repository = this.persistence.workerDelivery!;
91
+ const blocked = await repository.latestOutcome(row.conversationId, "blocked_policy");
92
+ if (blocked?.delivery.state !== "blocked_policy" || !await repository.transitionDelivery(blocked.delivery.id,
93
+ { from: "blocked_policy", to: "pending", explicitRetry: true })) {
94
+ throw new Error(`worker ${row.handle} has no policy-blocked delivery to retry`);
95
+ }
96
+ await (blocked.delivery.destination.kind === "native" ? this.flushNative() : this.flushAcp());
97
+ }
98
+
99
+ private async destination(scope: PersistenceScope, id: AgentConversationId, kind?: WorkerDestination["kind"]): Promise<WorkerDestination> {
100
+ return { id, kind: (await scope.conversations.get(id))?.controllerKind ?? kind ?? "acp" };
101
+ }
102
+
103
+ private binding(
104
+ row: WorkerRow, assignmentId: string, messageId: string, destination: WorkerDestination, policyNames: readonly string[],
105
+ ): WorkerAssignmentReservation {
106
+ return {
107
+ assignmentId, messageId, destination, workerConversationId: row.conversationId, workerHandle: row.handle,
108
+ originatingPolicyNames: policyNames, contributingPolicyNames: policyNames,
109
+ };
110
+ }
111
+ }
@@ -0,0 +1,103 @@
1
+ import { isAgentConversationId } from "../agent-ids.ts";
2
+ import type { AgentConversationManager } from "../agent/config.ts";
3
+ import { WorkerPolicyError } from "../errors.ts";
4
+ import type { OrchestratorConfig } from "./config.ts";
5
+ import type { SendWorkerInput, WorkerActor } from "./contracts.ts";
6
+ import type { Orchestrator } from "./orchestrator.ts";
7
+ import { composeDelegationPolicy } from "./policy.ts";
8
+ import { WORKER_SEND_DESCRIPTION } from "./tool-descriptions.ts";
9
+ import { ownPermissions } from "../permissions/policy.ts";
10
+ import { FunctionError, type NativeFunction, type NativeFunctionContext, type NativeFunctionsConfig } from "../native/functions.ts";
11
+
12
+ const names = ["delegate", "check", "list", "stop"] as const;
13
+ const string = { type: "string" } as const;
14
+ const handleOnly = { type: "object", properties: { worker: string }, required: ["worker"], additionalProperties: false };
15
+ const denyDelegation = { use: false, scope: "none", redirect: false } as const;
16
+ const askWorker = { default: "ask" } as const;
17
+
18
+ export function withDelegationTools(
19
+ functions: NativeFunctionsConfig | undefined,
20
+ config: OrchestratorConfig,
21
+ orchestrator: () => Orchestrator,
22
+ conversations: () => Pick<AgentConversationManager, "get">,
23
+ ): NativeFunctionsConfig {
24
+ for (const name of names) {
25
+ if (functions && Object.hasOwn(functions.tools, name)) throw new Error(`native delegation tool name is already registered: ${name}`);
26
+ }
27
+ const policies = new Map(Object.entries(config.policies ?? {}).map(([name, policy]) => [name, {
28
+ delegation: Object.freeze({ ...policy.delegation }),
29
+ permissions: ownPermissions(policy.workerPermissions) ?? askWorker,
30
+ }]));
31
+ const defaults = {
32
+ delegation: Object.freeze({ ...(config.defaults?.delegation ?? denyDelegation) }),
33
+ permissions: ownPermissions(config.defaults?.workerPermissions) ?? askWorker,
34
+ };
35
+ const ownerPolicies = new Set(config.ownerPolicies ?? ["owner"]);
36
+
37
+ async function actor(context: NativeFunctionContext): Promise<WorkerActor> {
38
+ const { channel, invocationId, policyNames, signal } = context;
39
+ if (!Array.isArray(policyNames)) throw new FunctionError("delegation_policy_unknown", "Missing delegation policy names");
40
+ const applicable = policyNames.length ? policyNames.map(name => {
41
+ const policy = policies.get(name);
42
+ if (!policy) throw new FunctionError("delegation_policy_unknown", "A contributing policy has no delegation rules");
43
+ return policy;
44
+ }) : [defaults];
45
+ signal.throwIfAborted();
46
+ if (!isAgentConversationId(channel)) throw new FunctionError("delegation_conversation_unavailable", "Unknown giving conversation");
47
+ const summary = await conversations().get(channel);
48
+ if (!summary || summary.deletedAt || summary.controllerKind === "acp") {
49
+ throw new FunctionError("delegation_conversation_unavailable", "Unknown giving conversation");
50
+ }
51
+ if (!context.takenSender) throw new FunctionError("delegation_sender_unavailable", "No taken-input lookup is available");
52
+ const sender = await context.takenSender();
53
+ signal.throwIfAborted();
54
+ return {
55
+ kind: "conversation", conversationId: channel, destinationKind: "native", sender, invocationId, policyNames: [...policyNames],
56
+ policy: composeDelegationPolicy(applicable.map(policy => policy.delegation)),
57
+ workerPermissions: applicable.map(policy => policy.permissions),
58
+ isOwner: policyNames.length > 0 && policyNames.every(name => ownerPolicies.has(name)),
59
+ };
60
+ }
61
+
62
+ function tool(description: string, parameters: Record<string, unknown>, call: (
63
+ args: Record<string, unknown>, actor: WorkerActor,
64
+ ) => Promise<unknown>): NativeFunction {
65
+ return {
66
+ description, parameters, group: "fixed",
67
+ async handler(args, context) {
68
+ try {
69
+ return await call(args, await actor(context));
70
+ } catch (error) {
71
+ if (error instanceof WorkerPolicyError) throw new FunctionError("delegation_policy_denied", error.message);
72
+ throw error;
73
+ }
74
+ },
75
+ };
76
+ }
77
+
78
+ return {
79
+ ...functions,
80
+ tools: {
81
+ ...functions?.tools,
82
+ delegate: tool(`Omit worker to open a worker. ${WORKER_SEND_DESCRIPTION}`, {
83
+ type: "object",
84
+ properties: { worker: string, text: string, about: string, redirect: { type: "boolean" },
85
+ assignment: { type: "string", enum: ["new"] } },
86
+ required: ["text"], additionalProperties: false,
87
+ }, async (args, actor) => {
88
+ const input = args as unknown as SendWorkerInput & { worker?: string };
89
+ if (input.worker !== undefined) return orchestrator().send(actor, input.worker, input);
90
+ if (input.assignment !== undefined || input.redirect !== undefined) {
91
+ throw new FunctionError("invalid_arguments", "assignment and redirect require an existing worker handle");
92
+ }
93
+ return orchestrator().open(actor, input);
94
+ }),
95
+ check: tool("Check a worker by handle, including its latest staged result and delivery state. Results for native destinations may be absent until the harness opens.", handleOnly,
96
+ (args, actor) => orchestrator().check(actor, args.worker as string)),
97
+ list: tool("List visible workers with their latest staged results and delivery states. Results for native destinations may be absent until the harness opens.", { type: "object", properties: {}, additionalProperties: false },
98
+ (_args, actor) => orchestrator().list(actor)),
99
+ stop: tool('Interrupt running work and clear pending prompts. Returns "stopped" after an interruption or "idle" if there was no work to stop.', handleOnly,
100
+ async (args, actor) => ({ status: await orchestrator().stop(actor, args.worker as string) })),
101
+ },
102
+ };
103
+ }