agl 43.2.0 → 43.3.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 (184) hide show
  1. package/changelog.md +20 -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.claudeharness.d.ts +16 -0
  11. package/dist_ts/classes.claudeharness.js +24 -2
  12. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  13. package/dist_ts/classes.codexclientadapter.js +14 -2
  14. package/dist_ts/classes.controller.d.ts +165 -11
  15. package/dist_ts/classes.controller.js +1095 -170
  16. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  17. package/dist_ts/classes.controllerdevices.js +6 -1
  18. package/dist_ts/classes.inbox.d.ts +72 -0
  19. package/dist_ts/classes.inbox.js +231 -0
  20. package/dist_ts/classes.inferencerouter.d.ts +10 -0
  21. package/dist_ts/classes.inferencerouter.js +5 -3
  22. package/dist_ts/classes.inferenceservice.js +2 -2
  23. package/dist_ts/classes.mcpclient.d.ts +1 -1
  24. package/dist_ts/classes.mcpclient.js +24 -6
  25. package/dist_ts/classes.mcpcontrollerhost.js +3 -1
  26. package/dist_ts/classes.mcptools.js +13 -8
  27. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  28. package/dist_ts/classes.mcpvalidation.js +32 -2
  29. package/dist_ts/classes.nativesessions.d.ts +17 -4
  30. package/dist_ts/classes.nativesessions.js +41 -9
  31. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  32. package/dist_ts/classes.opencodeclient.js +47 -3
  33. package/dist_ts/classes.publishedset.d.ts +38 -0
  34. package/dist_ts/classes.publishedset.js +50 -0
  35. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  36. package/dist_ts/classes.sessionfeed.js +18 -26
  37. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  38. package/dist_ts/classes.systemmetricssampler.js +15 -3
  39. package/dist_ts/classes.ticketstore.d.ts +50 -3
  40. package/dist_ts/classes.ticketstore.js +45 -8
  41. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  42. package/dist_ts/driver/classes.directreports.js +25 -6
  43. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  44. package/dist_ts/driver/classes.driverservice.js +50 -16
  45. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  46. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  47. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  48. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  49. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  50. package/dist_ts/fleet/classes.workercommand.js +15 -4
  51. package/dist_ts/fleet/classes.workers.d.ts +5 -1
  52. package/dist_ts/fleet/classes.workers.js +8 -2
  53. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  54. package/dist_ts/fleet/functions.workervalidation.js +2 -2
  55. package/dist_ts/fleet/interfaces.workers.d.ts +21 -3
  56. package/dist_ts/fleet/interfaces.workers.js +1 -1
  57. package/dist_ts/functions.agentmessage.d.ts +3 -0
  58. package/dist_ts/functions.agentmessage.js +4 -1
  59. package/dist_ts/functions.deviceapi.d.ts +151 -4
  60. package/dist_ts/functions.deviceapi.js +893 -38
  61. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  62. package/dist_ts/functions.fleetworkercli.js +11 -8
  63. package/dist_ts/functions.inferencecli.js +3 -1
  64. package/dist_ts/functions.mcpfleetworkertools.js +2 -2
  65. package/dist_ts/functions.ticketvalidation.js +11 -2
  66. package/dist_ts/interfaces.auth.d.ts +1 -1
  67. package/dist_ts/interfaces.auth.js +9 -1
  68. package/dist_ts/plugins.d.ts +3 -1
  69. package/dist_ts/plugins.js +7 -2
  70. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  71. package/dist_ts_authswitch/authority-contract.js +1 -1
  72. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  73. package/dist_ts_authswitch/authority-overview.js +17 -6
  74. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  75. package/dist_ts_authswitch/authority-placement.js +17 -10
  76. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  77. package/dist_ts_authswitch/authority-renewal.js +56 -0
  78. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  79. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  80. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  81. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  82. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  83. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  84. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  85. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  86. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  87. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  88. package/dist_ts_interfaces/devices.d.ts +1012 -5
  89. package/dist_ts_interfaces/devices.js +68 -2
  90. package/dist_ts_interfaces/fleetworkers.d.ts +5 -3
  91. package/dist_ts_interfaces/inbox.d.ts +234 -0
  92. package/dist_ts_interfaces/inbox.js +101 -0
  93. package/dist_ts_interfaces/index.d.ts +1 -0
  94. package/dist_ts_interfaces/index.js +2 -1
  95. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  96. package/dist_ts_interfaces/interfaces.js +4 -2
  97. package/dist_ts_interfaces/mcprequests.d.ts +34 -4
  98. package/dist_ts_interfaces/mcprequests.js +11 -1
  99. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  100. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  101. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  102. package/dist_ts_interfaces/plugins.d.ts +2 -1
  103. package/dist_ts_interfaces/plugins.js +4 -2
  104. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  105. package/dist_ts_interfaces/requests.accounts.js +3 -1
  106. package/dist_ts_interfaces/requests.d.ts +3 -2
  107. package/dist_ts_interfaces/requests.js +1 -1
  108. package/docs/authswitch.md +20 -1
  109. package/package.json +3 -3
  110. package/readme.md +112 -26
  111. package/ts/00_commitinfo_data.ts +1 -1
  112. package/ts/aglapi/aglapisurface.document.ts +196 -16
  113. package/ts/classes.accountsactions.ts +30 -3
  114. package/ts/classes.claudeharness.ts +27 -1
  115. package/ts/classes.codexclientadapter.ts +14 -1
  116. package/ts/classes.controller.ts +1294 -246
  117. package/ts/classes.controllerdevices.ts +6 -0
  118. package/ts/classes.inbox.ts +239 -0
  119. package/ts/classes.inferencerouter.ts +15 -2
  120. package/ts/classes.inferenceservice.ts +1 -1
  121. package/ts/classes.mcpclient.ts +24 -3
  122. package/ts/classes.mcpcontrollerhost.ts +2 -0
  123. package/ts/classes.mcptools.ts +12 -7
  124. package/ts/classes.mcpvalidation.ts +27 -1
  125. package/ts/classes.nativesessions.ts +50 -12
  126. package/ts/classes.opencodeclient.ts +55 -4
  127. package/ts/classes.publishedset.ts +56 -0
  128. package/ts/classes.sessionfeed.ts +17 -20
  129. package/ts/classes.systemmetricssampler.ts +13 -2
  130. package/ts/classes.ticketstore.ts +73 -12
  131. package/ts/driver/classes.directreports.ts +25 -6
  132. package/ts/driver/classes.driverservice.ts +75 -14
  133. package/ts/fleet/classes.claudeworkers.ts +112 -39
  134. package/ts/fleet/classes.codexworkers.ts +21 -6
  135. package/ts/fleet/classes.workercommand.ts +14 -4
  136. package/ts/fleet/classes.workers.ts +9 -2
  137. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  138. package/ts/fleet/functions.workervalidation.ts +1 -1
  139. package/ts/fleet/interfaces.workers.ts +20 -5
  140. package/ts/functions.agentmessage.ts +3 -0
  141. package/ts/functions.deviceapi.ts +1071 -34
  142. package/ts/functions.fleetworkercli.ts +10 -7
  143. package/ts/functions.inferencecli.ts +2 -0
  144. package/ts/functions.mcpfleetworkertools.ts +1 -1
  145. package/ts/functions.ticketvalidation.ts +11 -1
  146. package/ts/interfaces.auth.ts +8 -0
  147. package/ts/plugins.ts +7 -0
  148. package/ts_authswitch/authority-contract.ts +20 -0
  149. package/ts_authswitch/authority-overview.ts +28 -6
  150. package/ts_authswitch/authority-placement.ts +25 -17
  151. package/ts_authswitch/authority-renewal.ts +64 -0
  152. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  153. package/ts_authswitch/classes.authoritycli.ts +49 -2
  154. package/ts_authswitch/classes.authorityclient.ts +14 -4
  155. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  156. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  157. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  158. package/ts_authswitch/native-contracts.md +21 -0
  159. package/ts_authswitch/readme.md +1 -1
  160. package/ts_interfaces/devices.schema.json +3573 -603
  161. package/ts_interfaces/devices.ts +1093 -4
  162. package/ts_interfaces/fleetworkers.ts +5 -3
  163. package/ts_interfaces/inbox.ts +287 -0
  164. package/ts_interfaces/index.ts +1 -0
  165. package/ts_interfaces/interfaces.ts +9 -2
  166. package/ts_interfaces/mcprequests.ts +43 -4
  167. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  168. package/ts_interfaces/nativesessions.ts +17 -3
  169. package/ts_interfaces/plugins.ts +3 -1
  170. package/ts_interfaces/requests.accounts.ts +20 -0
  171. package/ts_interfaces/requests.ts +4 -0
  172. package/ts_web/00_commitinfo_data.ts +1 -1
  173. package/ts_web/accounts.plugins.ts +4 -2
  174. package/ts_web/classes.accountsreadmodel.ts +33 -0
  175. package/ts_web/classes.browserpresentation.ts +10 -5
  176. package/ts_web/classes.inboxfeed.ts +329 -0
  177. package/ts_web/classes.nativesessionstate.ts +9 -23
  178. package/ts_web/elements.accounts.ts +81 -0
  179. package/ts_web/elements.deployments.ts +66 -2
  180. package/ts_web/elements.harnesscontrollerapp.ts +107 -37
  181. package/ts_web/elements.inbox.ts +808 -0
  182. package/ts_web/functions.inbox.ts +95 -0
  183. package/ts_web/functions.sessioncards.ts +40 -0
  184. package/ts_web/plugins.ts +2 -0
