@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
@@ -0,0 +1,95 @@
1
+ import { ConnectionCancelledError } from "./errors.ts";
2
+
3
+ export class ConnectionAttempt<Progress = never> {
4
+ private readonly abort = new AbortController();
5
+ private readonly observers = new Set<(event: Progress) => void>();
6
+ private readonly progress: Progress[] = [];
7
+ private cleanup?: () => Promise<void>;
8
+ private cancellation?: ConnectionCancelledError;
9
+
10
+ get signal(): AbortSignal { return this.abort.signal; }
11
+
12
+ throwIfCancelled(): void {
13
+ if (this.cancellation) throw this.cancellation;
14
+ }
15
+
16
+ own(cleanup: () => Promise<void>): void {
17
+ this.throwIfCancelled();
18
+ this.cleanup = cleanup;
19
+ }
20
+
21
+ async cancel(): Promise<void> {
22
+ this.cancellation ??= new ConnectionCancelledError();
23
+ this.abort.abort(this.cancellation);
24
+ await this.cleanup?.();
25
+ }
26
+
27
+ observe(observer: (event: Progress) => void): void {
28
+ this.observers.add(observer);
29
+ for (const event of this.progress) {
30
+ if (this.signal.aborted) break;
31
+ observer(event);
32
+ }
33
+ }
34
+
35
+ report(event: Progress): void {
36
+ this.progress.push(event);
37
+ for (const observer of [...this.observers]) {
38
+ if (this.signal.aborted) break;
39
+ observer(event);
40
+ }
41
+ }
42
+ }
43
+
44
+ /** Equivalent attempts share readiness. An incompatible request cancels and drains the candidate first. */
45
+ export class ConnectionAttempts<T, Progress = never> {
46
+ private active?: { key: string; attempt: ConnectionAttempt<Progress>; result: Promise<T> };
47
+ private teardown = Promise.resolve();
48
+
49
+ run(key: string, work: (attempt: ConnectionAttempt<Progress>) => Promise<T>, observer?: (event: Progress) => void): Promise<T> {
50
+ const active = this.active;
51
+ if (active?.key === key) {
52
+ if (observer) active.attempt.observe(observer);
53
+ return active.result;
54
+ }
55
+ void this.cancel().catch(() => undefined);
56
+ const prior = this.teardown;
57
+ const attempt = new ConnectionAttempt<Progress>();
58
+ if (observer) attempt.observe(observer);
59
+ const result = prior.then(() => {
60
+ attempt.throwIfCancelled();
61
+ return work(attempt);
62
+ }).then(value => {
63
+ attempt.throwIfCancelled();
64
+ return value;
65
+ }, error => {
66
+ // A stopped attempt owns its public outcome, regardless of how the leaf unwinds.
67
+ attempt.throwIfCancelled();
68
+ throw error;
69
+ }).finally(() => {
70
+ if (this.active?.attempt === attempt) this.active = undefined;
71
+ });
72
+ this.active = { key, attempt, result };
73
+ return result;
74
+ }
75
+
76
+ cancel(): Promise<void> {
77
+ const active = this.active;
78
+ if (!active) return this.teardown;
79
+ this.active = undefined;
80
+ const teardown = Promise.all([this.teardown, active.attempt.cancel()]).then(() => undefined);
81
+ this.teardown = teardown.catch(() => undefined);
82
+ return teardown;
83
+ }
84
+ }
85
+
86
+ /** Observe the original promise even if its result loses the race. */
87
+ export function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
88
+ return new Promise((resolve, reject) => {
89
+ const abort = () => reject(signal.reason);
90
+ if (signal.aborted) abort();
91
+ else signal.addEventListener("abort", abort, { once: true });
92
+ const release = () => signal.removeEventListener("abort", abort);
93
+ void work.then(value => { release(); resolve(value); }, error => { release(); reject(error); });
94
+ });
95
+ }
@@ -0,0 +1,115 @@
1
+ import { AcpClient, type ConnectResult } from "./client.ts";
2
+ import type { AgentClient } from "./agent-client.ts";
3
+ import type { ConnectionAttempt } from "./connection-attempt.ts";
4
+ import type { AgentControllerConfig, AgentMode, ControllerStartEvent } from "./controller.ts";
5
+ import { ConnectionCancelledError, ProcessCrashError } from "./errors.ts";
6
+
7
+ export interface ReadyConnection {
8
+ client: AgentClient;
9
+ acp: AcpClient | null;
10
+ result: ConnectResult;
11
+ }
12
+
13
+ /**
14
+ * Bring up a fresh leaf for the configured adapter in `mode`. normal → AcpClient
15
+ * (connect + new/load session); degraded → PtyClient (spawn interactive CLI). PtyClient
16
+ * is dynamically imported so the normal-mode path never loads the degraded subpath.
17
+ */
18
+ export async function bringUp(
19
+ config: AgentControllerConfig,
20
+ attempt: ConnectionAttempt<ControllerStartEvent>,
21
+ mode: AgentMode,
22
+ sessionId?: string,
23
+ loadFailure = config.sessionLoadFailure,
24
+ ): Promise<ReadyConnection> {
25
+ const adapter = config.adapter;
26
+ if (mode === "degraded") {
27
+ const { PtyClient } = await import("./degraded/index.ts");
28
+ attempt.throwIfCancelled();
29
+ const client = new PtyClient({
30
+ adapter,
31
+ launcher: config.launcher,
32
+ execPrefix: config.execPrefix,
33
+ env: config.env,
34
+ cwd: config.cwd,
35
+ logger: config.logger,
36
+ });
37
+ try {
38
+ await client.start();
39
+ attempt.throwIfCancelled();
40
+ } catch (err) {
41
+ await client.stop();
42
+ throw err;
43
+ }
44
+ return { client, acp: null, result: { sessionId: "", resumed: false } };
45
+ }
46
+
47
+ const client = new AcpClient({
48
+ adapter,
49
+ launcher: config.launcher,
50
+ execPrefix: config.execPrefix,
51
+ env: config.env,
52
+ terminalEnv: config.terminalEnv,
53
+ cwd: config.cwd,
54
+ additionalDirectories: config.additionalDirectories,
55
+ sessionId,
56
+ sessionLoadFailure: loadFailure,
57
+ permissions: config.permissions, permissionRule: config.permissionRule,
58
+ clientInfo: config.clientInfo,
59
+ clientCapabilities: config.clientCapabilities,
60
+ clientHandlers: config.clientHandlers,
61
+ logger: config.logger,
62
+ wire: config.wire,
63
+ });
64
+ // connect() is fatal (no connection = nothing to do). startSession() is NOT: an
65
+ // unauthenticated agent may refuse session/new, but we keep the connection up so the
66
+ // user can /login and then create a session. (Auth state is opaque — see SPEC.)
67
+ try {
68
+ attempt.own(() => client.stop());
69
+ const capabilities = await client.connect();
70
+ attempt.throwIfCancelled();
71
+ attempt.report({ stage: "initialized", capabilities });
72
+ } catch (err) {
73
+ await client.stop();
74
+ attempt.throwIfCancelled();
75
+ throw err;
76
+ }
77
+ let result: ConnectResult;
78
+ try {
79
+ result = await client.startSession({
80
+ mcpServers: config.mcpServers,
81
+ additionalDirectories: config.additionalDirectories,
82
+ loadFailure: loadFailure,
83
+ ...(config.onSessionReplay ? { onReplayUpdate: config.onSessionReplay } : {}),
84
+ });
85
+ } catch (err) {
86
+ attempt.throwIfCancelled();
87
+ if (err instanceof ConnectionCancelledError || err instanceof ProcessCrashError ||
88
+ config.requireStartupSession || (sessionId && loadFailure === "error")) {
89
+ await client.stop();
90
+ throw err;
91
+ }
92
+ config.logger?.warn("session_start_failed", { error: String(err) });
93
+ result = { sessionId: "", resumed: false };
94
+ }
95
+ attempt.throwIfCancelled();
96
+ if (result.sessionId) {
97
+ attempt.report({
98
+ stage: "internal_session_acquired",
99
+ internalSessionId: result.sessionId,
100
+ disposition: result.resumed ? "resumed" : "created",
101
+ });
102
+ }
103
+ return { client, acp: client, result };
104
+ }
105
+
106
+ export function observeStartProgress(
107
+ config: AgentControllerConfig,
108
+ listener: ((event: ControllerStartEvent) => void) | undefined,
109
+ ): ((event: ControllerStartEvent) => void) | undefined {
110
+ if (!listener) return;
111
+ return event => {
112
+ try { listener(event); }
113
+ catch (error) { config.logger?.warn("controller_start_progress_listener_failed", { error: String(error) }); }
114
+ };
115
+ }
package/src/controller.ts CHANGED
@@ -1,7 +1,16 @@
1
+ import { ownPermissions, type PermissionPolicyConfig } from "./permissions/policy.ts";
1
2
  import { ForcedStopError } from "./operations/errors.ts";
