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
@@ -5,10 +5,10 @@ import { codexRecord, codexArray, codexString, codexSession, codexTimestamp, cod
5
5
  import { isCodexThreadId } from '../functions.codexidentity.js';
6
6
  import type { IFleetWorker, IFleetWorkerProfile, IFleetWorkerReport, IFleetWorkerTurnOutcome } from '../../ts_interfaces/fleetworkers.js';
7
7
  import { controllerSessionFeedExcerpt } from '../../ts_interfaces/sessionfeed.js';
8
- import type { IControllerAttention, IControllerMessageBundle } from '../../ts_interfaces/index.js';
8
+ import type { IControllerAttention, IControllerEvent, IControllerMessageBundle } from '../../ts_interfaces/index.js';
9
9
  import { controllerAttentionPending } from '../../ts_interfaces/index.js';
10
10
  import type { FleetWorkerLaunches, IFleetCodexCallerRuntime } from './classes.workerlaunches.js';
11
- import { FleetDispatchError, FleetNativeTurnError, fleetReportMarker, boundedFleetReport, type IFleetWorkerBackend, type IFleetWorkerObservedTurn, type IFleetNativeEvent, type IFleetNativeThread, type IFleetNativeSession, type IFleetNativePage, type IFleetNativeSendTurn, type IFleetNativeSendReceipt, type TFleetNativeReply } from './interfaces.workers.js';
11
+ import { FleetDispatchError, FleetNativeTurnError, fleetReportMarker, boundedFleetReport, type IFleetWorkerBackend, type IFleetWorkerObservedTurn, type IFleetNativeEvent, type IFleetNativeThread, type IFleetNativeSession, type IFleetNativePendingAttention, type IFleetNativePage, type IFleetNativeSendTurn, type IFleetNativeSendReceipt, type TFleetNativeReply } from './interfaces.workers.js';
12
12
 
13
13
  /** `turns` and `items` are the poll baseline; `turn` stays when the baseline is forgotten, so a failure stays observed. */
14
14
  interface ICodexObservation { turns?: Set<string>; items?: Map<string, string>; status?: IFleetWorkerReport['status']; excerpt?: string; turn?: IFleetWorkerObservedTurn }
@@ -25,13 +25,21 @@ const codexObservedTurn = (turn: Record<string, unknown>): IFleetWorkerObservedT
25
25
  ...(terminalTurnStates.has(turn.status) ? { outcome: { turnId, state: turn.status as IFleetWorkerTurnOutcome['state'], ...(limit ? { limit } : {}) } } : {}) };
26
26
  };
27
27
  export interface IFleetCodexConnection { supervisor: CodexSupervisor; adapter: CodexClientAdapter }
