agl 43.2.0 → 43.3.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 (213) hide show
  1. package/changelog.md +29 -0
  2. package/dist_serve/bundle.js +2845 -2638
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +1 -1
  5. package/dist_serve/bundle.js.third-party-notices.txt +1 -1
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +197 -17
  8. package/dist_ts/classes.accountsactions.d.ts +3 -1
  9. package/dist_ts/classes.accountsactions.js +21 -3
  10. package/dist_ts/classes.authstore.d.ts +7 -0
  11. package/dist_ts/classes.authstore.js +9 -1
  12. package/dist_ts/classes.claudeharness.d.ts +29 -2
  13. package/dist_ts/classes.claudeharness.js +35 -6
  14. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  15. package/dist_ts/classes.codexclientadapter.js +14 -2
  16. package/dist_ts/classes.controller.d.ts +187 -12
  17. package/dist_ts/classes.controller.js +1208 -186
  18. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  19. package/dist_ts/classes.controllerdevices.js +6 -1
  20. package/dist_ts/classes.inbox.d.ts +72 -0
  21. package/dist_ts/classes.inbox.js +231 -0
  22. package/dist_ts/classes.inferencerouter.d.ts +10 -0
  23. package/dist_ts/classes.inferencerouter.js +5 -3
  24. package/dist_ts/classes.inferenceservice.js +2 -2
  25. package/dist_ts/classes.mcpclient.d.ts +1 -1
  26. package/dist_ts/classes.mcpclient.js +24 -6
  27. package/dist_ts/classes.mcpcontrollerhost.js +6 -1
  28. package/dist_ts/classes.mcptools.js +18 -8
  29. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  30. package/dist_ts/classes.mcpvalidation.js +32 -2
  31. package/dist_ts/classes.nativesessions.d.ts +29 -4
  32. package/dist_ts/classes.nativesessions.js +41 -9
  33. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  34. package/dist_ts/classes.opencodeclient.js +47 -3
  35. package/dist_ts/classes.publishedset.d.ts +38 -0
  36. package/dist_ts/classes.publishedset.js +50 -0
  37. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  38. package/dist_ts/classes.sessionfeed.js +18 -26
  39. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  40. package/dist_ts/classes.systemmetricssampler.js +15 -3
  41. package/dist_ts/classes.ticketstore.d.ts +50 -3
  42. package/dist_ts/classes.ticketstore.js +45 -8
  43. package/dist_ts/classes.workercallers.js +4 -2
  44. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  45. package/dist_ts/driver/classes.directreports.js +42 -23
  46. package/dist_ts/driver/classes.directreportstore.d.ts +8 -1
  47. package/dist_ts/driver/classes.directreportstore.js +20 -10
  48. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  49. package/dist_ts/driver/classes.driverservice.js +50 -16
  50. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  51. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  52. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  53. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  54. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  55. package/dist_ts/fleet/classes.workercommand.js +15 -4
  56. package/dist_ts/fleet/classes.workers.d.ts +21 -1
  57. package/dist_ts/fleet/classes.workers.js +80 -40
  58. package/dist_ts/fleet/classes.workerstore.js +14 -8
  59. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  60. package/dist_ts/fleet/functions.workervalidation.js +11 -4
  61. package/dist_ts/fleet/interfaces.workers.d.ts +27 -5
  62. package/dist_ts/fleet/interfaces.workers.js +8 -4
  63. package/dist_ts/functions.agentmessage.d.ts +3 -0
  64. package/dist_ts/functions.agentmessage.js +4 -1
  65. package/dist_ts/functions.deviceapi.d.ts +198 -4
  66. package/dist_ts/functions.deviceapi.js +1060 -38
  67. package/dist_ts/functions.exactpersistence.d.ts +3 -0
  68. package/dist_ts/functions.exactpersistence.js +4 -0
  69. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  70. package/dist_ts/functions.fleetworkercli.js +11 -8
  71. package/dist_ts/functions.inferencecli.js +3 -1
  72. package/dist_ts/functions.mcpfleetworkertools.js +3 -3
  73. package/dist_ts/functions.ticketactor.d.ts +17 -1
  74. package/dist_ts/functions.ticketactor.js +55 -15
  75. package/dist_ts/functions.ticketvalidation.js +11 -2
  76. package/dist_ts/interfaces.auth.d.ts +1 -1
  77. package/dist_ts/interfaces.auth.js +9 -1
  78. package/dist_ts/plugins.d.ts +3 -1
  79. package/dist_ts/plugins.js +7 -2
  80. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  81. package/dist_ts_authswitch/authority-contract.js +1 -1
  82. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  83. package/dist_ts_authswitch/authority-overview.js +17 -6
  84. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  85. package/dist_ts_authswitch/authority-placement.js +17 -10
  86. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  87. package/dist_ts_authswitch/authority-renewal.js +56 -0
  88. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  89. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  90. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  91. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  92. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  93. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  94. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  95. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  96. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  97. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  98. package/dist_ts_interfaces/devices.d.ts +1027 -7
  99. package/dist_ts_interfaces/devices.js +68 -2
  100. package/dist_ts_interfaces/fleetworkers.d.ts +37 -10
  101. package/dist_ts_interfaces/fleetworkers.js +19 -8
  102. package/dist_ts_interfaces/inbox.d.ts +234 -0
  103. package/dist_ts_interfaces/inbox.js +101 -0
  104. package/dist_ts_interfaces/index.d.ts +1 -0
  105. package/dist_ts_interfaces/index.js +2 -1
  106. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  107. package/dist_ts_interfaces/interfaces.js +4 -2
  108. package/dist_ts_interfaces/mcprequests.d.ts +34 -4
  109. package/dist_ts_interfaces/mcprequests.js +11 -1
  110. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  111. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  112. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  113. package/dist_ts_interfaces/plugins.d.ts +2 -1
  114. package/dist_ts_interfaces/plugins.js +4 -2
  115. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  116. package/dist_ts_interfaces/requests.accounts.js +3 -1
  117. package/dist_ts_interfaces/requests.d.ts +3 -2
  118. package/dist_ts_interfaces/requests.js +1 -1
  119. package/dist_ts_interfaces/workercallers.d.ts +2 -0
  120. package/dist_ts_migration/classes.documentmigrationrunner.d.ts +14 -0
  121. package/dist_ts_migration/classes.documentmigrationrunner.js +20 -1
  122. package/dist_ts_migration/index.d.ts +1 -0
  123. package/dist_ts_migration/index.js +2 -1
  124. package/dist_ts_migration/v43_ticketactornames.d.ts +32 -0
  125. package/dist_ts_migration/v43_ticketactornames.js +236 -0
  126. package/docs/authswitch.md +20 -1
  127. package/package.json +3 -3
  128. package/readme.md +144 -27
  129. package/ts/00_commitinfo_data.ts +1 -1
  130. package/ts/aglapi/aglapisurface.document.ts +196 -16
  131. package/ts/classes.accountsactions.ts +30 -3
  132. package/ts/classes.authstore.ts +10 -0
  133. package/ts/classes.claudeharness.ts +45 -5
  134. package/ts/classes.codexclientadapter.ts +14 -1
  135. package/ts/classes.controller.ts +1412 -262
  136. package/ts/classes.controllerdevices.ts +6 -0
  137. package/ts/classes.inbox.ts +239 -0
  138. package/ts/classes.inferencerouter.ts +15 -2
  139. package/ts/classes.inferenceservice.ts +1 -1
  140. package/ts/classes.mcpclient.ts +24 -3
  141. package/ts/classes.mcpcontrollerhost.ts +5 -0
  142. package/ts/classes.mcptools.ts +17 -7
  143. package/ts/classes.mcpvalidation.ts +27 -1
  144. package/ts/classes.nativesessions.ts +63 -12
  145. package/ts/classes.opencodeclient.ts +55 -4
  146. package/ts/classes.publishedset.ts +56 -0
  147. package/ts/classes.sessionfeed.ts +17 -20
  148. package/ts/classes.systemmetricssampler.ts +13 -2
  149. package/ts/classes.ticketstore.ts +73 -12
  150. package/ts/classes.workercallers.ts +3 -1
  151. package/ts/driver/classes.directreports.ts +42 -23
  152. package/ts/driver/classes.directreportstore.ts +20 -9
  153. package/ts/driver/classes.driverservice.ts +75 -14
  154. package/ts/fleet/classes.claudeworkers.ts +112 -39
  155. package/ts/fleet/classes.codexworkers.ts +21 -6
  156. package/ts/fleet/classes.workercommand.ts +14 -4
  157. package/ts/fleet/classes.workers.ts +75 -41
  158. package/ts/fleet/classes.workerstore.ts +11 -7
  159. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  160. package/ts/fleet/functions.workervalidation.ts +8 -3
  161. package/ts/fleet/interfaces.workers.ts +26 -7
  162. package/ts/functions.agentmessage.ts +3 -0
  163. package/ts/functions.deviceapi.ts +1292 -34
  164. package/ts/functions.exactpersistence.ts +5 -0
  165. package/ts/functions.fleetworkercli.ts +10 -7
  166. package/ts/functions.inferencecli.ts +2 -0
  167. package/ts/functions.mcpfleetworkertools.ts +2 -2
  168. package/ts/functions.ticketactor.ts +58 -14
  169. package/ts/functions.ticketvalidation.ts +11 -1
  170. package/ts/interfaces.auth.ts +8 -0
  171. package/ts/plugins.ts +7 -0
  172. package/ts_authswitch/authority-contract.ts +20 -0
  173. package/ts_authswitch/authority-overview.ts +28 -6
  174. package/ts_authswitch/authority-placement.ts +25 -17
  175. package/ts_authswitch/authority-renewal.ts +64 -0
  176. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  177. package/ts_authswitch/classes.authoritycli.ts +49 -2
  178. package/ts_authswitch/classes.authorityclient.ts +14 -4
  179. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  180. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  181. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  182. package/ts_authswitch/native-contracts.md +21 -0
  183. package/ts_authswitch/readme.md +1 -1
  184. package/ts_interfaces/devices.schema.json +3576 -603
  185. package/ts_interfaces/devices.ts +1111 -6
  186. package/ts_interfaces/fleetworkers.ts +38 -10
  187. package/ts_interfaces/inbox.ts +287 -0
  188. package/ts_interfaces/index.ts +1 -0
  189. package/ts_interfaces/interfaces.ts +9 -2
  190. package/ts_interfaces/mcprequests.ts +43 -4
  191. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  192. package/ts_interfaces/nativesessions.ts +17 -3
  193. package/ts_interfaces/plugins.ts +3 -1
  194. package/ts_interfaces/requests.accounts.ts +20 -0
  195. package/ts_interfaces/requests.ts +4 -0
  196. package/ts_interfaces/workercallers.ts +2 -0
  197. package/ts_migration/classes.documentmigrationrunner.ts +21 -0
  198. package/ts_migration/index.ts +1 -0
  199. package/ts_migration/v43_ticketactornames.ts +225 -0
  200. package/ts_web/00_commitinfo_data.ts +1 -1
  201. package/ts_web/accounts.plugins.ts +4 -2
  202. package/ts_web/classes.accountsreadmodel.ts +33 -0
  203. package/ts_web/classes.browserpresentation.ts +10 -5
  204. package/ts_web/classes.inboxfeed.ts +329 -0
  205. package/ts_web/classes.nativesessionstate.ts +9 -23
  206. package/ts_web/elements.accounts.ts +81 -0
  207. package/ts_web/elements.deployments.ts +66 -2
  208. package/ts_web/elements.fleetworker.ts +4 -2
  209. package/ts_web/elements.harnesscontrollerapp.ts +107 -37
  210. package/ts_web/elements.inbox.ts +808 -0
  211. package/ts_web/functions.inbox.ts +95 -0
  212. package/ts_web/functions.sessioncards.ts +40 -0
  213. package/ts_web/plugins.ts +2 -0