@@ -1286,7 +1286,11 @@ export const createBoundedOpenCodeSelectedMessageSlice = (
1286
1286
  throw new Error('Selected OpenCode message shells exceeded the aggregate output budget.');
1287
1287
  };
1288
1288
 
1289
- export const normalizeOpenCodePermissions = (value: unknown): IControllerPermission[] => {
1289
+ /** A pending request as OpenCode lists it, which carries no time: the adapter adds when it entered (`createdAt`). */
1290
+ export type TOpenCodePendingPermission = Omit<IControllerPermission, 'createdAt'>;
1291
+ export type TOpenCodePendingQuestion = Omit<IControllerQuestion, 'createdAt'>;
1292
+
1293
+ export const normalizeOpenCodePermissions = (value: unknown): TOpenCodePendingPermission[] => {
1290
1294
  if (!Array.isArray(value) || value.length > maxCollectionEntries) {
1291
1295
  throw new Error('OpenCode returned an invalid permission list.');
1292
1296
  }
@@ -1337,7 +1341,7 @@ export const normalizeOpenCodePermissions = (value: unknown): IControllerPermiss
1337
1341
  return result;
1338
1342
  };
1339
1343
 
1340
- export const normalizeOpenCodeQuestions = (value: unknown): IControllerQuestion[] => {
1344
+ export const normalizeOpenCodeQuestions = (value: unknown): TOpenCodePendingQuestion[] => {
1341
1345
  if (!Array.isArray(value) || value.length > maxCollectionEntries) {
1342
1346
  throw new Error('OpenCode returned an invalid question list.');
1343
1347
  }
@@ -1626,6 +1630,20 @@ const openCodeTurnRefusalText = (errorArg: unknown): string | undefined => {
1626
1630
  return Buffer.byteLength(text, 'utf8') <= maxTurnRefusalBytes ? text : `${truncateUtf8(text, maxTurnRefusalBytes)}…`;
1627
1631
  };
1628
1632
 
1633
+ /** At most this many pending requests keep the time they entered. */
1634
+ const maxPendingSinceEntries = 4096;
1635
+
1636
+ /** The permission or question an `asked` event announces: the time it entered OpenCode's pending requests is now. */
1637
+ export const openCodeAskedRequest = (valueArg: unknown): { directory: string; kind: 'permission' | 'question'; id: string } | undefined => {
1638
+ if (!isRecord(valueArg) || typeof valueArg.directory !== 'string' || !isRecord(valueArg.payload)) return undefined;
1639
+ const { type, properties } = valueArg.payload;
1640
+ const kind = type === 'permission.asked' || type === 'permission.v2.asked' ? 'permission'
1641
+ : type === 'question.asked' || type === 'question.v2.asked' ? 'question' : undefined;
1642
+ if (!kind || !isRecord(properties) || typeof properties.id !== 'string' || properties.id.length === 0
1643
+ || Buffer.byteLength(properties.id, 'utf8') > maxIdentifierBytes) return undefined;
1644
+ return { directory: valueArg.directory, kind, id: properties.id };
1645
+ };
1646
+
1629
1647
  const normalizeEvent = (
1630
1648
  value: unknown,
1631
1649
  ): TNormalizedOpenCodeEvent | undefined => {
@@ -1863,6 +1881,11 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
1863
1881
  private eventTask?: Promise<void>;
1864
1882
  private readonly runtimeRequestAbortController = new AbortController();
1865
1883
  private readonly temporarySessionIds = new Set<string>();
1884
+ /**
1885
+ * When each pending permission and question entered OpenCode's pending requests, as this adapter first heard of it
1886
+ * (its `asked` event, or the first list that held it): OpenCode's requests carry no time of their own.
1887
+ */
1888
+ private readonly pendingSince = new Map<string, { at: number; directory: string }>();
1866
1889
  /** The message AGL last sent each session, by session ID: a refusal that follows is that message's. */
1867
1890
  private readonly lastSentMessageIds = new Map<string, string>();
1868
1891
  /** Why OpenCode refused a message AGL sent, by session ID and message ID (`openCodeTurnRefusalText`). */
@@ -3192,6 +3215,32 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
3192
3215
  }
3193
3216
  }
3194
3217
 
3218
+ /** Records that the request `idArg` of `kindArg` entered OpenCode's pending requests now, unless it was seen before. */
3219
+ private notePendingRequest(directoryArg: string, kindArg: 'permission' | 'question', idArg: string): number {
3220
+ const key = `${kindArg}:${idArg}`;
3221
+ const seen = this.pendingSince.get(key);
3222
+ if (seen) return seen.at;
3223
+ const at = Date.now();
3224
+ rememberNewest(this.pendingSince, key, { at, directory: directoryArg }, maxPendingSinceEntries);
3225
+ return at;
3226
+ }
3227
+
3228
+ /**
3229
+ * The directory's whole pending list of `kindArg` with the time each request entered it. The requests of the
3230
+ * directory that the list no longer holds are forgotten.
3231
+ */
3232
+ private withPendingSince<TRequest extends { id: IControllerRuntimeId }>(
3233
+ directoryArg: string,
3234
+ kindArg: 'permission' | 'question',
3235
+ requestsArg: TRequest[],
3236
+ ): Array<TRequest & { createdAt: number }> {
3237
+ const listed = new Set(requestsArg.map((requestArg) => `${kindArg}:${requestArg.id.nativeId}`));
3238
+ for (const [key, entry] of this.pendingSince) {
3239
+ if (entry.directory === directoryArg && key.startsWith(`${kindArg}:`) && !listed.has(key)) this.pendingSince.delete(key);
3240
+ }
3241
+ return requestsArg.map((requestArg) => ({ ...requestArg, createdAt: this.notePendingRequest(directoryArg, kindArg, requestArg.id.nativeId) }));
3242
+ }
3243
+
3195
3244
  public async listPermissions(
3196
3245
  directoryArg: string,
3197
3246
  sessionId?: string,
@@ -3208,7 +3257,7 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
3208
3257
  { signal: requestSignal }
3209
3258
  )
3210
3259
  );
3211
- const permissions = normalizeOpenCodePermissions(response);
3260
+ const permissions = this.withPendingSince(directory, 'permission', normalizeOpenCodePermissions(response));
3212
3261
  return validatedSessionId
3213
3262
  ? permissions.filter((permission) => permission.sessionId.nativeId === validatedSessionId)
3214
3263
  : permissions;
@@ -3230,7 +3279,7 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
3230
3279
  { signal: requestSignal }
3231
3280
  )
