agl 43.0.5 → 43.1.0

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 (142) hide show
  1. package/changelog.md +18 -0
  2. package/dist_serve/bundle.js +5186 -4683
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +29 -29
  5. package/dist_serve/bundle.js.third-party-notices.txt +29 -29
  6. package/dist_serve/third-party-notices.md +1 -1
  7. package/dist_ts/00_commitinfo_data.js +1 -1
  8. package/dist_ts/aglapi/aglapisurface.document.js +475 -4
  9. package/dist_ts/aglapi/interfaces.d.ts +10 -0
  10. package/dist_ts/aglapi/interfaces.js +3 -1
  11. package/dist_ts/classes.claudeharness.d.ts +14 -5
  12. package/dist_ts/classes.claudeharness.js +62 -2
  13. package/dist_ts/classes.codexclientadapter.d.ts +7 -5
  14. package/dist_ts/classes.codexclientadapter.js +38 -3
  15. package/dist_ts/classes.controller.d.ts +9 -2
  16. package/dist_ts/classes.controller.js +116 -24
  17. package/dist_ts/classes.inferencegateway.d.ts +8 -5
  18. package/dist_ts/classes.inferencegateway.js +62 -19
  19. package/dist_ts/classes.inferencespend.d.ts +9 -3
  20. package/dist_ts/classes.inferencespend.js +44 -16
  21. package/dist_ts/classes.mcpclient.d.ts +6 -4
  22. package/dist_ts/classes.mcpclient.js +6 -2
  23. package/dist_ts/classes.mcpcontrollerhost.js +5 -1
  24. package/dist_ts/classes.mcptools.d.ts +1 -1
  25. package/dist_ts/classes.mcptools.js +17 -4
  26. package/dist_ts/classes.opencodeclient.js +3 -1
  27. package/dist_ts/classes.proxycontrol.d.ts +22 -11
  28. package/dist_ts/classes.proxycontrol.js +6 -3
  29. package/dist_ts/classes.proxycontrolclient.d.ts +6 -5
  30. package/dist_ts/classes.proxycontrolclient.js +8 -6
  31. package/dist_ts/classes.proxydaemon.d.ts +8 -6
  32. package/dist_ts/classes.proxydaemon.js +35 -21
  33. package/dist_ts/classes.proxyleaseholder.d.ts +12 -4
  34. package/dist_ts/classes.proxyleaseholder.js +39 -9
  35. package/dist_ts/classes.proxystore.d.ts +4 -3
  36. package/dist_ts/classes.proxystore.js +17 -7
  37. package/dist_ts/classes.sessionfeed.d.ts +1 -1
  38. package/dist_ts/classes.validation.d.ts +7 -0
  39. package/dist_ts/classes.validation.js +49 -2
  40. package/dist_ts/driver/functions.drivertools.js +2 -2
  41. package/dist_ts/fleet/classes.codexworkers.d.ts +4 -11
  42. package/dist_ts/fleet/classes.codexworkers.js +6 -3
  43. package/dist_ts/fleet/classes.workers.d.ts +25 -13
  44. package/dist_ts/fleet/classes.workers.js +105 -9
  45. package/dist_ts/fleet/functions.workervalidation.d.ts +26 -1
  46. package/dist_ts/fleet/functions.workervalidation.js +40 -11
  47. package/dist_ts/fleet/interfaces.workers.d.ts +17 -11
  48. package/dist_ts/fleet/interfaces.workers.js +10 -1
  49. package/dist_ts/functions.confinedrelay.d.ts +21 -0
  50. package/dist_ts/functions.confinedrelay.js +65 -0
  51. package/dist_ts/functions.deviceapi.d.ts +4 -2
  52. package/dist_ts/functions.deviceapi.js +20 -2
  53. package/dist_ts/functions.elicitation.d.ts +49 -0
  54. package/dist_ts/functions.elicitation.js +418 -0
  55. package/dist_ts/functions.inferencecli.d.ts +3 -3
  56. package/dist_ts/functions.inferencecli.js +33 -10
  57. package/dist_ts/functions.inferencecliarguments.d.ts +2 -1
  58. package/dist_ts/functions.inferencecliarguments.js +29 -8
  59. package/dist_ts/functions.inferencelaunch.d.ts +35 -7
  60. package/dist_ts/functions.inferencelaunch.js +143 -16
  61. package/dist_ts/functions.mcpfleetworkertools.d.ts +63 -70
  62. package/dist_ts/functions.mcpfleetworkertools.js +32 -4
  63. package/dist_ts/functions.proxycontract.d.ts +21 -4
  64. package/dist_ts/functions.proxycontract.js +12 -5
  65. package/dist_ts/functions.proxyharnessconfig.d.ts +7 -0
  66. package/dist_ts/functions.proxyharnessconfig.js +11 -1
  67. package/dist_ts/interfaces.auth.d.ts +1 -1
  68. package/dist_ts/interfaces.auth.js +2 -1
  69. package/dist_ts_interfaces/devices.d.ts +133 -3
  70. package/dist_ts_interfaces/devices.js +3 -2
  71. package/dist_ts_interfaces/elicitations.d.ts +125 -0
  72. package/dist_ts_interfaces/elicitations.js +7 -0
  73. package/dist_ts_interfaces/fleetworkers.d.ts +119 -5
  74. package/dist_ts_interfaces/fleetworkers.js +14 -2
  75. package/dist_ts_interfaces/index.d.ts +1 -0
  76. package/dist_ts_interfaces/index.js +2 -1
  77. package/dist_ts_interfaces/interfaces.d.ts +3 -1
  78. package/dist_ts_interfaces/interfaces.js +2 -2
  79. package/dist_ts_interfaces/mcprequests.d.ts +5 -1
  80. package/dist_ts_interfaces/mcprequests.js +2 -1
  81. package/dist_ts_interfaces/nativesessions.d.ts +14 -0
  82. package/dist_ts_interfaces/requests.d.ts +3 -3
  83. package/dist_ts_interfaces/requests.fleetworkers.js +2 -2
  84. package/dist_ts_interfaces/requests.js +1 -1
  85. package/dist_ts_interfaces/requests.promptreply.d.ts +18 -0
  86. package/dist_ts_interfaces/sessionfeed.d.ts +3 -2
  87. package/dist_ts_interfaces/sessionfeed.js +1 -1
  88. package/package.json +3 -3
  89. package/readme.md +191 -24
  90. package/third-party-notices.md +1 -1
  91. package/ts/00_commitinfo_data.ts +1 -1
  92. package/ts/aglapi/aglapisurface.document.ts +474 -3
  93. package/ts/aglapi/interfaces.ts +2 -0
  94. package/ts/classes.claudeharness.ts +80 -9
  95. package/ts/classes.codexclientadapter.ts +41 -5
  96. package/ts/classes.controller.ts +142 -29
  97. package/ts/classes.inferencegateway.ts +69 -23
  98. package/ts/classes.inferencespend.ts +46 -13
  99. package/ts/classes.mcpclient.ts +8 -4
  100. package/ts/classes.mcpcontrollerhost.ts +4 -0
  101. package/ts/classes.mcptools.ts +17 -3
  102. package/ts/classes.opencodeclient.ts +2 -0
  103. package/ts/classes.proxycontrol.ts +27 -13
  104. package/ts/classes.proxycontrolclient.ts +9 -6
  105. package/ts/classes.proxydaemon.ts +49 -27
  106. package/ts/classes.proxyleaseholder.ts +43 -11
  107. package/ts/classes.proxystore.ts +21 -8
  108. package/ts/classes.sessionfeed.ts +1 -1
  109. package/ts/classes.validation.ts +52 -0
  110. package/ts/driver/functions.drivertools.ts +1 -1
  111. package/ts/fleet/classes.codexworkers.ts +8 -6
  112. package/ts/fleet/classes.workers.ts +101 -17
  113. package/ts/fleet/functions.workervalidation.ts +35 -9
  114. package/ts/fleet/interfaces.workers.ts +11 -4
  115. package/ts/functions.confinedrelay.ts +65 -0
  116. package/ts/functions.deviceapi.ts +24 -1
  117. package/ts/functions.elicitation.ts +443 -0
  118. package/ts/functions.inferencecli.ts +38 -13
  119. package/ts/functions.inferencecliarguments.ts +26 -5
  120. package/ts/functions.inferencelaunch.ts +143 -16
  121. package/ts/functions.mcpfleetworkertools.ts +34 -4
  122. package/ts/functions.proxycontract.ts +17 -4
  123. package/ts/functions.proxyharnessconfig.ts +11 -0
  124. package/ts/interfaces.auth.ts +1 -0
  125. package/ts_interfaces/devices.schema.json +476 -2
  126. package/ts_interfaces/devices.ts +146 -2
  127. package/ts_interfaces/elicitations.ts +148 -0
  128. package/ts_interfaces/fleetworkers.ts +96 -4
  129. package/ts_interfaces/index.ts +1 -0
  130. package/ts_interfaces/interfaces.ts +3 -1
  131. package/ts_interfaces/mcprequests.ts +1 -0
  132. package/ts_interfaces/nativesessions.ts +16 -0
  133. package/ts_interfaces/requests.fleetworkers.ts +1 -1
  134. package/ts_interfaces/requests.promptreply.ts +22 -0
  135. package/ts_interfaces/requests.ts +4 -0
  136. package/ts_interfaces/sessionfeed.ts +3 -2
  137. package/ts_web/00_commitinfo_data.ts +1 -1
  138. package/ts_web/classes.elicitationcards.ts +106 -0
  139. package/ts_web/classes.nativesessionstate.ts +38 -1
  140. package/ts_web/elements.fleetworker.ts +27 -2
  141. package/ts_web/elements.harnesscontrollerapp.ts +68 -1
  142. package/ts_web/functions.sessionchat.ts +5 -0
