agl 43.13.0 → 44.0.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 (99) hide show
  1. package/changelog.md +28 -0
  2. package/dist_serve/bundle.js +4473 -4235
  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_ts/00_commitinfo_data.js +2 -2
  7. package/dist_ts/aglapi/aglapisurface.document.js +37 -4
  8. package/dist_ts/classes.authstore.d.ts +60 -3
  9. package/dist_ts/classes.authstore.js +161 -13
  10. package/dist_ts/classes.controller.d.ts +63 -0
  11. package/dist_ts/classes.controller.js +502 -43
  12. package/dist_ts/classes.embeddeddb.js +7 -2
  13. package/dist_ts/classes.flexmodels.private.d.ts +39 -0
  14. package/dist_ts/classes.flexmodels.private.js +127 -1
  15. package/dist_ts/classes.flexprojectpreparation.d.ts +21 -0
  16. package/dist_ts/classes.flexprojectpreparation.js +69 -0
  17. package/dist_ts/classes.flexpromptqueue.d.ts +21 -1
  18. package/dist_ts/classes.flexpromptqueue.js +67 -7
  19. package/dist_ts/classes.flexrequestqueue.d.ts +11 -0
  20. package/dist_ts/classes.flexrequestqueue.js +40 -0
  21. package/dist_ts/classes.flexservice.d.ts +46 -14
  22. package/dist_ts/classes.flexservice.js +179 -55
  23. package/dist_ts/classes.flexstore.d.ts +68 -3
  24. package/dist_ts/classes.flexstore.js +277 -11
  25. package/dist_ts/classes.flexsubmissionmodels.d.ts +58 -0
  26. package/dist_ts/classes.flexsubmissionmodels.js +162 -0
  27. package/dist_ts/classes.flexsubmissionstore.d.ts +70 -0
  28. package/dist_ts/classes.flexsubmissionstore.js +323 -0
  29. package/dist_ts/classes.flexsupervisor.d.ts +10 -0
  30. package/dist_ts/classes.flexsupervisor.js +27 -1
  31. package/dist_ts/classes.harnessoperationmanager.d.ts +31 -0
  32. package/dist_ts/classes.harnessoperationmanager.js +69 -7
  33. package/dist_ts/classes.mcpclient.js +4 -3
  34. package/dist_ts/classes.mcpcontrollerhost.js +3 -2
  35. package/dist_ts/classes.pendingpromptstore.d.ts +11 -3
  36. package/dist_ts/classes.pendingpromptstore.js +66 -10
  37. package/dist_ts/classes.sessionidentityservice.d.ts +18 -1
  38. package/dist_ts/classes.sessionidentityservice.js +34 -4
  39. package/dist_ts/classes.ticketstore.d.ts +5 -3
  40. package/dist_ts/classes.ticketstore.js +7 -2
  41. package/dist_ts/classes.validation.d.ts +3 -0
  42. package/dist_ts/classes.validation.js +50 -1
  43. package/dist_ts/functions.deviceapi.js +7 -3
  44. package/dist_ts/interfaces.auth.d.ts +3 -1
  45. package/dist_ts/interfaces.auth.js +1 -1
  46. package/dist_ts/interfaces.flexipc.d.ts +29 -5
  47. package/dist_ts/interfaces.flexipc.js +13 -4
  48. package/dist_ts_authswitch/classes.authoritydatabase.d.ts +1 -0
  49. package/dist_ts_authswitch/classes.authoritydatabase.js +17 -5
  50. package/dist_ts_interfaces/flexadmission.d.ts +69 -0
  51. package/dist_ts_interfaces/flexadmission.js +2 -0
  52. package/dist_ts_interfaces/index.d.ts +1 -0
  53. package/dist_ts_interfaces/index.js +2 -1
  54. package/dist_ts_interfaces/interfaces.d.ts +10 -1
  55. package/dist_ts_interfaces/interfaces.js +2 -2
  56. package/dist_ts_interfaces/requests.d.ts +2 -1
  57. package/dist_ts_interfaces/requests.js +1 -1
  58. package/dist_ts_interfaces/tickets.d.ts +9 -1
  59. package/dist_ts_interfaces/tickets.js +11 -2
  60. package/dist_ts_migration/v10_flexharnessv3migration.js +4 -1
  61. package/docs/nosqldb11-migration.md +59 -0
  62. package/package.json +10 -9
  63. package/readme.md +5 -1
  64. package/ts/00_commitinfo_data.ts +1 -1
  65. package/ts/aglapi/aglapisurface.document.ts +36 -3
  66. package/ts/classes.authstore.ts +179 -11
  67. package/ts/classes.controller.ts +498 -40
  68. package/ts/classes.embeddeddb.ts +6 -1
  69. package/ts/classes.flexmodels.private.ts +109 -0
  70. package/ts/classes.flexprojectpreparation.ts +69 -0
  71. package/ts/classes.flexpromptqueue.ts +69 -6
  72. package/ts/classes.flexrequestqueue.ts +47 -0
  73. package/ts/classes.flexservice.ts +187 -51
  74. package/ts/classes.flexstore.ts +352 -10
  75. package/ts/classes.flexsubmissionmodels.ts +89 -0
  76. package/ts/classes.flexsubmissionstore.ts +312 -0
  77. package/ts/classes.flexsupervisor.ts +26 -0
  78. package/ts/classes.harnessoperationmanager.ts +79 -6
  79. package/ts/classes.mcpclient.ts +3 -2
  80. package/ts/classes.mcpcontrollerhost.ts +2 -1
  81. package/ts/classes.pendingpromptstore.ts +55 -6
  82. package/ts/classes.sessionidentityservice.ts +33 -2
  83. package/ts/classes.ticketstore.ts +11 -4
  84. package/ts/classes.validation.ts +42 -0
  85. package/ts/functions.deviceapi.ts +6 -2
  86. package/ts/interfaces.auth.ts +3 -1
  87. package/ts/interfaces.flexipc.ts +38 -4
  88. package/ts_authswitch/classes.authoritydatabase.ts +19 -5
  89. package/ts_interfaces/flexadmission.ts +52 -0
  90. package/ts_interfaces/index.ts +2 -0
  91. package/ts_interfaces/interfaces.ts +10 -1
  92. package/ts_interfaces/requests.ts +3 -0
  93. package/ts_interfaces/tickets.ts +12 -2
  94. package/ts_migration/v10_flexharnessv3migration.ts +3 -0
  95. package/ts_web/00_commitinfo_data.ts +1 -1
  96. package/ts_web/classes.browsersubmissions.ts +279 -0
  97. package/ts_web/classes.sessiondraftsync.ts +64 -1
  98. package/ts_web/elements.harnesscontrollerapp.ts +340 -5
  99. package/ts_web/functions.flexsubmissions.ts +88 -0
