agl 43.14.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 (89) hide show
  1. package/changelog.md +22 -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.pendingpromptstore.d.ts +11 -3
  34. package/dist_ts/classes.pendingpromptstore.js +66 -10
  35. package/dist_ts/classes.sessionidentityservice.d.ts +18 -1
  36. package/dist_ts/classes.sessionidentityservice.js +34 -4
  37. package/dist_ts/classes.validation.d.ts +3 -0
  38. package/dist_ts/classes.validation.js +50 -1
  39. package/dist_ts/functions.deviceapi.js +3 -1
  40. package/dist_ts/interfaces.auth.d.ts +3 -1
  41. package/dist_ts/interfaces.auth.js +1 -1
  42. package/dist_ts/interfaces.flexipc.d.ts +29 -5
  43. package/dist_ts/interfaces.flexipc.js +13 -4
  44. package/dist_ts_authswitch/classes.authoritydatabase.d.ts +1 -0
  45. package/dist_ts_authswitch/classes.authoritydatabase.js +17 -5
  46. package/dist_ts_interfaces/flexadmission.d.ts +69 -0
  47. package/dist_ts_interfaces/flexadmission.js +2 -0
  48. package/dist_ts_interfaces/index.d.ts +1 -0
  49. package/dist_ts_interfaces/index.js +2 -1
  50. package/dist_ts_interfaces/interfaces.d.ts +10 -1
  51. package/dist_ts_interfaces/interfaces.js +2 -2
  52. package/dist_ts_interfaces/requests.d.ts +2 -1
  53. package/dist_ts_interfaces/requests.js +1 -1
  54. package/dist_ts_migration/v10_flexharnessv3migration.js +4 -1
  55. package/docs/nosqldb11-migration.md +59 -0
  56. package/package.json +10 -9
  57. package/readme.md +5 -1
  58. package/ts/00_commitinfo_data.ts +1 -1
  59. package/ts/aglapi/aglapisurface.document.ts +36 -3
  60. package/ts/classes.authstore.ts +179 -11
  61. package/ts/classes.controller.ts +498 -40
  62. package/ts/classes.embeddeddb.ts +6 -1
  63. package/ts/classes.flexmodels.private.ts +109 -0
  64. package/ts/classes.flexprojectpreparation.ts +69 -0
  65. package/ts/classes.flexpromptqueue.ts +69 -6
  66. package/ts/classes.flexrequestqueue.ts +47 -0
  67. package/ts/classes.flexservice.ts +187 -51
  68. package/ts/classes.flexstore.ts +352 -10
  69. package/ts/classes.flexsubmissionmodels.ts +89 -0
  70. package/ts/classes.flexsubmissionstore.ts +312 -0
  71. package/ts/classes.flexsupervisor.ts +26 -0
  72. package/ts/classes.harnessoperationmanager.ts +79 -6
  73. package/ts/classes.pendingpromptstore.ts +55 -6
  74. package/ts/classes.sessionidentityservice.ts +33 -2
  75. package/ts/classes.validation.ts +42 -0
  76. package/ts/functions.deviceapi.ts +2 -0
  77. package/ts/interfaces.auth.ts +3 -1
  78. package/ts/interfaces.flexipc.ts +38 -4
  79. package/ts_authswitch/classes.authoritydatabase.ts +19 -5
  80. package/ts_interfaces/flexadmission.ts +52 -0
  81. package/ts_interfaces/index.ts +2 -0
  82. package/ts_interfaces/interfaces.ts +10 -1
  83. package/ts_interfaces/requests.ts +3 -0
  84. package/ts_migration/v10_flexharnessv3migration.ts +3 -0
  85. package/ts_web/00_commitinfo_data.ts +1 -1
  86. package/ts_web/classes.browsersubmissions.ts +279 -0
  87. package/ts_web/classes.sessiondraftsync.ts +64 -1
  88. package/ts_web/elements.harnesscontrollerapp.ts +340 -5
  89. package/ts_web/functions.flexsubmissions.ts +88 -0
@@ -4333,8 +4333,39 @@ export class ControllerSessionIdentityService {
4333
4333
  );
4334
4334
  }
4335
4335
 