@@ -1,16 +1,16 @@
1
1
  import * as plugins from '../plugins.js';
2
2
  import { controllerRuntimeIdKey, type IWorkerClaudeJobRequest, type TWorkerClaudeJobObservation } from '../../ts_interfaces/index.js';
3
- import type { IFleetEvent, IFleetWorker, IFleetWorkerProfile, IFleetWorkerJob, IFleetNativeMessageReceipt, TFleetEventKind, TFleetWorkerAction, TFleetWorkerRequest, TFleetWorkerResponse, TFleetWorkerJobAction, IFleetWorkerReport, IFleetRelaunchBlocker, IFleetWorkerDispatchHolder } from '../../ts_interfaces/fleetworkers.js';
3
+ import type { IFleetEvent, IFleetWorker, IFleetWorkerProfile, IFleetWorkerJob, IFleetNativeMessageReceipt, TFleetEventKind, TFleetWorkerAction, TFleetWorkerRequest, TFleetWorkerResponse, TFleetWorkerResponseTo, TFleetWorkerJobAction, IFleetWorkerReport, IFleetRelaunchBlocker, IFleetWorkerDispatchHolder, IFleetWorkerSummary, IFleetWorkerSummaryPage } from '../../ts_interfaces/fleetworkers.js';
4
4
  import type { IFleetConfiguration, IFleetOperation, IFleetTicketSync } from '../../ts_interfaces/fleet.js';
5
5
  import type { ITicketActor } from '../../ts_interfaces/tickets.js';
6
6
  import type { FleetTicketEffects, IFleetTicketReport } from './classes.ticketeffects.js';
7
- import type { IControllerSystemMetrics, IControllerFleetWorkerView, IReq_ControllerFleetWorkerRead, IControllerPermission, IControllerQuestion, TControllerPermissionReply } from '../../ts_interfaces/index.js';
7
+ import type { IControllerSystemMetrics, IControllerFleetWorkerView, IReq_ControllerFleetWorkerRead, IControllerNativeWait, IControllerAttention } from '../../ts_interfaces/index.js';
8
8
  import { FleetWorkerStore, type IFleetWorkerStore, type IFleetWorkerDocument } from './classes.workerstore.js';
