@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
@@ -1,3 +1,5 @@
1
+ import { DurableNativeMetering } from "../metering/native/durability.ts";
2
+ import { workerTerminalFailure } from "../persistence/worker-terminal-reason.ts";
1
3
  import { writeConversationError } from "./error-record-writer.ts";
2
4
  import type { OperationStalledError } from "../operations/errors.ts";
3
5
  import { randomUUID } from "node:crypto";
@@ -31,6 +33,7 @@ import type {
31
33
  } from "../persistence/provider-attachment.ts";
32
34
 
33
35
  import type { ManagerSettings } from "./manager-settings.ts";
36
+ import { sanitizeConversationErrorMessage } from "../persistence/error-records.ts";
34
37
  import {
35
38
  updateConversationIdentity,
36
39
  persistConversationObservations,
@@ -50,19 +53,31 @@ import type { MediaStore } from "../media/store.ts";
50
53
  export class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle {
51
54
  private readonly outputMedia = new WeakMap<object, string>();
52
55
  private readonly deliveredMessages = new Map<string, { ids: readonly string[]; throughSequence: number }>();
56
+ get reminders() { return this.agent.reminders; }
57
+ readonly nativeMetering: DurableNativeMetering;
58
+
53
59
  constructor(
54
60
  private readonly agent: Agent,
55
61
  private readonly conversationId: AgentConversationId,
56
62
  private readonly initialParticipants: readonly ParticipantRef[],
57
63
  private readonly settings: ManagerSettings,
58
64
  readonly recoverInPlace?: (error: unknown) => Promise<void>,
59
- ) {}
65
+ ) {
66
+ this.nativeMetering = new DurableNativeMetering(agent.persistence, conversationId, agent.id,
67
+ (record) => this.writeMeteringRecord(record));
68
+ }
60
69
 
61
70
  async operationFailed(input: { operationId: string; error: OperationStalledError }): Promise<void> {
62
71
  const written = await writeConversationError(this.agent, this.settings, {
63
72
  agentConversationId: this.conversationId, attemptId: input.operationId,
64
73
  operationId: input.operationId, source: "operation", code: "stalled", recoverability: "retryable",
65
- message: "The provider stopped producing output.", details: { phase: input.error.phase },
74
+ message: input.error.notice
75
+ ? sanitizeConversationErrorMessage(`The provider stopped producing output while retrying: ${input.error.notice.title}`)
76
+ : "The provider stopped producing output.",
77
+ details: {
78
+ phase: input.error.phase,
79
+ ...(input.error.notice ? { providerCode: input.error.notice.code ?? input.error.notice.category } : {}),
80
+ },
66
81
  });
67
82
  if (written.recordingError) throw written.recordingError;
68
83
  }
@@ -93,7 +108,7 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
93
108
  const participants: ParticipantRef[] = [];
94
109
  for (const part of parts) participants.push(await this.resolveParticipant(part.participantId));
95
110
  const participant = participants[0]!;
96
- const identity = await this.agent.identity.load({
111
+ const identity = this.settings.role === "worker" ? {} : await this.agent.identity.load({
97
112
  agentSessionId: this.agent.id,
98
113
  agentConversationId: this.conversationId,
99
114
  targetProviderContextId: input.targetProviderContextId,
@@ -182,6 +197,17 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
182
197
  const prepared = await this.withStoredParts(
183
198
  persistence, records, input.result.messages.map((message) => message.parts), pending);
184
199
  await this.persistObservationsInTransaction(persistence, prepared, true, persisted);
200
+ if (status === "completed") {
201
+ await persistence.workerDelivery?.recordFinal(
202
+ this.conversationId, input.operationId, input.messageIds,
203
+ );
204
+ } else if (status === "cancelled" && input.result.endedBy === "steer") {
205
+ await persistence.workerDelivery?.markSteered(this.conversationId, input.messageIds);
206
+ } else {
207
+ await persistence.workerDelivery?.recordFailure(
208
+ this.conversationId, input.operationId, input.messageIds, workerTerminalFailure(status === "cancelled", undefined, input.result.endedBy),
209
+ );
210
+ }
185
211
  // Delivery is tracked per provider context, so it holds when no user or assistant text is captured.
186
212
  const delivered = this.deliveredMessages.get(input.operationId);
187
213
  if (status === "completed" && delivered) {
@@ -213,6 +239,7 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
213
239
  });
214
240
  }
215
241
  });
242
+ void this.agent.nativeHarness?.flushWorkerDelivery();
216
243
  const deliveredIds = this.deliveredMessages.get(input.operationId)?.ids ?? [];
217
244
  if (status === "completed") for (const id of deliveredIds) pendingOutOfBandParts(this.agent).delete(id);
218
245
  this.deliveredMessages.delete(input.operationId);
@@ -258,7 +285,12 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
258
285
  }),