@@ -7,7 +7,7 @@ import * as plugins from '../plugins.js';
7
7
  import type { IFleetSessionBindingFailure, IFleetSessionBindings } from '../fleet/classes.workers.js';
8
8
  import type { IFleetNativeAgent, IFleetNativeThread } from '../fleet/interfaces.workers.js';
9
9
  import type { IResolvedNativeSession } from '../classes.nativesessions.js';
10
- import { DirectReportConflictError, DirectReportStore, type IDirectReportStore } from './classes.directreportstore.js';
10
+ import { DirectReportConflictError, DirectReportError, DirectReportStore, type IDirectReportStore } from './classes.directreportstore.js';
11
11
 
12
12
  /** What direct reports read from the fleet, the native inventories and the ticket board; the controller supplies it. */
13
13
  export interface IDirectReportsHost {
@@ -45,6 +45,19 @@ export type TDirectReportChannel =
45
45
  | { kind: 'fleet-worker'; report: IDirectReport; workerName: string }
46
46
  | { kind: 'session'; report: IDirectReport; nativeId: string; cwd: string };
47
47
 
48
+ /**
49
+ * Whether AGL reaches the report to read or message it: through the fleet worker it is, or the Codex thread it is. A
50
+ * Claude Code session the fleet does not run it reaches only as a second writer, so never.
51
+ */
52
+ export const directReportReachable = (report: IDirectReport): boolean => report.session.kind === 'fleet-worker' || report.session.harness === 'codex';
53
+
54
+ /** The native session a report is (`IDirectReport.sessionId`, `harness:nativeId`) as a runtime id. */
55
+ export const directReportRuntimeId = (report: IDirectReport): { harnessId: TFleetWorkerHarness; nativeId: string } => {
56
+ const separator = report.sessionId.indexOf(':'), harnessId = report.sessionId.slice(0, separator), nativeId = report.sessionId.slice(separator + 1);
57
+ if (separator < 0 || (harnessId !== 'claude' && harnessId !== 'codex') || !nativeId) throw new DirectReportError(`Direct report ${report.name} names no Claude Code or Codex session.`);
58
+ return { harnessId, nativeId };
59
+ };
60
+
48
61
  /** The newest line of `text` that starts with `result:`, the line a session ends a turn on. */
49
62
  export const directReportResultLine = (text: string): string | undefined => {
50
63
  const line = text.split(/\r?\n/u).findLast((lineArg) => /^\s*result:/iu.test(lineArg));
@@ -140,9 +153,9 @@ export class DirectReports implements IFleetSessionBindings {
140
153
  /** Appoints the fleet worker `workerName`, bound to a native session and a ticket, as the report `name`. */
141
154
  public async appoint(owner: string, request: IReq_ControllerDirectReportAppoint['request'], signal?: AbortSignal): Promise<IDirectReportView> {
142
155
  const workers = await this.host.workers(owner), worker = workers.find((view) => view.worker.name === request.workerName)?.worker;
143
- if (!worker) throw new Error('The fleet worker is unavailable.');
144
- if (!worker.nativeId) throw new Error('The fleet worker has no native session yet.');
145
- if (!worker.ticketKey) throw new Error('The fleet worker is bound to no ticket; a direct report is steered through its ticket.');
156
+ if (!worker) throw new DirectReportError('The fleet worker is unavailable.');
157
+ if (!worker.nativeId) throw new DirectReportError('The fleet worker has no native session yet.');
158
+ if (!worker.ticketKey) throw new DirectReportError('The fleet worker is bound to no ticket; a direct report is steered through its ticket.');
146
159
  const projects = request.projects ?? [await this.host.ticketProject(worker.ticketKey, signal)];
147
160
  const report = await this.store.create(owner, this.report(owner, request.name, { kind: 'fleet-worker', workerName: worker.name },
148
161
  `${worker.harness}:${worker.nativeId}`, projects, worker.ticketKey));
@@ -195,15 +208,15 @@ export class DirectReports implements IFleetSessionBindings {
195
208
  public async adopt(owner: string, request: IReq_ControllerDirectReportAdopt['request'], signal?: AbortSignal, actor?: ITicketActor): Promise<IDirectReportView> {
196
209
  const { harness, nativeId, relaunch } = request;
197
210
  if (harness === 'claude' && !relaunch) {
198
- throw new Error('A Claude Code session is adopted with a relaunch: the fleet resumes it under its own control, which gives it a verified identity.');
211
+ throw new DirectReportError('A Claude Code session is adopted with a relaunch: the fleet resumes it under its own control, which gives it a verified identity.');
199
212
  }
200
- if (harness === 'codex' && relaunch) throw new Error('A Codex thread is adopted by reference; only a Claude Code session is relaunched.');
213
+ if (harness === 'codex' && relaunch) throw new DirectReportError('A Codex thread is adopted by reference; only a Claude Code session is relaunched.');
201
214
  if ((await this.host.workers(owner)).some((view) => view.worker.harness === harness && view.worker.nativeId === nativeId)) {
202
- throw new Error('A fleet worker is bound to this session; appoint the worker instead.');
215
+ throw new DirectReportError('A fleet worker is bound to this session; appoint the worker instead.');
203
216
  }
204
217
  const observations: IDirectReportObservations = harness === 'claude' ? { claude: await this.host.claudeSessions() } : { codex: await this.host.codexThreads() };
205
218
  const session = (observations.claude ?? observations.codex ?? []).find((item) => item.sessionId === nativeId);
206
- if (!session) throw new Error(`The ${harness === 'claude' ? 'Claude Code session' : 'Codex thread'} is not on this host.`);
219
+ if (!session) throw new DirectReportError(`The ${harness === 'claude' ? 'Claude Code session' : 'Codex thread'} is not on this host.`);
207
220
  const project = await this.host.ticketProject(request.driverTicketKey, signal);
208
221
  if (!relaunch) {
209
222
  const report = await this.store.create(owner, this.report(owner, request.name, { kind: 'session', harness, nativeId },
@@ -212,14 +225,14 @@ export class DirectReports implements IFleetSessionBindings {
212
225
  }
213
226
  // Refused before the relaunch: a session that ran as a report keeps that report, and a name stays taken once used.
214
227
  const reports = await this.store.list(owner);
215
- if (reports.some((report) => report.name === request.name)) throw new Error('A direct report of that name exists.');
216
- if (reports.some((report) => report.state === 'active' && report.sessionId === `claude:${nativeId}`)) throw new Error('Another active direct report already holds this session.');
228
+ if (reports.some((report) => report.name === request.name)) throw new DirectReportError('A direct report of that name exists.');
229
+ if (reports.some((report) => report.state === 'active' && report.sessionId === `claude:${nativeId}`)) throw new DirectReportError('Another active direct report already holds this session.');
217
230
  // Only the host's own Claude Code home holds project conversations; a session its profile's home does not list is
218
231
  // refused by the relaunch itself.
219
232
  if ((await this.host.claudeProfiles()).some((profile) => profile.id === relaunch.profile && profile.home === undefined)) {
220
233
  const listed = await this.host.nativeSession({ harness: 'claude', nativeId }).catch((error: unknown) => { if (notListed(error)) return undefined; throw error; });
221
234
  if (listed?.session.readOnly?.reason === 'projectConversation') {
222
- throw new Error('An AGL project conversation records this Claude Code session, so it stays that project\'s: a relaunch would give the conversation a second writer.');
235
+ throw new DirectReportError('An AGL project conversation records this Claude Code session, so it stays that project\'s: a relaunch would give the conversation a second writer.');
223
236
  }
224
237
  }
225
238
  const worker = await this.host.relaunch(owner, { name: relaunch.workerName ?? request.name, profile: relaunch.profile, cwd: relaunch.cwd ?? session.cwd,
@@ -229,7 +242,7 @@ export class DirectReports implements IFleetSessionBindings {
229
242
  report = await this.store.create(owner, this.report(owner, request.name, { kind: 'fleet-worker', workerName: worker.name },
230
243
  `${worker.harness}:${worker.nativeId}`, request.projects ?? [project], request.driverTicketKey));
231
244
  } catch (error) {
232
- throw new Error(`The session was relaunched as fleet worker ${worker.name}, but its direct report was not recorded: ${error instanceof Error ? error.message : String(error)} Appoint the worker as the report.`.slice(0, 4096));
245
+ throw new DirectReportError(`The session was relaunched as fleet worker ${worker.name}, but its direct report was not recorded. Appoint the worker as the report.`, { cause: error });
233
246
  }
234
247
  return this.view(report, { workers: await this.host.workers(owner) }, await this.host.openQuestions(signal));
235
248
  }
@@ -237,7 +250,7 @@ export class DirectReports implements IFleetSessionBindings {
237
250
  /** Retires the report; its session is left as it is. */
238
251
  public async retire(owner: string, name: string): Promise<IDirectReport> {
239
252
  return await this.serialized(owner, name, () => this.store.update(owner, name, (report) => {
240
- if (report.state === 'retired') throw new Error('The direct report is retired.');
253
+ if (report.state === 'retired') throw new DirectReportError('The direct report is retired.');
241
254
  report.state = 'retired';
242
255
  }));
243
256
  }
@@ -251,27 +264,33 @@ export class DirectReports implements IFleetSessionBindings {
251
264
  */
252
265
  public async channelOf(owner: string, name: string): Promise<TDirectReportChannel> {
253
266
  const report = await this.store.get(owner, name);
254
- if (!report || report.state !== 'active') throw new Error(`Direct report ${name} is not an active direct report.`);
267
+ if (!report || report.state !== 'active') throw new DirectReportError(`Direct report ${name} is not an active direct report.`);
255
268
  const session = report.session;
256
269
  if (session.kind === 'fleet-worker') return { kind: 'fleet-worker', report, workerName: session.workerName };
257
- if (session.harness === 'claude') {
258
- throw new Error(`Direct report ${name} is a Claude Code session the fleet does not run, so it cannot be read or messaged: AGL reaches a Claude Code session only by resuming it in a process of its own, a second writer beside the one that runs it. Adopt the session with a relaunch (directreport_adopt) once it has settled.`);
270
+ if (!directReportReachable(report)) {
271
+ throw new DirectReportError(`Direct report ${name} is a Claude Code session the fleet does not run, so it cannot be read or messaged: AGL reaches a Claude Code session only by resuming it in a process of its own, a second writer beside the one that runs it. Adopt the session with a relaunch (directreport_adopt) once it has settled.`);
259
272
  }
260
273
  const thread = (await this.host.codexThreads()).find((item) => item.sessionId === session.nativeId);
261
- if (!thread) throw new Error(`Direct report ${name}'s Codex thread ${session.nativeId} is not among the threads of this host's Codex server.`);
274
+ if (!thread) throw new DirectReportError(`Direct report ${name}'s Codex thread ${session.nativeId} is not among the threads of this host's Codex server.`);
262
275
  return { kind: 'session', report, nativeId: session.nativeId, cwd: thread.cwd };
263
276
  }
264
277
 
265
278
  /**
266
- * The owner's workers an active direct report runs: those whose `reportsTo` names it. A worker that is itself an
267
- * active report's session reports to the owner.
279
+ * The owner's workers each active direct report runs, by the report's name: those whose `reportsTo` names it. A
280
+ * worker that is itself an active report's session reports to the owner, so to no report.
268
281
  */
269
- public async reportWorkers(owner: string): Promise<Set<string>> {
282
+ public async reportWorkers(owner: string): Promise<Map<string, IControllerFleetWorkerView[]>> {
270
283
  const active = (await this.store.list(owner)).filter((report) => report.state === 'active');
271
- if (!active.length) return new Set();
284
+ const groups = new Map<string, IControllerFleetWorkerView[]>();
285
+ if (!active.length) return groups;
272
286
  const names = new Set(active.map((report) => report.name));
273
287
  const reporting = new Set(active.flatMap((report) => report.session.kind === 'fleet-worker' ? [report.session.workerName] : []));
274
- return new Set((await this.host.workers(owner)).flatMap(({ worker }) => worker.reportsTo && names.has(worker.reportsTo) && !reporting.has(worker.name) ? [worker.name] : []));
288
+ for (const view of await this.host.workers(owner)) {
289
+ const superior = view.worker.reportsTo;
290
+ if (!superior || !names.has(superior) || reporting.has(view.worker.name)) continue;
291
+ groups.set(superior, [...groups.get(superior) ?? [], view]);
292
+ }
293
+ return groups;
275
294
  }
276
295
 
277
296
  /** The active report whose session is `sessionId` (`harness:nativeId`), if any. */
@@ -326,7 +345,7 @@ export class DirectReports implements IFleetSessionBindings {
326
345
  const current = await this.store.get(owner, name), move = current && directReportMove(current, workers);
327
346
  if (!current || !move) return;
328
347
  const ticketKey = move.to.ticketKey;
329
- if (current.session.kind === 'session' && !ticketKey) throw new Error(`Fleet worker ${move.to.name} is bound to no ticket.`);
348
+ if (current.session.kind === 'session' && !ticketKey) throw new DirectReportError(`Fleet worker ${move.to.name} is bound to no ticket.`);
330
349
  try {
331
350
  await this.store.update(owner, name, (next) => {
332
351
  if (!plugins.util.isDeepStrictEqual(next, current)) throw new DirectReportConflictError();
@@ -1,4 +1,5 @@
1
1
  import * as plugins from '../plugins.js';
2
+ import { exactError } from '../functions.exactpersistence.js';
2
3
  import type { IDirectReport } from '../../ts_interfaces/directreports.js';
3
4
 
4
5
  /**
@@ -62,12 +63,22 @@ export interface IDirectReportStore {
62
63
  update(owner: string, name: string, change: (report: IDirectReport) => void): Promise<IDirectReport>;
63
64
  }
64
65
 
66
+ /**
67
+ * A refusal or failure of the direct reports whose message AGL writes itself, never a dependency's text: the Driver view
68
+ * and a device show it as it is. A dependency's error it stands for is its `cause`, which the controller journals.
69
+ */
70
+ export class DirectReportError extends Error {
71
+ constructor(messageArg: string, optionsArg?: ErrorOptions) {
72
+ super(messageArg, optionsArg);
73
+ this.name = 'DirectReportError';
74
+ }
75
+ }
76
+
65
77
  /** Another write changed the report between its read and this write. */
66
- export class DirectReportConflictError extends Error {
67
- constructor() { super('The direct report changed concurrently.'); }
78
+ export class DirectReportConflictError extends DirectReportError {
79
+ constructor() { super('The direct report changed concurrently.'); this.name = 'DirectReportConflictError'; }
68
80
  }
69
81
 
70
- const exactError = (error: unknown, code: string): boolean => error instanceof plugins.nosqldb.SmartdataExactPersistenceError && error.code === code;
71
82
  type TStoredReport = plugins.nosqldb.TStoredDocument<IDirectReportDocument>;
72
83
  const persisted = (record: TStoredReport): IDirectReport => structuredClone(DirectReportModel.exact.toPersisted(record).report);
73
84
  const sessionTaken = 'Another active direct report already holds this session.';
@@ -76,7 +87,7 @@ const sessionTaken = 'Another active direct report already holds this session.';
76
87
  export class DirectReportStore implements IDirectReportStore {
77
88
  public async list(owner: string): Promise<IDirectReport[]> {
78
89
  const records = await DirectReportModel.exact.findStored({ filter: { owner }, sort: { id: 1 }, limit: 257 });
79
- if (records.length > 256) throw new Error('Direct report capacity exceeded.');
90
+ if (records.length > 256) throw new DirectReportError('Direct report capacity exceeded.');
80
91
  return records.map(persisted);
81
92
  }
82
93
 
@@ -90,10 +101,10 @@ export class DirectReportStore implements IDirectReportStore {
90
101
  ...(report.state === 'active' ? { activeSessionKey: report.sessionId } : {}) };
91
102
  try {
92
103
  const result = await DirectReportModel.exact.insert(candidate);
93
- if (result.status === 'conflict') throw new Error('A direct report of that name exists.');
104
+ if (result.status === 'conflict') throw new DirectReportError('A direct report of that name exists.');
94
105
  return persisted(result.document);
95
106
  } catch (error) {
96
- if (exactError(error, 'unique_conflict')) throw new Error(sessionTaken, { cause: error });
107
+ if (exactError(error, 'unique_conflict')) throw new DirectReportError(sessionTaken, { cause: error });
97
108
  if (!exactError(error, 'ambiguous_write')) throw error;
98
109
  return this.confirm(candidate, error);
99
110
  }
@@ -101,7 +112,7 @@ export class DirectReportStore implements IDirectReportStore {
101
112
 
102
113
  public async update(owner: string, name: string, change: (report: IDirectReport) => void): Promise<IDirectReport> {
103
114
  const current = await DirectReportModel.exact.findStoredOne({ id: `${owner}:${name}`, owner });
104
- if (!current) throw new Error('The direct report is unavailable.');
115
+ if (!current) throw new DirectReportError('The direct report is unavailable.');
105
116
  const next = structuredClone(DirectReportModel.exact.toPersisted(current));
106
117
  change(next.report); next.report.updatedAt = new Date().toISOString(); next.updateId = plugins.crypto.randomUUID();
107
118
  const activeSessionKey = next.report.state === 'active' ? next.report.sessionId : undefined;
@@ -113,7 +124,7 @@ export class DirectReportStore implements IDirectReportStore {
113
124
  if (result.status !== 'transitioned') throw new DirectReportConflictError();
114
125
  return persisted(result.document);
115
126
  } catch (error) {
116
- if (exactError(error, 'unique_conflict')) throw new Error(sessionTaken, { cause: error });
127
+ if (exactError(error, 'unique_conflict')) throw new DirectReportError(sessionTaken, { cause: error });
117
128
  if (!exactError(error, 'ambiguous_write')) throw error;
118
129
  return this.confirm(next, error);
119
130
  }
@@ -122,6 +133,6 @@ export class DirectReportStore implements IDirectReportStore {
122
133
  private async confirm(expected: IDirectReportDocument, error: unknown): Promise<IDirectReport> {
123
134
  const record = await DirectReportModel.exact.findStoredOne({ id: expected.id });
124
135
  if (record?.updateId === expected.updateId) return persisted(record);
125
- throw new Error('The direct report write outcome is unknown; read the direct reports before retrying.', { cause: error });
136
+ throw new DirectReportError('The direct report write outcome is unknown; read the direct reports before retrying.', { cause: error });
126
137
  }
127
138
  }
@@ -35,8 +35,11 @@ export interface IDriverServiceHost {
35
35
  requesterArg: string,
36
36
  signalArg: AbortSignal,
37
37
  ): Promise<void>;
38
- /** Text of the newest assistant message, for the `needs input:` line. */
39
- latestAssistantText(projectIdArg: string, nativeIdArg: string, signalArg?: AbortSignal): Promise<string | undefined>;
38
+ /**
39
+ * The newest assistant transcript entry that holds text, for the `needs input:` line: its id (stable for the entry),
40
+ * its text and when it was written.
41
+ */
42
+ latestAssistantMessage(projectIdArg: string, nativeIdArg: string, signalArg?: AbortSignal): Promise<IDriverAssistantMessage | undefined>;
40
43
  publish(statusArg: IControllerDriverStatus): void;
41
44
  /**
42
45
  * The driver session was seen for the first time in this process: fleet events start flowing into
@@ -53,6 +56,23 @@ export interface IDriverServiceHost {
53
56
  keepCacheWarm(projectIdArg: string, nativeIdArg: string, durationMsArg: number): Promise<void>;
54
57
  }
55
58
 
59
+ /** An assistant transcript entry of the driver session. */
60
+ export interface IDriverAssistantMessage {
61
+ id: string;
62
+ text: string;
63
+ /** Unix milliseconds. */
64
+ createdAt: number;
65
+ }
66
+
67
+ /** The driver's last turn ended on a `needs input:` line: the line, the entry it ends, and when it was written. */
68
+ export interface IDriverNeedsInput {
69
+ projectId: string;
70
+ nativeId: string;
71
+ line: string;
72
+ messageId: string;
73
+ at: number;
74
+ }
75
+
56
76
  export interface IDriverServiceOptions {
57
77
  store?: IDriverStore;
58
78
  refreshDelayMs?: number;
@@ -63,7 +83,17 @@ export interface IDriverServiceOptions {
63
83
  /** How long after the newest board event the driver keeps its prompt cache warm. */
64
84
  export const driverCacheWarmMs = 60 * 60 * 1000;
65
85
 
66
- const needsInputLine = /^needs input:/imu;
86
+ /**
87
+ * Whether a controller event carries streamed text, reasoning or tool content: it never changes the driver's status,
88
+ * and no device hears it as a driver change.
89
+ */
90
+ export const isStreamedContentEvent = (eventArg: IControllerEvent): boolean => Boolean(
91
+ eventArg.textUpdate || eventArg.reasoningUpdate || eventArg.toolExecution,
92
+ );
93
+
94
+ const needsInputLine = /^needs input:.*$/imu;
95
+ /** The `needs input:` line of an assistant text, trimmed; none when the text holds none. */
96
+ export const driverNeedsInputLine = (textArg: string): string | undefined => needsInputLine.exec(textArg)?.[0].trim();
67
97
  const sameStatus = (leftArg: IControllerDriverStatus, rightArg: IControllerDriverStatus): boolean => (
68
98
  leftArg.activity === rightArg.activity
69
99
  && leftArg.unreadCount === rightArg.unreadCount
@@ -92,7 +122,8 @@ export class DriverService {
92
122
  /** Whether this process created the driver session, and whether the host heard it exists. */
93
123
  private createdInProcess = false;
94
124
  private availableAnnounced = false;
95
- private assistantNeedsInput = false;
125
+ /** The `needs input:` line of the newest assistant text, while it holds one. */
126
+ private needsInputTurn?: Omit<IDriverNeedsInput, 'projectId' | 'nativeId'>;
96
127
  private closed = false;
97
128
  private readonly now: () => number;
98
129
  /** When the board last changed, on `now`'s clock. */
@@ -147,6 +178,22 @@ export class DriverService {
147
178
  return this.refresh(signalArg);
148
179
  }
149
180
 
181
+ /** The status as the last refresh found it, without reading anything. */
182
+ public current(): IControllerDriverStatus {
183
+ return structuredClone(this.status);
184
+ }
185
+
186
+ /**
187
+ * The driver's `needs input:` turn, as the last status refresh found it: only while its last turn ended on the line
188
+ * and nothing else holds it (no prompt of its own, no turn running). Its own prompts are session prompts.
189
+ */
190
+ public needsInput(): IDriverNeedsInput | undefined {
191
+ const { activity, projectId, sessionId, session } = this.status;
192
+ const turn = this.needsInputTurn;
193
+ if (activity !== 'needs_input' || session?.attention || !turn || projectId === undefined || sessionId === undefined) return undefined;
194
+ return { projectId, nativeId: sessionId.nativeId, ...turn };
195
+ }
196
+
150
197
  public ensure(
151
198
  projectIdArg: string | undefined,
152
199
  requesterArg: string,
@@ -170,14 +217,27 @@ export class DriverService {
170
217
  * text, reasoning and tool deltas never change it, so they are skipped.
171
218
  */
172
219
  public observe(eventArg: IControllerEvent): void {
173
- const record = this.record;
174
- if (!record || this.closed) return;
220
+ if (this.closed) return;
175
221
  if (eventArg.type !== 'session.changed' && eventArg.type !== 'sessions.changed' && eventArg.type !== 'permissions.changed') return;
176
- if (eventArg.textUpdate || eventArg.reasoningUpdate || eventArg.toolExecution) return;
177
- if (eventArg.projectId !== record.projectId) return;
178
- if (eventArg.sessionId !== undefined
179
- && (eventArg.sessionId.harnessId !== 'flex' || eventArg.sessionId.nativeId !== record.nativeId)) return;
180
- this.scheduleRefresh();
222
+ if (this.concerns(eventArg)) this.scheduleRefresh();
223
+ }
224
+
225
+ /**
226
+ * Whether the event is the driver session's own change of state, transcript or prompts (`session.changed`,
227
+ * `session.history.changed`, `permissions.changed` naming the session), never its streamed content: what a device
228
+ * hears as a driver change.
229
+ */
230
+ public isSessionChange(eventArg: IControllerEvent): boolean {
231
+ return (eventArg.type === 'session.changed' || eventArg.type === 'session.history.changed' || eventArg.type === 'permissions.changed')
232
+ && eventArg.sessionId !== undefined && this.concerns(eventArg);
233
+ }
234
+
235
+ /** An event of the driver's project about its session or the whole project, without streamed content. */
236
+ private concerns(eventArg: IControllerEvent): boolean {
237
+ const record = this.record;
238
+ if (!record || isStreamedContentEvent(eventArg) || eventArg.projectId !== record.projectId) return false;
239
+ return eventArg.sessionId === undefined
240
+ || (eventArg.sessionId.harnessId === 'flex' && eventArg.sessionId.nativeId === record.nativeId);
181
241
  }
182
242
 
183
243
  /**
@@ -360,10 +420,11 @@ export class DriverService {
360
420
  if (sessionArg.status === 'error') return 'error';
361
421
  const key = `${recordArg.nativeId}\0${sessionArg.updatedAt}`;
362
422
  if (this.assistantTextKey !== key) {
363
- const text = await this.host.latestAssistantText(recordArg.projectId, recordArg.nativeId, signalArg);
364
- this.assistantNeedsInput = text !== undefined && needsInputLine.test(text);
423
+ const message = await this.host.latestAssistantMessage(recordArg.projectId, recordArg.nativeId, signalArg);
424
+ const line = message === undefined ? undefined : driverNeedsInputLine(message.text);
425
+ this.needsInputTurn = message === undefined || line === undefined ? undefined : { line, messageId: message.id, at: message.createdAt };
365
426
  this.assistantTextKey = key;
366
427
  }
367
- return this.assistantNeedsInput ? 'needs_input' : 'idle';
428
+ return this.needsInputTurn ? 'needs_input' : 'idle';
368
429
  }
369
430
  }
@@ -5,7 +5,7 @@ import type { IFleetWorker, IFleetWorkerProfile, IFleetWorkerReport, IFleetWorke
5
5
  import { controllerSessionFeedExcerpt, type IControllerMessageBundle, type IControllerNativeWait } from '../../ts_interfaces/index.js';
6
6
  import { claudePage, claudeTranscript } from '../classes.claudeprojection.js';
7
7
  import { FleetDispatchError, FleetNativeTurnError, boundedFleetReport, fleetClaudeNativeWait, fleetMessageDigest, fleetReportMarker, type IFleetWorkerBackend, type IFleetWorkerObservedTurn, type IFleetNativeEvent, type IFleetNativeAgent, type IFleetNativeSession, type IFleetNativePage, type IFleetNativeSendTurn, type IFleetNativeSendReceipt } from './interfaces.workers.js';
8
- import { runFleetWorkerCommand, type IFleetWorkerCommand, type TFleetWorkerRunner } from './classes.workercommand.js';
8
+ import { runFleetWorkerCommand, type IFleetWorkerCommand, type TFleetWorkerOutputWatch, type TFleetWorkerRunner } from './classes.workercommand.js';
9
9
  import { sanitizeFailureText } from '../functions.failuredescription.js';
10
10
  import type { FleetWorkerLaunches } from './classes.workerlaunches.js';
11
11
  import { claudeCodeFleetFloor, claudeCodeVersionOutput, compareClaudeCodeReleases, isNewerClaudeCodeRelease, parseClaudeCodeRelease } from '../functions.claudecoderelease.js';
@@ -107,7 +107,7 @@ const claudeObservedTurn = (nativeId: string, agent: TClaudeAgent | undefined, r
107
107
  const modes = new Set(['acceptEdits', 'auto', 'bypassPermissions', 'default', 'dontAsk', 'manual', 'plan']);
108
108
  /** SendMessage resolves a recipient by its session name, never by the short agent id; a name another live session shares is ambiguous. */
109
109
  const address = (inventory: TClaudeAgent[], agent: TClaudeAgent): string => {
110
- if (!agent.name) throw new Error('Claude worker has no session name; SendMessage cannot address it.');
110
+ if (!agent.name) throw new Error('Claude session has no session name; SendMessage cannot address it.');
111
111
  if (inventory.filter((entry) => entry.name === agent.name && entry.pid !== undefined).length !== 1) {
112
112
  throw new Error(`Claude session name ${JSON.stringify(agent.name)} is shared by another live session; SendMessage cannot address it unambiguously.`);
113
113
  }
@@ -204,6 +204,45 @@ export const assertFleetClaudeDelivery = (output: string, expected: Array<{ to:
204
204
  if (result?.is_error === true || item?.success !== true || typeof item.msg_id !== 'string' || !item.msg_id) throw new FleetDispatchError('Claude recipient did not acknowledge queued delivery.', true);
205
205
  }
206
206
  };
207
+ /**
208
+ * The only tools a relay runs with. `--tools` limits Claude Code's own tools to them and `--strict-mcp-config` drops every
209
+ * configured MCP server, so a relayed message cannot drive any other tool in the permission mode the relay takes on from
210
+ * its recipient, bypassPermissions included; `--allowedTools` only pre-approves them. `--tools` takes several values, so
211
+ * it is passed as one `=` argument, or it would take the prompt as a tool (Claude Code 2.1.306).
212
+ */
213
+ const relayTools = ['SendMessage', 'Read', 'ToolSearch'] as const;
214
+ export const fleetClaudeRelayToolArguments: readonly string[] = [`--tools=${relayTools.join(',')}`, '--strict-mcp-config', `--allowedTools=${relayTools.join(',')}`];
215
+ const relayToolName = (value: unknown): string => typeof value === 'string' && /^[\w.:-]{1,128}$/u.test(value) ? value : '(unreadable)';
216
+ /**
217
+ * Judges a relay's stream-json output by its `system`/`init` record, which Claude Code 2.1.306 prints before it calls the
218
+ * model: `true` when the record lists exactly the relay tools, the refusal when it lists any other, lacks one, or a record
219
+ * other than a `system` one comes first, and `undefined` while the complete lines decide nothing yet. A refusal is
220
+ * dispatched once anything but `system` records was printed: the model answered, and anything may have run.
221
+ */
222
+ const relayToolsVerdict = (stdout: string, ended: boolean): true | FleetDispatchError | undefined => {
223
+ const lines = stdout.split('\n'), complete = ended ? lines : lines.slice(0, -1);
224
+ const records = complete.filter((line) => line.trim()).map((line) => { try { return record.safeParse(JSON.parse(line)).data; } catch { return undefined; } });
225
+ const answered = records.some((entry) => entry?.type !== 'system');
226
+ const refuse = (reason: string) => new FleetDispatchError(`Claude relay ${reason}; a relay runs only with ${relayTools.join(', ')}.${answered ? ' Inspect before retrying.' : ''}`, answered);
227
+ for (const entry of records) {
228
+ if (entry?.type !== 'system') return refuse('printed no system/init record before its first answer');
229
+ if (entry.subtype !== 'init') continue;
230
+ if (!Array.isArray(entry.tools)) return refuse('init record lists no tools');
231
+ const listed = entry.tools.map(relayToolName), wanted = new Set<string>(relayTools);
232
+ const extra = [...new Set(listed.filter((tool) => !wanted.has(tool)))], missing = relayTools.filter((tool) => !listed.includes(tool));
233
+ if (!extra.length && !missing.length && listed.length === relayTools.length) return true;
234
+ const named = (tools: string[]) => `${tools.slice(0, 16).join(', ')}${tools.length > 16 ? ` and ${tools.length - 16} more` : ''}`;
235
+ return refuse(`ran with ${extra.length ? `other tools (${named(extra)})` : ''}${extra.length && missing.length ? ' and ' : ''}${missing.length ? `without ${named(missing)}` : ''}${!extra.length && !missing.length ? 'a tool listed twice' : ''}`);
236
+ }
237
+ return ended ? refuse('printed no system/init record') : undefined;
238
+ };
239
+ /** The relay's watch while it runs: it is stopped as soon as its init record lists other tools. */
240
+ export const fleetClaudeRelayToolsWatch: TFleetWorkerOutputWatch = (stdout) => relayToolsVerdict(stdout, false);
241
+ /** Refuses a relay's complete output unless its init record lists exactly the relay tools. */
242
+ export const assertFleetClaudeRelayTools = (stdout: string): void => {
243
+ const verdict = relayToolsVerdict(stdout, true);
244
+ if (verdict !== true) throw verdict ?? new FleetDispatchError('Claude relay printed no system/init record.', true);
245
+ };
207
246
  const textOf = (content: unknown): string => typeof content === 'string' ? content : !Array.isArray(content) ? ''
208
247
  : content.map((part) => record.safeParse(part)).map((block) => block.success && block.data.type === 'text' && typeof block.data.text === 'string' ? block.data.text : '').filter(Boolean).join(' ');
209
248
  /**
@@ -278,9 +317,9 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
278
317
  }
279
318
  return executable;
280
319
  }
281
- private async run(profile: Pick<IFleetWorkerProfile, 'home'>, cwd: string, args: string[]): Promise<IFleetWorkerCommand> {
320
+ private async run(profile: Pick<IFleetWorkerProfile, 'home'>, cwd: string, args: string[], watch?: TFleetWorkerOutputWatch): Promise<IFleetWorkerCommand> {
282
321
  const env = this.env(profile), executable = await this.supportedExecutable(profile, cwd);
283
- return await this.runner(executable, args, cwd, env, this.signal);
322
+ return await this.runner(executable, args, cwd, env, this.signal, ...(watch ? [watch] : []));
284
323
  }
285
324
  private async command(profile: Pick<IFleetWorkerProfile, 'home'>, cwd: string, args: string[], mutation = false): Promise<string> {
286
325
  const result = await this.run(profile, cwd, args);
@@ -755,37 +794,53 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
755
794
  }
756
795
  }
757
796
  /**
758
- * Continues a settled background job that runs outside the fleet through Claude Code's own wake, so the job stays the
759
- * session's owner and AGL never becomes a second writer. Only a job its fresh inventory lists once, settled (reaped or
760
- * stopped) and with a readable conversation, is woken; anything else, and a message Claude Code would read as one of
761
- * its options, is refused before dispatch. Claude Code does not report when the woken turn ends, so `settled` never runs.
797
+ * Sends to a background job that runs outside the fleet through Claude Code itself, so the job stays the session's
798
+ * owner and AGL never becomes a second writer: a settled (reaped or stopped) job is woken with the message, a running
799
+ * one takes it in its inbox through the relay's SendMessage, addressed by its session name, which no other running
800
+ * session of its inventory or of the `peerHomes` inventories, read fresh here, may share. Only a job its fresh inventory lists once, with a readable conversation, in the
801
+ * state the sender prepared its message for (`jobDelivery`), takes it; anything else, and a wake message Claude Code
802
+ * would read as one of its options, is refused before dispatch. Claude Code does not report when the turn that reads
803
+ * the message ends, so `settled` never runs.
762
804
  */
763
805
  public async nativeSend(session: IFleetNativeSession, text: string, _settled: () => void, turn?: IFleetNativeSendTurn): Promise<IFleetNativeSendReceipt> {
764
806
  if (turn?.expectedTurnId !== undefined || turn?.agentMessage) {
765
807
  throw new FleetNativeTurnError("delivery_unsupported", "Claude Code background jobs do not support guarded native turn delivery.");
766
808
  }
767
809
  const profile = { home: session.home };
768
- let original: TClaudeAgent;
810
+ let original: TClaudeAgent, inbox: { to: string; mode: string; offset: number } | undefined;
769
811
  try {
770
812
  if (Buffer.byteLength(text) > 96 * 1024) throw new Error('A message to a Claude background job is limited to 96 KiB.');
771
- // Claude Code reads a leading dash as an option, and an option makes it start a copy instead of waking the job.
772
- if (text.startsWith('-')) throw new Error('Claude Code reads a message that starts with "-" as an option. Start the message with other text.');
773
- const listed = (await this.agents(session, profile)).filter((entry) => entry.sessionId === session.nativeId);
813
+ const inventory = await this.agents(session, profile), listed = inventory.filter((entry) => entry.sessionId === session.nativeId);
774
814
  if (listed.length !== 1) throw new Error(`Claude inventory does not hold session ${session.nativeId} exactly once.`);
775
815
  original = listed[0]!;
776
816
  if (original.kind !== 'background' || !original.id) throw new Error('This Claude Code session is no background job; Claude Code cannot wake it.');
777
- if (!resumable(original)) {
778
- throw new Error(`Claude background job ${original.id} is ${live(original) ? 'running' : original.state ?? 'in an unknown state'}; only a settled job is woken.`);
779
- }
780
817
  const transcript = await this.transcript(session, profile);
781
818
  if (!transcript.path || !transcript.records.length) throw new Error('Claude background job has no readable saved conversation.');
819
+ if (live(original) && original.state !== 'failed' && original.state !== 'stopped') {
820
+ // SendMessage reaches the running sessions of every home by name: the name is checked fresh against them all.
821
+ const peers: TClaudeAgent[] = [];
822
+ for (const home of session.peerHomes ?? []) peers.push(...await this.agents(session, { home }));
823
+ inbox = { to: address([...inventory, ...peers], original), mode: fleetClaudePermissionMode(transcript.records), offset: transcript.end };
824
+ } else if (!resumable(original)) {
825
+ throw new Error(`Claude background job ${original.id} is ${original.state ?? 'in an unknown state'}${live(original) ? '' : ' without a process'}; only a settled or running job takes a message.`);
826
+ } else if (text.startsWith('-')) {
827
+ // Claude Code reads a leading dash as an option, and an option makes it start a copy instead of waking the job.
828
+ throw new Error('Claude Code reads a message that starts with "-" as an option. Start the message with other text.');
829
+ }
830
+ if (session.jobDelivery !== undefined && session.jobDelivery !== (inbox ? 'inbox' : 'wake')) {
831
+ throw new Error(`Claude background job ${original.id} ${inbox ? 'started running' : 'settled'} since it was read; read it again and send again.`);
832
+ }
782
833
  } catch (error) { throw new FleetDispatchError(error instanceof Error ? error.message : 'Claude background job preflight failed.', false, { cause: error }); }
834
+ if (inbox) {
835
+ await this.relay(profile, session.cwd, inbox.mode, [{ session, to: inbox.to, text, offset: inbox.offset }]);
836
+ return { steered: false, job: 'inbox' };
837
+ }
783
838
  await this.wake(profile, session.cwd, session.nativeId, original, text);
784
839
  try { await this.awake(async () => (await this.agents(session, profile)).find((entry) => entry.sessionId === session.nativeId), original); }
785
840
  catch (error) {
786
841
  throw new FleetDispatchError(`Claude Code acknowledged the wake of background job ${original.id}, but its state is not confirmed: ${error instanceof Error ? error.message : 'unknown failure.'} Inspect it before sending again.`, true, { cause: error });
787
842
  }
788
- return { steered: false };
843
+ return { steered: false, job: 'wake' };
789
844
  }
790
845
  public async send(messages: Array<{ worker: IFleetWorker; profile: IFleetWorkerProfile; text: string }>): Promise<void> {
791
846
  const groups = new Map<string, Array<{ worker: IFleetWorker; profile: IFleetWorkerProfile; text: string; to: string; mode: string; offset: number }>>();
@@ -818,32 +873,50 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
818
873
  dispatched = true; await this.revive(message.worker, message.profile, message.text, current, message.baseline);
819
874
  }
820
875
  for (const group of groups.values()) {
821
- const directory = await plugins.fs.promises.mkdtemp(plugins.path.join(plugins.os.tmpdir(), 'agl-fleet-relay-'));
822
- try {
823
- const file = plugins.path.join(directory, 'messages.json');
824
- const expected = group.map((item) => ({ to: item.to, message: item.text }));
825
- await plugins.fs.promises.writeFile(file, JSON.stringify(expected), { mode: 0o600 });
826
- const prompt = `Read ${JSON.stringify(file)}. For each object call SendMessage with its to and message values unchanged. Deliver the file's contents, unchanged. Do not send anything else. Report every tool receipt.`;
827
- const earlier = dispatched; dispatched = true;
828
- const result = await this.run(group[0]!.profile, group[0]!.worker.cwd, ['-p', '--output-format', 'stream-json', '--verbose', '--permission-mode', group[0]!.mode, '--allowedTools=SendMessage,Read,ToolSearch', prompt]);
829
- try {
830
- if (result.code !== 0) throw fleetClaudeRelayFailure(result);
831
- assertFleetClaudeDelivery(result.stdout, expected);
832
- } catch (error) {
833
- // The relay ended before it sent anything, or Claude refused every send: none of it reached a recipient.
834
- if (error instanceof FleetDispatchError && !error.dispatched) dispatched = earlier;
835
- throw error;
836
- }
837
- for (const message of group) {
838
- const after = await this.transcript(message.worker, message.profile, message.offset);
839
- if (held(after.records)) throw new FleetDispatchError('Claude target held the peer message.', true);
840
- const current = await this.transcript(message.worker, message.profile);
841
- if (fleetClaudePermissionMode(current.records) !== message.mode) throw new FleetDispatchError('Claude recipient permission mode changed during delivery; inspect the receipt.', true);
842
- }
843
- } finally { await plugins.fs.promises.rm(directory, { recursive: true }); }
876
+ const earlier = dispatched; dispatched = true;
877
+ try { await this.relay(group[0]!.profile, group[0]!.worker.cwd, group[0]!.mode, group.map((item) => ({ session: item.worker, to: item.to, text: item.text, offset: item.offset }))); }
878
+ catch (error) {
879
+ // None of it reached a recipient.
880
+ if (error instanceof FleetDispatchError && !error.dispatched) dispatched = earlier;
881
+ throw error;
882
+ }
844
883
  }
845
884
  } catch (error) { throw new FleetDispatchError(error instanceof Error ? error.message : 'Claude relay failed.', dispatched || error instanceof FleetDispatchError && error.dispatched, { cause: error }); }
846
885
  }
886
+ /**
887
+ * The one relay, for a fleet steer and a native send alike: one `claude -p` run in `cwd`, in the recipients' permission
888
+ * mode `mode`, with exactly the relay tools, calls Claude Code's own SendMessage once per recipient, addressed by its
889
+ * session name (`to`); each receipt must prove queued delivery, and each recipient's transcript after `offset` must hold
890
+ * no held message and still the same permission mode. Throws `FleetDispatchError`, not dispatched only when none of it
891
+ * can have reached a recipient: the relay ended or was stopped before it sent anything, or Claude refused every send.
892
+ */
893
+ private async relay(profile: Pick<IFleetWorkerProfile, 'home'>, cwd: string, mode: string,
894
+ recipients: ReadonlyArray<{ session: Pick<IFleetWorker, 'nativeId' | 'cwd'>; to: string; text: string; offset: number }>): Promise<void> {
895
+ const unprepared = (error: unknown) => new FleetDispatchError('The relay\'s message file could not be prepared.', false, { cause: error });
896
+ let directory: string;
897
+ try { directory = await plugins.fs.promises.mkdtemp(plugins.path.join(plugins.os.tmpdir(), 'agl-fleet-relay-')); }
898
+ catch (error) { throw unprepared(error); }
899
+ try {
900
+ const file = plugins.path.join(directory, 'messages.json');
901
+ const expected = recipients.map((item) => ({ to: item.to, message: item.text }));
902
+ try { await plugins.fs.promises.writeFile(file, JSON.stringify(expected), { mode: 0o600 }); } catch (error) { throw unprepared(error); }
903
+ const prompt = `Read ${JSON.stringify(file)}. For each object call SendMessage with its to and message values unchanged. Deliver the file's contents, unchanged. Do not send anything else. Report every tool receipt.`;
904
+ const result = await this.run(profile, cwd, ['-p', '--output-format', 'stream-json', '--verbose', '--permission-mode', mode,
905
+ ...fleetClaudeRelayToolArguments, prompt], fleetClaudeRelayToolsWatch);
906
+ assertFleetClaudeRelayTools(result.stdout);
907
+ if (result.code !== 0) throw fleetClaudeRelayFailure(result);
908
+ assertFleetClaudeDelivery(result.stdout, expected);
909
+ for (const recipient of recipients) {
910
+ const after = await this.transcript(recipient.session, profile, recipient.offset);
911
+ if (held(after.records)) throw new FleetDispatchError('Claude target held the peer message.', true);
912
+ const current = await this.transcript(recipient.session, profile);
913
+ if (fleetClaudePermissionMode(current.records) !== mode) throw new FleetDispatchError('Claude recipient permission mode changed during delivery; inspect the receipt.', true);
914
+ }
915
+ } catch (error) {
916
+ if (error instanceof FleetDispatchError) throw error;
917
+ throw new FleetDispatchError(error instanceof Error ? error.message : 'Claude relay failed.', true, { cause: error });
918
+ } finally { await plugins.fs.promises.rm(directory, { recursive: true }); }
919
+ }
847
920
  public async stop(worker: IFleetWorker, profile: IFleetWorkerProfile): Promise<void> {
848
921
  const agent = await this.agent(worker, profile);
849
922
  if (!live(agent)) {