@@ -217,8 +217,13 @@ export class EmbeddedControllerDatabase {
217
217
  const errors: unknown[] = [];
218
218
  if (localDb) {
219
219
  try {
220
- await localDb.stop();
220
+ const result = await localDb.stop();
221
221
  if (this.localDb === localDb) this.localDb = undefined;
222
+ // NoSQLDB 11 resolves after a forced exit too. Releasing the child is not proof
223
+ // that it drained its writes, so a serving engine must acknowledge a clean stop.
224
+ if (!result.clean && this.connectionUri) {
225
+ throw new Error('Embedded database engine did not shut down cleanly.', { cause: result });
226
+ }
222
227
  } catch (errorArg) {
223
228
  errors.push(errorArg);
224
229
  }
@@ -105,6 +105,28 @@ export interface IFlexMigrationDocument {
105
105
  completedAt: string;
106
106
  }
107
107
 
108
+ /**
109
+ * The write witness of one Flex namespace (`flex_namespace_writes`): every Flex namespace write
110
+ * transaction increments `writeCount` in the same transaction; a write of a store whose provenance
111
+ * is activated for the key increments `knownWriteCount` too. Equal counts mean every write since
112
+ * the last qualification was known. Project management is outside the witness.
113
+ */
114
+ export interface IFlexNamespaceWritesDocument {
115
+ id: string;
116
+ controllerId: string;
117
+ storageKey: string;
118
+ writeCount: number;
119
+ knownWriteCount: number;
120
+ }
121
+
122
+ /** FlexHarness's session-local recovery proof of one namespace (`flex_scope_recovery`). */
123
+ export interface IFlexScopeRecoveryDocument {
124
+ id: string;
125
+ controllerId: string;
126
+ storageKey: string;
127
+ proof: plugins.flexharness.IFlexScopeRecoverySnapshot;
128
+ }
129
+
108
130
  export interface IFlexLegacyPublicCandidateManifest {
109
131
  candidateId: string;
110
132
  revision: number;
@@ -408,6 +430,34 @@ export function assertFlexMigrationDocument(
408
430
  ) throw new Error('Invalid Flex migration document.');
409
431
  }
410
432
 
433
+ export function assertFlexNamespaceWritesDocument(
434
+ valueArg: unknown,
435
+ ): asserts valueArg is IFlexNamespaceWritesDocument {
436
+ if (
437
+ !isFlexPlainObject(valueArg)
438
+ || !hasFlexExactKeys(valueArg, ['id', 'controllerId', 'storageKey', 'writeCount', 'knownWriteCount'])
439
+ || !isBoundedString(valueArg.id, 1024)
440
+ || !isBoundedString(valueArg.controllerId, 512)
441
+ || !isBoundedString(valueArg.storageKey, 512)
442
+ || !isNonNegativeInteger(valueArg.writeCount)
443
+ || !isNonNegativeInteger(valueArg.knownWriteCount)
444
+ || valueArg.knownWriteCount > valueArg.writeCount
445
+ ) throw new plugins.flexharness.FlexHarnessStoreFormatError('Invalid Flex namespace write witness.');
446
+ }
447
+
448
+ export function assertFlexScopeRecoveryDocument(
449
+ valueArg: unknown,
450
+ ): asserts valueArg is IFlexScopeRecoveryDocument {
451
+ if (
452
+ !isFlexPlainObject(valueArg)
453
+ || !hasFlexExactKeys(valueArg, ['id', 'controllerId', 'storageKey', 'proof'])
454
+ || !isBoundedString(valueArg.id, 1024)
455
+ || !isBoundedString(valueArg.controllerId, 512)
456
+ || !isBoundedString(valueArg.storageKey, 512)
457
+ ) throw new plugins.flexharness.FlexHarnessStoreFormatError('Invalid Flex scope recovery document.');
458
+ plugins.flexharness.assertFlexScopeRecoverySnapshot(valueArg.proof);
459
+ }
460
+
411
461
  export function assertFlexModelChoiceDocument(
412
462
  valueArg: unknown,
413
463
  ): asserts valueArg is IFlexModelChoiceDocument {
@@ -702,6 +752,51 @@ export class FlexMigrationModel extends plugins.nosqldb.SmartDataDbDoc<
702
752
  public completedAt!: string;
703
753
  }
704
754
 
755
+ @plugins.nosqldb.managed({ collectionName: 'flex_namespace_writes' })
756
+ @plugins.nosqldb.exactPersistence({ assertDocument: assertFlexNamespaceWritesDocument })
757
+ export class FlexNamespaceWritesModel extends plugins.nosqldb.SmartDataDbDoc<
758
+ FlexNamespaceWritesModel,
759
+ IFlexNamespaceWritesDocument
760
+ > {
761
+ declare static exact: plugins.nosqldb.TExact<FlexNamespaceWritesModel>;
762
+
763
+ @plugins.nosqldb.unI()
764
+ public id!: string;
765
+
766
+ @plugins.nosqldb.index()
767
+ public controllerId!: string;
768
+
769
+ @plugins.nosqldb.index()
770
+ public storageKey!: string;
771
+
772
+ @plugins.nosqldb.svDb()
773
+ public writeCount!: number;
774
+
775
+ @plugins.nosqldb.svDb()
776
+ public knownWriteCount!: number;
777
+ }
778
+
779
+ @plugins.nosqldb.managed({ collectionName: 'flex_scope_recovery' })
780
+ @plugins.nosqldb.exactPersistence({ assertDocument: assertFlexScopeRecoveryDocument })
781
+ export class FlexScopeRecoveryModel extends plugins.nosqldb.SmartDataDbDoc<
782
+ FlexScopeRecoveryModel,
783
+ IFlexScopeRecoveryDocument
784
+ > {
785
+ declare static exact: plugins.nosqldb.TExact<FlexScopeRecoveryModel>;
786
+
787
+ @plugins.nosqldb.unI()
788
+ public id!: string;
789
+
790
+ @plugins.nosqldb.index()
791
+ public controllerId!: string;
792
+
793
+ @plugins.nosqldb.index()
794
+ public storageKey!: string;
795
+
796
+ @plugins.nosqldb.svDb()
797
+ public proof!: plugins.flexharness.IFlexScopeRecoverySnapshot;
798
+ }
799
+
705
800
  const scopedIdentityHash = (
706
801
  controllerIdArg: string,
707
802
  storageKeyArg: string,
@@ -738,6 +833,16 @@ export const flexMigrationId = (
738
833
  storageKeyArg: string,
739
834
  ): string => `flex-migration:${scopedIdentityHash(controllerIdArg, storageKeyArg, 'flexharness-v3')}`;
740
835
 
836
+ export const flexNamespaceWritesId = (
837
+ controllerIdArg: string,
838
+ storageKeyArg: string,
839
+ ): string => `flex-namespace-writes:${scopedIdentityHash(controllerIdArg, storageKeyArg, 'namespace-writes')}`;
840
+
841
+ export const flexScopeRecoveryId = (
842
+ controllerIdArg: string,
843
+ storageKeyArg: string,
844
+ ): string => `flex-scope-recovery:${scopedIdentityHash(controllerIdArg, storageKeyArg, 'scope-recovery')}`;
845
+
741
846
  @plugins.nosqldb.managed({ collectionName: 'flex_model_choices' })
742
847
  export class FlexModelChoiceModel extends plugins.nosqldb.SmartDataDbDoc<
743
848
  FlexModelChoiceModel,
@@ -771,6 +876,8 @@ export const registerFlexPrivateModels = (
771
876
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexDomainHeadModel);
772
877
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexWriterLeaseModel);
773
878
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexMigrationModel);
879
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexNamespaceWritesModel);
880
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexScopeRecoveryModel);
774
881
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexModelChoiceModel);
775
882
  };