259
286
  }));
260
287
  const parts = input.messages.map((message) => message.parts);
261
- await this.updateIdentity(await this.persistMessagesWithParts(records, parts));
288
+ await this.updateIdentity(await this.persistMessagesWithParts(records, parts, true, async scope => {
289
+ await scope.workerDelivery?.recordFailure(
290
+ this.conversationId, input.operationId, input.messageIds, workerTerminalFailure(false, input.error),
291
+ );
292
+ }));
293
+ void this.agent.nativeHarness?.flushWorkerDelivery();
262
294
  }
263
295
 
264
296
  resolveAdapter(adapterId: string) {
@@ -329,12 +361,14 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
329
361
  records: readonly NewConversationRecord[],
330
362
  parts: readonly (readonly ResolvedPart[] | undefined)[],
331
363
  audit = true,
364
+ terminal?: (scope: PersistenceScope) => Promise<void>,
332
365
  ): Promise<readonly ConversationRecord[]> {
333
366
  const persisted: ConversationRecord[] = [];
334
367
  const pending: Array<readonly [object, string]> = [];
335
368
  await this.agent.persistence.transaction(async (scope) => {
336
369
  const prepared = await this.withStoredParts(scope, records, parts, pending);
337
370
  await this.persistObservationsInTransaction(scope, prepared, audit, persisted);
371
+ await terminal?.(scope);
338
372
  });
339
373
  for (const [part, ref] of pending) this.outputMedia.set(part, ref);
340
374
  this.agent.publishCommittedRecords(persisted);
@@ -343,6 +377,11 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
343
377
  }
344
378
 
345
379
  async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
