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,6 +217,47 @@ export class ControllerPendingPromptStore {
217
217
  }).then(() => settled);
218
218
  }
219
219
 
220
+ /**
221
+ * Authoritative admission: the callback commits this exact waiting owner together with its
222
+ * immutable receipt/conversation intent. No asynchronous mirror constitutes acceptance.
223
+ * The transfer pins ownership until the derived in-memory queue has published the operation.
224
+ */
225
+ public admit(recordArg: IPendingPromptRecord, commitArg: (documentArg: IControllerPendingPromptDocument) => Promise<void>): Promise<void> {
226
+ if (this.closed) return Promise.reject(new Error('Pending message persistence is closed.'));
227
+ const record = { ...cloneRecord(recordArg), dispatch: 'waiting' as const };
228
+ return this.enqueue(async () => {
229
+ this.transfers.set(record.promptId, record);
230
+ try {
231
+ await commitArg(this.documentOf(record));
232
+ } catch (errorArg) {
233
+ if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) === 'not_committed') this.transfers.delete(record.promptId);
234
+ throw errorArg;
235
+ }
236
+ const key = this.sessionKey(record.projectId, record.sessionId);
237
+ const stored = this.stored.get(key) ?? new Set<string>();
238
+ stored.add(record.promptId);
239
+ this.stored.set(key, stored);
240
+ this.desired.set(key, [...(this.desired.get(key) ?? []).filter(entry => entry.promptId !== record.promptId), record]);
241
+ });
242
+ }
243
+
244
+ /** Legacy Flex callers share the same awaited pending owner, without a browser receipt. */
245
+ public admitExisting(recordArg: IPendingPromptRecord): Promise<void> {
246
+ return this.admit(recordArg, async documentArg => {
247
+ const transaction = this.database.createSession();
248
+ try {
249
+ await transaction.withTransaction(async session => {
250
+ const inserted = await ControllerPendingPromptModel.exact.insert(documentArg, { session });
251
+ if (inserted.status !== 'inserted') throw new Error('The pending input identity is already admitted.');
252
+ }, { timeoutMS: 20_000 });
253
+ } catch (errorArg) {
254
+ if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) === 'not_committed') throw errorArg;
255
+ const stored = await ControllerPendingPromptModel.exact.findStoredOne({ id: documentArg.id });
256
+ if (!stored || !plugins.util.isDeepStrictEqual(ControllerPendingPromptModel.exact.toPersisted(stored), documentArg)) throw errorArg;
257
+ } finally { await transaction.close().catch(errorArg => console.error('Closing pending admission failed.', errorArg)); }
258
+ });
259
+ }
260
+
220
261
  /** Stores the conversation's queued and steering messages as they are now. */