28
- export type TFleetCodexConnectionFactory = (cwd: string) => IFleetCodexConnection;
29
- const connection: TFleetCodexConnectionFactory = (directory) => {
28
+ /** `onAttention` hears of every thread whose requests AGL holds on the connection came or went. */
29
+ export type TFleetCodexConnectionFactory = (cwd: string, onAttention: (threadIdArg: string) => void) => IFleetCodexConnection;
30
+ /**
31
+ * The events of the fleet's Codex connection, which serves no browser: of them only a request (a permission, a
32
+ * question or an MCP form) coming or going is told on, as the thread it belongs to.
33
+ */
34
+ export const fleetCodexAttentionEvents = (onAttentionArg: (threadIdArg: string) => void) => (eventArg: IControllerEvent): void => {
35
+ if (eventArg.type === 'permissions.changed' && eventArg.sessionId) onAttentionArg(eventArg.sessionId.nativeId);
36
+ };
37
+ const connection: TFleetCodexConnectionFactory = (directory, onAttention) => {
30
38
  let adapter: CodexClientAdapter;
31
39
  const supervisor = new CodexSupervisor({ directory, sharedOnly: true,
32
40
  onNotification: (event) => { adapter.onNotification(event); },
33
41
  onServerRequest: (request) => { adapter.onServerRequest(request); }, onUnavailable: () => {} });
34
- adapter = new CodexClientAdapter(supervisor, () => {});
42
+ adapter = new CodexClientAdapter(supervisor, fleetCodexAttentionEvents(onAttention));
35
43
  return { supervisor, adapter };
36
44
  };
37
45
  /** A shared-daemon observer. Shutdown closes this connection, never the daemon or its turns. */
@@ -45,6 +53,8 @@ export class FleetCodexWorkers implements IFleetWorkerBackend {
45
53
  private readonly factory: TFleetCodexConnectionFactory = connection,
46
54
  /** Proves each worker thread's caller identity; without it workers call AGL as whoever their MCP bridge enrolls as. */
47
55
  private readonly callers?: FleetWorkerLaunches,
56
+ /** Told of every native thread whose requests this connection holds for AGL came or went. */
57
+ private readonly onNativeAttention?: (nativeIdArg: string) => void,
48
58
  ) {}
49
59
  /** The connection the fleet uses now, as the controller proves a worker thread's origin on it. */
50
60
  private callerRuntime(): IFleetCodexCallerRuntime {
@@ -71,7 +81,7 @@ export class FleetCodexWorkers implements IFleetWorkerBackend {
71
81
  const previous = this.runtime; await previous.supervisor.stop();
72
82
  if (this.runtime === previous) { this.runtime = undefined; this.starting = undefined; }
73
83
  }
74
- this.runtime ??= this.factory(worker.cwd);
84
+ this.runtime ??= this.factory(worker.cwd, (threadIdArg) => this.onNativeAttention?.(threadIdArg));
75
85
  this.starting ??= this.runtime.supervisor.start(); await this.starting;
76
86
  return this.runtime.adapter;
77
87
  }
@@ -253,6 +263,11 @@ export class FleetCodexWorkers implements IFleetWorkerBackend {
253
263
  const latest = codexArray(result.data, 1).map(codexRecord)[0];
254
264
  return latest?.status === 'inProgress' ? codexString(latest.id) : undefined;
255
265
  }
266
+ /** Every native thread with requests this connection holds for AGL, without reading anything. */
267
+ public nativePendingAttention(): IFleetNativePendingAttention[] {
268
+ return (this.runtime?.adapter.pendingAttention() ?? []).flatMap((entry) => entry.projectId === 'fleet'
269
+ ? [{ nativeId: entry.threadId, cwd: entry.directory, title: entry.session.title, attention: entry.attention }] : []);
270
+ }
256
271
  /** The requests of turns this connection runs in the thread that wait for an answer. */
257
272
  public async nativeAttention(session: IFleetNativeSession): Promise<IControllerAttention> {
258
273
  return (await this.scoped(session)).attention(session.nativeId);
@@ -2,9 +2,14 @@ import * as plugins from '../plugins.js';
2
2
  import { FleetDispatchError } from './interfaces.workers.js';
3
3
 
4
4
  export interface IFleetWorkerCommand { stdout: string; stderr: string; code: number }
5
- export type TFleetWorkerRunner = (command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv, signal: AbortSignal) => Promise<IFleetWorkerCommand>;
5
+ /**
6
+ * Judges a child's stdout while it runs, from everything it printed so far: `undefined` while that decides nothing yet,
7
+ * `true` once the output is accepted (the watch then ends), or the error the child is stopped and the run fails with.
8
+ */
9
+ export type TFleetWorkerOutputWatch = (stdout: string) => true | Error | undefined;
10
+ export type TFleetWorkerRunner = (command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv, signal: AbortSignal, watch?: TFleetWorkerOutputWatch) => Promise<IFleetWorkerCommand>;
6
11
  /** Only owns the short-lived management/relay child, never a native background worker. */
7
- export const runFleetWorkerCommand: TFleetWorkerRunner = (command, args, cwd, env, signal) => {
12
+ export const runFleetWorkerCommand: TFleetWorkerRunner = (command, args, cwd, env, signal, watch) => {
8
13
  signal.throwIfAborted();
9
14
  return new Promise((resolve, reject) => {
10
15
  const child = plugins.childProcess.spawn(command, args, { cwd, env, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });
@@ -15,10 +20,15 @@ export const runFleetWorkerCommand: TFleetWorkerRunner = (command, args, cwd, en
15
20
  const abort = () => { failure = new FleetDispatchError('Native worker command cancelled; its dispatch outcome may be unknown.', Boolean(child.pid)); stop(); };
16
21
  const timer = setTimeout(() => { failure = new FleetDispatchError('Native worker command timed out; inspect before retrying.', Boolean(child.pid)); stop(); }, 90_000);
17
22
  signal.addEventListener('abort', abort, { once: true });
23
+ let watching = watch;
18
24
  const collect = (kind: 'stdout' | 'stderr', chunk: Buffer) => {
19
25
  bytes += chunk.length;
20
- if (bytes > 8 * 1024 * 1024) { failure = new FleetDispatchError('Native worker output limit exceeded.', Boolean(child.pid)); stop(); }
21
- else (kind === 'stdout' ? out : err).push(chunk);
26
+ if (bytes > 8 * 1024 * 1024) { failure = new FleetDispatchError('Native worker output limit exceeded.', Boolean(child.pid)); stop(); return; }
27
+ (kind === 'stdout' ? out : err).push(chunk);
28
+ if (kind !== 'stdout' || !watching || failure) return;
29
+ const verdict = watching(Buffer.concat(out).toString('utf8'));
30
+ if (verdict === true) watching = undefined;
31
+ else if (verdict) { failure = verdict; watching = undefined; stop(); }
22
32
  };
23
33
  child.stdout.on('data', (chunk: Buffer) => collect('stdout', chunk)); child.stderr.on('data', (chunk: Buffer) => collect('stderr', chunk));
24
34
  child.on('error', (error) => { failure = new FleetDispatchError('Native worker executable failed.', false, { cause: error }); });
@@ -10,7 +10,7 @@ import { FleetEvents } from './classes.events.js';
10
10
  import { FleetClaudeWorkers } from './classes.claudeworkers.js';
11
11
  import { FleetCodexWorkers } from './classes.codexworkers.js';
12
12
  import type { FleetWorkerLaunches } from './classes.workerlaunches.js';
13
- import { FleetDispatchError, FleetWorkerError, fleetMessageDigest, fleetReportMarker, type IFleetWorkerBackend, type IFleetWorkerObservedTurn, type IFleetNativeAgent, type IFleetNativeThread, type IFleetNativeSession, type IFleetNativePage, type IFleetNativeSendTurn, type IFleetNativeSendReceipt, type TFleetNativeReply } from './interfaces.workers.js';
13
+ import { FleetDispatchError, FleetWorkerError, fleetMessageDigest, fleetReportMarker, type IFleetWorkerBackend, type IFleetWorkerObservedTurn, type IFleetNativeAgent, type IFleetNativeThread, type IFleetNativeSession, type IFleetNativePendingAttention, type IFleetNativePage, type IFleetNativeSendTurn, type IFleetNativeSendReceipt, type TFleetNativeReply } from './interfaces.workers.js';
14
14
  import { assertFleetWorkerRequest, validateFleetWorkerProfiles } from './functions.workervalidation.js';
15
15
  import { readControllerProcessIdentity, controllerProcessIdentityIsLive } from '../classes.processinspection.js';
16
16
  import { ticketActorSchema } from '../functions.ticketvalidation.js';
@@ -49,6 +49,8 @@ export interface IFleetWorkersOptions {
49
49
  nativeMessages?: IFleetNativeMessages;
50
50
  /** Told each Claude Code release newer than the verified one that the default Claude backend runs on. */
51
51
  claudeReleases?: (releaseArg: string) => void;
52
+ /** Told of each native Codex thread whose requests the default Codex backend holds for AGL came or went. */
53
+ onNativeCodexAttention?: (nativeIdArg: string) => void;
52
54
  }
53
55
  /** The fleet events that change what the Driver view shows of the fleet's workers. */
54
56
  export const fleetWorkerViewEventKinds: ReadonlySet<TFleetEventKind> = new Set<TFleetEventKind>(['worker.changed', 'worker.turn.ended', 'worker.report.mid_turn', 'worker.reaped', 'worker.credential.failed']);
@@ -86,6 +88,8 @@ export class FleetWorkers {
86
88
  private readonly backends: { claude: IFleetWorkerBackend; codex: IFleetWorkerBackend };
87
89
  private readonly jobs = new Map<string, IOwnedWorkerJob>();
88
90
  private readonly queues = new Map<string, Promise<unknown>>();
91
+ /** The jobs whose dispatch may have reached a native session; see `dispatch`. */
92
+ private readonly dispatchedJobs = new WeakSet<IFleetWorkerJob>();
89
93
  /** Each owner's running repair of what follows its native sessions; see `repairBindings`. */
90
94
  private readonly bindingRepairs = new Map<string, Promise<IBindingRepair>>();
91
95
  private bindingRevision = 0;
@@ -108,7 +112,7 @@ export class FleetWorkers {
108
112
  constructor(private readonly options: IFleetWorkersOptions = {}) {
109
113
  this.store = options.store ?? new FleetWorkerStore(); this.events = options.events ?? new FleetEvents();
110
114
  this.backends = options.backends ?? { claude: new FleetClaudeWorkers(this.abort.signal, undefined, undefined, options.callers, options.claudeReleases),
111
- codex: new FleetCodexWorkers(this.abort.signal, undefined, options.callers) };
115
+ codex: new FleetCodexWorkers(this.abort.signal, undefined, options.callers, options.onNativeCodexAttention) };
112
116
  }
113
117
  public start(): void {
114
118
  if (this.pollTimer || this.abort.signal.aborted) return;
@@ -243,9 +247,8 @@ export class FleetWorkers {
243
247
  // Like every fleet refusal, a session the send may not wake fails the job with its reason.
244
248
  const snapshot: IFleetWorkerJob = { id: plugins.crypto.randomUUID(), action: 'native-message', state: 'running' };
245
249
  const job: IOwnedWorkerJob = { owner, snapshot, completion: Promise.resolve() }; this.jobs.set(snapshot.id, job);
246
- job.completion = nativeMessages.send(owner, input as TFleetWorkerRequest<'native-message'>, actor)
247
- .then((receipt) => { snapshot.nativeMessage = receipt; snapshot.state = 'succeeded'; },
248
- (error: unknown) => { snapshot.state = 'failed'; snapshot.error = this.error(error); });
250
+ job.completion = this.dispatch(snapshot, () => nativeMessages.send(owner, input as TFleetWorkerRequest<'native-message'>, actor))
251
+ .then((receipt) => { snapshot.nativeMessage = receipt; snapshot.state = 'succeeded'; }, (error: unknown) => this.failJob(snapshot, error));
249
252
  return { job: this.publicJob(snapshot) } as TFleetWorkerResponseTo<T, R>;
250
253
  }
251
254
  const profiles = validateFleetWorkerProfiles(configuration.workerProfiles ?? []);
@@ -265,8 +268,8 @@ export class FleetWorkers {
265
268
  // Adoptions of one native session run one at a time, whatever their names and owners: a relaunch of a session
266
269
  // another adoption is binding would start a second process on it.
267
270
  const adopted = action === 'adopt' ? (input as TFleetWorkerRequest<'adopt'>).nativeId : undefined;
268
- job.completion = (recoveringActiveJob ? Promise.reject(new Error('Worker job is still running; inspect it before recovery.'))
269
- : this.exclusive(owner, names, async () => adopted === undefined ? await run() : await this.exclusive('', [`native:${adopted}`], run))).catch((error: unknown) => { snapshot.state = 'failed'; snapshot.error = this.error(error); });
271
+ job.completion = (recoveringActiveJob ? Promise.reject(new FleetWorkerError('worker_fenced', 'Worker job is still running; inspect it before recovery.'))
272
+ : this.exclusive(owner, names, async () => adopted === undefined ? await run() : await this.exclusive('', [`native:${adopted}`], run))).catch((error: unknown) => this.failJob(snapshot, error));
270
273
  return { job: this.publicJob(snapshot) } as TFleetWorkerResponseTo<T, R>;
271
274
  }
272
275
  /**
@@ -288,7 +291,7 @@ export class FleetWorkers {
288
291
  this.abort.signal.throwIfAborted(); signal?.throwIfAborted();
289
292
  const { worker } = await this.store.get(owner, name), backend = this.backends[worker.harness];
290
293
  if (worker.lostDispatch) return { ...this.view(worker), bundles: [], earlier: false };
291
- if (!worker.nativeId) throw new Error('Worker has no native identity yet.');
294
+ if (!worker.nativeId) throw new FleetWorkerError('worker_fenced', 'Worker has no native identity yet.');
292
295
  const page = await backend.history(worker, worker.profile, limit, before);
293
296
  signal?.throwIfAborted();
294
297
  return { ...this.view(worker), ...page };
@@ -305,7 +308,7 @@ export class FleetWorkers {
305
308
  private nativeBackend<K extends 'nativeHistory' | 'nativeSend' | 'nativeTurn' | 'nativeAttention' | 'nativeReply'>(harness: IFleetWorker['harness'], method: K): NonNullable<IFleetWorkerBackend[K]> {
306
309
  this.abort.signal.throwIfAborted();
307
310
  const backend = this.backends[harness], operation = backend[method];
308
- if (!operation) throw new Error(`The ${harness} backend does not serve native sessions.`);
311
+ if (!operation) throw new FleetWorkerError('worker_conflict', `The ${harness} backend does not serve native sessions.`);
309
312
  return operation.bind(backend) as NonNullable<IFleetWorkerBackend[K]>;
310
313
  }
311
314
  /** A listed native session's transcript page, read-only, through the reader its harness's workers use. */
@@ -327,9 +330,14 @@ export class FleetWorkers {
327
330
  public async relaunchBlocker(configuration: IFleetConfiguration, profileId: string, nativeId: string, cwd: string): Promise<IFleetRelaunchBlocker | undefined> {
328
331
  this.abort.signal.throwIfAborted();
329
332
  const profile = this.profile(validateFleetWorkerProfiles(configuration.workerProfiles ?? []), profileId), backend = this.backends[profile.harness];
330
- if (!backend.relaunchBlocker) throw new Error('Only a Claude Code session is relaunched.');
333
+ if (!backend.relaunchBlocker) throw new FleetWorkerError('worker_conflict', 'Only a Claude Code session is relaunched.');
331
334
  return await backend.relaunchBlocker(cwd, profile, nativeId);
332
335
  }
336
+ /** Every native session of `harness` with requests its backend holds for AGL, without reading anything. */
337
+ public nativePendingAttention(harness: IFleetWorker['harness']): IFleetNativePendingAttention[] {
338
+ if (this.abort.signal.aborted) return [];
339
+ return this.backends[harness].nativePendingAttention?.() ?? [];
340
+ }
333
341
  public async nativeAttention(harness: IFleetWorker['harness'], session: IFleetNativeSession): Promise<IControllerAttention> {
334
342
  return await this.nativeBackend(harness, 'nativeAttention')(session);
335
343
  }
@@ -453,10 +461,10 @@ export class FleetWorkers {
453
461
  return await this.backends.codex.threads?.(plugins.os.homedir(), maxAgeMs) ?? [];
454
462
  }
455
463
  private admitJob(): void {
456
- if (this.admissionClosed || this.abort.signal.aborted) throw new Error('The fleet is closing and admits no new worker job.');
464
+ if (this.admissionClosed || this.abort.signal.aborted) throw new FleetWorkerError('fleet_unavailable', 'The fleet is closing and admits no new worker job.');
457
465
  if (this.jobs.size < 512) return;
458
466
  for (const [id, job] of this.jobs) if (['succeeded', 'failed'].includes(job.snapshot.state)) { this.jobs.delete(id); break; }
459
- if (this.jobs.size >= 512) throw new Error('Fleet worker job capacity reached.');
467
+ if (this.jobs.size >= 512) throw new FleetWorkerError('fleet_unavailable', 'Fleet worker job capacity reached.');
460
468
  }
461
469
  /**
462
470
  * Steers the worker bound to the native session `sessionId` (`harness:nativeId`) with a ticket notice, through the
@@ -475,12 +483,12 @@ export class FleetWorkers {
475
483
  const running = this.exclusive(owner, [worker.name], async () => {
476
484
  snapshot.state = 'running'; this.abort.signal.throwIfAborted();
477
485
  const claimed = await this.claim(owner, worker.name, snapshot, false, fleetMessageDigest(text));
478
- try { await this.backends[claimed.harness].send([{ worker: claimed, profile: claimed.profile, text }]); }
486
+ try { await this.dispatch(snapshot, () => this.backends[claimed.harness].send([{ worker: claimed, profile: claimed.profile, text }])); }
479
487
  catch (error) { await this.finish(owner, claimed, snapshot, error instanceof FleetDispatchError && error.dispatched ? 'unknown' : claimed.state, this.error(error)); throw error; }
480
488
  snapshot.workers = [await this.finish(owner, claimed, snapshot, 'live')];
481
489
  return snapshot.workers[0]!;
482
490
  });
483
- job.completion = running.then(() => { snapshot.state = 'succeeded'; }, (error: unknown) => { snapshot.state = 'failed'; snapshot.error = this.error(error); });
491
+ job.completion = running.then(() => { snapshot.state = 'succeeded'; }, (error: unknown) => this.failJob(snapshot, error));
484
492
  return this.publicWorker(await running);
485
493
  }
486
494
  private publicWorker(worker: IFleetWorker): IFleetWorker {
@@ -575,11 +583,37 @@ export class FleetWorkers {
575
583
  const { stayed, revision } = await this.rebindSessions(owner, { names: [worker.name], own: worker.name,
576
584
  stayed: (failures) => failures.find((failure) => failure.workerName === worker.name) ?? failures.find((failure) => failure.nextName === worker.name) });
577
585
  await this.recordBinding(owner, worker.name, revision, stayed, (current) => {
578
- if (current.pending || current.state !== 'live') throw new Error('Worker recovery fence changed.');
586
+ if (current.pending || current.state !== 'live') throw new FleetWorkerError('worker_fenced', 'Worker recovery fence changed.');
579
587
  });
580
588
  if (stayed) throw new Error(stayed.error);
581
589
  }
582
590
  private error(error: unknown): string { return (error instanceof Error ? error.message : 'Fleet worker operation failed.').slice(0, 4096); }
591
+ /**
592
+ * Fails `job` with `error`, the one place a job failure is recorded: its message, its code exactly when the fleet
593
+ * refused it itself (`FleetWorkerError`), so a reader tells AGL's own text from a dependency's output by the code, and
594
+ * its outcome. The outcome is `refused` only where nothing can have reached a native session: the job never dispatched
595
+ * (`dispatch`) and the error is a refusal, the fleet's own or a dispatch's that sent nothing. Any other failure, a
596
+ * refusal after a dispatch (a fence the settling found changed) and every untyped error included, is `unknown`.
597
+ */
598
+ private failJob(job: IFleetWorkerJob, error: unknown): void {
599
+ job.state = 'failed'; job.error = this.error(error);
600
+ if (error instanceof FleetWorkerError) job.errorCode = error.code;
601
+ const refusal = error instanceof FleetWorkerError || error instanceof FleetDispatchError && !error.dispatched;
602
+ job.errorOutcome = refusal && !this.dispatchedJobs.has(job) ? 'refused' : 'unknown';
603
+ }
604
+ /**
605
+ * Runs `effect`, a dispatch of `job` to a native session (a start, relaunch, send, stop or archive, a native message):
606
+ * from its call on the job may have reached the session, unless it is the job's first dispatch and failed with a
607
+ * `FleetDispatchError` that sent nothing. Every native effect of a job goes through it, so `failJob` knows the outcome.
608
+ */
609
+ private async dispatch<T>(job: IFleetWorkerJob, effect: () => Promise<T>): Promise<T> {
610
+ const earlier = this.dispatchedJobs.has(job);
611
+ this.dispatchedJobs.add(job);
612
+ try { return await effect(); } catch (error) {
613
+ if (!earlier && error instanceof FleetDispatchError && !error.dispatched) this.dispatchedJobs.delete(job);
614
+ throw error;
615
+ }
616
+ }
583
617
  private async exclusive<T>(owner: string, names: string[], action: () => Promise<T>): Promise<T> {
584
618
  const keys = [...new Set(names)].sort().map((name) => `${owner}:${name}`);
585
619
  const before = keys.map((key) => this.queues.get(key) ?? Promise.resolve());
@@ -588,16 +622,16 @@ export class FleetWorkers {
588
622
  try { return await running; } finally { for (const key of keys) if (this.queues.get(key) === running) this.queues.delete(key); }
589
623
  }
590
624
  private profile(profiles: IFleetWorkerProfile[], id: string): IFleetWorkerProfile {
591
- const profile = profiles.find((item) => item.id === id); if (!profile) throw new Error('Worker profile is not configured in the AGL Configuration master.'); return structuredClone(profile);
625
+ const profile = profiles.find((item) => item.id === id); if (!profile) throw new FleetWorkerError('worker_conflict', 'Worker profile is not configured in the AGL Configuration master.'); return structuredClone(profile);
592
626
  }
593
627
  private changed(owner: string, worker: IFleetWorker): void { this.events.publish({ kind: 'worker.changed', workerId: worker.id, workerName: worker.name, ...(worker.ticketKey ? { ticketKey: worker.ticketKey } : {}), status: worker.state, ...(worker.error ? { error: worker.error } : {}) }, owner); }
594
628
  private assertTicket(worker: IFleetWorker, ticketKey: string | undefined): void {
595
- if (!ticketKey || worker.ticketKey !== ticketKey) throw new Error('Worker is not associated with this ticket; inspect or explicitly adopt its binding.');
629
+ if (!ticketKey || worker.ticketKey !== ticketKey) throw new FleetWorkerError('ticket_mismatch', 'Worker is not associated with this ticket; inspect or explicitly adopt its binding.');
596
630
  }
597
631
  private async dispatchHolder(): Promise<IFleetWorkerDispatchHolder> {
598
632
  this.holder ??= (async () => {
599
633
  const identity = await readControllerProcessIdentity(process.pid);
600
- if (!identity) throw new Error('Fleet controller process identity cannot be proven.');
634
+ if (!identity) throw new FleetWorkerError('fleet_unavailable', 'Fleet controller process identity cannot be proven.');
601
635
  return { controllerId: this.controllerId, host: plugins.os.hostname(), pid: identity.pid, fingerprint: identity.fingerprint };
602
636
  })();
603
637
  return await this.holder;
@@ -605,12 +639,12 @@ export class FleetWorkers {
605
639
  private async assertRecoverable(worker: IFleetWorker): Promise<void> {
606
640
  if (!worker.pending) return;
607
641
  const holder = worker.pending.holder;
608
- if (holder.host !== plugins.os.hostname()) throw new Error('Worker dispatch belongs to another host; reconcile it on that host.');
642
+ if (holder.host !== plugins.os.hostname()) throw new FleetWorkerError('worker_fenced', 'Worker dispatch belongs to another host; reconcile it on that host.');
609
643
  if (holder.controllerId === this.controllerId) {
610
644
  const active = this.jobs.get(worker.pending.id)?.snapshot;
611
- if (active?.state === 'running' || active?.state === 'queued') throw new Error('Worker dispatch job is still running.');
645
+ if (active?.state === 'running' || active?.state === 'queued') throw new FleetWorkerError('worker_fenced', 'Worker dispatch job is still running.');
612
646
  } else if (await controllerProcessIdentityIsLive(holder.pid, holder.fingerprint)) {
613
- throw new Error('Worker dispatch controller is still running; reconcile it through that controller.');
647
+ throw new FleetWorkerError('worker_fenced', 'Worker dispatch controller is still running; reconcile it through that controller.');
614
648
  }
615
649
  }
616
650
  /**
@@ -618,7 +652,7 @@ export class FleetWorkers {
618
652
  * session never started (stopped, unbound and settled) is taken over instead: a refused relaunch keeps its name.
619
653
  */
620
654
  private async reserve(owner: string, name: string, cwd: string, profile: IFleetWorkerProfile, job: IFleetWorkerJob, predecessor?: string, actor?: ITicketActor, reportsTo?: string, unstarted?: IFleetWorker): Promise<IFleetWorker> {
621
- await plugins.fs.promises.access(cwd); if (!(await plugins.fs.promises.stat(cwd)).isDirectory()) throw new Error('Worker cwd is not a directory.');
655
+ await plugins.fs.promises.access(cwd); if (!(await plugins.fs.promises.stat(cwd)).isDirectory()) throw new FleetWorkerError('worker_conflict', 'Worker cwd is not a directory.');
622
656
  const now = new Date().toISOString();
623
657
  const worker: IFleetWorker = { id: `${owner}:${name}`, name, harness: profile.harness, profileId: profile.id, profile, cwd,
624
658
  ...(job.ticketKey ? { ticketKey: job.ticketKey } : {}),
@@ -628,7 +662,7 @@ export class FleetWorkers {
628
662
  else {
629
663
  await this.store.update(owner, name, (current) => {
630
664
  if (current.state !== 'stopped' || current.nativeId || current.pending || current.lostDispatch || current.predecessor || current.successor
631
- || current.ticketKey !== job.ticketKey) throw new Error('Native binding fence changed.');
665
+ || current.ticketKey !== job.ticketKey) throw new FleetWorkerError('worker_fenced', 'Native binding fence changed.');
632
666
  for (const key of Object.keys(current) as Array<keyof IFleetWorker>) delete current[key];
633
667
  Object.assign(current, structuredClone(worker));
634
668
  });
@@ -644,12 +678,12 @@ export class FleetWorkers {
644
678
  const commented = !reconfirmed || !this.options.ticketEffects || !!await this.options.ticketEffects.saved(`fleet:reconfirmed:${reconfirmed.id}`);
645
679
  const doc = await this.store.update(owner, name, (worker) => {
646
680
  if (ticketBound) this.assertTicket(worker, job.ticketKey);
647
- if (worker.pending || worker.state === 'unknown' || worker.state === 'starting') throw new Error('Worker has an unresolved dispatch; inspect its native identity before proceeding.');
648
- if (worker.state === 'archived') throw new Error('Worker is archived.');
649
- if (worker.lostDispatch && job.action !== 'stop' && job.action !== 'archive') throw new Error('Worker dispatch was resolved as lost; only stop/archive are allowed.');
681
+ if (worker.pending || worker.state === 'unknown' || worker.state === 'starting') throw new FleetWorkerError('worker_fenced', 'Worker has an unresolved dispatch; inspect its native identity before proceeding.');
682
+ if (worker.state === 'archived') throw new FleetWorkerError('worker_archived', 'Worker is archived.');
683
+ if (worker.lostDispatch && job.action !== 'stop' && job.action !== 'archive') throw new FleetWorkerError('worker_fenced', 'Worker dispatch was resolved as lost; only stop/archive are allowed.');
650
684
  const keep = worker.reconfirmedDispatch && (worker.reconfirmedDispatch.id !== reconfirmed?.id || !commented);
651
685
  if (keep && job.action !== 'stop' && job.action !== 'archive') {
652
- throw new Error(`Worker reconfirmation ${worker.reconfirmedDispatch!.id} has no saved ticket comment; reconfirm the worker again before dispatching to it.`);
686
+ throw new FleetWorkerError('worker_fenced', `Worker reconfirmation ${worker.reconfirmedDispatch!.id} has no saved ticket comment; reconfirm the worker again before dispatching to it.`);
653
687
  }
654
688
  worker.pending = { id: job.id, action: job.action, startedAt: new Date().toISOString(), holder, ...(digest ? { digest } : {}) };
655
689
  // A reconfirmation stays only while it is the worker's latest dispatch outcome; its ticket comment keeps it.
@@ -659,7 +693,7 @@ export class FleetWorkers {
659
693
  /** Settles `job` on `worker` with `error`, which is a binding that stayed on it when `binding` is set. */
660
694
  private async finish(owner: string, worker: IFleetWorker, job: IFleetWorkerJob, state: IFleetWorker['state'], error?: string, binding = false): Promise<IFleetWorker> {
661
695
  const doc = await this.store.update(owner, worker.name, (current) => {
662
- if (current.pending?.id !== job.id) throw new Error('Worker dispatch fence changed.');
696
+ if (current.pending?.id !== job.id) throw new FleetWorkerError('worker_fenced', 'Worker dispatch fence changed.');
663
697
  current.state = state; if (state !== 'unknown') delete current.pending;
664
698
  if (error) current.error = error; else delete current.error;
665
699
  if (error && binding) current.errorSource = 'binding'; else delete current.errorSource;
@@ -669,11 +703,11 @@ export class FleetWorkers {
669
703
  private async startNative(owner: string, worker: IFleetWorker, job: IFleetWorkerJob, start: string | ((bind: (nativeId: string) => Promise<void>) => Promise<void>)): Promise<IFleetWorker> {
670
704
  const launch = typeof start === 'string' ? (bind: (nativeId: string) => Promise<void>) => this.backends[worker.harness].start(worker, worker.profile, start, bind) : start;
671
705
  try {
672
- await launch(async (nativeId) => {
706
+ await this.dispatch(job, () => launch(async (nativeId) => {
673
707
  const doc = await this.store.update(owner, worker.name, (current) => {
674
- if (current.pending?.id !== job.id || current.nativeId && current.nativeId !== nativeId) throw new Error('Native binding fence changed.'); current.nativeId = nativeId;
708
+ if (current.pending?.id !== job.id || current.nativeId && current.nativeId !== nativeId) throw new FleetWorkerError('worker_fenced', 'Native binding fence changed.'); current.nativeId = nativeId;
675
709
  }); worker.nativeId = doc.worker.nativeId;
676
- });
710
+ }));
677
711
  return await this.finish(owner, worker, job, 'live');
678
712
  } catch (error) { await this.finish(owner, worker, job, error instanceof FleetDispatchError && !error.dispatched ? 'stopped' : 'unknown', this.error(error)); throw error; }
679
713
  }
@@ -794,15 +828,15 @@ export class FleetWorkers {
794
828
  }
795
829
  if (job.action === 'adopt' && (input as TFleetWorkerRequest<'adopt'>).relaunch !== undefined) {
796
830
  const args = input as TFleetWorkerRequest<'adopt'>, profile = this.profile(profiles, args.profile), backend = this.backends[profile.harness];
797
- if (!backend.relaunch) throw new Error('Only a Claude Code session is relaunched; a Codex worker gains its identity at its next steer, so adopt it without relaunch.');
831
+ if (!backend.relaunch) throw new FleetWorkerError('worker_conflict', 'Only a Claude Code session is relaunched; a Codex worker gains its identity at its next steer, so adopt it without relaunch.');
798
832
  // The native binding is unique across owners, so the bound check reads every owner's workers.
799
833
  const documents = await this.store.list(), named = documents.find((doc) => doc.owner === owner && doc.worker.name === args.name)?.worker;
800
834
  // Only a worker of the same ticket whose own start or relaunch was refused before its session started gives its
801
835
  // name to a relaunch; a dispatch resolved as lost keeps its record.
802
- if (named && (named.state !== 'stopped' || named.nativeId || named.pending || named.lostDispatch || named.predecessor || named.successor)) throw new Error('A relaunch adopts its session as a new worker; this worker name is taken.');
836
+ if (named && (named.state !== 'stopped' || named.nativeId || named.pending || named.lostDispatch || named.predecessor || named.successor)) throw new FleetWorkerError('worker_conflict', 'A relaunch adopts its session as a new worker; this worker name is taken.');
803
837
  if (named) this.assertTicket(named, args.ticketKey);
804
838
  if (documents.some((doc) => doc.worker.harness === profile.harness && doc.worker.nativeId === args.nativeId && doc.worker.state !== 'archived')) {
805
- throw new Error('A fleet worker is bound to this session already.');
839
+ throw new FleetWorkerError('worker_conflict', 'A fleet worker is bound to this session already.');
806
840
  }
807
841
  const worker = await this.reserve(owner, args.name, args.cwd, profile, job, undefined, actor, reportsTo, named);
808
842
  job.workers = [await this.startNative(owner, worker, job, (bind) => backend.relaunch!(worker, profile, args.nativeId,
@@ -827,15 +861,15 @@ export class FleetWorkers {
827
861
  || existing.ticketKey !== undefined && existing.ticketKey !== args.ticketKey || existing.cwd !== args.cwd
828
862
  || existing.harness !== profile.harness || existing.nativeId && existing.nativeId !== args.nativeId
829
863
  || !plugins.util.isDeepStrictEqual(existing.profile, profile)) {
830
- throw new Error(`Existing worker cannot be adopted as this native identity.${existing.nativeId && existing.nativeId !== args.nativeId ? ' To move it onto a successor session of its lane, re-bind it with a reason.' : ''}`);
864
+ throw new FleetWorkerError('worker_conflict', `Existing worker cannot be adopted as this native identity.${existing.nativeId && existing.nativeId !== args.nativeId ? ' To move it onto a successor session of its lane, re-bind it with a reason.' : ''}`);
831
865
  }
832
866
  await this.assertRecoverable(existing);
833
867
  }
834
- if ((await this.backends[candidate.harness].observe(candidate, profile)).status === 'gone') throw new Error('Native worker identity cannot be observed for adoption.');
868
+ if ((await this.backends[candidate.harness].observe(candidate, profile)).status === 'gone') throw new FleetWorkerError('worker_conflict', 'Native worker identity cannot be observed for adoption.');
835
869
  // Adoption never starts/resumes a turn. Native bindings are unique across owners.
836
870
  if (existing) {
837
871
  const doc = await this.store.update(owner, args.name, (current) => {
838
- if (!plugins.util.isDeepStrictEqual(current, existing)) throw new Error('Worker recovery fence changed.');
872
+ if (!plugins.util.isDeepStrictEqual(current, existing)) throw new FleetWorkerError('worker_fenced', 'Worker recovery fence changed.');
839
873
  current.nativeId = args.nativeId; current.ticketKey = args.ticketKey; current.state = 'live'; delete current.pending; delete current.error; delete current.errorSource;
840
874
  if (actor && !current.ticketActor) current.ticketActor = actor;
841
875
  if (reportsTo && !current.reportsTo) current.reportsTo = reportsTo;
@@ -894,8 +928,8 @@ export class FleetWorkers {
894
928
  catch (error) { stayed = this.error(error); }
895
929
  if (stayed) { await this.finish(owner, claimed, job, old.state, stayed, binding); throw new Error(stayed); }
896
930
  try {
897
- await this.backends[old.harness].stop(old, old.profile);
898
- await this.backends[old.harness].archive(old, old.profile);
931
+ await this.dispatch(job, () => this.backends[old.harness].stop(old, old.profile));
932
+ await this.dispatch(job, () => this.backends[old.harness].archive(old, old.profile));
899
933
  job.workers = [await this.finish(owner, claimed, job, 'archived'), next];
900
934
  } catch (error) { await this.finish(owner, claimed, job, 'unknown', this.error(error)); throw error; }
901
935
  return;
@@ -914,14 +948,14 @@ export class FleetWorkers {
914
948
  for (const harness of ['claude', 'codex'] as const) {
915
949
  const group = workers.filter((worker) => worker.harness === harness).map((worker) => ({ worker, profile: worker.profile, text: messages.find((message) => message.name === worker.name)!.text }));
916
950
  if (!group.length) continue;
917
- await this.backends[harness].send(group); admitted = true;
951
+ await this.dispatch(job, () => this.backends[harness].send(group)); admitted = true;
918
952
  }
919
953
  } catch (error) { throw new FleetDispatchError(this.error(error), admitted || error instanceof FleetDispatchError && error.dispatched, { cause: error }); }
920
954
  } else for (const worker of workers) {
921
955
  if (worker.lostDispatch) continue;
922
956
  // A worker whose start the harness refused has no native session to settle.
923
957
  if (job.action === 'archive' && !worker.nativeId) continue;
924
- await this.backends[worker.harness][job.action as 'stop' | 'archive'](worker, worker.profile);
958
+ await this.dispatch(job, () => this.backends[worker.harness][job.action as 'stop' | 'archive'](worker, worker.profile));
925
959
  }
926
960
  job.workers = [];
927
961
  for (const worker of workers) job.workers.push(await this.finish(owner, worker, job, job.action === 'archive' ? 'archived' : job.action === 'stop' ? 'stopped' : 'live'));
@@ -1,6 +1,8 @@
1
1
  import * as plugins from '../plugins.js';
2
+ import { exactError } from '../functions.exactpersistence.js';
2
3
  import type { IFleetWorker } from '../../ts_interfaces/fleetworkers.js';
3
4
  import { fleetWorkerSchema } from './functions.workervalidation.js';
5
+ import { FleetWorkerError } from './interfaces.workers.js';
4
6
 
5
7
  export interface IFleetWorkerDocument { id: string; owner: string; updateId: string; worker: IFleetWorker; nativeKey?: string }
6
8
  const documentSchema = plugins.z.object({ id: plugins.z.string().min(1), owner: plugins.z.string().min(1),
@@ -28,7 +30,7 @@ export interface IFleetWorkerStore {
28
30
  create(owner: string, worker: IFleetWorker): Promise<IFleetWorkerDocument>;
29
31
  update(owner: string, name: string, change: (worker: IFleetWorker) => void): Promise<IFleetWorkerDocument>;
30
32
  }
31
- const ambiguous = (error: unknown): boolean => error instanceof plugins.nosqldb.SmartdataExactPersistenceError && error.code === 'ambiguous_write';
33
+ const nativeBindingTaken = 'Another fleet worker already holds this native session.';
32
34
  /** The auth store owns the model manager and database; this adapter owns no connection. */
33
35
  export class FleetWorkerStore implements IFleetWorkerStore {
34
36
  public async list(owner?: string): Promise<IFleetWorkerDocument[]> {
@@ -38,7 +40,7 @@ export class FleetWorkerStore implements IFleetWorkerStore {
38
40
  }
39
41
  public async get(owner: string, name: string): Promise<IFleetWorkerDocument> {
40
42
  const record = await FleetWorkerModel.exact.findStoredOne({ id: `${owner}:${name}`, owner });
41
- if (!record) throw new Error('Fleet worker is unavailable for this owner.');
43
+ if (!record) throw new FleetWorkerError('worker_not_found', 'Fleet worker is unavailable for this owner.');
42
44
  return structuredClone(FleetWorkerModel.exact.toPersisted(record));
43
45
  }
44
46
  public async create(owner: string, worker: IFleetWorker): Promise<IFleetWorkerDocument> {
@@ -46,10 +48,11 @@ export class FleetWorkerStore implements IFleetWorkerStore {
46
48
  ...(worker.nativeId ? { nativeKey: `${worker.harness}:${worker.nativeId}` } : {}) };
47
49
  try {
48
50
  const result = await FleetWorkerModel.exact.insert(candidate);
49
- if (result.status === 'conflict') throw new Error('The fleet worker name or native binding already exists.');
51
+ if (result.status === 'conflict') throw new FleetWorkerError('worker_conflict', 'The fleet worker name already exists.');
50
52
  return structuredClone(FleetWorkerModel.exact.toPersisted(result.document));
51
53
  } catch (error) {
52
- if (!ambiguous(error)) throw error;
54
+ if (exactError(error, 'unique_conflict')) throw new FleetWorkerError('worker_conflict', nativeBindingTaken, { cause: error });
55
+ if (!exactError(error, 'ambiguous_write')) throw error;
53
56
  const record = await FleetWorkerModel.exact.findStoredOne({ id: candidate.id });
54
57
  if (record?.updateId === candidate.updateId) return structuredClone(FleetWorkerModel.exact.toPersisted(record));
55
58
  throw new Error('Fleet worker reservation outcome is unknown; inspect the registry before retrying.', { cause: error });
@@ -57,16 +60,17 @@ export class FleetWorkerStore implements IFleetWorkerStore {
57
60
  }
58
61
  public async update(owner: string, name: string, change: (worker: IFleetWorker) => void): Promise<IFleetWorkerDocument> {
59
62
  const current = await FleetWorkerModel.exact.findStoredOne({ id: `${owner}:${name}`, owner });
60
- if (!current) throw new Error('Fleet worker is unavailable for this owner.');
63
+ if (!current) throw new FleetWorkerError('worker_not_found', 'Fleet worker is unavailable for this owner.');
61
64
  const next = structuredClone(FleetWorkerModel.exact.toPersisted(current));
62
65
  change(next.worker); next.worker.updatedAt = new Date().toISOString(); next.updateId = plugins.crypto.randomUUID();
63
66
  if (next.worker.nativeId) next.nativeKey = `${next.worker.harness}:${next.worker.nativeId}`;
64
67
  try {
65
68
  const result = await FleetWorkerModel.exact.transition({ current, change: (model) => { Object.assign(model, next); } });
66
- if (result.status !== 'transitioned') throw new Error('Fleet worker changed concurrently.');
69
+ if (result.status !== 'transitioned') throw new FleetWorkerError('worker_fenced', 'Fleet worker changed concurrently.');
67
70
  return structuredClone(FleetWorkerModel.exact.toPersisted(result.document));
68
71
  } catch (error) {
69
- if (!ambiguous(error)) throw error;
72
+ if (exactError(error, 'unique_conflict')) throw new FleetWorkerError('worker_conflict', nativeBindingTaken, { cause: error });
73
+ if (!exactError(error, 'ambiguous_write')) throw error;
70
74
  const record = await FleetWorkerModel.exact.findStoredOne({ id: next.id });
71
75
  if (record?.updateId === next.updateId) return structuredClone(FleetWorkerModel.exact.toPersisted(record));
72
76
  throw new Error('Fleet worker transition outcome is unknown; inspect the registry before retrying.', { cause: error });
@@ -126,7 +126,7 @@ export const listUnboundDrivers = async (
126
126
  export const unboundDriverLines = (resultArg: { drivers: IFleetUnboundDriver[]; errors: string[] }): string => {
127
127
  const lines = resultArg.drivers.map((driver) => `- ${driver.name ? JSON.stringify(driver.name) : 'unnamed job'} ${driver.nativeId}`
128
128
  + ` (${driver.state}, ${driver.cwd}; looks like a driver by ${driver.driverLike.join(' and ')}): `
129
- + (driver.nativeMessage ? `message it once it settles with ${driver.nativeMessage}, or adopt it: ${driver.adopt}`
129
+ + (driver.nativeMessage ? `message it with ${driver.nativeMessage} (a running job by its unique session name), or adopt it once it settles: ${driver.adopt}`
130
130
  : driver.adopt ? `adopt it: ${driver.adopt}`
131
131
  : `the archived worker ${JSON.stringify(driver.archivedWorker)} still binds it, so it cannot be adopted`));
132
132
  return [lines.length ? lines.join('\n') : '- none found', ...resultArg.errors.map((error) => `- not read: ${error}`)].join('\n');
@@ -1,5 +1,5 @@
1
1
  import * as plugins from '../plugins.js';
2
- import { fleetWorkerJobWaitMaximumMs, type IFleetWorkerProfile, type TFleetWorkerAction, type TFleetWorkerRequest, type TFleetWorkerResponse } from '../../ts_interfaces/fleetworkers.js';
2
+ import { fleetWorkerErrorCodes, fleetWorkerErrorOutcomes, fleetWorkerJobWaitMaximumMs, type IFleetWorkerProfile, type TFleetWorkerAction, type TFleetWorkerRequest, type TFleetWorkerResponse } from '../../ts_interfaces/fleetworkers.js';
3
3
  import { fleetTicketKeySchema as ticketKey, fleetTicketSyncSchema as ticketSync } from './functions.ticketcontext.js';
4
4
  import { ticketActorSchema } from '../functions.ticketvalidation.js';
5
5
  import { controllerAgentMessageMaxTextBytes, controllerNativeWaitReasons, controllerSessionFeedLimits, isControllerAgentMessageSender } from '../../ts_interfaces/index.js';
@@ -119,17 +119,22 @@ const nativeWait = plugins.z.object({ reason: plugins.z.enum(controllerNativeWai
119
119
  const report = plugins.z.object({ worker: fleetWorkerSchema, status: reportStatus,
120
120
  turnId: text.optional(), turnStatus: text.optional(), outcome: outcome.optional(), reportId: text.optional(), text: plugins.z.string().max(64 * 1024),
121
121
  truncated: plugins.z.boolean(), error: plugins.z.string().max(4096).optional() }).strict();
122
- const nativeMessage = plugins.z.object({ delivery: plugins.z.literal('native-wake'), nativeId: plugins.z.string().uuid(), jobId: text, cwd,
122
+ const nativeMessage = plugins.z.object({ delivery: plugins.z.enum(['native-wake', 'native-inbox']), nativeId: plugins.z.string().uuid(), jobId: text, cwd,
123
123
  profileId: name.optional(), note: plugins.z.string().min(1).max(4096), adopt: plugins.z.string().min(1).max(8192) }).strict();
124
124
  const job = plugins.z.object({ id: text, action: plugins.z.enum(['start', 'adopt', 'resolve-lost', 'reconfirm', 'steer', 'report', 'stop', 'archive', 'refresh', 'move', 'native-message']),
125
125
  ticketKey: ticketKey.optional(),
126
126
  ticketSync: ticketSync.optional(),
127
127
  state: plugins.z.enum(['queued', 'running', 'succeeded', 'failed']), workers: plugins.z.array(fleetWorkerSchema).max(64).optional(),
128
- report: report.optional(), nativeMessage: nativeMessage.optional(), error: plugins.z.string().max(4096).optional() }).strict().superRefine((value, context) => {
128
+ report: report.optional(), nativeMessage: nativeMessage.optional(), error: plugins.z.string().max(4096).optional(),
129
+ errorCode: plugins.z.enum(fleetWorkerErrorCodes).optional(), errorOutcome: plugins.z.enum(fleetWorkerErrorOutcomes).optional() }).strict().superRefine((value, context) => {
129
130
  if (value.state === 'failed' && !value.error || value.state === 'succeeded' && (value.action === 'report' ? !value.report
130
131
  : value.action === 'native-message' ? !value.nativeMessage : !value.workers)) {
131
132
  context.addIssue({ code: 'custom', message: 'Incomplete fleet worker job outcome.' });
132
133
  }
134
+ // A code names the fleet's own refusal of a failed job.
135
+ if (value.errorCode !== undefined && value.state !== 'failed') context.addIssue({ code: 'custom', message: 'Only a failed fleet worker job has an error code.' });
136
+ // So does the outcome of what it dispatched.
137
+ if (value.errorOutcome !== undefined && value.state !== 'failed') context.addIssue({ code: 'custom', message: 'Only a failed fleet worker job has an error outcome.' });
133
138
  });
134
139
  const event = plugins.z.object({ id: plugins.z.number().int().positive(),
135
140
  kind: plugins.z.enum(['worker.changed', 'worker.turn.ended', 'worker.report.mid_turn', 'worker.reaped', 'worker.credential.failed', 'worker.observation.failed', 'release.finished', 'release.failed', 'ticket.applied', 'ticket.failed', 'ticket.unknown',
@@ -1,6 +1,6 @@
1
1
  import * as plugins from '../plugins.js';
2
2
  import type { IFleetWorker, IFleetWorkerProfile, IFleetWorkerReport, IFleetWorkerTurnOutcome, IFleetRelaunchBlocker, IFleetWorkerAbsenceProof, IFleetWorkerSessionProof, IFleetWorkerRebindProof, TFleetWorkerErrorCode } from '../../ts_interfaces/fleetworkers.js';
3
- import type { IControllerAttention, IControllerMessageBundle, IControllerNativeWait, TControllerElicitationReply, TControllerPermissionReply } from '../../ts_interfaces/index.js';
3
+ import type { IControllerAttention, IControllerMessageBundle, IControllerNativeWait, TControllerElicitationReply, TControllerNativeJobDelivery, TControllerPermissionReply } from '../../ts_interfaces/index.js';
4
4
 
5
5
  /** The owner's answer to a request of a native session: a permission, a question (`null` rejects it) or an MCP elicitation. */
6
6
  export type TFleetNativeReply = { permission: TControllerPermissionReply } | { answers: string[][] | null } | { elicitation: TControllerElicitationReply };
@@ -8,9 +8,13 @@ export type TFleetNativeReply = { permission: TControllerPermissionReply } | { a
8
8
  export class FleetDispatchError extends Error {
9
9
  constructor(message: string, public readonly dispatched: boolean, options?: ErrorOptions) { super(message, options); this.name = 'FleetDispatchError'; }
10
10
  }
11
- /** A fleet worker read's refusal; see `fleetWorkerErrorCodes`. Its message names only what the caller asked for. */
11
+ /**
12
+ * A refusal of the fleet whose text AGL writes itself, never a dependency's, so its message names only AGL's own values
13
+ * (a worker, a ticket, a profile, a harness); see `fleetWorkerErrorCodes`. A job it fails records its code
14
+ * (`IFleetWorkerJob.errorCode`).
15
+ */
12
16
  export class FleetWorkerError extends Error {
13
- constructor(public readonly code: TFleetWorkerErrorCode, message: string) { super(message); this.name = 'FleetWorkerError'; }
17
+ constructor(public readonly code: TFleetWorkerErrorCode, message: string, options?: ErrorOptions) { super(message, options); this.name = 'FleetWorkerError'; }
14
18
  }
15
19
  /**
16
20
  * A native send refused before anything reached the session: its running turn is not the one the sender read
@@ -25,8 +29,11 @@ export class FleetNativeTurnError extends Error {
25
29
  * `agentMessage` steers a turn another client runs only when `expectedTurnId` names it, as an agent message must.
26
30
  */
27
31
  export interface IFleetNativeSendTurn { expectedTurnId?: string; agentMessage?: boolean }
28
- /** Whether a native send steered the running turn or started the next one, and that turn's id when known. */
29
- export interface IFleetNativeSendReceipt { steered: boolean; turnId?: string }
32
+ /**
33
+ * Whether a native send steered the running turn or started the next one, and that turn's id when known; for a Claude
34
+ * Code background job, whether it was woken or took the message in its inbox (`job`).
35
+ */
36
+ export interface IFleetNativeSendReceipt { steered: boolean; turnId?: string; job?: TControllerNativeJobDelivery }
30
37
  export interface IFleetNativeEvent {
31
38
  nativeId: string; kind: 'worker.turn.ended' | 'worker.report.mid_turn' | 'worker.reaped' | 'worker.credential.failed'; turnId?: string; status?: string;
32
39
  text?: string; reportId?: string; truncated?: boolean; error?: string;
@@ -56,11 +63,21 @@ export interface IFleetNativeThread {
56
63
  /** Why the thread waits for a person in the harness's own client: set exactly when `status` is `waiting`. */
57
64
  nativeWait?: IControllerNativeWait;
58
65
  }
66
+ /** A native session with requests a backend holds for AGL: where it runs, its title and the requests. */
67
+ export interface IFleetNativePendingAttention {
68
+ nativeId: string;
69
+ cwd: string;
70
+ title: string;
71
+ attention: IControllerAttention;
72
+ }
59
73
  /**
60
74
  * A native session the fleet lists but does not bind: `cwd` is the directory its own source lists, `home` the profile
61
- * home whose Claude Code holds it (the host's own when absent).
75
+ * home whose Claude Code holds it (the host's own when absent). `jobDelivery` is how the sender prepared its message for a
76
+ * Claude Code background job; a job found in the other state is refused before anything is sent. `peerHomes` are the
77
+ * other Claude Code homes whose running sessions SendMessage reaches by name, so a running job's name must be unique
78
+ * across them too when its inbox is addressed.
62
79
  */
63
- export interface IFleetNativeSession { nativeId: string; cwd: string; home?: string }
80
+ export interface IFleetNativeSession { nativeId: string; cwd: string; home?: string; jobDelivery?: TControllerNativeJobDelivery; peerHomes?: string[] }
64
81
  /** A transcript page read-only: `nextCursor` pages to older bundles, and `earlier` says older bundles exist at all. */
65
82
  export interface IFleetNativePage { bundles: IControllerMessageBundle[]; earlier: boolean; nextCursor?: string }
66
83
  export interface IFleetWorkerBackend {
@@ -109,6 +126,8 @@ export interface IFleetWorkerBackend {
109
126
  nativeTurn?(session: IFleetNativeSession): Promise<string | undefined>;
110
127
  /** The requests of turns the backend runs in a native session that wait for an answer. */
111
128
  nativeAttention?(session: IFleetNativeSession): Promise<IControllerAttention>;
129
+ /** Every native session with requests the backend holds for AGL, from what it holds alone (no read). */
130
+ nativePendingAttention?(): IFleetNativePendingAttention[];
112
131
  nativeReply?(session: IFleetNativeSession, requestId: string, reply: TFleetNativeReply): Promise<void>;
113
132
  /** Drops the worker's poll baseline: the next poll observes it afresh and reports nothing it observed before. */
114
133
  forget?(worker: IFleetWorker): void;