2
- import type { OperationLifecycleConfig, OutputListener } from "./operations/contracts.ts";
3
+ import type { OperationLifecycleConfig, OutputListener, SupervisedProvider } from "./operations/contracts.ts";
4
+ import type {
5
+ ConversationController,
6
+ PreparedTurn,
7
+ TurnContent,
8
+ TurnEvent,
9
+ TurnRun,
10
+ UsageListener,
11
+ } from "./conversation-controller/contracts.ts";
3
12
  import {
4
- AcpClient,
13
+ type AcpClient,
5
14
  type AcpClientConfig,
6
15
  type ConnectResult,
7
16
  type SessionLoadFailure,
@@ -24,7 +33,10 @@ import type {
24
33
  WireEntry,
25
34
  } from "./types.ts";
26
35
  import { NotConnectedError } from "./errors.ts";
36
+ import { conversationCapabilitiesOf, type ConversationCapabilities } from "./conversation-controller/capabilities.ts";
27
37
  import type { ClientPrompt } from "./agent-client.ts";
38
+ import { ConnectionAttempts, type ConnectionAttempt } from "./connection-attempt.ts";
39
+ import { bringUp, observeStartProgress, type ReadyConnection } from "./controller-connection.ts";
28
40
 
29
41
  const NO_AVAILABLE_COMMANDS: readonly InternalSessionCommand[] = Object.freeze([]);
30
42
 
@@ -42,7 +54,7 @@ type ObservableLeaf = AgentClient & {
42
54
  subscribeOutput?(listener: OutputListener): () => void;
43
55
  };
44
56
 
45
- export interface AgentControllerConfig {
57
+ export interface AgentControllerConfig extends PermissionPolicyConfig {
46
58
  operationLifecycle?: OperationLifecycleConfig;
47
59
  /** The single adapter this controller drives. Switching adapter = a new AgentSession. */
48
60
  adapter: Adapter;
@@ -56,17 +68,20 @@ export interface AgentControllerConfig {
56
68
  execPrefix?: string[];
57
69
  /** @deprecated Use launcher and its exact spawnEnv. */
58
70
  env?: Record<string, string>;
71
+ /** Exact environment for built-in ACP terminals. */
72
+ terminalEnv?: Record<string, string>;
59
73
  cwd?: string;
60
74
  additionalDirectories?: string[];
61
75
  /** Session id to load on start(). */
62
76
  sessionId?: string;
63
77
  /** Policy when sessionId cannot be loaded. Default "new" for compatibility. */
64
78
  sessionLoadFailure?: SessionLoadFailure;
79
+ /** @internal First use of a deferred Agent conversation must surface session creation errors. */
80
+ requireStartupSession?: boolean;
65
81
  /** Receives the history a loaded `sessionId` replays (raw `session/update` notifications). */
66
82
  onSessionReplay?: (notification: unknown) => void;
67
83
  /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
68
84
  mcpServers?: schema.McpServer[];
69
- defaultPermission?: "approve" | "cancel";
70
85
  clientInfo?: AcpClientConfig["clientInfo"];
71
86
  /** What we let the agent do through us (terminals, filesystem). All on by default. */
72
87
  clientCapabilities?: AcpClientConfig["clientCapabilities"];
@@ -78,7 +93,7 @@ export interface AgentControllerConfig {
78
93
  }
79
94
 
80
95
  /** @internal Startup observations used by the managed AgentSession coordinator. */
81
- export type AgentControllerStartEvent =
96
+ export type ControllerStartEvent =
82
97
  | { readonly stage: "initialized"; readonly capabilities: Capabilities }
83
98
  | {
84
99
  readonly stage: "internal_session_acquired";
@@ -119,7 +134,7 @@ export interface SetConfigFromStringResult {
119
134
  * mutable "current client" behavior such as adapter switching and config validation,
120
135
  * so CLIs and app UIs do not have to reimplement it.
121
136
  */
122
- export class AgentController implements AgentClient {
137
+ export class HarnessController implements AgentClient, ConversationController {
123
138
  // `current` is the universal leaf (prompt/interrupt/stop) — an AcpClient in normal
124
139
  // mode, a PtyClient in degraded mode. `acp` is the SAME object only in normal mode,
125
140
  // typed for the rich ACP surface; it is null when degraded (that surface genuinely
@@ -128,6 +143,7 @@ export class AgentController implements AgentClient {
128
143
  private readonly connectionListeners = new Set<() => void>();
129
144
  private detachDisconnect: (() => void) | null = null;
130
145
  private stopping: Promise<void> = Promise.resolve();
146
+ private readonly connections = new ConnectionAttempts<ConnectResult, ControllerStartEvent>();
131
147
  private current: AgentClient | null = null;
132
148
  private acp: AcpClient | null = null;
133
149
  private mode: AgentMode;
@@ -139,10 +155,13 @@ export class AgentController implements AgentClient {
139
155
  (update: unknown, sessionId: string | null) => void
140
156
  >();
141
157
  private readonly outputListeners = new Set<OutputListener>();
158
+ private readonly turnListeners = new Set<(event: TurnEvent) => void>();
159
+ /** Turns reported by `send` that have not been prepared or abandoned yet. */
160
+ private readonly reportedTurns = new Set<string>();
142
161
  private detachOutput: (() => void) | null = null;
143
162
  private detachUsageUpdates: (() => void) | null = null;
144
-
145
163
  constructor(private readonly config: AgentControllerConfig) {
164
+ this.config = { ...config, permissions: ownPermissions(config.permissions) };
146
165
  this.mode = config.mode ?? "normal";
147
166
  }
148
167
 
@@ -165,18 +184,18 @@ export class AgentController implements AgentClient {
165
184
  }
166
185
  }
167
186
 
168
- async reconnect(sessionId: string): Promise<ConnectResult> {
169
- await this.stopping;
170
- await this.stop();
171
- const brought = await this.bringUp(this.mode, sessionId, undefined, "error");
172
- this.current = brought.client;
173
- this.acp = brought.acp;
174
- this.attachAvailableCommandSource();
175
- if (!brought.result.resumed || brought.result.sessionId !== sessionId) {
176
- await this.stop();
177
- throw new Error("provider did not load the requested session");
178
- }
179
- return brought.result;
187
+ reconnect(sessionId: string): Promise<ConnectResult> {
188
+ return this.connections.run(`reconnect:${sessionId}`, async attempt => {
189
+ await this.stopCurrent();
190
+ attempt.throwIfCancelled();
191
+ const brought = await bringUp(this.config, attempt, this.mode, sessionId, "error");
192
+ attempt.throwIfCancelled();
193
+ if (!brought.result.resumed || brought.result.sessionId !== sessionId) {
194
+ await brought.client.stop();
195
+ throw new Error("provider did not load the requested session");
196
+ }
197
+ return this.installConnection(attempt, brought);
198
+ });
180
199
  }
181
200
 
182
201
  get cancelGraceMs(): number | undefined { return this.config.adapter.cancelGraceMs; }
@@ -208,6 +227,11 @@ export class AgentController implements AgentClient {
208
227
  return this.requireAcp().capabilities;
209
228
  }
210
229
 
230
+ /** What the backend offers, in neutral terms; `backend` is null before connecting and in PTY mode. */
231
+ get conversationCapabilities(): ConversationCapabilities {
232
+ return conversationCapabilitiesOf(this.acp);
233
+ }
234
+
211
235
  get configOptions(): ConfigOptions {
212
236
  return this.acp?.configOptions ?? new Map();
213
237
  }
@@ -235,7 +259,7 @@ export class AgentController implements AgentClient {
235
259
  *
236
260
  * Degraded (pty) mode has no ACP notifications, so this simply never fires there.
237
261
  */
238
- subscribeUsageUpdate(listener: (update: unknown, sessionId: string | null) => void): () => void {
262
+ subscribeUsageUpdate(listener: UsageListener): () => void {
239
263
  this.usageUpdateListeners.add(listener);
240
264
  return () => this.usageUpdateListeners.delete(listener);
241
265
  }
@@ -245,30 +269,42 @@ export class AgentController implements AgentClient {
245
269
  return () => this.outputListeners.delete(listener);
246
270
  }
247
271
 
248
- async start(onProgress?: (event: AgentControllerStartEvent) => void): Promise<ConnectResult> {
249
- await this.stopping;
250
- if (this.current && !this.isConnected) await this.stop();
251
- if (this.current) {
252
- return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
253
- }
254
- const brought = await this.bringUp(this.mode, this.config.sessionId, onProgress);
255
- this.current = brought.client;
256
- this.acp = brought.acp;
257
- this.attachAvailableCommandSource();
258
- return brought.result;
272
+ start(onProgress?: (event: ControllerStartEvent) => void): Promise<ConnectResult> {
273
+ return this.startConnection(false, onProgress);
259
274
  }
260
275
 
261
276
  /** Explicitly create a fresh provider thread, ignoring any startup load target. */
262
- async startFresh(onProgress?: (event: AgentControllerStartEvent) => void): Promise<ConnectResult> {
263
- await this.stopping;
264
- if (this.current && !this.isConnected) await this.stop();
265
- if (this.current) {
266
- if (!this.acp) throw new Error("fresh provider sessions require ACP normal mode");
267
- return await this.newSession();
268
- }
269
- const brought = await this.bringUp(this.mode, undefined, onProgress);
277
+ startFresh(onProgress?: (event: ControllerStartEvent) => void): Promise<ConnectResult> {
278
+ return this.startConnection(true, onProgress);
279
+ }
280
+
281
+ private startConnection(fresh: boolean, onProgress?: (event: ControllerStartEvent) => void): Promise<ConnectResult> {
282
+ return this.connections.run(fresh ? "fresh" : "start", async attempt => {
283
+ await this.stopping;
284
+ if (this.current && !this.isConnected) await this.stopCurrent();
285
+ attempt.throwIfCancelled();
286
+ if (this.current && !fresh) return this.existingConnection();
287
+ if (this.current) {
288
+ if (!this.acp) throw new Error("fresh provider sessions require ACP normal mode");
289
+ attempt.own(() => this.stopCurrent());
290
+ const result = await this.newSession();
291
+ attempt.throwIfCancelled();
292
+ return result;
293
+ }
294
+ const brought = await bringUp(this.config, attempt, this.mode, fresh ? undefined : this.config.sessionId);
295
+ return this.installConnection(attempt, brought);
296
+ }, observeStartProgress(this.config, onProgress));
297
+ }
298
+
299
+ private existingConnection(): ConnectResult {
300
+ return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
301
+ }
302
+
303
+ private installConnection(attempt: ConnectionAttempt<ControllerStartEvent>, brought: ReadyConnection, mode = this.mode): ConnectResult {
304
+ attempt.throwIfCancelled();
270
305
  this.current = brought.client;
271
306
  this.acp = brought.acp;
307
+ this.mode = mode;
272
308
  this.attachAvailableCommandSource();
273
309
  return brought.result;
274
310
  }
@@ -289,6 +325,66 @@ export class AgentController implements AgentClient {
289
325
  .finally(() => this.forceStopListeners.delete(forced));
290
326
  }
291
327
 
328
+ // --- turn path (ConversationController; controller-interface spec) -----------------------------
329
+
330
+ /**
331
+ * Session-scheduled: makes no provider call. Reports `turn_started` for the run synchronously,
332
+ * inside this call (`sentBySession: true`), and returns an already resolved promise. The turn's
333
+ * provider work starts when its prepared turn's `prompt()` is called.
334
+ */
335
+ send(run: TurnRun): Promise<void> {
336
+ const turnId = run.turnId;
337
+ if (!turnId) throw new Error("send: a session-scheduled run requires its turnId");
338
+ if (run.messageIds.length === 0) throw new Error("a run carries at least one message id");
339
+ if (new Set(run.messageIds).size !== run.messageIds.length) {
340
+ throw new Error(`a run repeats a message id: ${run.messageIds.join(", ")}`);
341
+ }
342
+ this.reportedTurns.add(turnId);
343
+ const event: TurnEvent = {
344
+ kind: "turn_started",
345
+ turnId,
346
+ cause: { messageIds: Object.freeze([...run.messageIds]) },
347
+ sentBySession: true,
348
+ };
349
+ for (const listener of [...this.turnListeners]) listener(event);
350
+ return Promise.resolve();
351
+ }
352
+
353
+ /** `turn_started` only: this controller never folds items into a running turn (`turn_took`). */
354
+ subscribeTurns(listener: (event: TurnEvent) => void): () => void {
355
+ this.turnListeners.add(listener);
356
+ return () => this.turnListeners.delete(listener);
357
+ }
358
+
359
+ /**
360
+ * Starts nothing. The returned turn's `prompt()` calls `prompt` with the content's input and
361
+ * handlers; its output, cancel and force stop are this controller's own, since it only ever runs
362
+ * one turn. `live` is always true (nothing is held).
363
+ */
364
+ prepareTurn(turnId: string, content: TurnContent): PreparedTurn {
365
+ this.reportedTurns.delete(turnId);
366
+ return { turnId, live: true, ...this.supervisedContent(content) };
367
+ }
368
+
369
+ /** An internal prompt (summary, recap, seed): the same shape, no turn bookkeeping. */
370
+ prepareInternalPrompt(content: TurnContent): SupervisedProvider {
371
+ return this.supervisedContent(content);
372
+ }
373
+
374
+ /** Releases a reported turn the session won't run. Idempotent; never stops provider work. */
375
+ abandonTurn(turnId: string, _reason: unknown): void {
376
+ this.reportedTurns.delete(turnId);
377
+ }
378
+
379
+ private supervisedContent(content: TurnContent): SupervisedProvider {
380
+ return {
381
+ prompt: () => this.prompt({ ...(content.input ?? {}), handlers: content.handlers }),
382
+ subscribeOutput: (listener) => this.subscribeOutput(listener),
383
+ cancel: () => this.cancel(),
384
+ forceStop: () => this.forceStop(),
385
+ };
386
+ }
387
+
292
388
  cancel(): void { this.current?.interrupt(); }
293
389
 
294
390
  forceStop(): Promise<void> {
@@ -330,6 +426,10 @@ export class AgentController implements AgentClient {
330
426
  }
331
427
 
332
428
  async stop(): Promise<void> {
429
+ await Promise.all([this.connections.cancel(), this.stopCurrent()]);
430
+ }
431
+
432
+ private async stopCurrent(): Promise<void> {
333
433
  const client = this.current;
334
434
  this.current = null;
335
435
  this.acp = null;
@@ -357,18 +457,18 @@ export class AgentController implements AgentClient {
357
457
  * current leaf and brings up a fresh one in the new mode (sessions do NOT carry across —
358
458
  * the two transports are unrelated). Returns the new leaf's connect result.
359
459
  */
360
- async setMode(mode: AgentMode): Promise<ConnectResult> {
361
- if (mode === this.mode && this.current) {
362
- return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
363
- }
364
- const previous = this.current;
365
- const brought = await this.bringUp(mode);
366
- this.current = brought.client;
367
- this.acp = brought.acp;
368
- this.mode = mode;
369
- this.attachAvailableCommandSource();
370
- if (previous) await previous.stop();
371
- return brought.result;
460
+ setMode(mode: AgentMode): Promise<ConnectResult> {
461
+ return this.connections.run(`mode:${mode}`, async attempt => {
462
+ await this.stopping;
463
+ attempt.throwIfCancelled();
464
+ if (mode === this.mode && this.current) return this.existingConnection();
465
+ const previous = this.current;
466
+ const brought = await bringUp(this.config, attempt, mode);
467
+ const result = this.installConnection(attempt, brought, mode);
468
+ if (previous) await previous.stop();
469
+ attempt.throwIfCancelled();
470
+ return result;
471
+ });
372
472
  }
373
473
 
374
474
  /** Authenticate the connection. Available whenever connected over ACP (with or without a session). */
@@ -543,103 +643,6 @@ export class AgentController implements AgentClient {
543
643
  ];
544
644
  }
545
645
 
546
- /**
547
- * Bring up a fresh leaf for the configured adapter in `mode`. normal → AcpClient
548
- * (connect + new/load session); degraded → PtyClient (spawn interactive CLI). PtyClient
549
- * is dynamically imported so the normal-mode path never loads the degraded subpath.
550
- */
551
- private async bringUp(
552
- mode: AgentMode,
553
- sessionId?: string,
554
- onProgress?: (event: AgentControllerStartEvent) => void,
555
- loadFailure = this.config.sessionLoadFailure,
556
- ): Promise<{ client: AgentClient; acp: AcpClient | null; result: ConnectResult }> {
557
- const adapter = this.config.adapter;
558
- if (mode === "degraded") {
559
- const { PtyClient } = await import("./degraded/index.ts");
560
- const client = new PtyClient({
561
- adapter,
562
- launcher: this.config.launcher,
563
- execPrefix: this.config.execPrefix,
564
- env: this.config.env,
565
- cwd: this.config.cwd,
566
- logger: this.config.logger,
567
- });
568
- try {
569
- await client.start();
570
- } catch (err) {
571
- await client.stop();
572
- throw err;
573
- }
574
- return { client, acp: null, result: { sessionId: "", resumed: false } };
575
- }
576
-
577
- const client = new AcpClient({
578
- adapter,
579
- launcher: this.config.launcher,
580
- execPrefix: this.config.execPrefix,
581
- env: this.config.env,
582
- cwd: this.config.cwd,
583
- additionalDirectories: this.config.additionalDirectories,
584
- sessionId,
585
- sessionLoadFailure: loadFailure,
586
- defaultPermission: this.config.defaultPermission,
587
- clientInfo: this.config.clientInfo,
588
- clientCapabilities: this.config.clientCapabilities,
589
- clientHandlers: this.config.clientHandlers,
590
- logger: this.config.logger,
591
- wire: this.config.wire,
592
- });
593
- // connect() is fatal (no connection = nothing to do). startSession() is NOT: an
594
- // unauthenticated agent may refuse session/new, but we keep the connection up so the
595
- // user can /login and then create a session. (Auth state is opaque — see SPEC.)
596
- try {
597
- const capabilities = await client.connect();
598
- this.reportStartProgress(onProgress, { stage: "initialized", capabilities });
599
- } catch (err) {
600
- await client.stop();
601
- throw err;
602
- }
603
- let result: ConnectResult;
604
- try {
605
- result = await client.startSession({
606
- mcpServers: this.config.mcpServers,
607
- additionalDirectories: this.config.additionalDirectories,
608
- loadFailure: loadFailure,
609
- ...(this.config.onSessionReplay ? { onReplayUpdate: this.config.onSessionReplay } : {}),
610
- });
611
- } catch (err) {
612
- if (sessionId && loadFailure === "error") {
613
- await client.stop();
614
- throw err;
615
- }
616
- this.config.logger?.warn("session_start_failed", { error: String(err) });
617
- result = { sessionId: "", resumed: false };
618
- }
619
- if (result.sessionId) {
620
- this.reportStartProgress(onProgress, {
621
- stage: "internal_session_acquired",
622
- internalSessionId: result.sessionId,
623
- disposition: result.resumed ? "resumed" : "created",
624
- });
625
- }
626
- return { client, acp: client, result };
627
- }
628
-
629
- private reportStartProgress(
630
- listener: ((event: AgentControllerStartEvent) => void) | undefined,
631
- event: AgentControllerStartEvent,
632
- ): void {
633
- if (!listener) return;
634
- try {
635
- listener(event);
636
- } catch (error) {
637
- this.config.logger?.warn("controller_start_progress_listener_failed", {
638
- error: String(error),
639
- });
640
- }
641
- }
642
-
643
646
  private requireCurrent(): AgentClient {
644
647
  if (!this.current) throw new NotConnectedError("AgentController is not started — call start() first");
645
648
  return this.current;
@@ -700,6 +703,13 @@ export class AgentController implements AgentClient {
700
703
  }
701
704
  }
702
705
 
706
+ /** @deprecated Renamed `HarnessController`; the old name stays exported. */
707
+ export const AgentController = HarnessController;
708
+ /** @deprecated Renamed `HarnessController`. */
709
+ export type AgentController = HarnessController;
710
+ /** @deprecated Renamed `ControllerStartEvent`. */
711
+ export type AgentControllerStartEvent = ControllerStartEvent;
712
+
703
713
  export function parseConfigValue(
704
714
  option: ConfigOption,
705
715
  rawValue: string,