380
+ if (record.nativeUsage) return this.nativeMetering.record(record);
381
+ return this.writeMeteringRecord(record);
382
+ }
383
+
384
+ private async writeMeteringRecord(record: OperationMeteringRecord): Promise<void> {
346
385
  const level = this.settings.capture.metering;
347
386
  let reference: ConversationRecord | undefined;
348
387
  await this.agent.persistence.transaction(async (persistence) => {
@@ -407,6 +446,7 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
407
446
  private async persistObservations(
408
447
  records: readonly NewConversationRecord[],
409
448
  audit = true,
449
+ terminal?: (scope: PersistenceScope) => Promise<void>,
410
450
  ): Promise<readonly ConversationRecord[]> {
411
451
  return await persistConversationObservations(this.agent, this.settings, records, audit);
412
452
  }
@@ -0,0 +1,13 @@
1
+ import type { AgentConversationSummary } from "../../persistence/backend.ts";
2
+ import type { ConversationPersistenceContext } from "./types.ts";
3
+
4
+ export function conversationPersistenceContext(summary: AgentConversationSummary): ConversationPersistenceContext {
5
+ return {
6
+ agentConversationId: summary.agentConversationId,
7
+ participants: summary.participants,
8
+ ...(summary.title !== undefined && summary.title !== null ? { title: summary.title } : {}),
9
+ ...(summary.metadata !== undefined && summary.metadata !== null ? { metadata: summary.metadata } : {}),
10
+ adopted: summary.adopted === true,
11
+ ...(summary.role ? { role: summary.role } : {}),
12
+ };
13
+ }
@@ -49,6 +49,13 @@ export class ConversationSettingsResolver {
49
49
  ) {}
50
50
 
51
51
  settingsFor(context: ConversationPersistenceContext): ManagerSettings {
52
+ const settings = this.#resolve(context);
53
+ if (context.role !== "worker") return settings;
54
+ if (settings.capture.message !== "content") throw new Error('worker conversations require message capture "content"');
55
+ return { ...settings, role: "worker" };
56
+ }
57
+
58
+ #resolve(context: ConversationPersistenceContext): ManagerSettings {
52
59
  if (!this.resolver) return this.base;
53
60
  const override = this.resolver(context);
54
61
  if (override === undefined) return this.base;
@@ -37,6 +37,7 @@ export interface ConversationPersistenceContext {
37
37
  readonly metadata?: string;
38
38
  /** True when the conversation was created by adopting an existing provider session. */
39
39
  readonly adopted: boolean;
40
+ readonly role?: "worker";
40
41
  }
41
42
 
42
43
  /**
@@ -41,6 +41,7 @@ export async function updateConversationIdentity(
41
41
  conversationId: AgentConversationId,
42
42
  records: readonly ConversationRecord[],
43
43
  ): Promise<void> {
44
+ if (settings.role === "worker") return;
44
45
  await agent.identity.update({
45
46
  agentSessionId: agent.id,
46
47
  agentConversationId: conversationId,
@@ -1,32 +1,58 @@
1
- import type { Adapter } from "./adapters.ts";
1
+ import { NATIVE_ADAPTER_COMMAND, isNativeAdapter, type Adapter, type AgentAdapter, type NativeAdapter } from "./adapters.ts";
2
2
 
3
3
  export interface AgentAdapterRegistration {
4
4
  readonly id: string;
5
- readonly adapter: Adapter;
5
+ readonly adapter: AgentAdapter;
6
6
  }
7
7
 
8
8
  /** Mutable agent-scoped adapter directory. IDs are routing names, not trust assertions. */
9
9
  export class AgentAdapterRegistry {
10
10
  private readonly values = new Map<string, Adapter>();
11
+ /**
12
+ * Native adapters, by id. Each also has an `Adapter`-shaped entry in `values` (a placeholder command
13
+ * that is never spawned), so everything that lists or resolves adapters keeps one shape.
14
+ */
15
+ private readonly natives = new Map<string, NativeAdapter>();
11
16
 
12
17
  constructor(registrations: readonly AgentAdapterRegistration[] = []) {
13
18
  for (const registration of registrations) this.register(registration.id, registration.adapter);
14
19
  }
15
20
 
16
- register(id: string, adapter: Adapter): void {
21
+ register(id: string, adapter: AgentAdapter): void {
17
22
  const normalized = normalizeAdapterId(id);
18
23
  if (this.values.has(normalized)) throw new Error(`adapter is already registered: ${normalized}`);
19
- this.values.set(normalized, ownAdapter(adapter));
24
+ this.store(normalized, adapter);
20
25
  }
21
26
 
22
- replace(id: string, adapter: Adapter): void {
23
- this.values.set(normalizeAdapterId(id), ownAdapter(adapter));
27
+ replace(id: string, adapter: AgentAdapter): void {
28
+ this.store(normalizeAdapterId(id), adapter);
24
29
  }
25
30
 
26
31
  remove(id: string): boolean {
32
+ this.natives.delete(normalizeAdapterId(id));
27
33
  return this.values.delete(normalizeAdapterId(id));
28
34
  }
29
35
 
36
+ /** The native adapter registered under `id`, or null when the id names an external harness (or nothing). */
37
+ native(id: string): NativeAdapter | null {
38
+ return this.natives.get(normalizeAdapterId(id)) ?? null;
39
+ }
40
+
41
+ private store(id: string, adapter: AgentAdapter): void {
42
+ if (!isNativeAdapter(adapter)) {
43
+ this.natives.delete(id);
44
+ this.values.set(id, ownAdapter(adapter));
45
+ return;
46
+ }
47
+ if (adapter.defaultPolicy !== undefined && !adapter.defaultPolicy.trim()) throw new Error("defaultPolicy cannot be blank");
48
+ this.natives.set(id, Object.freeze({
49
+ kind: "native" as const,
50
+ ...(adapter.defaultPolicy ? { defaultPolicy: adapter.defaultPolicy } : {}),
51
+ ...(adapter.displayName ? { displayName: adapter.displayName } : {}),
52
+ }));
53
+ this.values.set(id, ownAdapter({ command: [...NATIVE_ADAPTER_COMMAND], ...(adapter.displayName ? { displayName: adapter.displayName } : {}) }));
54
+ }
55
+
30
56
  get(id: string): Adapter | null {
31
57
  const adapter = this.values.get(normalizeAdapterId(id));
32
58
  return adapter ? ownAdapter(adapter) : null;
@@ -38,7 +64,7 @@ export class AgentAdapterRegistry {
38
64
  return adapter;
39
65
  }
40
66
 
41
- list(): readonly AgentAdapterRegistration[] {
67
+ list(): readonly (AgentAdapterRegistration & { readonly adapter: Adapter })[] {
42
68
  return Object.freeze([...this.values].map(([id, adapter]) => Object.freeze({
43
69
  id,
44
70
  adapter: ownAdapter(adapter),
@@ -1,4 +1,8 @@
1
+ import type { ConsumerReminderEvent } from "./native/reminders/wire.ts";
2
+ import type { ReminderEvent } from "./native/reminders/service.ts";
3
+ import type { ConversationPermissionEvent } from "./permissions/conversation.ts";
1
4
  import type { OperationActivity } from "./operations/contracts.ts";
5
+ import type { ItemsReceipt, TurnCause } from "./conversation-controller/contracts.ts";
2
6
  import type { AgentMode } from "./controller.ts";
3
7
  import type { MessageEvent, PendingMessageId, PromptEndedBy } from "./steering/contracts.ts";
4
8
  import type { Adapter } from "./adapters.ts";
@@ -205,13 +209,22 @@ export interface HandoffResult {
205
209
 
206
210
  /** Conversation-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
207
211
  export type AgentSessionEvent =
212
+ | ReminderEvent
213
+ | ConsumerReminderEvent
214
+ | ConversationPermissionEvent
208
215
  | { kind: "provider_reconnected"; via: "loaded" | "recovered" | "fresh"; internalSessionId: string }
209
216
  | { kind: "operation_stage_changed"; activity: OperationActivity }
210
217
  | { kind: "state_changed"; state: AgentSessionState }
211
- | { kind: "turn_started"; turnId: string }
218
+ | {
219
+ kind: "turn_started";
220
+ turnId: string;
221
+ /** Why the turn started: the messages it carries (every message of a combined steer run). */
222
+ cause: TurnCause;
223
+ }
212
224
  | { kind: "turn_completed"; turnId: string; result: PromptResult }
213
225
  | { kind: "turn_failed"; turnId: string; error: string }
214
226
  | MessageEvent
227
+ | ItemsReceipt
215
228
  | { kind: "presentation_recorded"; item: TranscriptPresentationItem }
216
229
  | { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
217
230
  | { kind: "handoff_started"; handoffId: string; fromInternalSessionId: string | null }
@@ -12,6 +12,14 @@ export class AgentSessionPromptBlockedError extends Error {
12
12
  }
13
13
  }
14
14
 
15
+ /** The conversation stopped observing a native input before a turn took it. */
16
+ export class NativeInputStoppedError extends Error {
17
+ constructor(readonly messageId: string) {
18
+ super("the conversation stopped observing this native input");
19
+ this.name = "NativeInputStoppedError";
20
+ }
21
+ }
22
+
15
23
  export class ContinuationUnavailableError extends Error {
16
24
  constructor(readonly continuation: ContinuationReport, options?: ErrorOptions) {
17
25
  super("recorded internal session could not be loaded", options);
@@ -1,3 +1,5 @@
1
+ import type { ReminderService } from "./native/reminders/service.ts";
2
+ import type { NativeMeteringRecovery } from "./metering/native/durability.ts";
1
3
  import type { AgentConversationId, AgentSessionId } from "./agent-ids.ts";
2
4
  import type { Adapter } from "./adapters.ts";
3
5
  import type { AgentMode } from "./controller.ts";
@@ -37,8 +39,9 @@ export interface OwnedPromptInput {
37
39
  };
38
40
  }
39
41
 
40
- /** How a turn's assistant messages ended, for its commit. */
41
- interface OwnedPromptMessageEnds {
42
+ interface OwnedPromptTurnMessages {
43
+ /** The turn's input message IDs in cause order, including messages taken after it began. */
44
+ readonly messageIds: readonly string[];
42
45
  /**
43
46
  * When each message that ended before the turn did (the next message or a tool call began)
44
47
  * received its last text, in order. Those messages are completed at these times; the rest take
@@ -56,7 +59,7 @@ export interface OwnedPromptPreparation {
56
59
  readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
57
60
  }
58
61
 
59
- export interface OwnedPromptCompleted extends OwnedPromptInput, OwnedPromptMessageEnds {
62
+ export interface OwnedPromptCompleted extends OwnedPromptInput, OwnedPromptTurnMessages {
60
63
  readonly result: AgentSessionPromptResult;
61
64
  readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
62
65
  readonly providerAttachment: ProviderAttachmentState;
@@ -77,13 +80,15 @@ export class OwnedPromptPostCommitError extends Error {
77
80
  }
78
81
  }
79
82
 
80
- export interface OwnedPromptFailed extends OwnedPromptInput, OwnedPromptMessageEnds {
83
+ export interface OwnedPromptFailed extends OwnedPromptInput, OwnedPromptTurnMessages {
81
84
  readonly messages: readonly ResponseMessage[];
82
85
  readonly error: unknown;
83
86
  }
84
87
 
85
88
  /** @internal Agent-owned persistence and identity boundary for a conversation turn. */
86
89
  export interface AgentConversationOwnerLifecycle {
90
+ readonly reminders?: ReminderService;
91
+ readonly nativeMetering?: NativeMeteringRecovery;
87
92
  operationFailed?(input: { readonly operationId: string; readonly error: OperationStalledError }): Promise<void>;
88
93
  recoverInPlace?(error: unknown): Promise<void>;
89
94
  beforePrompt(input: OwnedPromptInput): Promise<OwnedPromptPreparation>;
@@ -0,0 +1,137 @@
1
+ import type * as schema from "@agentclientprotocol/sdk";
2
+ import type { Adapter } from "./adapters.ts";
3
+ import type { AgentConversationId, AgentSessionId } from "./agent-ids.ts";
4
+ import type { NativeControllerBinding } from "./conversation-controller/index.ts";
5
+ import type { AgentControllerConfig, AgentMode } from "./controller.ts";
6
+ import type { Logger } from "./logger.ts";
7
+ import type { MeteringConfig } from "./metering/record.ts";
8
+ import type { OperationLifecycleConfig } from "./operations/contracts.ts";
9
+ import type { ConversationPermissionConfig } from "./permissions/policy.ts";
10
+ import type { AgentSessionCheckpoint } from "./persistence/checkpoint.ts";
11
+ import type { AgentSessionPersistenceOptions } from "./persistence/config.ts";
12
+ import type { ParticipantRef } from "./persistence/backend.ts";
13
+ import type { SessionManager } from "./session-manager.ts";
14
+ import type { PromptDelivery } from "./steering/index.ts";
15
+ import type { WireEntry } from "./types.ts";
16
+ import type { AgentConversationOwnerLifecycle } from "./agent-conversation-owner.ts";
17
+ import type { OpenContinuationOptions, ProviderSession, TranscriptActivityConfig } from "./agent-conversation-contracts.ts";
18
+
19
+ export interface AgentSessionConfig extends ConversationPermissionConfig {
20
+ /** Cancels the factory's startup before it returns the conversation. */
21
+ signal?: AbortSignal;
22
+ /** @internal Agent-owned ACP startup policy. */
23
+ deferProviderStart?: boolean;
24
+ /** The resolved adapter this conversation talks to. */
25
+ adapter: Adapter;
26
+ /** Stable adapter id for the catalog/display (e.g. "codex"). */
27
+ adapterId: string;
28
+ /** Talk over ACP ("normal") or scrape a pty ("degraded"). Default "normal". */
29
+ mode?: AgentMode;
30
+ /** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
31
+ launcher?: AgentControllerConfig["launcher"];
32
+ /**
33
+ * Binds this conversation to a channel of a shared native harness instead of an external harness
34
+ * process. Opt-in: absent for every ACP conversation. `adapter` is then display only.
35
+ */
36
+ native?: NativeControllerBinding;
37
+ /** Override the owning Agent’s idle stop window for this conversation. */
38
+ idleStopWindowMs?: number;
39
+ /** @internal Resolves native routes in the owning Agent. */
40
+ isNativeAdapter?: (adapterId: string) => boolean;
41
+ /** @deprecated Use launcher. */
42
+ execPrefix?: string[];
43
+ /** @deprecated Use launcher and its exact spawnEnv. */
44
+ env?: Record<string, string>;
45
+ /** Exact environment for built-in ACP terminals. */
46
+ terminalEnv?: Record<string, string>;
47
+ cwd?: string;
48
+ /** Additional absolute directories declared to the provider. */
49
+ additionalDirectories?: string[];
50
+ /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
51
+ mcpServers?: schema.McpServer[];
52
+ /**
53
+ * How a prompt sent while a turn is running waits when the prompt does not say. `queue` runs it after
54
+ * the turn ends; `steer` delivers it at the next tool boundary. Default `steer`.
55
+ */
56
+ busyDelivery?: PromptDelivery;
57
+ clientInfo?: { name: string; title?: string; version?: string };
58
+ /** What we let the agent do through us (terminals, filesystem). All on by default. */
59
+ clientCapabilities?: AgentControllerConfig["clientCapabilities"];
60
+ /** Client-side ACP implementations; their presence determines advertisement. */
61
+ clientHandlers?: AgentControllerConfig["clientHandlers"];
62
+ logger?: Logger;
63
+ /** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
64
+ wire?: (entry: WireEntry) => void;
65
+ /** Optional catalog. When present, the session records itself here. */
66
+ sessions?: SessionManager;
67
+ /** New v2 persistence. Direct sessions remain persistence-free when omitted. */
68
+ persistence?: false | AgentSessionPersistenceOptions;
69
+ /** Stable creation transaction/incarnation ID; required by direct v2 persistence. */
70
+ creationId?: string;
71
+ /**
72
+ * Absolute path to an append-only transcript file. This selects history storage only;
73
+ * file existence never selects the provider thread. Omitted means no transcript.
74
+ */
75
+ transcriptPath?: string;
76
+ /**
77
+ * Directory for `<encoded-agentSessionId>.jsonl`. This selects history storage only;
78
+ * the directory is not a session catalog and is not scanned during creation.
79
+ */
80
+ transcriptDir?: string;
81
+ /**
82
+ * Also record activity (thinking, tool calls and their output, plans) as `t:"activity"`
83
+ * lines. Off by default — it makes transcripts larger, and `readTranscript()` ignores
84
+ * them either way; read them with `readTranscriptLines()`.
85
+ *
86
+ * Lines are SETTLED records, not raw deltas: the session folds the delta stream and
87
+ * writes checkpoints (announced → input → settled), typically 2–3 lines per tool call
88
+ * instead of one per notification. Fold them back with `foldRecords()`, last-wins on
89
+ * `recordId`. `true` selects the defaults below.
90
+ */
91
+ transcriptActivity?: boolean | TranscriptActivityConfig;
92
+ /** Stable logical identity. Minted if omitted; always available on the created object. */
93
+ agentSessionId?: string;
94
+ /** Provider-thread startup intent. Default `{ kind: "new" }`. */
95
+ providerSession?: ProviderSession;
96
+ /** Stale limits per operation kind (turns, internal inference, recap). */
97
+ operationLifecycle?: OperationLifecycleConfig;
98
+ /**
99
+ * Token/cost metering policy. Optional: omitting it selects best-effort enforcement
100
+ * with the pinned models.dev catalog and no restored state. Metering is not something a
101
+ * consumer must turn on merely to see protocol facts.
102
+ */
103
+ metering?: MeteringConfig;
104
+ /**
105
+ * @deprecated Use `providerSession: { kind: "load", internalSessionId, onFailure }`.
106
+ * Retains the historical fallback-to-new behavior for compatibility.
107
+ */
108
+ internalSessionId?: string;
109
+ title?: string;
110
+ /** Stable conversation identity when this runtime is owned by an Agent. */
111
+ agentConversationId?: AgentConversationId;
112
+ /** Stable owning agent identity. Omitted for detached compatibility conversations. */
113
+ ownerAgentSessionId?: AgentSessionId;
114
+ /** Other sides of this conversation. The owning agent is implied. */
115
+ participants?: readonly ParticipantRef[];
116
+ /** @internal Installed by AgentConversationManager. */
117
+ ownerLifecycle?: AgentConversationOwnerLifecycle;
118
+ }
119
+
120
+ /** Direct restoration input. Phase 5A intentionally supports the safe recorded-thread path. */
121
+ export interface AgentSessionOpenConfig extends Omit<
122
+ AgentSessionConfig,
123
+ | "agentSessionId"
124
+ | "creationId"
125
+ | "providerSession"
126
+ | "internalSessionId"
127
+ | "mode"
128
+ | "persistence"
129
+ | "sessions"
130
+ > {
131
+ /** Required for directory/default path resolution; exact-file inference is a later slice. */
132
+ agentSessionId: string;
133
+ persistence: AgentSessionPersistenceOptions;
134
+ /** Optional consumer copy must exactly match transcript authority in this first slice. */
135
+ checkpoint?: AgentSessionCheckpoint;
136
+ continuation?: OpenContinuationOptions;
137
+ }