3232
3281
  );
3233
- const questions = normalizeOpenCodeQuestions(response);
3282
+ const questions = this.withPendingSince(directory, 'question', normalizeOpenCodeQuestions(response));
3234
3283
  return validatedSessionId
3235
3284
  ? questions.filter((question) => question.sessionId.nativeId === validatedSessionId)
3236
3285
  : questions;
@@ -4356,6 +4405,8 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
4356
4405
  }
4357
4406
  }
4358
4407
 
4408
+ const asked = openCodeAskedRequest(event);
4409
+ if (asked) this.notePendingRequest(asked.directory, asked.kind, asked.id);
4359
4410
  const normalized = normalizeEvent(event);
4360
4411
  if (!normalized) continue;
4361
4412
  if ('toolStreamGap' in normalized) {
@@ -0,0 +1,56 @@
1
+ import * as plugins from './plugins.js';
2
+
3
+ /**
4
+ * One published change of a `PublishedSet`: the values that are new or changed and the ids that left, or `reset` when
5
+ * more changed than a delta carries, after which a client lists the set again.
6
+ */
7
+ export type TPublishedSetDelta<TValue> = { epoch: string; revision: number } & (
8
+ | { upserts: TValue[]; removed: string[] }
9
+ | { reset: true }
10
+ );
11
+
12
+ /**
13
+ * What a read model last published, by id, in its order, and the deltas between two publications: the one diff the
14
+ * session feed and the Inbox publish their changes with. `epoch` names this process's set, `revision` counts its
15
+ * publications; a client applies a delta only on its epoch at the next revision.
16
+ */
17
+ export class PublishedSet<TValue extends { id: string }> {
18
+ public readonly epoch = plugins.crypto.randomUUID();
19
+ private revisionValue = 0;
20
+ private entries = new Map<string, { value: TValue; json: string }>();
21
+
22
+ /** A change of more than `deltaLimitArg` values publishes a reset. */
23
+ constructor(private readonly deltaLimitArg: number) {}
24
+
25
+ public get revision(): number {
26
+ return this.revisionValue;
27
+ }
28
+
29
+ /** The published values, in the order they were published. */
30
+ public values(): TValue[] {
31
+ return [...this.entries.values()].map((entryArg) => entryArg.value);
32
+ }
33
+
34
+ public get(idArg: string): TValue | undefined {
35
+ return this.entries.get(idArg)?.value;
36
+ }
37
+
38
+ /**
39
+ * Publishes `valuesArg` in their order and answers the delta from the previous publication, or `undefined` when no
40
+ * value changed, came or left and `changedArg` (a change beside the values, such as a count) is not set. A read
41
+ * model whose order follows from its values' fields never reorders without a changed value.
42
+ */
43
+ public publish(valuesArg: readonly TValue[], changedArg = false): TPublishedSetDelta<TValue> | undefined {
44
+ const next = new Map(valuesArg.map((valueArg) => [valueArg.id, { value: valueArg, json: JSON.stringify(valueArg) }]));
45
+ const upserts: TValue[] = [];
46
+ const removed: string[] = [];
47
+ for (const [id, entry] of next) if (this.entries.get(id)?.json !== entry.json) upserts.push(entry.value);
48
+ for (const id of this.entries.keys()) if (!next.has(id)) removed.push(id);
49
+ // Insertion order is the order `values()` returns.
50
+ this.entries = next;
51
+ if (upserts.length === 0 && removed.length === 0 && !changedArg) return undefined;
52
+ this.revisionValue += 1;
53
+ const base = { epoch: this.epoch, revision: this.revisionValue };
54
+ return upserts.length + removed.length > this.deltaLimitArg ? { ...base, reset: true } : { ...base, upserts, removed };
55
+ }
56
+ }
@@ -1,6 +1,7 @@
1
1
  import * as plugins from './plugins.js';
2
2
  import { resolveControllerTerminalAgentTranscript } from './functions.terminalagents.js';
3
3
  import { codexQualifiedIdentity } from './functions.codexidentity.js';
4
+ import { PublishedSet } from './classes.publishedset.js';
4
5
  import { fleetClaudeNativeWait, type IFleetNativeAgent, type IFleetNativeThread } from './fleet/interfaces.workers.js';
5
6
  import {
6
7
  controllerSessionFeedExcerpt,
@@ -218,9 +219,7 @@ interface IRowDraft {
218
219
  */
219
220
  export class SessionFeed {
220
221
  private readonly abort = new AbortController();
221
- private readonly epoch = plugins.crypto.randomUUID();
222
- private revision = 0;
223
- private published = new Map<string, { row: IControllerSessionFeedRow; json: string }>();
222
+ private readonly published = new PublishedSet<IControllerSessionFeedRow>(controllerSessionFeedLimits.deltaRows);
224
223
  private readonly options: Required<Omit<ISessionFeedOptions, 'maxAgeMs'>> & { maxAgeMs: Record<TSessionFeedSource, number> };
225
224
 
226
225
  private conversations: ISessionFeedConversation[] = [];
@@ -295,19 +294,24 @@ export class SessionFeed {
295
294
  public async list(): Promise<IReq_ControllerSessionFeedList['response']> {
296
295
  this.abort.signal.throwIfAborted();
297
296
  await this.flush(true);
298
- return { epoch: this.epoch, revision: this.revision, rows: [...this.published.values()].map((entry) => entry.row) };
297
+ return { epoch: this.published.epoch, revision: this.published.revision, rows: this.published.values() };
298
+ }
299
+
300
+ /** The rows as the feed published them last, newest first, without reading anything. */
301
+ public publishedRows(): IControllerSessionFeedRow[] {
302
+ return this.published.values();
299
303
  }
300
304
 
301
305
  /** A row as the feed published it last, without reading anything: what events about the session may name. */
302
306
  public publishedRow(rowIdArg: string): IControllerSessionFeedRow | undefined {
303
- return this.published.get(rowIdArg)?.row;
307
+ return this.published.get(rowIdArg);
304
308
  }
305
309
 
306
310
  /** A row after reading every stale source, as `list()` reads; undefined while the feed does not list it. */
307
311
  public async find(rowIdArg: string): Promise<IControllerSessionFeedRow | undefined> {
308
312
  this.abort.signal.throwIfAborted();
309
313
  await this.flush(true);
310
- return this.published.get(rowIdArg)?.row;
314
+ return this.published.get(rowIdArg);
311
315
  }
312
316
 
313
317
  /**
@@ -321,7 +325,7 @@ export class SessionFeed {
321
325
  const run = this.acknowledging.catch(() => undefined).then(async () => {
322
326
  const acknowledged = await this.readAcknowledgements();
323
327
  if (acknowledged.get(rowIdArg) === updatedAtArg) return;
324
- const row = this.published.get(rowIdArg)?.row;
328
+ const row = this.published.get(rowIdArg);
325
329
  if (!row) throw new SessionFeedAcknowledgementError('sessionfeed_row_not_found', 'The session feed lists no such row; list the feed again.');
326
330
  if (row.state !== 'failed') throw new SessionFeedAcknowledgementError('sessionfeed_row_not_failed', 'Only a failed row can be acknowledged.');
327
331
  if (row.updatedAt !== updatedAtArg) {
@@ -371,6 +375,10 @@ export class SessionFeed {
371
375
  }
372
376
  return;
373
377
  }
378
+ // A permission, question or MCP form a harness holds came or went: the conversation may need input, or no longer.
379
+ case 'permissions.changed':
380
+ this.markStale('conversations', 'projects');
381
+ return;
374
382
  case 'fleet.workers.changed':
375
383
  this.markStale('fleet');
376
384
  return;
@@ -732,19 +740,8 @@ export class SessionFeed {
732
740
  }
733
741
 
734
742
  private publish(rowsArg: IControllerSessionFeedRow[]): void {
735
- const next = new Map(rowsArg.map((row) => [row.id, { row, json: JSON.stringify(row) }]));
736
- const upserts: IControllerSessionFeedRow[] = [];
737
- const removed: string[] = [];
738
- for (const [id, entry] of next) if (this.published.get(id)?.json !== entry.json) upserts.push(entry.row);
739
- for (const id of this.published.keys()) if (!next.has(id)) removed.push(id);
740
- // Insertion order is the list order `list()` returns.
741
- this.published = next;
742
- if (upserts.length === 0 && removed.length === 0) return;
743
- this.revision += 1;
744
- const base = { epoch: this.epoch, revision: this.revision };
745
- this.sources.publish(upserts.length + removed.length > controllerSessionFeedLimits.deltaRows
746
- ? { ...base, reset: true }
747
- : { ...base, upserts, removed });
743
+ const delta = this.published.publish(rowsArg);
744
+ if (delta) this.sources.publish(delta);
748
745
  }
749
746
 
750
747
  private report(sourceArg: string, errorArg: unknown): void {
@@ -521,6 +521,12 @@ export class SystemMetricsSampler {
521
521
  }
522
522
  }
523
523
 
524
+ /**
525
+ * Retires the sampler and drains its source. The source's own stop lets every probe in flight finish
526
+ * (smartsystem ≥ 4.0.2: up to its request deadline) and rejects naming the probe workers that are hung or
527
+ * failed; that rejection reaches the caller unchanged. A rejected stop is not kept: the next call asks the
528
+ * source again, which no longer names a hung worker that has exited since.
529
+ */
524
530
  public stop(): Promise<void> {
525
531
  if (this.stopPromise) return this.stopPromise;
526
532
  this.stopped = true;
@@ -528,12 +534,17 @@ export class SystemMetricsSampler {
528
534
  this.recordingTimer = undefined;
529
535
  this.recorder = undefined;
530
536
  this.cachedSample = undefined;
531
- this.stopPromise = (async () => {
537
+ const stopping = (async () => {
532
538
  await this.recordingPromise?.catch(() => undefined);
533
539
  await this.inFlightSample?.catch(() => undefined);
534
540
  await this.source.stop?.();
535
541
  })();
536
- return this.stopPromise;
542
+ this.stopPromise = stopping;
543
+ // Every caller receives `stopping` itself and owns its rejection; this handler only forgets it.
544
+ void stopping.catch(() => {
545
+ if (this.stopPromise === stopping) this.stopPromise = undefined;
546
+ });
547
+ return stopping;
537
548
  }
538
549
 
539
550
  private async readFreshSample(): Promise<IControllerSystemMetrics> {
@@ -3,7 +3,7 @@ import {
3
3
  isTicketAutoLabel, ticketColumns, ticketDoneColumns, ticketErrorMessages, type ITicket, type ITicketActor, type ITicketActivity, type ITicketBoard,
4
4
  type ITicketChanges, type ITicketCreate, type ITicketFilters, type ITicketMove, type ITicketPerson, type ITicketQuestion,
5
5
  type TTicketLink, type TTicketOperation, type TTicketRequest, type TTicketResponse,
6
- type TTicketFleetEvent, type ITicketFleetEventResult, type ITicketComment, type TTicketData, type ITicketOpenQuestion,
6
+ type TTicketFleetEvent, type ITicketFleetEventResult, type ITicketComment, type TTicketData, type ITicketOpenQuestion, type TTicketAutoLabel,
7
7
  type ITicketDetail, type ITicketGet, type ITicketAsk, type ITicketMaintenanceWindow, ticketHistoryPage,
8
8
  } from '../ts_interfaces/tickets.js';
9
9
  import {
@@ -57,8 +57,16 @@ interface ITicketTrack {
57
57
  refusal?: ITicketChange;
58
58
  }
59
59
 
60
+ /**
61
+ * Every code a `TicketError` carries: a refusal `ticketErrorMessages` explains, a concurrent change the transaction
62
+ * lost (`concurrent_change`, nothing written), a transaction whose commit outcome is unknown (`outcome_unknown`), a
63
+ * fleet event key that names another request, and an owner capability the controller could not verify.
64
+ */
65
+ export type TTicketErrorCode = keyof typeof ticketErrorMessages | 'concurrent_change' | 'outcome_unknown'
66
+ | 'ticket_fleet_event_conflict' | 'unauthorized';
67
+
60
68
  export class TicketError extends Error {
61
- constructor(public readonly code: string, messageArg: string, public readonly currentRevision?: number) {
69
+ constructor(public readonly code: TTicketErrorCode, messageArg: string, public readonly currentRevision?: number) {
62
70
  super(messageArg);
63
71
  this.name = 'TicketError';
64
72
  }
@@ -69,6 +77,55 @@ export const ticketAssignedTo = (ticketArg: TTicketData, actorArg: ITicketActor)
69
77
  ? actorArg.sessionId !== undefined && (ticketArg.assignee?.sessionId ?? ticketArg.assignee?.id) === actorArg.sessionId
70
78
  : ticketArg.assignee?.id === actorArg.id
71
79
  );
80
+
81
+ /**
82
+ * The filters of a listing (`list`, `board`, `search`) as one predicate over the tickets `visible` shows (AutoLabels
83
+ * computed): mine (assigned to `actorArg`), a project, a column, a hand label or an AutoLabel, and text in the key,
84
+ * title, description or source words, ignoring case.
85
+ */
86
+ export const ticketFilter = (filtersArg: ITicketFilters, actorArg: ITicketActor | undefined): (ticketArg: ITicket) => boolean => {
87
+ const text = filtersArg.text?.toLocaleLowerCase();
88
+ return (ticketArg) => (
89
+ (!filtersArg.mine || (actorArg !== undefined && ticketAssignedTo(ticketArg, actorArg)))
90
+ && (!filtersArg.project || ticketArg.project === filtersArg.project)
91
+ && (!filtersArg.status || ticketArg.columnId === filtersArg.status)
92
+ && (!filtersArg.label || ticketArg.labels.includes(filtersArg.label) || (ticketArg.autoLabels ?? []).some((labelArg) => labelArg === filtersArg.label))
93
+ && (!text || [ticketArg.key, ticketArg.title, ticketArg.description, ticketArg.source.text].some((valueArg) => valueArg.toLocaleLowerCase().includes(text)))
94
+ );
95
+ };
96
+
97
+ /**
98
+ * Whose tickets a board shows, as the browser's board (dees-kanban) narrows by assignee: a person by `id` (the owner by
99
+ * the owner's principal id, as the board's "Assigned to me" does), nobody, or the session a person's `sessionId` names.
100
+ */
101
+ export type TTicketAssigneeFilter = { kind: 'person'; id: string } | { kind: 'unassigned' } | { kind: 'session'; sessionId: string };
102
+
103
+ /** What a board narrows by beyond a listing's own filters (`ITicketFilters`, `ticketFilter`). */
104
+ export interface ITicketBoardNarrowing {
105
+ /** An epic's key: its own tasks, the tickets whose parent it is, as the board's epic filter matches them. */
106
+ epic?: string;
107
+ assignee?: TTicketAssigneeFilter;
108
+ /** An AutoLabel the ticket carries; unlike the listing's `label`, never a hand label of that name. */
109
+ autoLabel?: TTicketAutoLabel;
110
+ }
111
+
112
+ /**
113
+ * Whether a ticket stays on a board narrowed by an epic, an assignee and an AutoLabel, beside `ticketFilter`, as the
114
+ * browser's board (dees-kanban `visibleTasks`) narrows: the epic filter matches `ticket.parentId === epic`, the epic's
115
+ * direct children and never their subtasks; the AutoLabel filter the ticket's AutoLabels alone.
116
+ */
117
+ export const ticketBoardNarrows = (ticketArg: ITicket, narrowingArg: ITicketBoardNarrowing): boolean => {
118
+ if (narrowingArg.epic !== undefined && ticketArg.parentId !== narrowingArg.epic) return false;
119
+ if (narrowingArg.autoLabel !== undefined && !(ticketArg.autoLabels ?? []).includes(narrowingArg.autoLabel)) return false;
120
+ const filter = narrowingArg.assignee;
121
+ if (filter === undefined) return true;
122
+ switch (filter.kind) {
123
+ case 'person': return ticketArg.assignee?.id === filter.id;
124
+ case 'unassigned': return ticketArg.assignee === undefined;
125
+ case 'session': return ticketArg.assignee?.sessionId === filter.sessionId;
126
+ }
127
+ };
128
+
72
129
  export const ticketCanEdit = (ticketArg: TTicketData, actorArg: ITicketActor): boolean => (
73
130
  actorArg.role !== 'worker' || (ticketAssignedTo(ticketArg, actorArg) && workerColumns.has(ticketArg.columnId))
74
131
  );
@@ -332,6 +389,15 @@ export class TicketStore {
332
389
  * out: a done ticket asks nobody.
333
390
  */
334
391
  public async openQuestions(signalArg?: AbortSignal): Promise<ITicketOpenQuestion[]> {
392
+ return (await this.openQuestionTickets(signalArg))
393
+ .map(({ ticket, question }) => ({ ticketKey: ticket.key, project: ticket.project, question }));
394
+ }
395
+
396
+ /**
397
+ * Every open question with its whole ticket, oldest first, as `openQuestions` reads them: a question whose ticket is
398
+ * gone or done is left out. The Inbox reads a deploy plan's and a maintenance window's question from its ticket.
399
+ */
400
+ public async openQuestionTickets(signalArg?: AbortSignal): Promise<Array<{ ticket: TTicketData; question: ITicketQuestion }>> {
335
401
  const questions: ITicketQuestion[] = [];
336
402
  let after: string | undefined;
337
403
  while (true) {
@@ -352,7 +418,7 @@ export class TicketStore {
352
418
  }
353
419
  return structuredClone(questions.flatMap((questionArg) => {
354
420
  const ticket = tickets.get(questionArg.ticketId);
355
- return ticket && !ticketDoneColumns.includes(ticket.columnId) ? [{ ticketKey: ticket.key, project: ticket.project, question: questionArg }] : [];
421
+ return ticket && !ticketDoneColumns.includes(ticket.columnId) ? [{ ticket, question: questionArg }] : [];
356
422
  })).sort((leftArg, rightArg) => leftArg.question.createdAt.localeCompare(rightArg.question.createdAt));
357
423
  }
358
424
 
@@ -738,17 +804,12 @@ export class TicketStore {
738
804
  const filters: ITicketFilters = methodArg === 'search'
739
805
  ? { text: (requestArg as TTicketRequest<'search'>).query, label: (requestArg as TTicketRequest<'search'>).label }
740
806
  : requestArg as ITicketFilters;
741
- const text = filters.text?.toLocaleLowerCase();
742
807
  const all = await this.allTickets(sessionArg);
743
808
  await this.countOpenQuestions(trackArg, sessionArg);
744
- const tickets = all.map((recordArg) => this.visible(recordArg.ticket, actorArg, trackArg)).filter((ticketArg) => (
745
- (!filters.mine || (actorArg !== undefined && ticketAssignedTo(ticketArg, actorArg)))
746
- && (!filters.project || ticketArg.project === filters.project)
747
- && (!filters.status || ticketArg.columnId === filters.status)
748
- && (!filters.label || ticketArg.labels.includes(filters.label) || ticketArg.autoLabels!.some((labelArg) => labelArg === filters.label))
749
- && (!text || [ticketArg.key, ticketArg.title, ticketArg.description, ticketArg.source.text].some((valueArg) => valueArg.toLocaleLowerCase().includes(text)))
750
- )).sort((leftArg, rightArg) => ticketColumns.indexOf(leftArg.columnId) - ticketColumns.indexOf(rightArg.columnId)
751
- || leftArg.order - rightArg.order);
809
+ const matches = ticketFilter(filters, actorArg);
810
+ const tickets = all.map((recordArg) => this.visible(recordArg.ticket, actorArg, trackArg)).filter(matches)
811
+ .sort((leftArg, rightArg) => ticketColumns.indexOf(leftArg.columnId) - ticketColumns.indexOf(rightArg.columnId)
812
+ || leftArg.order - rightArg.order);
752
813
  if (methodArg !== 'board') return { tickets };
753
814
  if (!actorArg) throw new TicketError('ticket_identity_required', ticketErrorMessages.ticket_identity_required);
754
815
  const { role: _role, ...viewer } = actorArg;
@@ -45,6 +45,19 @@ export type TDirectReportChannel =
45
45
  | { kind: 'fleet-worker'; report: IDirectReport; workerName: string }
46
46
  | { kind: 'session'; report: IDirectReport; nativeId: string; cwd: string };
47
47
 
48
+ /**
49
+ * Whether AGL reaches the report to read or message it: through the fleet worker it is, or the Codex thread it is. A
50
+ * Claude Code session the fleet does not run it reaches only as a second writer, so never.
51
+ */
52
+ export const directReportReachable = (report: IDirectReport): boolean => report.session.kind === 'fleet-worker' || report.session.harness === 'codex';
53
+
54
+ /** The native session a report is (`IDirectReport.sessionId`, `harness:nativeId`) as a runtime id. */
55
+ export const directReportRuntimeId = (report: IDirectReport): { harnessId: TFleetWorkerHarness; nativeId: string } => {
56
+ const separator = report.sessionId.indexOf(':'), harnessId = report.sessionId.slice(0, separator), nativeId = report.sessionId.slice(separator + 1);
57
+ if (separator < 0 || (harnessId !== 'claude' && harnessId !== 'codex') || !nativeId) throw new Error(`Direct report ${report.name} names no Claude Code or Codex session.`);
58
+ return { harnessId, nativeId };
59
+ };
60
+
48
61
  /** The newest line of `text` that starts with `result:`, the line a session ends a turn on. */
49
62
  export const directReportResultLine = (text: string): string | undefined => {
50
63
  const line = text.split(/\r?\n/u).findLast((lineArg) => /^\s*result:/iu.test(lineArg));
@@ -254,7 +267,7 @@ export class DirectReports implements IFleetSessionBindings {
254
267
  if (!report || report.state !== 'active') throw new Error(`Direct report ${name} is not an active direct report.`);
255
268
  const session = report.session;
256
269
  if (session.kind === 'fleet-worker') return { kind: 'fleet-worker', report, workerName: session.workerName };
257
- if (session.harness === 'claude') {
270
+ if (!directReportReachable(report)) {
258
271
  throw new Error(`Direct report ${name} is a Claude Code session the fleet does not run, so it cannot be read or messaged: AGL reaches a Claude Code session only by resuming it in a process of its own, a second writer beside the one that runs it. Adopt the session with a relaunch (directreport_adopt) once it has settled.`);
259
272
  }
260
273
  const thread = (await this.host.codexThreads()).find((item) => item.sessionId === session.nativeId);
@@ -263,15 +276,21 @@ export class DirectReports implements IFleetSessionBindings {
263
276
  }
264
277
 
265
278
  /**
266
- * The owner's workers an active direct report runs: those whose `reportsTo` names it. A worker that is itself an
267
- * active report's session reports to the owner.
279
+ * The owner's workers each active direct report runs, by the report's name: those whose `reportsTo` names it. A
280
+ * worker that is itself an active report's session reports to the owner, so to no report.
268
281
  */
269
- public async reportWorkers(owner: string): Promise<Set<string>> {
282
+ public async reportWorkers(owner: string): Promise<Map<string, IControllerFleetWorkerView[]>> {
270
283
  const active = (await this.store.list(owner)).filter((report) => report.state === 'active');
271
- if (!active.length) return new Set();
284
+ const groups = new Map<string, IControllerFleetWorkerView[]>();
285
+ if (!active.length) return groups;
272
286
  const names = new Set(active.map((report) => report.name));
273
287
  const reporting = new Set(active.flatMap((report) => report.session.kind === 'fleet-worker' ? [report.session.workerName] : []));
274
- return new Set((await this.host.workers(owner)).flatMap(({ worker }) => worker.reportsTo && names.has(worker.reportsTo) && !reporting.has(worker.name) ? [worker.name] : []));
288
+ for (const view of await this.host.workers(owner)) {
289
+ const superior = view.worker.reportsTo;
290
+ if (!superior || !names.has(superior) || reporting.has(view.worker.name)) continue;
291
+ groups.set(superior, [...groups.get(superior) ?? [], view]);
292
+ }
293
+ return groups;
275
294
  }
276
295
 
277
296
  /** The active report whose session is `sessionId` (`harness:nativeId`), if any. */
@@ -35,8 +35,11 @@ export interface IDriverServiceHost {
35
35
  requesterArg: string,
36
36
  signalArg: AbortSignal,
37
37
  ): Promise<void>;
38
- /** Text of the newest assistant message, for the `needs input:` line. */
39
- latestAssistantText(projectIdArg: string, nativeIdArg: string, signalArg?: AbortSignal): Promise<string | undefined>;
38
+ /**
39
+ * The newest assistant transcript entry that holds text, for the `needs input:` line: its id (stable for the entry),
40
+ * its text and when it was written.
41
+ */
42
+ latestAssistantMessage(projectIdArg: string, nativeIdArg: string, signalArg?: AbortSignal): Promise<IDriverAssistantMessage | undefined>;
40
43
  publish(statusArg: IControllerDriverStatus): void;
41
44
  /**
42
45
  * The driver session was seen for the first time in this process: fleet events start flowing into
@@ -53,6 +56,23 @@ export interface IDriverServiceHost {
53
56
  keepCacheWarm(projectIdArg: string, nativeIdArg: string, durationMsArg: number): Promise<void>;
54
57
  }
55
58
 
59
+ /** An assistant transcript entry of the driver session. */
60
+ export interface IDriverAssistantMessage {
61
+ id: string;
62
+ text: string;
63
+ /** Unix milliseconds. */
64
+ createdAt: number;
65
+ }
66
+
67
+ /** The driver's last turn ended on a `needs input:` line: the line, the entry it ends, and when it was written. */
68
+ export interface IDriverNeedsInput {
69
+ projectId: string;
70
+ nativeId: string;
71
+ line: string;
72
+ messageId: string;
73
+ at: number;
74
+ }
75
+
56
76
  export interface IDriverServiceOptions {
57
77
  store?: IDriverStore;
58
78
  refreshDelayMs?: number;
@@ -63,7 +83,17 @@ export interface IDriverServiceOptions {
63
83
  /** How long after the newest board event the driver keeps its prompt cache warm. */
64
84
  export const driverCacheWarmMs = 60 * 60 * 1000;
65
85
 
66
- const needsInputLine = /^needs input:/imu;
86
+ /**
87
+ * Whether a controller event carries streamed text, reasoning or tool content: it never changes the driver's status,
88
+ * and no device hears it as a driver change.
89
+ */
90
+ export const isStreamedContentEvent = (eventArg: IControllerEvent): boolean => Boolean(
91
+ eventArg.textUpdate || eventArg.reasoningUpdate || eventArg.toolExecution,
92
+ );
93
+
94
+ const needsInputLine = /^needs input:.*$/imu;
95
+ /** The `needs input:` line of an assistant text, trimmed; none when the text holds none. */
96
+ export const driverNeedsInputLine = (textArg: string): string | undefined => needsInputLine.exec(textArg)?.[0].trim();
67
97
  const sameStatus = (leftArg: IControllerDriverStatus, rightArg: IControllerDriverStatus): boolean => (
68
98
  leftArg.activity === rightArg.activity
69
99
  && leftArg.unreadCount === rightArg.unreadCount
@@ -92,7 +122,8 @@ export class DriverService {
92
122
  /** Whether this process created the driver session, and whether the host heard it exists. */
93
123
  private createdInProcess = false;
94
124
  private availableAnnounced = false;
95
- private assistantNeedsInput = false;
125
+ /** The `needs input:` line of the newest assistant text, while it holds one. */
126
+ private needsInputTurn?: Omit<IDriverNeedsInput, 'projectId' | 'nativeId'>;
96
127
  private closed = false;
97
128
  private readonly now: () => number;
98
129
  /** When the board last changed, on `now`'s clock. */
@@ -147,6 +178,22 @@ export class DriverService {
147
178
  return this.refresh(signalArg);
148
179
  }
149
180
 
181
+ /** The status as the last refresh found it, without reading anything. */
182
+ public current(): IControllerDriverStatus {
183
+ return structuredClone(this.status);
184
+ }
185
+
186
+ /**
187
+ * The driver's `needs input:` turn, as the last status refresh found it: only while its last turn ended on the line
188
+ * and nothing else holds it (no prompt of its own, no turn running). Its own prompts are session prompts.
189
+ */
190
+ public needsInput(): IDriverNeedsInput | undefined {
191
+ const { activity, projectId, sessionId, session } = this.status;
192
+ const turn = this.needsInputTurn;
193
+ if (activity !== 'needs_input' || session?.attention || !turn || projectId === undefined || sessionId === undefined) return undefined;
194
+ return { projectId, nativeId: sessionId.nativeId, ...turn };
195
+ }
196
+
150
197
  public ensure(
151
198
  projectIdArg: string | undefined,
152
199
  requesterArg: string,
@@ -170,14 +217,27 @@ export class DriverService {
170
217
  * text, reasoning and tool deltas never change it, so they are skipped.
171
218
  */
172
219
  public observe(eventArg: IControllerEvent): void {
173
- const record = this.record;
174
- if (!record || this.closed) return;
220
+ if (this.closed) return;
175
221
  if (eventArg.type !== 'session.changed' && eventArg.type !== 'sessions.changed' && eventArg.type !== 'permissions.changed') return;
176
- if (eventArg.textUpdate || eventArg.reasoningUpdate || eventArg.toolExecution) return;
177
- if (eventArg.projectId !== record.projectId) return;
178
- if (eventArg.sessionId !== undefined
179
- && (eventArg.sessionId.harnessId !== 'flex' || eventArg.sessionId.nativeId !== record.nativeId)) return;
180
- this.scheduleRefresh();
222
+ if (this.concerns(eventArg)) this.scheduleRefresh();
223
+ }
224
+
225
+ /**
226
+ * Whether the event is the driver session's own change of state, transcript or prompts (`session.changed`,
227
+ * `session.history.changed`, `permissions.changed` naming the session), never its streamed content: what a device
228
+ * hears as a driver change.
229
+ */
230
+ public isSessionChange(eventArg: IControllerEvent): boolean {
231
+ return (eventArg.type === 'session.changed' || eventArg.type === 'session.history.changed' || eventArg.type === 'permissions.changed')
232
+ && eventArg.sessionId !== undefined && this.concerns(eventArg);
233
+ }
234
+
235
+ /** An event of the driver's project about its session or the whole project, without streamed content. */
236
+ private concerns(eventArg: IControllerEvent): boolean {
237
+ const record = this.record;
238
+ if (!record || isStreamedContentEvent(eventArg) || eventArg.projectId !== record.projectId) return false;
239
+ return eventArg.sessionId === undefined
240
+ || (eventArg.sessionId.harnessId === 'flex' && eventArg.sessionId.nativeId === record.nativeId);
181
241
  }
182
242
 
183
243
  /**
@@ -360,10 +420,11 @@ export class DriverService {
360
420
  if (sessionArg.status === 'error') return 'error';
361
421
  const key = `${recordArg.nativeId}\0${sessionArg.updatedAt}`;
362
422
  if (this.assistantTextKey !== key) {
363
- const text = await this.host.latestAssistantText(recordArg.projectId, recordArg.nativeId, signalArg);
364
- this.assistantNeedsInput = text !== undefined && needsInputLine.test(text);
423
+ const message = await this.host.latestAssistantMessage(recordArg.projectId, recordArg.nativeId, signalArg);
424
+ const line = message === undefined ? undefined : driverNeedsInputLine(message.text);
425
+ this.needsInputTurn = message === undefined || line === undefined ? undefined : { line, messageId: message.id, at: message.createdAt };
365
426
  this.assistantTextKey = key;
366
427
  }
367
- return this.assistantNeedsInput ? 'needs_input' : 'idle';
428
+ return this.needsInputTurn ? 'needs_input' : 'idle';
368
429
  }
369
430
  }