776
883
 
@@ -785,5 +892,7 @@ export const initFlexPrivateModels = async (): Promise<void> => {
785
892
  await FlexDomainHeadModel.exact.prepare();
786
893
  await FlexWriterLeaseModel.exact.prepare();
787
894
  await FlexMigrationModel.exact.prepare();
895
+ await FlexNamespaceWritesModel.exact.prepare();
896
+ await FlexScopeRecoveryModel.exact.prepare();
788
897
  await FlexModelChoiceModel.init();
789
898
  };
@@ -0,0 +1,69 @@
1
+ import { FlexServiceError, type TFlexProjectPreparationState } from './interfaces.flexipc.js';
2
+
3
+ interface IFlexProjectPreparationWaiter {
4
+ readonly projectId: string;
5
+ resolve(): void;
6
+ reject(errorArg: unknown): void;
7
+ }
8
+
9
+ /**
10
+ * The preparation of each project in one Flex child generation, as the child reports it
11
+ * (`project.preparation`). A mutating request of a project waits here until the project is
12
+ * ready, outside that request's control budget, so a long preparation never turns the request
13
+ * into an unknown outcome. Waiting sends nothing to the child.
14
+ *
15
+ * A project the child has not reported yet is not ready. `failed` and the end of the generation
16
+ * (`reset`) refuse every waiter with `NOT_READY`; a waiter's own signal refuses it with its reason.
17
+ */
18
+ export class FlexProjectPreparation {
19
+ private readonly states = new Map<string, TFlexProjectPreparationState>();
20
+ private readonly waiters = new Set<IFlexProjectPreparationWaiter>();
21
+
22
+ /** Ends the generation: forgets every project and refuses every waiter. */
23
+ public reset(reasonArg: unknown = new FlexServiceError('NOT_READY')): void {
24
+ this.states.clear();
25
+ for (const waiter of [...this.waiters]) waiter.reject(reasonArg);
26
+ }
27
+
28
+ public changed(projectIdArg: string, stateArg: TFlexProjectPreparationState): void {
29
+ this.states.set(projectIdArg, stateArg);
30
+ if (stateArg === 'preparing') return;
31
+ for (const waiter of [...this.waiters]) {
32
+ if (waiter.projectId !== projectIdArg) continue;
33
+ if (stateArg === 'ready') waiter.resolve();
34
+ else waiter.reject(new FlexServiceError('NOT_READY'));
35
+ }
36
+ }
37
+
38
+ public state(projectIdArg: string): TFlexProjectPreparationState | undefined {
39
+ return this.states.get(projectIdArg);
40
+ }
41
+
42
+ /** The number of waiters not yet settled, for tests. */
43
+ public get waiting(): number {
44
+ return this.waiters.size;
45
+ }
46
+
47
+ public wait(projectIdArg: string, signalArg: AbortSignal): Promise<void> {
48
+ if (signalArg.aborted) return Promise.reject(signalArg.reason);
49
+ const state = this.states.get(projectIdArg);
50
+ if (state === 'ready') return Promise.resolve();
51
+ if (state === 'failed') return Promise.reject(new FlexServiceError('NOT_READY'));
52
+ return new Promise<void>((resolve, reject) => {
53
+ const finish = (errorArg?: unknown): void => {
54
+ if (!this.waiters.delete(waiter)) return;
55
+ signalArg.removeEventListener('abort', abort);
56
+ if (errorArg === undefined) resolve();
57
+ else reject(errorArg);
58
+ };
59
+ const abort = (): void => finish(signalArg.reason);
60
+ const waiter: IFlexProjectPreparationWaiter = {
61
+ projectId: projectIdArg,
62
+ resolve: () => finish(),
63
+ reject: (errorArg) => finish(errorArg),
64
+ };
65
+ this.waiters.add(waiter);
66
+ signalArg.addEventListener('abort', abort, { once: true });
67
+ });
68
+ }
69
+ }
@@ -102,6 +102,11 @@ export interface IFlexPromptQueueHost {
102
102
  /** Bounds every dispatch the queue starts on its own. */
103
103
  readonly dispatchSignal: AbortSignal;
104
104
  canDispatch(projectIdArg: string, sessionIdArg: IControllerRuntimeId): boolean;
105
+ /**
106
+ * Resolves once the Flex child prepared the project, so a start never waits for preparation
107
+ * inside its control budget. Refused when the child generation ends or the signal aborts.
108
+ */
109
+ waitForProjectReady(projectIdArg: string, signalArg: AbortSignal): Promise<void>;
105
110
  withSubmissionAdmission(
106
111
  projectIdArg: string,
107
112
  sessionIdArg: IControllerRuntimeId,
@@ -119,6 +124,8 @@ export interface IFlexPromptQueueHost {
119
124
  progressArg: IFlexPromptDispatchProgress,
120
125
  signalArg: AbortSignal,
121
126
  ): Promise<void>;
127
+ /** Immutable admission may steer the existing run after its waiting owner committed. */
128
+ steerPrompt?(submissionArg: IFlexPromptSubmission, progressArg: IFlexPromptDispatchProgress, signalArg: AbortSignal): Promise<boolean>;
122
129
  /**
123
130
  * Whether the session holds messages that join its next turn: those a stopped turn left, and
124
131
  * with `resendArg` (an explicit Resend) also those a failed start held.
@@ -210,6 +217,10 @@ export class ControllerFlexPromptQueue {
210
217
  /** Every Flex prompt this queue admitted, until the operation manager releases it. */
211
218
  private readonly submissions = new Map<string, IFlexPromptSubmission>();
212
219
  private readonly drains = new Map<string, Promise<void>>();
220
+ /** Sessions whose drain hands a queued steer to the running turn, until that drain ends. */
221
+ private readonly steering = new Set<string>();
222
+ /** Steering sessions scheduled during that hand-over; each is scheduled again once its drain ends. */
223
+ private readonly rescheduled = new Set<string>();
213
224
  /** Counts finished session prompts, so a refusal can tell whether it is already stale. */
214
225
  private readonly activityEpochs = new Map<string, number>();
215
226
  private readonly holds = new Map<string, IFlexHeldSession>();
@@ -245,6 +256,7 @@ export class ControllerFlexPromptQueue {
245
256
  }
246
257
  const observedEpoch = this.activityEpoch(operation.projectId, operation.sessionId);
247
258
  try {
259
+ await this.host.waitForProjectReady(operation.projectId, signalArg);
248
260
  await this.host.startPrompt(submissionArg, [], progressArg, signalArg);
249
261
  return 'started';
250
262
  } catch (errorArg) {
@@ -257,6 +269,13 @@ export class ControllerFlexPromptQueue {
257
269
  }
258
270
  }
259
271
 
272
+ /** Derives one queued operation from a committed ledger owner; acceptance never waits on native work. */
273
+ public admit(submissionArg: IFlexPromptSubmission): void {
274
+ this.host.operations.queuePrompt(submissionArg.operation);
275
+ this.host.operations.acceptQueued(submissionArg.operation);
276
+ this.adoptQueued(submissionArg);
277
+ }
278
+
260
279
  /**
261
280
  * Takes a prompt the operation manager queued without `submit`, such as a steer its turn did not
262
281
  * take in, and dispatches it in its place in the session's queue.
@@ -337,11 +356,21 @@ export class ControllerFlexPromptQueue {
337
356
  }
338
357
  }
339
358
 
340
- /** Dispatches the queued session head, with the entries behind it, when the session can take it. */
359
+ /**
360
+ * Dispatches the queued session head, with the entries behind it, when the session can take it.
361
+ * A drain that steers runs beside the session's running turn, which can end meanwhile: a schedule
362
+ * asked for once the steer was claimed is kept and runs when the drain ends, so a steer the ended
363
+ * run refused starts the next turn instead of waiting for a wake-up that already came. Any other
364
+ * drain drops it: a refused start waits for the session's next finish (`requeueRefused`).
365
+ */
341
366
  public schedule(projectIdArg: string, sessionIdArg: IControllerRuntimeId): void {
342
367
  const key = this.sessionKey(projectIdArg, sessionIdArg);
343
- if (this.drains.has(key) || !this.canDispatch(projectIdArg, sessionIdArg)) return;
344
- if (!this.queuedHead(projectIdArg, sessionIdArg)) return;
368
+ if (this.drains.has(key)) {
369
+ if (this.steering.has(key)) this.rescheduled.add(key);
370
+ return;
371
+ }
372
+ if (!this.canDispatch(projectIdArg, sessionIdArg)) return;
373
+ if (!this.queuedHead(projectIdArg, sessionIdArg) && !this.queuedSteer(projectIdArg, sessionIdArg)) return;
345
374
  let retryNow = false;
346
375
  let drain!: Promise<void>;
347
376
  drain = this.host.trackTask(this.dispatchQueued(projectIdArg, sessionIdArg).then((retryArg) => {
@@ -349,7 +378,9 @@ export class ControllerFlexPromptQueue {
349
378
  })).finally(() => {
350
379
  if (this.drains.get(key) !== drain) return;
351
380
  this.drains.delete(key);
352
- if (retryNow) this.schedule(projectIdArg, sessionIdArg);
381
+ this.steering.delete(key);
382
+ const rescheduled = this.rescheduled.delete(key);
383
+ if (retryNow || rescheduled) this.schedule(projectIdArg, sessionIdArg);
353
384
  });
354
385
  this.drains.set(key, drain);
355
386
  void drain.catch(() => undefined);
@@ -478,6 +509,15 @@ export class ControllerFlexPromptQueue {
478
509
  return this.activityEpochs.get(this.sessionKey(projectIdArg, sessionIdArg)) ?? 0;
479
510
  }
480
511
 
512
+ private queuedSteer(projectIdArg: string, sessionIdArg: IControllerRuntimeId): IFlexPromptSubmission | undefined {
513
+ if (!this.host.steerPrompt) return undefined;
514
+ const active = this.host.operations.getActive(projectIdArg, sessionIdArg);
515
+ if (!active || (active.state !== 'accepted' && active.state !== 'outcomeUnknown')) return undefined;
516
+ return this.host.operations.listSessionActive(projectIdArg, sessionIdArg)
517
+ .filter(operation => operation.state === 'queued' && operation.reservation.delivery === 'steer')
518
+ .map(operation => this.submissions.get(operation.reservation.operationId)).find(submission => submission !== undefined);
519
+ }
520
+
481
521
  private queuedHead(
482
522
  projectIdArg: string,
483
523
  sessionIdArg: IControllerRuntimeId,
@@ -537,14 +577,37 @@ export class ControllerFlexPromptQueue {
537
577
  const observedEpoch = this.activityEpoch(projectIdArg, sessionIdArg);
538
578
  const progress = createFlexPromptDispatchProgress();
539
579
  // An admission refused before it ran settles the head this drain was scheduled for.
540
- const scheduledHead = this.queuedHead(projectIdArg, sessionIdArg);
580
+ const scheduledHead = this.queuedHead(projectIdArg, sessionIdArg) ?? this.queuedSteer(projectIdArg, sessionIdArg);
541
581
  let admitted = false;
542
582
  let failing: IFlexPromptSubmission[] = [];
543
583
  let dispatched = false;
584
+ try {
585
+ await this.host.waitForProjectReady(projectIdArg, signal);
586
+ } catch {
587
+ // Nothing was claimed. The child generation that ended owns its queues' cleanup, and the
588
+ // next generation's readiness schedules them again; an aborted signal stops the controller.
589
+ return false;
590
+ }
544
591
  try {
545
592
  await this.host.withSubmissionAdmission(projectIdArg, sessionIdArg, signal, async () => {
546
593
  admitted = true;
547
- if (!this.canDispatch(projectIdArg, sessionIdArg) || !this.queuedHead(projectIdArg, sessionIdArg)) return;
594
+ if (!this.canDispatch(projectIdArg, sessionIdArg)) return;
595
+ const steer = this.queuedSteer(projectIdArg, sessionIdArg);
596
+ if (steer) {
597
+ failing = [steer];
598
+ this.host.operations.assertCurrentHarnessAdmission(steer.operation);
599
+ this.host.operations.beginQueuedSteerSubmission(steer.operation);
600
+ this.steering.add(this.sessionKey(projectIdArg, sessionIdArg));
601
+ if (await this.host.steerPrompt!(steer, progress, signal)) {
602
+ this.host.onQueueChanged(projectIdArg, sessionIdArg);
603
+ dispatched = true;
604
+ } else {
605
+ this.host.operations.returnUndispatchedToQueue(steer.operation);
606
+ this.host.onQueueChanged(projectIdArg, sessionIdArg);
607
+ }
608
+ return;
609
+ }
610
+ if (!this.queuedHead(projectIdArg, sessionIdArg)) return;
548
611
  // The user started a turn: the messages a stopped turn left go into it first, and those a
549
612
  // failed start held when the turn is an explicit Resend.
550
613
  const resend = this.queuedSubmissions(projectIdArg, sessionIdArg).some((submission) => submission.resend);
@@ -0,0 +1,47 @@
1
+ import { KeyedAccessQueue } from './classes.keyedaccessqueue.js';
2
+
3
+ /**
4
+ * Orders a session's requests without holding the other sessions of its project. Project-wide
5
+ * operations are barriers: they drain earlier session requests and exclude every later one.
6
+ * A cancelled waiter answers immediately but keeps its place until it can leave without running.
7
+ */
8
+ export class FlexRequestQueue {
9
+ private readonly projects = new KeyedAccessQueue();
10
+ private readonly sessions = new KeyedAccessQueue();
11
+
12
+ public get pendingProjects(): number {
13
+ return this.projects.size;
14
+ }
15
+
16
+ public run<T>(
17
+ projectIdArg: string,
18
+ sessionIdArg: string | undefined,
19
+ signalArg: AbortSignal,
20
+ operationArg: () => Promise<T>,
21
+ ): Promise<T> {
22
+ signalArg.throwIfAborted();
23
+ let started = false;
24
+ const start = (): Promise<T> => {
25
+ signalArg.throwIfAborted();
26
+ started = true;
27
+ return operationArg();
28
+ };
29
+ const operation = sessionIdArg === undefined
30
+ ? this.projects.exclusive(projectIdArg, start)
31
+ : this.projects.shared(projectIdArg, () => this.sessions.exclusive(
32
+ JSON.stringify([projectIdArg, sessionIdArg]),
33
+ start,
34
+ ));
35
+ return new Promise<T>((resolve, reject) => {
36
+ const cancelled = (): void => {
37
+ // Once started, only the operation can judge whether its effects may have happened.
38
+ if (!started) reject(signalArg.reason);
39
+ };
40
+ if (signalArg.aborted) cancelled();
41
+ else signalArg.addEventListener('abort', cancelled, { once: true });
42
+ void operation.then(resolve, reject).finally(() => {
43
+ signalArg.removeEventListener('abort', cancelled);
44
+ });
45
+ });
46
+ }
47
+ }