4336
+ /**
4337
+ * The managed identity and native generation of an existing Flex conversation, read from the
4338
+ * controller's records without loading its transcript. Admission calls it under the store's
4339
+ * project mutation lane, which orders it against every identity change.
4340
+ */
4341
+ public async flexSubmissionIdentity(inputArg: {
4342
+ projectIdentityId: string; runtimeId: TControllerSessionId & { harnessId: 'flex' }; sessionIdentityId: string;
4343
+ }, sessionArg?: plugins.nosqldb.SmartdataSession): Promise<{ sessionIdentityId: string; sessionGenerationId: string; sessionGenerationSequence: number }> {
4344
+ const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId);
4345
+ if (!isBase64UrlBytes(inputArg.sessionIdentityId, 32)) throw new ControllerSessionIdentityError('invalid_input', 'The conversation identity is invalid.');
4346
+ const options = sessionArg ? { session: sessionArg } : {};
4347
+ const stored = await ControllerSessionLocatorModel.exact.findStoredOne({ id: input.locatorId }, options);
4348
+ if (!stored) throw new ControllerSessionIdentityError('not_found', 'The conversation identity is not managed.');
4349
+ const locator = ControllerSessionLocatorModel.exact.toPersisted(stored);
4350
+ this.assertLocatorScope(locator, input);
4351
+ if (locator.sessionIdentityId !== inputArg.sessionIdentityId || (locator.state !== 'attached' && locator.state !== 'detached')) {
4352
+ throw new ControllerSessionIdentityError('concurrent_change', 'The conversation identity changed.');
4353
+ }
4354
+ const id = controllerManagedSessionDocumentId(this.issuerId, input.projectIdentityId, 'flex', locator.sessionIdentityId);
4355
+ const membershipStored = await ControllerManagedSessionModel.exact.findStoredOne({ id }, options);
4356
+ if (!membershipStored) throw new ControllerSessionIdentityError('not_found', 'The conversation is not managed.');
4357
+ const membership = ControllerManagedSessionModel.exact.toPersisted(membershipStored);
4358
+ this.assertManagedSessionScope(membership, input.projectIdentityId, input.runtimeId, locator.sessionIdentityId);
4359
+ if (membership.state !== 'active' || membership.providerSessionGeneration !== locator.providerSessionGeneration
4360
+ || membership.sessionGenerationId === undefined || membership.sessionGenerationSequence === undefined) {
4361
+ throw new ControllerSessionIdentityError('concurrent_change', 'The managed conversation generation changed.');
4362
+ }
4363
+ return { sessionIdentityId: locator.sessionIdentityId, sessionGenerationId: membership.sessionGenerationId, sessionGenerationSequence: membership.sessionGenerationSequence };
4364
+ }
4365
+
4336
4366
  public beginManagedSessionCreation(
4337
4367
  inputArg: IBeginControllerManagedSessionCreationInput,
4368
+ sessionArg?: plugins.nosqldb.SmartdataSession,
4338
4369
  ): Promise<IControllerSessionCreationObligation> {
4339
4370
  if (inputArg.runtimeId?.harnessId === 'codex') {
4340
4371
  return Promise.reject(new Error('Codex requires a server-assigned creation intent.'));
@@ -4385,10 +4416,10 @@ export class ControllerSessionIdentityService {
4385
4416
  };
4386
4417
  let stored: TStoredSessionCreationObligation | undefined;
4387
4418
  try {
4388
- const result = await ControllerSessionCreationObligationModel.exact.insert(candidate);
4419
+ const result = await ControllerSessionCreationObligationModel.exact.insert(candidate, sessionArg ? { session: sessionArg } : {});
4389
4420
  stored = result.document;
4390
4421
  } catch (errorArg) {
4391
- if (!isAmbiguousWrite(errorArg)) throw errorArg;
4422
+ if (sessionArg || !isAmbiguousWrite(errorArg)) throw errorArg;
4392
4423
  stored = await this.readSessionCreationObligation(
4393
4424
  input.projectIdentityId,
4394
4425
  input.runtimeId,
@@ -2760,3 +2760,45 @@ export const assertElicitationReplyRequest = (
2760
2760
  assertRelatedRuntimeIds(sessionId, requestId, 'requestId');
2761
2761
  return { projectId, sessionId, requestId, reply: assertElicitationReply(value.reply) };
2762
2762
  };
2763
+
2764
+ /** Direct immutable Flex admission, independent of the mutable shared composer. */
2765
+ export const assertFlexSubmissionGetRequest = (valueArg: unknown): interfaces.IReq_ControllerFlexSubmissionGet['request'] => {
2766
+ const value = assertObject(valueArg, 'Flex submission lookup');
2767
+ assertKeys(value, ['version', 'projectId', 'clientMessageId']);
2768
+ if (value.version !== 1) throw new Error('The Flex submission version is unsupported.');
2769
+ return { version: 1, projectId: assertProjectId(value.projectId, 'projectId'), clientMessageId: assertOpaqueIdentifier(value.clientMessageId, 'clientMessageId') };
2770
+ };
2771
+
2772
+ export const assertFlexSubmissionAdmitRequest = (valueArg: unknown): interfaces.IControllerFlexSubmissionInput => {
2773
+ const value = assertObject(valueArg, 'Flex submission');
2774
+ assertKeys(value, ['version', 'projectId', 'clientMessageId', 'conversation', 'text', 'attachments', 'model', 'providerConnectionId', 'delivery'], ['capturedDraft']);
2775
+ const lookup = assertFlexSubmissionGetRequest({ version: value.version, projectId: value.projectId, clientMessageId: value.clientMessageId });
2776
+ const conversation = assertObject(value.conversation, 'conversation');
2777
+ let target: interfaces.TControllerFlexAdmissionConversation;
2778
+ if (conversation.kind === 'existing') {
2779
+ assertKeys(conversation, ['kind', 'sessionId', 'sessionIdentityId']);
2780
+ const sessionIdentityId = assertString(conversation.sessionIdentityId, 'sessionIdentityId', 43, 43);
2781
+ if (!/^[A-Za-z0-9_-]{43}$/u.test(sessionIdentityId)) throw new Error('The conversation identity is invalid.');
2782
+ target = { kind: 'existing', sessionId: assertControllerRuntimeId(conversation.sessionId, 'sessionId', ['flex']) as interfaces.IControllerRuntimeId & { harnessId: 'flex' }, sessionIdentityId };
2783
+ } else if (conversation.kind === 'new') {
2784
+ assertKeys(conversation, ['kind', 'clientConversationId'], ['title', 'scratchpad']);
2785
+ target = { kind: 'new', clientConversationId: assertOpaqueIdentifier(conversation.clientConversationId, 'clientConversationId'),
2786
+ ...(conversation.title === undefined ? {} : { title: assertString(conversation.title, 'title', 1, 512) }),
2787
+ ...(conversation.scratchpad === undefined ? {} : { scratchpad: assertString(conversation.scratchpad, 'scratchpad', 0, 65536) }) };
2788
+ } else throw new Error('The Flex conversation target is invalid.');
2789
+ const text = assertString(value.text, 'text', 1, controllerMaxDraftTextBytes);
2790
+ if (!text.trim() || Buffer.byteLength(text, 'utf8') > controllerMaxDraftTextBytes) throw new Error('The message text must fit the controller input limit.');
2791
+ const model = assertModelChoice(value.model);
2792
+ if (model.harnessId !== 'flex') throw new Error('A Flex submission requires a Flex model.');
2793
+ const providerConnectionId = assertFlexConnectionId(value.providerConnectionId, 'providerConnectionId');
2794
+ const delivery = assertOptionalPromptDelivery(value.delivery, { harnessId: 'flex', nativeId: 'validation' });
2795
+ if (!delivery) throw new Error('The Flex submission requires an explicit delivery.');
2796
+ let capturedDraft: { revision: number } | undefined;
2797
+ if (value.capturedDraft !== undefined) {
2798
+ const draft = assertObject(value.capturedDraft, 'capturedDraft');
2799
+ assertKeys(draft, ['revision']);
2800
+ capturedDraft = { revision: assertDraftRevision(draft.revision, 'capturedDraft.revision') };
2801
+ if (target.kind !== 'existing') throw new Error('A shared draft binding requires an existing conversation.');
2802
+ }
2803
+ return { ...lookup, conversation: target, text, attachments: assertDraftAttachments(value.attachments), model, providerConnectionId, delivery, ...(capturedDraft ? { capturedDraft } : {}) };
2804
+ };
@@ -271,6 +271,8 @@ export const deviceControllerRefusals: Readonly<Record<Exclude<TControllerRefusa
271
271
  invalid_settings: 'controller_failed',
272
272
  temp_password_invalid: 'controller_failed',
273
273
  temp_password_limit: 'controller_failed',
274
+ // Only a CLI store attached to the controller's engine meets it; the controller owns its engine.
275
+ not_database_owner: 'controller_failed',
274
276
  // The configuration authority the driver, the direct reports and the deploy monitor read.
275
277
  invalid_argument: 'controller_failed',
276
278
  conflict: 'concurrent_change',
@@ -202,7 +202,9 @@ export type TAuthErrorCode =
202
202
  | 'invalid_resource'
203
203
  | 'invalid_settings'
204
204
  | 'temp_password_invalid'
205
- | 'temp_password_limit';
205
+ | 'temp_password_limit'
206
+ /** A store attached to an engine another process owns: it never writes projects, locators or managed sessions. */
207
+ | 'not_database_owner';
206
208
 
207
209
  export class AuthError extends Error {
208
210
  public readonly code: TAuthErrorCode;
@@ -57,6 +57,17 @@ export interface IFlexPromptRunAdmission {
57
57
  runId: string;
58
58
  generation: TFlexPromptAdmissionGeneration;
59
59
  }
60
+ /**
61
+ * FlexHarness's answer to a generation-fenced deletion (`deleteSessionGenerationCohort`): the root
62
+ * generation's deletion completed, or it did not match because no live session and no retained
63
+ * cleanup tombstone of any generation holds the id (`absent`), or because another generation holds
64
+ * it (`superseded`, naming that generation).
65
+ */
66
+ export type TFlexSessionDeletionResult =
67
+ | { matched: true }
68
+ | { matched: false; reason: 'absent' }
69
+ | { matched: false; reason: 'superseded'; current: TFlexSessionGeneration };
70
+
60
71
  export type TFlexSessionGenerationCohortEntry =
61
72
  plugins.flexharness.IFlexSessionGenerationCohortEntry;
62
73
  export type TFlexSlashCommandDescriptor = plugins.flexharness.IFlexSlashCommandDescriptor;
@@ -72,7 +83,7 @@ export type TFlexSessionIdentity = plugins.flexharness.IFlexSessionIdentity;
72
83
  /** What one FlexHarness load of a project's sessions took. */
73
84
  export type TFlexScopeLoadMetrics = plugins.flexharness.IFlexScopeLoadMetrics;
74
85
 
75
- export const flexIpcProtocolVersion = 40 as const;
86
+ export const flexIpcProtocolVersion = 41 as const;
76
87
  /**
77
88
  * The installation's own Flex runs, which belong to no project: the configuration projection's adapting run, and
78
89
  * Session Intelligence over a session outside every project.
@@ -823,7 +834,7 @@ export interface IFlexRequestMap {
823
834
  root: TFlexSessionGenerationCohortEntry;
824
835
  authorizedCohort: TFlexSessionGenerationCohortEntry[];
825
836
  };
826
- response: { matched: boolean };
837
+ response: TFlexSessionDeletionResult;
827
838
  };
828
839
  'session.compact': {
829
840
  request: { scopeId: string; sessionId: string; model?: IFlexModelChoice };
@@ -1181,7 +1192,19 @@ type TFlexChildSessionEvent = TFlexSessionGeneration & {
1181
1192
  sessionId: string;
1182
1193
  };
1183
1194
 
1195
+ /**
1196
+ * A project's preparation in one child generation: `preparing` while the child makes the
1197
+ * project's scope ready, `ready` once mutating requests of the project may be sent, `failed` when
1198
+ * it could not (or the project was removed). Child readiness is not project readiness.
1199
+ */
1200
+ export type TFlexProjectPreparationState = 'preparing' | 'ready' | 'failed';
1201
+
1184
1202
  export type TFlexChildEvent =
1203
+ | {
1204
+ type: 'project.preparation';
1205
+ scopeId: string;
1206
+ state: TFlexProjectPreparationState;
1207
+ }
1185
1208
  | (TFlexChildSessionEvent & {
1186
1209
  type: 'session.history.changed';
1187
1210
  direction: 'undo' | 'redo' | 'branch';
@@ -3471,8 +3494,15 @@ export const isFlexResponseResult = <TMethod extends TFlexRequestMethod>(
3471
3494
  return isFlexPlainObject(valueArg) && hasFlexExactKeys(valueArg, [], ['warmUntil'])
3472
3495
  && (valueArg.warmUntil === undefined || isIsoDate(valueArg.warmUntil));
3473
3496
  case 'session.delete':
3474
- return isFlexPlainObject(valueArg) && hasFlexExactKeys(valueArg, ['matched'])
3475
- && typeof valueArg.matched === 'boolean';
3497
+ return isFlexPlainObject(valueArg) && (
3498
+ (hasFlexExactKeys(valueArg, ['matched']) && valueArg.matched === true)
3499
+ || (hasFlexExactKeys(valueArg, ['matched', 'reason']) && valueArg.matched === false
3500
+ && valueArg.reason === 'absent')
3501
+ || (hasFlexExactKeys(valueArg, ['matched', 'reason', 'current']) && valueArg.matched === false
3502
+ && valueArg.reason === 'superseded' && isFlexPlainObject(valueArg.current)
3503
+ && hasFlexExactKeys(valueArg.current, ['sessionGenerationId', 'sessionGenerationSequence'])
3504
+ && isFlexSessionGeneration(valueArg.current))
3505
+ );
3476
3506
  case 'session.compact':
3477
3507
  return isFlexPlainObject(valueArg) && hasFlexExactKeys(valueArg, ['compacted'])
3478
3508
  && valueArg.compacted === true;
@@ -3585,6 +3615,10 @@ const flexRetryReasons: ReadonlySet<string> = new Set<TFlexRetryReason>([
3585
3615
  const isFlexChildEvent = (valueArg: unknown): valueArg is TFlexChildEvent => {
3586
3616
  if (!isFlexPlainObject(valueArg)) return false;
3587
3617
  switch (valueArg.type) {
3618
+ case 'project.preparation':
3619
+ return hasFlexExactKeys(valueArg, ['type', 'scopeId', 'state'])
3620
+ && isControllerProjectId(valueArg.scopeId)
3621
+ && ['preparing', 'ready', 'failed'].includes(String(valueArg.state));
3588
3622
  case 'session.history.changed':
3589
3623
  return hasFlexExactKeys(
3590
3624
  valueArg,
@@ -275,6 +275,7 @@ export class AuthSwitchAuthorityDatabase {
275
275
  private engine?: plugins.nosqldbEngine.LocalNoSqlDb;
276
276
  private database?: plugins.nosqldb.SmartdataDb;
277
277
  private started = false;
278
+ private engineStarted = false;
278
279
  private readonly deviceOperationObservers = new Set<(operationId: string) => void>();
279
280
  private readonly nativeHandoffObservers = new Set<(operationId: string) => void>();
280
281
 
@@ -297,6 +298,7 @@ export class AuthSwitchAuthorityDatabase {
297
298
  this.engine = engine;
298
299
  try {
299
300
  const connection = await engine.start();
301
+ this.engineStarted = true;
300
302
  const database = new plugins.nosqldb.SmartdataDb({ mongoDbUrl: connection.connectionUri, mongoDbName: 'authswitch' });
301
303
  this.database = database;
302
304
  await database.init();
@@ -330,7 +332,9 @@ export class AuthSwitchAuthorityDatabase {
330
332
  }
331
333
  this.started = true;
332
334
  } catch (error) {
333
- try { await this.stop(); } catch { /* Preserve the original startup error. */ }
335
+ try { await this.stop(); } catch (cleanupError) {
336
+ throw new AggregateError([error, cleanupError], 'Authswitch database startup failed and cleanup was incomplete.', { cause: error });
337
+ }
334
338
  throw error;
335
339
  }
336
340
  }
@@ -3639,11 +3643,21 @@ export class AuthSwitchAuthorityDatabase {
3639
3643
  this.started = false;
3640
3644
  const database = this.database;
3641
3645
  const engine = this.engine;
3642
- this.database = undefined;
3643
- this.engine = undefined;
3644
3646
  const errors: unknown[] = [];
3645
- if (database) try { await database.close(); } catch (error) { errors.push(error); }
3646
- if (engine) try { await engine.stop(); } catch (error) { errors.push(error); }
3647
+ if (database) try {
3648
+ await database.close();
3649
+ if (this.database === database) this.database = undefined;
3650
+ } catch (error) { errors.push(error); }
3651
+ if (engine) try {
3652
+ const result = await engine.stop();
3653
+ if (this.engine === engine) this.engine = undefined;
3654
+ const requiredCleanStop = this.engineStarted;
3655
+ this.engineStarted = false;
3656
+ // A resolved NoSQLDB 11 stop can still have forced an unclean engine exit.
3657
+ if (requiredCleanStop && !result.clean) {
3658
+ throw new Error('Authswitch database engine did not shut down cleanly.', { cause: result });
3659
+ }
3660
+ } catch (error) { errors.push(error); }
3647
3661
  if (errors.length) throw new AggregateError(errors, 'Authswitch database shutdown was incomplete.');
3648
3662
  }
3649
3663
  }
@@ -0,0 +1,52 @@
1
+ import type * as plugins from './plugins.js';
2
+ import type { IControllerDraftAttachment, IControllerRuntimeId, TControllerHeldPromptReason, TControllerModelChoice, TControllerPromptDelivery } from './interfaces.js';
3
+
4
+ /** Immutable browser input. One new intent is reused for every rapid send to that conversation. */
5
+ export type TControllerFlexAdmissionConversation =
6
+ | { kind: 'existing'; sessionId: IControllerRuntimeId & { harnessId: 'flex' }; sessionIdentityId: string }
7
+ | { kind: 'new'; clientConversationId: string; title?: string; scratchpad?: string };
8
+
9
+ export interface IControllerFlexSubmissionInput {
10
+ version: 1;
11
+ projectId: string;
12
+ clientMessageId: string;
13
+ conversation: TControllerFlexAdmissionConversation;
14
+ text: string;
15
+ attachments: IControllerDraftAttachment[];
16
+ model: TControllerModelChoice & { harnessId: 'flex' };
17
+ providerConnectionId: string;
18
+ delivery: TControllerPromptDelivery;
19
+ /** Clears only this shared draft revision after commit; never consumes a mutable draft. */
20
+ capturedDraft?: { revision: number };
21
+ }
22
+
23
+ export interface IControllerFlexSubmissionReceipt {
24
+ version: 1;
25
+ clientMessageId: string;
26
+ operationId: string;
27
+ projectId: string;
28
+ sessionId: IControllerRuntimeId & { harnessId: 'flex' };
29
+ sessionGenerationId: string;
30
+ /** Native authority assigns this only on materialization; absent while creation is pending. */
31
+ sessionGenerationSequence?: number;
32
+ sessionIdentityId?: string;
33
+ clientConversationId?: string;
34
+ serverSequence: number;
35
+ acceptedAt: number;
36
+ state: 'waiting' | 'handedOver' | 'held' | 'settled';
37
+ heldReason?: TControllerHeldPromptReason;
38
+ creation: 'pending' | 'ready' | 'uncertain' | 'retired';
39
+ }
40
+
41
+ export interface IReq_ControllerFlexSubmissionAdmit extends plugins.typedrequestInterfaces.implementsTR<plugins.typedrequestInterfaces.ITypedRequest, IReq_ControllerFlexSubmissionAdmit> {
42
+ method: 'controller.flex.submission.admit';
43
+ request: IControllerFlexSubmissionInput;
44
+ response: IControllerFlexSubmissionReceipt;
45
+ }
46
+
47
+ /** Exact readback only. An unknown result never authorizes an automatic resend. */
48
+ export interface IReq_ControllerFlexSubmissionGet extends plugins.typedrequestInterfaces.implementsTR<plugins.typedrequestInterfaces.ITypedRequest, IReq_ControllerFlexSubmissionGet> {
49
+ method: 'controller.flex.submission.get';
50
+ request: { version: 1; projectId: string; clientMessageId: string };
51
+ response: { version: 1; receipt: IControllerFlexSubmissionReceipt | null };
52
+ }
@@ -39,3 +39,5 @@ export * from './proxycapacity.js';
39
39
  export * from './devices.js';
40
40
  export * from './requests.devices.js';
41
41
  export * from './push.js';
42
+
43
+ export * from './flexadmission.js';
@@ -5,7 +5,7 @@ import type {
5
5
  TControllerBrowserPaintAvailability,
6
6
  TControllerBrowserPaintTermination,
7
7
  } from './browserpaint.js';
8
- export const controllerProtocolVersion = 53 as const;
8
+ export const controllerProtocolVersion = 54 as const;
9
9
  export const controllerUpgradeManagementVersion = 2 as const;
10
10
  export const controllerPackageName = 'agl' as const;
11
11
  /** The systemd user unit `agl service install` writes; a controller it runs reports it in its status. */
@@ -984,6 +984,15 @@ export interface IControllerNativeWait {
984
984
  }
985
985
 
986
986
  export interface IControllerSession {
987
+ /** Exact managed Flex identity for immutable admission, supplied without a transcript generation read. */
988
+ sessionIdentityId?: string;
989
+ /** Controller-owned conversation intent, discoverable before native materialization. */
990
+ flexAdmission?: {
991
+ clientConversationId?: string;
992
+ creation: 'pending' | 'ready' | 'uncertain' | 'retired';
993
+ sessionGenerationId: string;
994
+ sessionGenerationSequence?: number;
995
+ };
987
996
  id: IControllerRuntimeId;
988
997
  title: string;
989
998
  parentId?: IControllerRuntimeId;
@@ -1,3 +1,4 @@
1
+ import type { IReq_ControllerFlexSubmissionAdmit, IReq_ControllerFlexSubmissionGet } from './flexadmission.js';
1
2
  import type {
2
3
  IReq_ControllerConfigurationResourceGet,
3
4
  IReq_ControllerConfigurationStateGet,
@@ -241,6 +242,8 @@ export * from './requests.workspace.js';
241
242
  export * from './requests.events.js';
242
243
 
243
244
  export type TControllerRequest =
245
+ | IReq_ControllerFlexSubmissionAdmit
246
+ | IReq_ControllerFlexSubmissionGet
244
247
  | IReq_ControllerConfigurationResourceGet
245
248
  | IReq_ControllerConfigurationStateGet
246
249
  | IReq_ControllerConfigurationSummaryGet
@@ -144,6 +144,9 @@ export class FlexHarnessV3MigrationRunner {
144
144
  if (!await hasCompletedFlexV3Migration(this.store, storageKey)) {
145
145
  const legacySnapshot = await loadLegacyFlexSnapshot(this.store, storageKey);
146
146
  if (legacySnapshot) {
147
+ // A migration is not a recovery-aware writer: every write it makes of this namespace, in
148
+ // every domain, counts as unknown, so the next preparation qualifies the namespace again.
149
+ this.store.scopeRecovery.deactivateWriteProvenance(storageKey);
147
150
  await plugins.flexharnessMigration.migrateLegacyFlexHarnessSnapshot(
148
151
  storageKey,
149
152
  legacySnapshot,
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: 'agl',
6
- version: '43.14.0',
6
+ version: '44.0.0',
7
7
  description: 'Agent Gateway Layer for OpenCode, FlexHarness, and Codex sessions'
8
8
  }
@@ -0,0 +1,279 @@
1
+ const freezeSnapshot = <T>(valueArg: T): T => {
2
+ if (valueArg !== null && typeof valueArg === 'object') {
3
+ for (const value of Object.values(valueArg)) freezeSnapshot(value);
4
+ Object.freeze(valueArg);
5
+ }
6
+ return valueArg;
7
+ };
8
+
9
+ export type TBrowserSubmissionState = 'submitting' | 'admitted' | 'refused' | 'unknown' | 'blocked';
10
+
11
+ /** A click-time message, kept in this page's memory only until its exact durable owner appears. */
12
+ export interface IBrowserSubmission<TSnapshot, TReceipt> {
13
+ readonly id: string;
14
+ readonly scope: string;
15
+ readonly snapshot: TSnapshot;
16
+ readonly createdAt: number;
17
+ readonly state: TBrowserSubmissionState;
18
+ readonly attempted: boolean;
19
+ /** Sends refused with a transient code before this one; each was definitely not admitted. */
20
+ readonly retries: number;
21
+ readonly receipt?: TReceipt;
22
+ readonly error?: string;
23
+ }
24
+
25
+ export interface IBrowserSubmissionsOptions<TSnapshot, TReceipt> {
26
+ /** Resolves on durable admission, never on native creation or execution. */
27
+ admit(submissionArg: IBrowserSubmission<TSnapshot, TReceipt>): Promise<TReceipt>;
28
+ /** A missing receipt does not prove that an earlier admission did not happen. */
29
+ lookup(submissionArg: IBrowserSubmission<TSnapshot, TReceipt>): Promise<TReceipt | undefined>;
30
+ /**
31
+ * `definite`: the controller proved nothing was admitted. `transient`: a definite refusal whose
32
+ * cause may pass (the harness is starting, an operation limit), so the same ID with the same
33
+ * snapshot is sent again after a bounded backoff.
34
+ */
35
+ failure(errorArg: unknown): { definite: boolean; transient?: boolean; message: string };
36
+ changed(): void;
37
+ /** The waits before each resend of a transient refusal; its length bounds the resends. */
38
+ retryDelaysMs?: readonly number[];
39
+ /** A creation of unknown outcome keeps its dependent admissions fenced as well. */
40
+ canContinue?(receiptArg: TReceipt): boolean;
41
+ admitted?(submissionArg: IBrowserSubmission<TSnapshot, TReceipt>): void;
42
+ }
43
+
44
+ /** Waits before resending a transiently refused submission; three resends at most. */
45
+ export const defaultBrowserSubmissionRetryDelaysMs: readonly number[] = [500, 2_000, 5_000];
46
+
47
+ /**
48
+ * Admission order belongs to a browser conversation intent, not to native execution. An uncertain
49
+ * request fences later messages in that intent. Reconnection reads receipts only: an attempted
50
+ * snapshot is never sent again, including when lookup has not found a receipt yet. The one resend
51
+ * is of a definite refusal with a transient code: the same ID and snapshot, after a bounded backoff,
52
+ * while the conversation's later messages wait behind it. An unknown outcome, a lost connection or
53
+ * any other refusal is never resent.
54
+ */
55
+ export class BrowserSubmissions<TSnapshot, TReceipt> {
56
+ private entries: Array<IBrowserSubmission<TSnapshot, TReceipt>> = [];
57
+ private readonly draining = new Map<string, number>();
58
+ private readonly checking = new Map<string, Promise<void>>();
59
+ private readonly retryTimers = new Map<string, ReturnType<typeof setTimeout>>();
60
+ /** Rows asked to be read while a read of theirs was in flight. */
61
+ private readonly checkAgain = new Set<string>();
62
+ private epoch = 0;
63
+ private connected = true;
64
+ private disposed = false;
65
+
66
+ constructor(private readonly options: IBrowserSubmissionsOptions<TSnapshot, TReceipt>) {}
67
+
68
+ public get current(): readonly IBrowserSubmission<TSnapshot, TReceipt>[] {
69
+ return this.entries;
70
+ }
71
+
72
+ /** Capture and feedback are synchronous; neither waits for a draft write or an admission. */
73
+ public capture(idArg: string, scopeArg: string, snapshotArg: TSnapshot): IBrowserSubmission<TSnapshot, TReceipt> {
74
+ if (this.disposed) throw new Error('The browser submission queue is closed.');
75
+ if (this.entries.some((entry) => entry.id === idArg)) throw new Error('The submission ID is already in use.');
76
+ const fenced = !this.connected || this.entries.some((entry) => (
77
+ entry.scope === scopeArg && (entry.state === 'unknown' || entry.state === 'blocked'
78
+ || (entry.receipt !== undefined && this.options.canContinue?.(entry.receipt) === false))
79
+ ));
80
+ const entry: IBrowserSubmission<TSnapshot, TReceipt> = {
81
+ id: idArg,
82
+ scope: scopeArg,
83
+ snapshot: freezeSnapshot(structuredClone(snapshotArg)),
84
+ createdAt: Date.now(),
85
+ state: fenced ? 'blocked' : 'submitting',
86
+ attempted: false,
87
+ retries: 0,
88
+ };
89
+ this.entries = [...this.entries, entry];
90
+ this.options.changed();
91
+ void this.drain(scopeArg);
92
+ return entry;
93
+ }
94
+
95
+ /** The app tears down through this as well, so no resend timer outlives the connection. */
96
+ public disconnect(): void {
97
+ if (this.disposed) return;
98
+ this.connected = false;
99
+ this.epoch += 1;
100
+ this.clearRetryTimers();
101
+ this.entries = this.entries.map((entry) => entry.state === 'submitting'
102
+ ? { ...entry, state: entry.attempted ? 'unknown' : 'blocked',
103
+ error: entry.attempted ? 'Admission unconfirmed. Reconnect to check its receipt; this message will not be resent.' : undefined }
104
+ : entry);
105
+ this.options.changed();
106
+ }
107
+
108
+ /**
109
+ * Only reads are replayed after a disconnect, once per reconnection: an unknown outcome and every
110
+ * admitted receipt, whose changes the lost connection did not report. A receipt can release
111
+ * never-attempted followers.
112
+ */
113
+ public async reconnect(): Promise<void> {
114
+ if (this.disposed || this.connected) return;
115
+ this.connected = true;
116
+ await Promise.all(this.entries.filter((entry) => entry.state === 'unknown' || entry.state === 'admitted')
117
+ .map((entry) => this.check(entry.id)));
118
+ for (const scope of new Set(this.entries.map((entry) => entry.scope))) this.releaseFollowers(scope);
119
+ }
120
+
121
+ /**
122
+ * Reads the row's receipt; never sends. A check asked for while a read of the row is in flight
123
+ * may follow a change that read missed, so the row is read once more after it.
124
+ */
125
+ public check(idArg: string): Promise<void> {
126
+ const checking = this.checking.get(idArg);
127
+ if (checking) {
128
+ this.checkAgain.add(idArg);
129
+ return checking;
130
+ }
131
+ if (!this.checkable(idArg)) return Promise.resolve();
132
+ let task: Promise<void> | undefined;
133
+ task = (async () => {
134
+ try {
135
+ do {
136
+ this.checkAgain.delete(idArg);
137
+ await this.read(idArg);
138
+ } while (this.checkAgain.has(idArg) && this.checkable(idArg));
139
+ } finally {
140
+ // In the same turn as the last loop test: a check asked for later starts a read of its own.
141
+ this.checkAgain.delete(idArg);
142
+ if (this.checking.get(idArg) === task) this.checking.delete(idArg);
143
+ }
144
+ })();
145
+ this.checking.set(idArg, task);
146
+ return task;
147
+ }
148
+
149
+ /** Forget only rows an exact durable identity, not text or a timestamp, has replaced. */
150
+ public reconcile(isCarriedArg: (submissionArg: IBrowserSubmission<TSnapshot, TReceipt>) => boolean): void {
151
+ const kept = this.entries.filter((entry) => entry.state !== 'admitted'
152
+ || (entry.receipt !== undefined && this.options.canContinue?.(entry.receipt) === false)
153
+ || !isCarriedArg(entry));
154
+ if (kept.length === this.entries.length) return;
155
+ this.entries = kept;
156
+ this.options.changed();
157
+ }
158
+
159
+ public dispose(): void {
160
+ this.disposed = true;
161
+ this.epoch += 1;
162
+ this.entries = [];
163
+ this.clearRetryTimers();
164
+ }
165
+
166
+ private clearRetryTimers(): void {
167
+ for (const timer of this.retryTimers.values()) clearTimeout(timer);
168
+ this.retryTimers.clear();
169
+ }
170
+
171
+ private checkable(idArg: string): boolean {
172
+ const entry = this.entries.find((candidate) => candidate.id === idArg);
173
+ return entry !== undefined && (entry.state === 'unknown' || entry.state === 'admitted') && this.connected && !this.disposed;
174
+ }
175
+
176
+ private async read(idArg: string): Promise<void> {
177
+ const entry = this.entries.find((candidate) => candidate.id === idArg);
178
+ if (!entry || (entry.state !== 'unknown' && entry.state !== 'admitted') || !this.connected || this.disposed) return;
179
+ const epoch = this.epoch;
180
+ try {
181
+ const receipt = await this.options.lookup(entry);
182
+ if (this.disposed || epoch !== this.epoch || receipt === undefined) return;
183
+ const current = this.entries.find((candidate) => candidate.id === idArg);
184
+ if (!current) return;
185
+ if (current.state === 'admitted' && JSON.stringify(current.receipt) === JSON.stringify(receipt)) return;
186
+ const admitted = this.update(idArg, { state: 'admitted', receipt, error: undefined });
187
+ if (admitted) this.options.admitted?.(admitted);
188
+ if (this.options.canContinue?.(receipt) === false) this.blockFollowers(entry.scope);
189
+ else this.releaseFollowers(entry.scope);
190
+ } catch {
191
+ // A failed read proves nothing. Keep both the uncertain row and its dependent fence.
192
+ }
193
+ }
194
+
195
+ private async drain(scopeArg: string): Promise<void> {
196
+ const epoch = this.epoch;
197
+ if (this.disposed || !this.connected || this.scopeFenced(scopeArg) || this.draining.get(scopeArg) === epoch
198
+ || this.retryTimers.has(scopeArg)) return;
199
+ this.draining.set(scopeArg, epoch);
200
+ try {
201
+ while (!this.disposed && this.connected && epoch === this.epoch) {
202
+ const entry = this.entries.find((candidate) => candidate.scope === scopeArg
203
+ && (candidate.state === 'submitting' || candidate.state === 'unknown' || candidate.state === 'blocked'));
204
+ if (!entry || entry.state !== 'submitting' || entry.attempted) return;
205
+ const attempted = this.update(entry.id, { attempted: true })!;
206
+ try {
207
+ const receipt = await this.options.admit(attempted);
208
+ if (this.disposed || epoch !== this.epoch) return;
209
+ const admitted = this.update(entry.id, { state: 'admitted', receipt, error: undefined });
210
+ if (admitted) this.options.admitted?.(admitted);
211
+ if (this.options.canContinue?.(receipt) === false) {
212
+ this.blockFollowers(scopeArg);
213
+ return;
214
+ }
215
+ } catch (errorArg) {
216
+ if (this.disposed || epoch !== this.epoch) return;
217
+ const failure = this.options.failure(errorArg);
218
+ const delays = this.options.retryDelaysMs ?? defaultBrowserSubmissionRetryDelaysMs;
219
+ if (failure.definite && failure.transient && attempted.retries < delays.length) {
220
+ // Nothing was admitted: the same snapshot goes again under its ID once the wait ends.
221
+ this.update(entry.id, { attempted: false, retries: attempted.retries + 1 });
222
+ this.scheduleRetry(scopeArg, delays[attempted.retries]!);
223
+ return;
224
+ }
225
+ this.update(entry.id, { state: failure.definite ? 'refused' : 'unknown', error: failure.message });
226
+ if (!failure.definite) {
227
+ this.blockFollowers(scopeArg);
228
+ return;
229
+ }
230
+ }
231
+ }
232
+ } finally {
233
+ if (this.draining.get(scopeArg) === epoch) this.draining.delete(scopeArg);
234
+ // A receipt lookup may have resolved while the old connection's request was still settling.
235
+ if (!this.disposed && this.connected && !this.scopeFenced(scopeArg) && !this.retryTimers.has(scopeArg)
236
+ && this.entries.some((entry) => entry.scope === scopeArg && entry.state === 'submitting')) {
237
+ void this.drain(scopeArg);
238
+ }
239
+ }
240
+ }
241
+
242
+ private scheduleRetry(scopeArg: string, delayMsArg: number): void {
243
+ if (this.retryTimers.has(scopeArg)) return;
244
+ this.retryTimers.set(scopeArg, setTimeout(() => {
245
+ this.retryTimers.delete(scopeArg);
246
+ void this.drain(scopeArg);
247
+ }, delayMsArg));
248
+ }
249
+
250
+ private scopeFenced(scopeArg: string): boolean {
251
+ return this.entries.some((entry) => entry.scope === scopeArg
252
+ && (entry.state === 'unknown' || (entry.receipt !== undefined && this.options.canContinue?.(entry.receipt) === false)));
253
+ }
254
+
255
+ private blockFollowers(scopeArg: string): void {
256
+ this.entries = this.entries.map((entry) => entry.scope === scopeArg && entry.state === 'submitting' && !entry.attempted
257
+ ? { ...entry, state: 'blocked' } : entry);
258
+ this.options.changed();
259
+ }
260
+
261
+ private releaseFollowers(scopeArg: string): void {
262
+ if (this.scopeFenced(scopeArg)) return;
263
+ this.entries = this.entries.map((entry) => entry.scope === scopeArg && entry.state === 'blocked' && !entry.attempted
264
+ ? { ...entry, state: 'submitting', error: undefined } : entry);
265
+ this.options.changed();
266
+ void this.drain(scopeArg);
267
+ }
268
+
269
+ private update(idArg: string, patchArg: Partial<IBrowserSubmission<TSnapshot, TReceipt>>): IBrowserSubmission<TSnapshot, TReceipt> | undefined {
270
+ let updated: IBrowserSubmission<TSnapshot, TReceipt> | undefined;
271
+ this.entries = this.entries.map((entry) => {
272
+ if (entry.id !== idArg) return entry;
273
+ updated = { ...entry, ...patchArg };
274
+ return updated;
275
+ });
276
+ if (updated) this.options.changed();
277
+ return updated;
278
+ }
279
+ }