9
9
  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, fleetMessageDigest, fleetReportMarker, type IFleetWorkerBackend, type IFleetNativeAgent, type IFleetNativeThread, type IFleetNativeSession, type IFleetNativePage, type IFleetNativeSendTurn, type IFleetNativeSendReceipt } from './interfaces.workers.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';
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';
@@ -53,11 +53,31 @@ export interface IFleetWorkersOptions {
53
53
  /** The fleet events that change what the Driver view shows of the fleet's workers. */
54
54
  export const fleetWorkerViewEventKinds: ReadonlySet<TFleetEventKind> = new Set<TFleetEventKind>(['worker.changed', 'worker.turn.ended', 'worker.report.mid_turn', 'worker.reaped', 'worker.credential.failed']);
55
55
  interface IOwnedWorkerJob { owner: string; snapshot: IFleetWorkerJob; completion: Promise<void> }
56
+ /** What the views show of a worker's native session (`FleetWorkers.observation`). */
57
+ interface IFleetWorkerObservation { status?: IFleetWorkerReport['status'] | undefined; turn?: IFleetWorkerObservedTurn | undefined; nativeWait?: IControllerNativeWait | undefined; excerpt?: string | undefined }
56
58
  /** Durable bindings, including when no worker poller has been started since controller restart. */
57
59
  export const fleetNativeSessionNames = async (storeArg: IFleetWorkerStore = new FleetWorkerStore()): Promise<Map<string, string>> =>
58
60
  new Map((await storeArg.list()).filter(({ worker }) => worker.nativeId && worker.state !== 'archived')
59
61
  .map(({ worker }) => [controllerRuntimeIdKey({ harnessId: worker.harness, nativeId: worker.nativeId! }), worker.name]));
60
62
 
63
+ /** The summary page size when the request names none. */
64
+ export const fleetWorkerSummaryDefaultLimit = 50;
65
+ /** Where a summary page continues: after the worker `id` created at `createdAt`, in the filter `filter` digests. */
66
+ interface IFleetWorkerListCursor { filter: string; createdAt: string; id: string }
67
+ const listCursorSchema = plugins.z.object({ filter: plugins.z.string().regex(/^[A-Za-z0-9_-]{22}$/u), createdAt: plugins.z.string().min(1).max(64),
68
+ id: plugins.z.string().min(1).max(4096) }).strict();
69
+ /** The digest a cursor carries of the filter it pages: archived, ticket, state and harness. */
70
+ const listFilterDigest = (request: TFleetWorkerRequest<'list'>): string => plugins.crypto.createHash('sha256')
71
+ .update(JSON.stringify([request.archived === true, request.ticketKey ?? null, request.state ?? null, request.harness ?? null])).digest('base64url').slice(0, 22);
72
+ /** Summary order: newest created first, then by id. Both are immutable, so a page boundary never moves. */
73
+ const compareListed = (a: Pick<IFleetWorker, 'createdAt' | 'id'>, b: Pick<IFleetWorker, 'createdAt' | 'id'>): number =>
74
+ a.createdAt !== b.createdAt ? (a.createdAt > b.createdAt ? -1 : 1) : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
75
+ const encodeListCursor = (cursor: IFleetWorkerListCursor): string => Buffer.from(JSON.stringify(cursor)).toString('base64url');
76
+ const decodeListCursor = (cursor: string): IFleetWorkerListCursor => {
77
+ try { return listCursorSchema.parse(JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'))); }
78
+ catch { throw new FleetWorkerError('list_cursor_invalid', 'The cursor is not the nextCursor of a fleet worker summary page; list again without cursor.'); }
79
+ };
80
+
61
81
  /** Durable native bindings and dispatch fences; transient jobs/events never claim crash recovery. */
62
82
  export class FleetWorkers {
63
83
  public readonly events: FleetEvents;
@@ -196,19 +216,25 @@ export class FleetWorkers {
196
216
  this.ticketEvent(owner, worker.ticketKey!, written.sync, worker.id); return written.sync;
197
217
  }
198
218
  /** `reportsTo` names the direct report whose session asks; a worker it starts or adopts reports to it. */
199
- public async execute<T extends TFleetWorkerAction>(action: T, request: TFleetWorkerRequest<T>, configuration: IFleetConfiguration, owner: string, signal?: AbortSignal, actor?: ITicketActor, reportsTo?: string): Promise<TFleetWorkerResponse<T>> {
219
+ public async execute<T extends TFleetWorkerAction, R extends TFleetWorkerRequest<T> = TFleetWorkerRequest<T>>(action: T, request: R, configuration: IFleetConfiguration, owner: string, signal?: AbortSignal, actor?: ITicketActor, reportsTo?: string): Promise<TFleetWorkerResponseTo<T, R>> {
200
220
  this.abort.signal.throwIfAborted(); signal?.throwIfAborted();
201
221
  const input = assertFleetWorkerRequest(action, request);
202
222
  const rebinding = action === 'adopt' && (input as TFleetWorkerRequest<'adopt'>).rebind === true;
203
223
  const attributed = action === 'resolve-lost' || action === 'reconfirm' || rebinding ? ticketActorSchema.refine(value => value.role === 'driver' || value.role === 'owner').parse(actor)
204
224
  : this.options.ticketEffects && ['start', 'adopt', 'refresh', 'move'].includes(action) ? this.options.ticketEffects.actor(actor) : undefined;
205
- if (action === 'list') return { workers: (await this.store.list(owner)).map((doc) => this.publicWorker(doc.worker)).filter((worker) =>
206
- ((input as TFleetWorkerRequest<'list'>).archived || worker.state !== 'archived') && (!input.ticketKey || worker.ticketKey === input.ticketKey)) } as TFleetWorkerResponse<T>;
207
- if (action === 'watch') { const watch = input as TFleetWorkerRequest<'watch'>; return await this.events.watch(owner, watch.cursor, watch.timeoutMs, signal, watch.ticketKey) as TFleetWorkerResponse<T>; }
225
+ if (action === 'list') return await this.list(owner, input as TFleetWorkerRequest<'list'>) as TFleetWorkerResponseTo<T, R>;
226
+ if (action === 'get') {
227
+ const { name, id } = input as TFleetWorkerRequest<'get'>;
228
+ const worker = (await this.store.list(owner)).find((doc) => name !== undefined ? doc.worker.name === name : doc.worker.id === id)?.worker;
229
+ if (!worker) throw new FleetWorkerError('worker_not_found', `This owner has no fleet worker ${name !== undefined ? `named ${name}` : `with id ${id}`}.`);
230
+ return this.view(worker) as TFleetWorkerResponseTo<T, R>;
231
+ }
232
+ if (action === 'job-wait') return await this.jobWait(owner, input as TFleetWorkerRequest<'job-wait'>, signal) as TFleetWorkerResponseTo<T, R>;
233
+ if (action === 'watch') { const watch = input as TFleetWorkerRequest<'watch'>; return await this.events.watch(owner, watch.cursor, watch.timeoutMs, signal, watch.ticketKey) as TFleetWorkerResponseTo<T, R>; }
208
234
  if (action === 'status') {
209
235
  const job = this.jobs.get((input as TFleetWorkerRequest<'status'>).id);
210
236
  if (!job || job.owner !== owner || input.ticketKey !== undefined && job.snapshot.ticketKey !== input.ticketKey) throw new Error('Fleet worker job is unavailable for this owner and ticket.');
211
- return { job: this.publicJob(job.snapshot) } as TFleetWorkerResponse<T>;
237
+ return { job: this.publicJob(job.snapshot) } as TFleetWorkerResponseTo<T, R>;
212
238
  }
213
239
  if (action === 'native-message') {
214
240
  const nativeMessages = this.options.nativeMessages;
@@ -220,13 +246,14 @@ export class FleetWorkers {
220
246
  job.completion = nativeMessages.send(owner, input as TFleetWorkerRequest<'native-message'>, actor)
221
247
  .then((receipt) => { snapshot.nativeMessage = receipt; snapshot.state = 'succeeded'; },
222
248
  (error: unknown) => { snapshot.state = 'failed'; snapshot.error = this.error(error); });
223
- return { job: this.publicJob(snapshot) } as TFleetWorkerResponse<T>;
249
+ return { job: this.publicJob(snapshot) } as TFleetWorkerResponseTo<T, R>;
224
250
  }
225
251
  const profiles = validateFleetWorkerProfiles(configuration.workerProfiles ?? []);
226
252
  this.admitJob();
227
253
  const snapshot: IFleetWorkerJob = { id: plugins.crypto.randomUUID(), action: action as TFleetWorkerJobAction, state: 'queued', ...(input.ticketKey ? { ticketKey: input.ticketKey } : {}) };
228
254
  const job: IOwnedWorkerJob = { owner, snapshot, completion: Promise.resolve() }; this.jobs.set(snapshot.id, job);
229
- const names = 'messages' in input ? input.messages.map((message) => message.name) : 'name' in input ? [input.name, ...('nextName' in input ? [input.nextName] : [])] : [];
255
+ const mutation = input as TFleetWorkerRequest<TFleetWorkerJobAction>;
256
+ const names = 'messages' in mutation ? mutation.messages.map((message) => message.name) : 'name' in mutation ? [mutation.name, ...('nextName' in mutation ? [mutation.nextName] : [])] : [];
230
257
  // Recovery requires a new, deliberate request after the original job settles.
231
258
  // Do not turn adoption requested during a dispatch into a deferred fence release.
232
259
  const recoveringActiveJob = ['adopt', 'resolve-lost', 'reconfirm'].includes(action) && names.some((name) => this.queues.has(`${owner}:${name}`));
@@ -240,7 +267,7 @@ export class FleetWorkers {
240
267
  const adopted = action === 'adopt' ? (input as TFleetWorkerRequest<'adopt'>).nativeId : undefined;
241
268
  job.completion = (recoveringActiveJob ? Promise.reject(new Error('Worker job is still running; inspect it before recovery.'))
242
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); });
243
- return { job: this.publicJob(snapshot) } as TFleetWorkerResponse<T>;
270
+ return { job: this.publicJob(snapshot) } as TFleetWorkerResponseTo<T, R>;
244
271
  }
245
272
  /**
246
273
  * Calls the listener whenever what `views()` shows may have changed: a worker lifecycle event, or a status the
@@ -303,16 +330,66 @@ export class FleetWorkers {
303
330
  if (!backend.relaunchBlocker) throw new Error('Only a Claude Code session is relaunched.');
304
331
  return await backend.relaunchBlocker(cwd, profile, nativeId);
305
332
  }
306
- public async nativeAttention(harness: IFleetWorker['harness'], session: IFleetNativeSession): Promise<{ permissions: IControllerPermission[]; questions: IControllerQuestion[] }> {
333
+ public async nativeAttention(harness: IFleetWorker['harness'], session: IFleetNativeSession): Promise<IControllerAttention> {
307
334
  return await this.nativeBackend(harness, 'nativeAttention')(session);
308
335
  }
309
- public async nativeReply(harness: IFleetWorker['harness'], session: IFleetNativeSession, requestId: string, reply: { permission: TControllerPermissionReply } | { answers: string[][] | null }): Promise<void> {
336
+ public async nativeReply(harness: IFleetWorker['harness'], session: IFleetNativeSession, requestId: string, reply: TFleetNativeReply): Promise<void> {
310
337
  await this.nativeBackend(harness, 'nativeReply')(session, requestId, reply);
311
338
  }
339
+ /**
340
+ * The owner's workers the request filters: every public record (`full`, in registry order), or one summary page,
341
+ * newest created first, with the counts of the whole filtered set. A cursor of another filter, or one continuing
342
+ * after a worker the registry no longer holds as it was, is refused, never restarted.
343
+ */
344
+ private async list(owner: string, request: TFleetWorkerRequest<'list'>): Promise<TFleetWorkerResponse<'list'>> {
345
+ const workers = (await this.store.list(owner)).map((doc) => doc.worker);
346
+ const matching = workers.filter((worker) => (request.archived || worker.state !== 'archived') && (!request.ticketKey || worker.ticketKey === request.ticketKey)
347
+ && (!request.state || worker.state === request.state) && (!request.harness || worker.harness === request.harness));
348
+ if (request.view !== 'summary') return { workers: matching.map((worker) => this.publicWorker(worker)) };
349
+ const filter = listFilterDigest(request);
350
+ matching.sort(compareListed);
351
+ let start = 0;
352
+ if (request.cursor !== undefined) {
353
+ const cursor = decodeListCursor(request.cursor);
354
+ if (cursor.filter !== filter) throw new FleetWorkerError('list_cursor_mismatch', 'The cursor pages another filter (archived, ticketKey, state, harness); repeat that filter or list again without cursor.');
355
+ const anchor = workers.find((worker) => worker.id === cursor.id);
356
+ if (anchor?.createdAt !== cursor.createdAt) throw new FleetWorkerError('list_cursor_stale', 'The cursor continues after a worker this owner no longer holds as it was; list again without cursor.');
357
+ start = matching.findIndex((worker) => compareListed(worker, cursor) > 0);
358
+ if (start < 0) start = matching.length;
359
+ }
360
+ const page = matching.slice(start, start + (request.limit ?? fleetWorkerSummaryDefaultLimit)), last = page.at(-1);
361
+ const result: IFleetWorkerSummaryPage = { view: 'summary', workers: page.map((worker) => this.summary(worker)), total: matching.length,
362
+ fenced: matching.filter((worker) => worker.pending).length,
363
+ failed: matching.filter((worker) => worker.error !== undefined || this.observation(worker).turn?.outcome?.state === 'failed').length };
364
+ if (last && start + page.length < matching.length) result.nextCursor = encodeListCursor({ filter, createdAt: last.createdAt, id: last.id });
365
+ return result;
366
+ }
367
+ private summary(worker: IFleetWorker): IFleetWorkerSummary {
368
+ const { status, turn, nativeWait } = this.observation(worker), outcome = turn?.outcome;
369
+ return { id: worker.id, name: worker.name, harness: worker.harness, profileId: worker.profileId, ...(worker.ticketKey ? { ticketKey: worker.ticketKey } : {}),
370
+ state: worker.state, ...(worker.nativeId ? { nativeId: worker.nativeId } : {}), cwd: worker.cwd, updatedAt: worker.updatedAt,
371
+ observed: { ...(status ? { status } : {}), ...(outcome ? { outcome: structuredClone(outcome) } : {}), ...(nativeWait ? { nativeWait: structuredClone(nativeWait) } : {}) },
372
+ fence: { ...(worker.pending ? { pending: { action: worker.pending.action, since: worker.pending.startedAt } } : {}),
373
+ ...(worker.lostDispatch ? { lostDispatch: true } : {}), ...(worker.reconfirmedDispatch ? { reconfirmed: true } : {}),
374
+ ...(worker.error !== undefined ? { error: true } : {}) } };
375
+ }
376
+ /**
377
+ * The owner's job `id` once it settled, or as it is after `timeoutMs` (`timedOut`). Neither the timeout nor an
378
+ * abandoned wait cancels the job. A job the controller no longer holds is `job_unavailable`, never failed.
379
+ */
380
+ private async jobWait(owner: string, request: TFleetWorkerRequest<'job-wait'>, signal?: AbortSignal): Promise<TFleetWorkerResponse<'job-wait'>> {
381
+ const timeout = new AbortController(), timer = setTimeout(() => timeout.abort(), request.timeoutMs);
382
+ try { return { job: await this.settled(owner, request.id, signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal), timedOut: false }; }
383
+ catch (error) {
384
+ const job = this.jobs.get(request.id);
385
+ if (signal?.aborted || !timeout.signal.aborted || !job || job.owner !== owner) throw error;
386
+ return { job: this.publicJob(job.snapshot), timedOut: !['succeeded', 'failed'].includes(job.snapshot.state) };
387
+ } finally { clearTimeout(timer); }
388
+ }
312
389
  /** The job once it succeeded or failed; the job runs on when the signal aborts the wait. */
313
390
  public async settled(owner: string, id: string, signal?: AbortSignal): Promise<IFleetWorkerJob> {
314
391
  const job = this.jobs.get(id);
315
- if (!job || job.owner !== owner) throw new Error('Fleet worker job is unavailable for this owner.');
392
+ if (!job || job.owner !== owner) throw new FleetWorkerError('job_unavailable', 'Fleet worker job is unavailable for this owner.');
316
393
  if (signal) {
317
394
  signal.throwIfAborted();
318
395
  let cancel!: () => void;
@@ -323,12 +400,19 @@ export class FleetWorkers {
323
400
  return this.publicJob(job.snapshot);
324
401
  }
325
402
  private view(worker: IFleetWorker): IControllerFleetWorkerView {
326
- if (worker.lostDispatch) return { worker: this.publicWorker(worker), status: worker.state === 'archived' ? 'archived' : 'gone' };
327
- const backend = this.backends[worker.harness], status = backend.observed?.(worker), excerpt = backend.observedExcerpt?.(worker), turn = backend.observedTurn?.(worker);
328
- const nativeWait = backend.observedNativeWait?.(worker);
403
+ const { status, turn, nativeWait, excerpt } = this.observation(worker);
329
404
  return { worker: this.publicWorker(worker), ...(status ? { status } : {}), ...(turn?.outcome ? { outcome: structuredClone(turn.outcome) } : {}),
330
405
  ...(turn?.startedAt ? { turnStartedAt: turn.startedAt } : {}), ...(nativeWait ? { nativeWait: structuredClone(nativeWait) } : {}), ...(excerpt ? { excerpt } : {}) };
331
406
  }
407
+ /**
408
+ * What the views show of a worker's native session, the one place a lost dispatch is applied: it is gone (archived once
409
+ * archived) with no turn, native wait or excerpt; any other worker shows its backend's last observation.
410
+ */
411
+ private observation(worker: IFleetWorker): IFleetWorkerObservation {
412
+ if (worker.lostDispatch) return { status: worker.state === 'archived' ? 'archived' : 'gone' };
413
+ const backend = this.backends[worker.harness];
414
+ return { status: backend.observed?.(worker), turn: backend.observedTurn?.(worker), nativeWait: backend.observedNativeWait?.(worker), excerpt: backend.observedExcerpt?.(worker) };
415
+ }
332
416
  /** The host's Claude Code sessions of the profile home `home` (the default home when absent), read at most `maxAgeMs` ago. */
333
417
  public async nativeAgents(home: string | undefined, maxAgeMs: number): Promise<IFleetNativeAgent[]> {
334
418
  return await this.backends.claude.inventory?.(home, plugins.os.homedir(), maxAgeMs) ?? [];
@@ -1,16 +1,21 @@
1
1
  import * as plugins from '../plugins.js';
2
- import type { IFleetWorkerProfile, TFleetWorkerAction, TFleetWorkerRequest, TFleetWorkerResponse } from '../../ts_interfaces/fleetworkers.js';
2
+ import { 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
- import { controllerAgentMessageMaxTextBytes, isControllerAgentMessageSender } from '../../ts_interfaces/index.js';
5
+ import { controllerAgentMessageMaxTextBytes, controllerNativeWaitReasons, controllerSessionFeedLimits, isControllerAgentMessageSender } from '../../ts_interfaces/index.js';
6
6
 
7
7
  const name = plugins.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u);
8
8
  const text = plugins.z.string().min(1).max(4096).refine((value) => !/[\0\r\n]/u.test(value));
9
9
  const body = plugins.z.string().min(1).max(128 * 1024).refine((value) => !value.includes('\0') && Buffer.byteLength(value) <= 128 * 1024);
10
10
  const cwd = text.refine((value) => plugins.path.isAbsolute(value));
11
11
  const reason = text.max(2048).refine(value => value.trim().length > 0);
12
+ const harness = plugins.z.enum(['claude', 'codex']);
13
+ const workerState = plugins.z.enum(['starting', 'live', 'stopped', 'archived', 'unknown']);
14
+ const reportStatus = plugins.z.enum(['busy', 'idle', 'blocked', 'stopped', 'archived', 'reaped', 'gone']);
15
+ /** A summary list page's continuation: base64url, as `FleetWorkers` encodes it. */
16
+ const listCursor = plugins.z.string().regex(/^[A-Za-z0-9_-]{1,1024}$/u, 'cursor is the nextCursor of a fleet worker summary page');
12
17
  export const fleetWorkerProfileSchema = plugins.z.object({
13
- id: name, harness: plugins.z.enum(['claude', 'codex']), model: text, effort: text,
18
+ id: name, harness, model: text, effort: text,
14
19
  home: cwd.optional(), preamble: body.optional(),
15
20
  permissionMode: plugins.z.enum(['acceptEdits', 'auto', 'bypassPermissions', 'manual', 'dontAsk', 'plan']).optional(),
16
21
  modelProvider: text.optional(), approvalPolicy: plugins.z.enum(['never', 'on-request', 'on-failure', 'untrusted']).optional(),
@@ -36,8 +41,12 @@ export const fleetWorkerRequestSchemas = {
36
41
  report: plugins.z.object({ name, ticketKey }).strict(), stop: plugins.z.object({ name, ticketKey }).strict(), archive: plugins.z.object({ name, ticketKey }).strict(),
37
42
  refresh: plugins.z.object({ name, nextName: name, profile: name.optional(), handoff: body, note: body.optional(), ticketKey }).strict(),
38
43
  move: plugins.z.object({ name, nextName: name, profile: name, handoff: body, note: body.optional(), ticketKey }).strict(),
39
- list: plugins.z.object({ archived: plugins.z.boolean().optional(), ticketKey: ticketKey.optional() }).strict(),
44
+ list: plugins.z.object({ archived: plugins.z.boolean().optional(), ticketKey: ticketKey.optional(), view: plugins.z.enum(['summary', 'full']).optional(),
45
+ limit: plugins.z.number().int().min(1).max(100).optional(), cursor: listCursor.optional(), state: workerState.optional(), harness: harness.optional() }).strict(),
46
+ get: plugins.z.object({ name: name.optional(), id: text.optional() }).strict()
47
+ .refine((value) => (value.name === undefined) !== (value.id === undefined), 'Name the worker by either name or id.'),
40
48
  status: plugins.z.object({ id: text, ticketKey: ticketKey.optional() }).strict(),
49
+ 'job-wait': plugins.z.object({ id: text, timeoutMs: plugins.z.number().int().min(0).max(fleetWorkerJobWaitMaximumMs) }).strict(),
41
50
  watch: plugins.z.object({ ticketKey: ticketKey.optional(), cursor: plugins.z.object({ epoch: text, after: plugins.z.number().int().nonnegative() }).strict().optional(),
42
51
  timeoutMs: plugins.z.number().int().min(0).max(15_000).optional() }).strict(),
43
52
  'native-message': plugins.z.object({
@@ -51,6 +60,11 @@ export const assertFleetWorkerRequest = <T extends TFleetWorkerAction>(action: T
51
60
  if (!Object.hasOwn(fleetWorkerRequestSchemas, action)) throw new Error('Unknown fleet worker action.');
52
61
  const result = fleetWorkerRequestSchemas[action].parse(input);
53
62
  if ('nextName' in result && 'name' in result && result.nextName === result.name) throw new Error('A successor must have a new worker name.');
63
+ if (action === 'list') {
64
+ const list = result as TFleetWorkerRequest<'list'>;
65
+ if (list.view !== 'summary' && (list.limit !== undefined || list.cursor !== undefined)) throw new Error('limit and cursor page the summary view only.');
66
+ if (list.state === 'archived' && !list.archived) throw new Error('Archived workers are listed only with archived: true.');
67
+ }
54
68
  if (action === 'adopt') {
55
69
  const adopt = result as TFleetWorkerRequest<'adopt'>;
56
70
  if (adopt.rebind && adopt.reason === undefined) throw new Error('A re-bind requires a reason.');
@@ -67,10 +81,10 @@ const dispatch = plugins.z.object({ id: text, action: text, startedAt: text,
67
81
  }).strict();
68
82
  const resolver = ticketActorSchema.refine(actor => actor.role === 'driver' || actor.role === 'owner');
69
83
  export const fleetWorkerSchema = plugins.z.object({
70
- id: text, name, harness: plugins.z.enum(['claude', 'codex']), profileId: name, profile: fleetWorkerProfileSchema, cwd, nativeId: text.optional(),
84
+ id: text, name, harness, profileId: name, profile: fleetWorkerProfileSchema, cwd, nativeId: text.optional(),
71
85
  ticketKey: ticketKey.optional(),
72
86
  ticketActor: ticketActorSchema.refine(actor => actor.role !== 'worker').optional(), reportsTo: name.optional(),
73
- state: plugins.z.enum(['starting', 'live', 'stopped', 'archived', 'unknown']), createdAt: text, updatedAt: text,
87
+ state: workerState, createdAt: text, updatedAt: text,
74
88
  pending: dispatch.optional(),
75
89
  lostDispatch: plugins.z.object({ id: text, state: plugins.z.literal('lost'), dispatch: dispatch.optional(), resolvedAt: text,
76
90
  actor: resolver, reason: text.max(2048),
@@ -101,7 +115,8 @@ export const fleetWorkerSchema = plugins.z.object({
101
115
  });
102
116
  const outcome = plugins.z.object({ turnId: text, state: plugins.z.enum(['completed', 'interrupted', 'failed']),
103
117
  limit: plugins.z.enum(['usage_limit', 'usage_reserve', 'rate_limit']).optional() }).strict();
104
- const report = plugins.z.object({ worker: fleetWorkerSchema, status: plugins.z.enum(['busy', 'idle', 'blocked', 'stopped', 'archived', 'reaped', 'gone']),
118
+ const nativeWait = plugins.z.object({ reason: plugins.z.enum(controllerNativeWaitReasons) }).strict();
119
+ const report = plugins.z.object({ worker: fleetWorkerSchema, status: reportStatus,
105
120
  turnId: text.optional(), turnStatus: text.optional(), outcome: outcome.optional(), reportId: text.optional(), text: plugins.z.string().max(64 * 1024),
106
121
  truncated: plugins.z.boolean(), error: plugins.z.string().max(4096).optional() }).strict();
107
122
  const nativeMessage = plugins.z.object({ delivery: plugins.z.literal('native-wake'), nativeId: plugins.z.string().uuid(), jobId: text, cwd,
@@ -125,12 +140,23 @@ const event = plugins.z.object({ id: plugins.z.number().int().positive(),
125
140
  ticketSync: ticketSync.optional(),
126
141
  text: plugins.z.string().max(64 * 1024).optional(), truncated: plugins.z.boolean().optional(), error: plugins.z.string().max(4096).optional(),
127
142
  repo: text.optional(), operationId: text.optional(), version: text.optional(), target: text.optional(), metrics: plugins.z.record(plugins.z.string(), plugins.z.unknown()).optional() }).strict();
143
+ const summary = plugins.z.object({ id: text, name, harness, profileId: name, ticketKey: ticketKey.optional(), state: workerState, nativeId: text.optional(), cwd, updatedAt: text,
144
+ observed: plugins.z.object({ status: reportStatus.optional(), outcome: outcome.optional(), nativeWait: nativeWait.optional() }).strict(),
145
+ fence: plugins.z.object({ pending: plugins.z.object({ action: text, since: text }).strict().optional(), lostDispatch: plugins.z.literal(true).optional(),
146
+ reconfirmed: plugins.z.literal(true).optional(), error: plugins.z.literal(true).optional() }).strict() }).strict();
147
+ const count = plugins.z.number().int().min(0).max(1024);
148
+ const summaryPage = plugins.z.object({ view: plugins.z.literal('summary'), workers: plugins.z.array(summary).max(100), total: count, fenced: count, failed: count,
149
+ nextCursor: listCursor.optional() }).strict();
150
+ const view = plugins.z.object({ worker: fleetWorkerSchema, status: reportStatus.optional(), outcome: outcome.optional(), turnStartedAt: text.optional(),
151
+ nativeWait: nativeWait.optional(), excerpt: plugins.z.string().max(controllerSessionFeedLimits.excerptChars).optional() }).strict();
128
152
  export const assertFleetWorkerResponse = <T extends TFleetWorkerAction>(action: T, input: unknown): TFleetWorkerResponse<T> => {
129
- const schema = action === 'list' ? plugins.z.object({ workers: plugins.z.array(fleetWorkerSchema).max(1024) }).strict()
153
+ const schema = action === 'list' ? plugins.z.union([plugins.z.object({ workers: plugins.z.array(fleetWorkerSchema).max(1024) }).strict(), summaryPage])
154
+ : action === 'get' ? view
155
+ : action === 'job-wait' ? plugins.z.object({ job, timedOut: plugins.z.boolean() }).strict()
130
156
  : action === 'watch' ? plugins.z.object({ cursor: fleetWorkerRequestSchemas.watch.shape.cursor.unwrap(), reset: plugins.z.boolean(), events: plugins.z.array(event).max(64) }).strict()
131
157
  : plugins.z.object({ job }).strict();
132
158
  const value = schema.parse(input);
133
- if ('job' in value && action !== 'status' && value.job.action !== action) throw new Error('Fleet worker response action mismatch.');
159
+ if ('job' in value && action !== 'status' && action !== 'job-wait' && value.job.action !== action) throw new Error('Fleet worker response action mismatch.');
134
160
  return value as TFleetWorkerResponse<T>;
135
161
  };
136
162
 
@@ -1,10 +1,17 @@
1
1
  import * as plugins from '../plugins.js';
2
- import type { IFleetWorker, IFleetWorkerProfile, IFleetWorkerReport, IFleetWorkerTurnOutcome, IFleetRelaunchBlocker, IFleetWorkerAbsenceProof, IFleetWorkerSessionProof, IFleetWorkerRebindProof } from '../../ts_interfaces/fleetworkers.js';
3
- import type { IControllerMessageBundle, IControllerNativeWait, IControllerPermission, IControllerQuestion, TControllerPermissionReply } from '../../ts_interfaces/index.js';
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';
4
+
5
+ /** The owner's answer to a request of a native session: a permission, a question (`null` rejects it) or an MCP elicitation. */
6
+ export type TFleetNativeReply = { permission: TControllerPermissionReply } | { answers: string[][] | null } | { elicitation: TControllerElicitationReply };
4
7
 
5
8
  export class FleetDispatchError extends Error {
6
9
  constructor(message: string, public readonly dispatched: boolean, options?: ErrorOptions) { super(message, options); this.name = 'FleetDispatchError'; }
7
10
  }
11
+ /** A fleet worker read's refusal; see `fleetWorkerErrorCodes`. Its message names only what the caller asked for. */
12
+ export class FleetWorkerError extends Error {
13
+ constructor(public readonly code: TFleetWorkerErrorCode, message: string) { super(message); this.name = 'FleetWorkerError'; }
14
+ }
8
15
  /**
9
16
  * A native send refused before anything reached the session: its running turn is not the one the sender read
10
17
  * (`concurrent_change`), the expected turn ended (`turn_ended`), or another client's turn was to be steered without
@@ -101,8 +108,8 @@ export interface IFleetWorkerBackend {
101
108
  /** The id of the turn a native session runs now, read-only; `undefined` while it runs none. */
102
109
  nativeTurn?(session: IFleetNativeSession): Promise<string | undefined>;
103
110
  /** The requests of turns the backend runs in a native session that wait for an answer. */
104
- nativeAttention?(session: IFleetNativeSession): Promise<{ permissions: IControllerPermission[]; questions: IControllerQuestion[] }>;
105
- nativeReply?(session: IFleetNativeSession, requestId: string, reply: { permission: TControllerPermissionReply } | { answers: string[][] | null }): Promise<void>;
111
+ nativeAttention?(session: IFleetNativeSession): Promise<IControllerAttention>;
112
+ nativeReply?(session: IFleetNativeSession, requestId: string, reply: TFleetNativeReply): Promise<void>;
106
113
  /** Drops the worker's poll baseline: the next poll observes it afresh and reports nothing it observed before. */
107
114
  forget?(worker: IFleetWorker): void;
108
115
  /** The native status the last poll observed, without reading native state again. */
@@ -0,0 +1,65 @@
1
+ import * as plugins from './plugins.js';
2
+ import { aglProxyRelayDefaultPort, aglProxyRelayFile } from './functions.proxycontract.js';
3
+
4
+ /**
5
+ * AGL's relay for a confined Codex run (AGL-1614), which a container starts its command through:
6
+ * `node /run/agl-proxy-relay/agl-relay.mjs -- codex exec …`. Codex has no Unix-socket transport for its model provider, so
7
+ * the relay listens on `127.0.0.1:<port>` inside the container (`AGL_PROXY_RELAY_PORT`, `aglProxyRelayDefaultPort` when
8
+ * unset), which has no network but its own loopback, and pipes each connection byte for byte to the confined listener's
9
+ * socket the launcher names (`AGL_PROXY_SOCKET`, in the directory mounted at `aglProxyConfinedMountPoint`), and to nothing
10
+ * else: a connection the socket does not take is closed. Once it listens it runs the command with its standard streams
11
+ * and environment, passes it SIGTERM, SIGINT and SIGHUP, and exits with its status (128 plus the signal's number for a
12
+ * command a signal ended, 127 for one that could not start). It writes nothing to standard output, which is the
13
+ * command's, and its own failures to standard error. Plain Node.js, no dependencies: the container needs `node` and
14
+ * nothing of AGL.
15
+ */
16
+ export const aglProxyRelaySource = `// AGL relay (AGL-1614): loopback TCP inside the container to the confined proxy socket, then the command.
17
+ import net from 'node:net';
18
+ import os from 'node:os';
19
+ import { spawn } from 'node:child_process';
20
+ const fail = (codeArg, textArg) => { process.stderr.write('agl-relay: ' + textArg + '\\n'); process.exit(codeArg); };
21
+ const socketPath = process.env.AGL_PROXY_SOCKET;
22
+ if (!socketPath || !socketPath.startsWith('/')) {
23
+ fail(2, 'AGL_PROXY_SOCKET names no socket; start the container with agl proxy confined run --harness codex.');
24
+ }
25
+ const portText = process.env.AGL_PROXY_RELAY_PORT || '${aglProxyRelayDefaultPort}';
26
+ const port = Number(portText);
27
+ if (!/^[0-9]{1,5}$/.test(portText) || port < 1 || port > 65535) fail(2, 'AGL_PROXY_RELAY_PORT is no port from 1 to 65535.');
28
+ const separator = process.argv.indexOf('--');
29
+ const command = separator < 0 ? [] : process.argv.slice(separator + 1);
30
+ if (!command.length) fail(2, 'usage: node ${aglProxyRelayFile} -- <command> [arguments]');
31
+ // Half-open on both sides: each side's end reaches the other through its pipe, so a client that ends its request still
32
+ // gets the whole answer, byte for byte. A failure on either side, or a client that is gone, ends both at once.
33
+ const server = net.createServer({ allowHalfOpen: true }, (client) => {
34
+ const upstream = net.createConnection({ path: socketPath, allowHalfOpen: true });
35
+ client.on('error', () => upstream.destroy()); upstream.on('error', () => client.destroy());
36
+ client.on('close', () => upstream.destroy()); upstream.on('close', (failedArg) => { if (failedArg) client.destroy(); });
37
+ client.pipe(upstream); upstream.pipe(client);
38
+ });
39
+ server.on('error', (error) => fail(1, 'cannot listen on 127.0.0.1:' + port + ': ' + error.message));
40
+ server.listen(port, '127.0.0.1', () => {
41
+ const child = spawn(command[0], command.slice(1), { stdio: 'inherit' });
42
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(signal, () => { child.kill(signal); });
43
+ child.on('error', (error) => fail(127, command[0] + ': ' + error.message));
44
+ child.on('exit', (code, signal) => {
45
+ server.close();
46
+ process.exit(code ?? 128 + (signal ? os.constants.signals[signal] ?? 0 : 0));
47
+ });
48
+ });
49
+ `;
50
+
51
+ /**
52
+ * A Codex run's relay on the host: a directory of this run's alone (0700, in the temporary directory) holding the relay
53
+ * (0444), which the container mounts read-only. `remove` deletes it once the container is gone.
54
+ */
55
+ export const writeConfinedRelay = async (): Promise<{ directory: string; remove: () => Promise<void> }> => {
56
+ const directory = await plugins.fs.promises.mkdtemp(plugins.path.join(plugins.os.tmpdir(), 'agl-proxy-relay-'));
57
+ const remove = () => plugins.fs.promises.rm(directory, { recursive: true, force: true });
58
+ try {
59
+ await plugins.fs.promises.writeFile(plugins.path.join(directory, aglProxyRelayFile), aglProxyRelaySource, { mode: 0o444, flag: 'wx' });
60
+ } catch (errorArg) {
61
+ await remove();
62
+ throw errorArg;
63
+ }
64
+ return { directory, remove };
65
+ };
@@ -5,6 +5,7 @@ import type {
5
5
  IControllerQuestion,
6
6
  IControllerRuntimeId,
7
7
  IControllerSessionFeedRow,
8
+ TControllerElicitation,
8
9
  TControllerEventType,
9
10
  TControllerSessionFeedDelta,
10
11
  } from '../ts_interfaces/index.js';
@@ -18,16 +19,18 @@ import {
18
19
  type IDeviceSessionRow,
19
20
  type IReq_DeviceAuthChallenge,
20
21
  type IReq_DeviceAuthProve,
22
+ type IReq_DeviceElicitationReply,
21
23
  type IReq_DevicePair,
22
24
  type IReq_DevicePermissionReply,
23
25
  type IReq_DeviceQuestionReply,
24
26
  type IReq_DeviceSessionRead,
25
27
  type IReq_DeviceSessionSend,
26
28
  type TDeviceEvent,
29
+ type TDeviceElicitation,
27
30
  type TDeviceMessagePart,
28
31
  } from '../ts_interfaces/devices.js';
29
32
  import { isControllerSessionFeedRowId } from '../ts_interfaces/sessionfeed.js';
30
- import { assertKeys, assertObject, assertQuestionAnswers } from './classes.validation.js';
33
+ import { assertElicitationReply, assertKeys, assertObject, assertQuestionAnswers } from './classes.validation.js';
31
34
  import { sessionFeedRowId } from './classes.sessionfeed.js';
32
35
 
33
36
  /*
@@ -127,6 +130,16 @@ export const deviceQuestions = (questionsArg: readonly IControllerQuestion[]): I
127
130
  })),
128
131
  }));
129
132
 
133
+ export const deviceElicitations = (elicitationsArg: readonly TControllerElicitation[]): TDeviceElicitation[] => elicitationsArg
134
+ .map((elicitationArg): TDeviceElicitation => {
135
+ const base = { id: elicitationArg.id.nativeId, serverName: elicitationArg.serverName, message: elicitationArg.message, createdAt: elicitationArg.createdAt };
136
+ switch (elicitationArg.mode) {
137
+ case 'form': return { mode: 'form', ...base, fields: structuredClone(elicitationArg.schema.fields) };
138
+ case 'url': return { mode: 'url', ...base, url: elicitationArg.url };
139
+ case 'unsupported': return { mode: 'unsupported', ...base, reason: elicitationArg.reason };
140
+ }
141
+ });
142
+
130
143
  /**
131
144
  * The row id a device names a conversation by, when the feed lists it as something a device opens; events about any
132
145
  * other session (a driver, a child, a terminal's agent, one the feed has not listed yet) reach no device.
@@ -279,6 +292,16 @@ export const assertDeviceQuestionReplyRequest = (valueArg: unknown): IReq_Device
279
292
  };
280
293
  };
281
294
 
295
+ export const assertDeviceElicitationReplyRequest = (valueArg: unknown): IReq_DeviceElicitationReply['request'] => {
296
+ const value = assertObject(valueArg, 'device elicitation reply request');
297
+ assertKeys(value, ['sessionId', 'elicitationId', 'reply']);
298
+ return {
299
+ sessionId: assertRowId(value.sessionId),
300
+ elicitationId: assertText(value.elicitationId, 'elicitationId', 512),
301
+ reply: assertElicitationReply(value.reply),
302
+ };
303
+ };
304
+
282
305
  export const assertDevicePairingCancelRequest = (valueArg: unknown): { pairingId: string } => {
283
306
  const value = assertObject(valueArg, 'pairing cancel request');
284
307
  assertKeys(value, ['pairingId']);