221
262
  public sync(
222
263
  projectIdArg: string,
@@ -238,8 +279,8 @@ export class ControllerPendingPromptStore {
238
279
  * Marks the conversation's live messages `promptIdsArg` as handed to their runtime, durably when
239
280
  * the promise resolves. Every native dispatch of a message that left the controller's queue awaits
240
281
  * it after the queue claim and before the native call, so a message stored as `waiting` can never
241
- * have reached its runtime. A message that is not stored, and that no write in progress stores,
242
- * takes the mark from the caller's mirror (`sync`) when it is written, without waiting here.
282
+ * have reached its runtime. A missing record is inserted from its exact admitted owner, and
283
+ * an absent owner refuses the dispatch instead of pretending its hand-over was durable.
243
284
  */
244
285
  public recordHandOver(
245
286
  projectIdArg: string,
@@ -252,17 +293,25 @@ export class ControllerPendingPromptStore {
252
293
  this.desired.set(key, (this.desired.get(key) ?? []).map((record) => (
253
294
  ids.has(record.promptId) && record.heldReason === undefined ? { ...record, dispatch: 'handedOver' as const } : record
254
295
  )));
255
- if (!this.flushing.has(key) && ![...ids].some((id) => this.stored.get(key)?.has(id))) return Promise.resolve();
256
296
  return this.enqueue(async () => {
257
297
  for (const id of ids) {
258
- if (!this.stored.get(key)?.has(id)) continue;
259
- const current = await ControllerPendingPromptModel.exact.findStoredOne({ id });
260
- if (!current) continue;
298
+ let current = await ControllerPendingPromptModel.exact.findStoredOne({ id });
299
+ if (!current) {
300
+ const record = this.transfers.get(id) ?? this.desired.get(key)?.find(entry => entry.promptId === id);
301
+ if (!record || record.heldReason !== undefined) throw new Error('The pending message has no durable admission owner.');
302
+ await this.insert({ ...record, dispatch: 'handedOver' });
303
+ current = await ControllerPendingPromptModel.exact.findStoredOne({ id });
304
+ if (!current) throw new Error('The pending message hand-over could not be confirmed.');
305
+ const stored = this.stored.get(key) ?? new Set<string>();
306
+ stored.add(id);
307
+ this.stored.set(key, stored);
308
+ }
261
309
  const document = ControllerPendingPromptModel.exact.toPersisted(current);
262
310
  if (document.controllerId !== this.controllerId || document.projectId !== projectIdArg
263
311
  || !plugins.util.isDeepStrictEqual(document.sessionId, sessionIdArg)) {
264
312
  throw new Error('The pending message belongs to another conversation.');
265
313
  }
314
+ // A held row being resent is rewritten by its transfer; held rows carry no dispatch mark.
266
315
  if (document.heldReason !== undefined || document.dispatch === 'handedOver') continue;
267
316
  const candidate: IControllerPendingPromptDocument = { ...document, dispatch: 'handedOver' };
268
317
  try {
@@ -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,
@@ -5,7 +5,7 @@ import {
5
5
  type TTicketLink, type TTicketOperation, type TTicketRequest, type TTicketResponse,
6
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
- type ITicketOverviewRequest, type ITicketPageRequest, ticketPageErrorMessages,
8
+ type ITicketOverviewRequest, type ITicketPageRequest, ticketPageErrorMessages, ticketBusyErrorMessages,
9
9
  } from '../ts_interfaces/tickets.js';
10
10
  import { TicketCursorError, ticketOverview, ticketPage } from './functions.ticketlisting.js';
11
11
  import {
@@ -71,10 +71,12 @@ interface ITicketTrack {
71
71
  /**
72
72
  * Every code a `TicketError` carries: a refusal `ticketErrorMessages` explains, a concurrent change the transaction
73
73
  * lost (`concurrent_change`, nothing written), a transaction whose commit outcome is unknown (`outcome_unknown`), a
74
- * fleet event key that names another request, and an owner capability the controller could not verify.
74
+ * fleet event key that names another request, and an owner capability the controller could not verify. A transaction
75
+ * that reached its deadline before its commit is `ticket_busy` (`ticketBusyErrorMessages`): nothing was written, and the
76
+ * request may be made again.
75
77
  */
76
- export type TTicketErrorCode = keyof typeof ticketErrorMessages | keyof typeof ticketPageErrorMessages | 'concurrent_change' | 'outcome_unknown'
77
- | 'ticket_fleet_event_conflict' | 'unauthorized';
78
+ export type TTicketErrorCode = keyof typeof ticketErrorMessages | keyof typeof ticketPageErrorMessages
79
+ | keyof typeof ticketBusyErrorMessages | 'concurrent_change' | 'outcome_unknown' | 'ticket_fleet_event_conflict' | 'unauthorized';
78
80
 
79
81
  export class TicketError extends Error {
80
82
  constructor(public readonly code: TTicketErrorCode, messageArg: string, public readonly currentRevision?: number) {
@@ -481,6 +483,11 @@ export class TicketStore {
481
483
  if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) !== 'not_committed') {
482
484
  throw new TicketError('outcome_unknown', 'The ticket transaction outcome is unknown; read the board before retrying.');
483
485
  }
486
+ // The deadline expired before the commit: the board stayed busy (lost write conflicts or a slow database) and
487
+ // nothing was written, so the request may be made again. A cancellation and a store shutdown keep their errors.
488
+ if (errorArg instanceof plugins.nosqldb.SmartdataPersistenceError && errorArg.code === 'timeout') {
489
+ throw new TicketError('ticket_busy', ticketBusyErrorMessages.ticket_busy);
490
+ }
484
491
  if (errorArg instanceof TicketError && errorArg.code === 'ticket_revision_conflict' && track?.refusal) {
485
492
  this.observe({ changes: [track.refusal] });
486
493
  }
@@ -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',
@@ -447,12 +449,14 @@ export const deviceDirectReportJobRefusal = (jobArg: IFleetWorkerJob): plugins.t
447
449
  /**
448
450
  * How the ticket store's refusals outside `ticketErrorMessages` reach a device: a concurrent change the transaction lost
449
451
  * wrote nothing and reads as the board having changed meanwhile; a commit whose outcome is unknown may have happened,
450
- * which a client never resends but reads the ticket again to learn; a fleet event's conflict and an owner capability the
451
- * controller could not verify answer no device request.
452
+ * which a client never resends but reads the ticket again to learn; a transaction that reached its deadline before its
453
+ * commit (`ticket_busy`) changed nothing and reads as the controller being busy, to be tried again; a fleet event's
454
+ * conflict and an owner capability the controller could not verify answer no device request.
452
455
  */
453
456
  const deviceTicketStoreRefusals: Readonly<Record<Exclude<TTicketErrorCode, keyof typeof ticketErrorMessages>, TDeviceRefusalCode>> = {
454
457
  concurrent_change: 'ticket_revision_conflict',
455
458
  outcome_unknown: 'outcome_unknown',
459
+ ticket_busy: 'operation_limit',
456
460
  ticket_fleet_event_conflict: 'invalid_request',
457
461
  unauthorized: 'invalid_request',
458
462
  ticket_cursor_invalid: 'invalid_request',
@@ -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
@@ -503,6 +503,16 @@ export const ticketPageErrorMessages = {
503
503
  ticket_cursor_invalid: 'The cursor is not the nextCursor of a ticket page; list again without cursor.',
504
504
  ticket_cursor_mismatch: 'The cursor pages other filters, another sort or another view; repeat those or list again without cursor.',
505
505
  } as const;
506
- export type TTicketClientErrorCode = Uppercase<keyof typeof ticketErrorMessages | keyof typeof ticketPageErrorMessages>;
507
- export const ticketClientErrorMessages = Object.fromEntries(Object.entries({ ...ticketErrorMessages, ...ticketPageErrorMessages })
506
+ /**
507
+ * A ticket transaction that reached its deadline before its commit: the board stayed busy, nothing was changed, and the
508
+ * request may be made again. Kept apart from `ticketErrorMessages`, which the device contract lists code by code: a
509
+ * device reads it as `operation_limit`.
510
+ */
511
+ export const ticketBusyErrorMessages = {
512
+ ticket_busy: 'The ticket board was too busy to carry out this request in time, and nothing was changed: read the ticket, then try again.',
513
+ } as const;
514
+ export type TTicketClientErrorCode = Uppercase<keyof typeof ticketErrorMessages | keyof typeof ticketPageErrorMessages
515
+ | keyof typeof ticketBusyErrorMessages>;
516
+ export const ticketClientErrorMessages = Object.fromEntries(Object.entries({ ...ticketErrorMessages, ...ticketPageErrorMessages,
517
+ ...ticketBusyErrorMessages })
508
518
  .map(([codeArg, messageArg]) => [codeArg.toUpperCase(), messageArg])) as Record<TTicketClientErrorCode, string>;
@@ -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.13.0',
6
+ version: '44.0.0',
7
7
  description: 'Agent Gateway Layer for OpenCode, FlexHarness, and Codex sessions'
8
8
  }