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
@@ -1,3 +1,7 @@
1
+ import { FlexSubmissionError } from './classes.flexsubmissionstore.js';
2
+ import type { IFlexAdmissionConversationDocument } from './classes.flexsubmissionmodels.js';
3
+ import type { IControllerFlexSubmissionInput, IControllerFlexSubmissionReceipt, IReq_ControllerFlexSubmissionAdmit, IReq_ControllerFlexSubmissionGet } from '../ts_interfaces/flexadmission.js';
4
+ import { assertFlexSubmissionAdmitRequest, assertFlexSubmissionGetRequest } from './classes.validation.js';
1
5
  import { flexMessageDeliveryProof, type TFlexDeliveryEvidence, type TFlexDeliveryProof } from './functions.flexdeliveryproof.js';
2
6
  import { FleetWorkers, fleetNativeSessionNames } from './fleet/classes.workers.js';
3
7
  import { FleetTicketEffects } from './fleet/classes.ticketeffects.js';
@@ -574,6 +578,7 @@ import {
574
578
  type TFlexHostRequestMethod,
575
579
  type TFlexHostResponse,
576
580
  type TFlexSessionGeneration,
581
+ type TFlexSessionDeletionResult,
577
582
  } from './interfaces.flexipc.js';
578
583
  import { SessionIntelligenceReader } from './classes.sessionintelligencereader.js';
579
584
  import {
@@ -696,6 +701,8 @@ const requireFlexSessionProviderGeneration = (sessionArg: TFlexSession): string
696
701
  const isManagedRuntimeId = (
697
702
  runtimeIdArg: IControllerRuntimeId,
698
703
  ): runtimeIdArg is TControllerSessionId => runtimeIdArg.harnessId !== 'controller';
704
+ /** What the controller does with a Flex deletion obligation after FlexHarness's answer. */
705
+ type TFlexDeletionSettlement = 'complete' | 'retire';
699
706
  /**
700
707
  * A lease or catalog Flex asked of AGL's inference proxy and did not get: an account the proxy found needing a sign-in
701
708
  * (`account_needs_login`) is `PROVIDER_REAUTH_REQUIRED`, which Accounts repairs; anything else is the proxy being
@@ -2956,6 +2963,7 @@ const asTypedResponseError = (
2956
2963
  if (errorArg instanceof ConfigurationError) {
2957
2964
  return new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
2958
2965
  }
2966
+ if (errorArg instanceof FlexSubmissionError) return new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
2959
2967
  if (errorArg instanceof ControllerDraftConflictError) {
2960
2968
  return new plugins.typedrequest.TypedResponseError(errorArg.message, { code: 'concurrent_change' });
2961
2969
  }
@@ -3272,6 +3280,8 @@ export class OpenCodeController {
3272
3280
  private readonly finishedFlexSteerRuns = new Map<string, IFlexSteerRunFinish>();
3273
3281
  /** The messages the conversations have not taken in; set once the controller loaded them. */
3274
3282
  private pendingPromptStore?: ControllerPendingPromptStore;
3283
+ private readonly flexAdmissionCreationPending = new Set<string>();
3284
+ private readonly flexAdmissionCreationTasks = new Map<string, Promise<void>>();
3275
3285
  /** Removals of stored message files, run one after another. */
3276
3286
  private attachmentCollection: Promise<void> = Promise.resolve();
3277
3287
  /** The engine that keeps the files of accepted messages; only this controller process runs it. */
@@ -4373,6 +4383,8 @@ export class OpenCodeController {
4373
4383
  progressArg,
4374
4384
  signalArg,
4375
4385
  ),
4386
+ steerPrompt: (submissionArg, progressArg, signalArg) => this.steerFlexTurn(submissionArg, progressArg, signalArg),
4387
+ waitForProjectReady: (projectIdArg, signalArg) => this.requireFlexSupervisor().waitForProjectReady(projectIdArg, signalArg),
4376
4388
  hasRejoinablePrompts: (projectIdArg, sessionIdArg, resendArg) => (
4377
4389
  this.hasRejoinablePrompts(projectIdArg, sessionIdArg, resendArg)
4378
4390
  ),
@@ -7033,6 +7045,13 @@ export class OpenCodeController {
7033
7045
  conversations.push(this.toTrackedConversation(entry, project, session));
7034
7046
  }
7035
7047
  }
7048
+ const listed = new Set(conversations.map(entry => this.sessionStateMutationKey(entry.projectId, entry.session.id)));
7049
+ for (const intent of await this.listUnfinishedFlexAdmissions()) {
7050
+ if (listed.has(this.sessionStateMutationKey(intent.projectId, intent.content.sessionId))) continue;
7051
+ const project = await this.requireAuthStore().getProject(intent.projectId);
7052
+ if (!project || project.removalStartedAt || project.removedAt) continue;
7053
+ conversations.push({ projectId: project.id, projectName: project.name, session: this.provisionalFlexSession(intent), origin: 'created', trackedAt: intent.content.creationRequestedAt ?? 0 });
7054
+ }
7036
7055
  // Active conversations order by live harness activity; AGL-archived ones order by when
7037
7056
  // they were archived, because their session timestamps come from a cache.
7038
7057
  conversations.sort((left, right) => {
@@ -7601,8 +7620,11 @@ export class OpenCodeController {
7601
7620
  ? await this.listManagedClaudeSessions(projectId, signalArg)
7602
7621
  : [];
7603
7622
  const driverNativeIds = await this.driverNativeIds(projectId, sessions);
7623
+ const provisional = (await this.listUnfinishedFlexAdmissions(projectId))
7624
+ .filter(intent => !sessions.some(session => controllerRuntimeIdKey(session.id) === controllerRuntimeIdKey(intent.content.sessionId)))
7625
+ .map(intent => this.provisionalFlexSession(intent));
7604
7626
  return {
7605
- sessions: [...sessions, ...codexSessions, ...claudeSessions].filter((session) => (
7627
+ sessions: [...sessions, ...codexSessions, ...claudeSessions, ...provisional].filter((session) => (
7606
7628
  session.id.harnessId !== 'flex' || !driverNativeIds.has(session.id.nativeId)
7607
7629
  )).map((session) => ({
7608
7630
  ...session,
@@ -7615,6 +7637,44 @@ export class OpenCodeController {
7615
7637
  );
7616
7638
  }
7617
7639
 
7640
+ /**
7641
+ * The admitted Flex conversations whose native creation is unfinished, read from the store only
7642
+ * while this controller knows of one (`flexAdmissionCreationPending`): lists never pay for it otherwise.
7643
+ */
7644
+ private async listUnfinishedFlexAdmissions(projectIdArg?: string): Promise<IFlexAdmissionConversationDocument[]> {
7645
+ const prefix = projectIdArg === undefined ? undefined : `${projectIdArg}\0`;
7646
+ if (![...this.flexAdmissionCreationPending].some((key) => prefix === undefined || key.startsWith(prefix))) return [];
7647
+ return this.requireAuthStore().requireFlexSubmissions().listUnfinishedConversations(projectIdArg);
7648
+ }
7649
+
7650
+ private provisionalFlexSession(conversationArg: IFlexAdmissionConversationDocument): IControllerSession {
7651
+ const content = conversationArg.content;
7652
+ return { id: content.sessionId, title: content.title ?? 'New Flex conversation', createdAt: content.creationRequestedAt ?? 0,
7653
+ updatedAt: content.creationRequestedAt ?? 0, status: content.creation === 'uncertain' ? 'error' : 'idle',
7654
+ ...(content.sessionIdentityId === undefined ? {} : { sessionIdentityId: content.sessionIdentityId }),
7655
+ flexAdmission: { ...(content.clientConversationId === undefined ? {} : { clientConversationId: content.clientConversationId }),
7656
+ creation: content.creation, sessionGenerationId: content.sessionGenerationId,
7657
+ ...(content.sessionGenerationSequence === undefined ? {} : { sessionGenerationSequence: content.sessionGenerationSequence }) } };
7658
+ }
7659
+
7660
+ /**
7661
+ * The detail of an admitted Flex conversation FlexHarness has not created yet. Only conversations
7662
+ * whose creation is unfinished (`flexAdmissionCreationPending`) are looked up: every other read
7663
+ * goes to the child as before, with no extra store read.
7664
+ */
7665
+ private async provisionalFlexDetail(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<IControllerSessionDetail | undefined> {
7666
+ if (sessionIdArg.harnessId !== 'flex') return undefined;
7667
+ if (!this.flexAdmissionCreationPending.has(this.sessionStateMutationKey(projectIdArg, sessionIdArg))) return undefined;
7668
+ const conversation = await this.requireAuthStore().requireFlexSubmissions().conversation(projectIdArg, sessionIdArg);
7669
+ if (!conversation || conversation.content.creation === 'ready' || conversation.content.creation === 'retired') return undefined;
7670
+ const state = await this.requireAuthStore().getSessionState(projectIdArg, sessionIdArg);
7671
+ return { session: this.provisionalFlexSession(conversation), messagePage: { bundles: [] },
7672
+ pendingPrompts: this.pendingPromptsForSession(projectIdArg, sessionIdArg, []), permissions: [], questions: [], elicitations: [], todos: [],
7673
+ scratchpad: state.scratchpad, intelligenceExchanges: state.intelligenceExchanges,
7674
+ ...(state.modelChoice === undefined ? {} : { modelChoice: state.modelChoice }), ...(state.providerConnectionId === undefined ? {} : { providerConnectionId: state.providerConnectionId }),
7675
+ toolStreamCursor: this.getFlexToolStreamCursor(), messageStreamCursor: this.getFlexMessageStreamCursor() };
7676
+ }
7677
+
7618
7678
  private async readSessionForPrincipal(
7619
7679
  principalArg: TControllerOperationPrincipal,
7620
7680
  peerIdArg: string,
@@ -7630,6 +7690,8 @@ export class OpenCodeController {
7630
7690
  },
7631
7691
  async () => {
7632
7692
  const project = await this.resolveProject(projectId);
7693
+ const provisional = await this.provisionalFlexDetail(projectId, sessionId);
7694
+ if (provisional) return provisional;
7633
7695
  await this.assertSessionIsNotIntelligenceTemporary(projectId, sessionId, signalArg);
7634
7696
  await this.assertSessionExists(projectId, sessionId, signalArg);
7635
7697
  if (sessionId.harnessId === 'codex') return this.readCodexSessionDetail(projectId, sessionId.nativeId, signalArg);
@@ -8147,6 +8209,20 @@ export class OpenCodeController {
8147
8209
  await store.transferHeld(requestArg.promptId, this.pendingPromptRecordOf({ reservation: operation }));
8148
8210
  transferredStore = store;
8149
8211
  }
8212
+ if (sessionId.harnessId === 'flex') operation = this.harnessOperationManager.bindPromptSelection(operation, selectedModel, selectedProviderConnectionId);
8213
+ // `transferHeld` committed the resend's pending owner before any dispatch, as an admission
8214
+ // does: the input is durably admitted, so a steer the ending run refuses returns to the queue.
8215
+ if (sessionId.harnessId === 'flex' && requestArg.source === 'held') this.harnessOperationManager.admitInput(operation);
8216
+ if (sessionId.harnessId === 'flex' && requestArg.source !== 'held') {
8217
+ const pending = this.openPendingPromptStore();
8218
+ if (pending) {
8219
+ await pending.admitExisting({ ...this.pendingPromptRecordOf({ reservation: operation }),
8220
+ ...(selectedModel === undefined ? {} : { model: selectedModel }),
8221
+ ...(selectedProviderConnectionId === undefined ? {} : { providerConnectionId: selectedProviderConnectionId }) });
8222
+ transferredStore = pending;
8223
+ this.harnessOperationManager.admitInput(operation);
8224
+ }
8225
+ }
8150
8226
  if (sessionId.harnessId === 'opencode') {
8151
8227
  if (this.queueOpenCodePromptIfBlocked({
8152
8228
  operation,
@@ -8554,6 +8630,183 @@ export class OpenCodeController {
8554
8630
  );
8555
8631
  }
8556
8632
 
8633
+ /**
8634
+ * Commits immutable browser input before any native create/start/provider validation. Admission
8635
+ * neither waits for nor refuses a Flex reconciliation or project readiness: it takes the auth
8636
+ * store's project mutation lane, commits one transaction and answers. Dispatch waits instead.
8637
+ */
8638
+ private async admitFlexSubmission(inputArg: IControllerFlexSubmissionInput, signalArg: AbortSignal): Promise<IControllerFlexSubmissionReceipt> {
8639
+ if (this.lifecycleState !== 'ready' || this.stopRequested) throw new plugins.typedrequest.TypedResponseError('The controller is not accepting input.', { code: 'controller_unavailable' });
8640
+ const authStore = this.requireAuthStore();
8641
+ return authStore.withFlexSubmissionAdmission(inputArg.projectId, async ledger => {
8642
+ const duplicate = await ledger.existing(inputArg);
8643
+ if (duplicate) return duplicate; // Never redispatch a receipt, even after a lost acknowledgement.
8644
+ const configurationRevision = inputArg.conversation.kind === 'new'
8645
+ ? (await this.configurationAuthority?.getInstalledFlexProjection())?.revision : undefined;
8646
+ const conversation = await ledger.resolve(inputArg, configurationRevision);
8647
+ const sessionId = conversation.content.sessionId;
8648
+ const release = this.reserveHarnessSubmissionAdmission(inputArg.projectId, sessionId, true);
8649
+ let operation: TControllerHarnessOperationReservation | undefined;
8650
+ let committed = false;
8651
+ try {
8652
+ signalArg.throwIfAborted();
8653
+ this.assertSessionMutationAdmission(inputArg.projectId, sessionId, true);
8654
+ operation = await this.harnessOperationManager.reserveMessage(inputArg.projectId, sessionId, {
8655
+ text: inputArg.text, attachments: inputArg.attachments, model: inputArg.model, providerConnectionId: inputArg.providerConnectionId, durableAdmission: true,
8656
+ }, inputArg.delivery);
8657
+ if (inputArg.attachments.length > 0) operation = await this.storeOperationAttachments(operation);
8658
+ const reserved = operation;
8659
+ const admission = await ledger.admit(inputArg, conversation, this.pendingPromptRecordOf({ reservation: reserved }), () => {
8660
+ this.assertSessionMutationAdmission(inputArg.projectId, sessionId, true);
8661
+ this.harnessOperationManager.assertDurableAdmissionCurrent(reserved);
8662
+ }, signalArg);
8663
+ if (admission.status === 'duplicate') {
8664
+ // This reservation committed nothing; the earlier admission owns the message.
8665
+ await this.harnessOperationManager.fail(reserved);
8666
+ operation = undefined;
8667
+ return admission.receipt;
8668
+ }
8669
+ const receipt = admission.receipt;
8670
+ committed = true;
8671
+ // The pending owner is committed, so the input is durably admitted (as `controller.session.send`
8672
+ // records it): a dispatch the child refused before taking it, such as a steer of a run that
8673
+ // was already ending, returns it to the queue instead of holding it as uncertain.
8674
+ this.harnessOperationManager.admitInput(operation);
8675
+ const key = this.sessionStateMutationKey(inputArg.projectId, sessionId);
8676
+ if (conversation.content.creation !== 'ready') this.flexAdmissionCreationPending.add(key);
8677
+ this.flexPromptQueue.admit({ operation, prompt: harnessOperationPrompt(operation), model: inputArg.model, providerConnectionId: inputArg.providerConnectionId });
8678
+ this.openPendingPromptStore()!.finishTransfer(operation.operationId);
8679
+ // The shared composer is cleared only while it still holds exactly what was sent, at the
8680
+ // revision the click captured: later typing is a newer revision and stays. A draft that
8681
+ // differs is never a reason to refuse the immutable message.
8682
+ if (inputArg.capturedDraft) {
8683
+ this.harnessOperationManager.clearCapturedDraft(inputArg.projectId, sessionId, inputArg.capturedDraft.revision, {
8684
+ text: inputArg.text,
8685
+ attachments: inputArg.attachments,
8686
+ });
8687
+ }
8688
+ this.claimUnusedSession(inputArg.projectId, sessionId);
8689
+ this.queueHarnessPromptChanged(inputArg.projectId, sessionId);
8690
+ if (conversation.content.creation === 'pending') this.scheduleFlexAdmissionCreation(conversation);
8691
+ return receipt;
8692
+ } catch (errorArg) {
8693
+ if (operation) {
8694
+ if (committed || errorArg instanceof FlexSubmissionError && errorArg.code === 'outcome_unknown') this.harnessOperationManager.markOutcomeUnknown(operation);
8695
+ else await this.harnessOperationManager.fail(operation);
8696
+ }
8697
+ throw errorArg;
8698
+ } finally { release(); }
8699
+ });
8700
+ }
8701
+
8702
+ /**
8703
+ * Starts the native creation of an admitted conversation that is still `pending`, once per
8704
+ * conversation at a time. Its messages wait in the queue meanwhile (`flexAdmissionCreationPending`).
8705
+ */
8706
+ private scheduleFlexAdmissionCreation(conversationArg: IFlexAdmissionConversationDocument): void {
8707
+ const key = this.sessionStateMutationKey(conversationArg.projectId, conversationArg.content.sessionId);
8708
+ if (this.flexAdmissionCreationTasks.has(key)) return;
8709
+ const task = this.trackOperationPromise(
8710
+ Promise.resolve().then(() => this.materializeFlexAdmissionConversation(conversationArg)),
8711
+ ).finally(() => {
8712
+ if (this.flexAdmissionCreationTasks.get(key) === task) this.flexAdmissionCreationTasks.delete(key);
8713
+ });
8714
+ this.flexAdmissionCreationTasks.set(key, task);
8715
+ void task.catch((errorArg) => console.error('Creating a Flex conversation with admitted messages failed.', errorArg));
8716
+ }
8717
+
8718
+ /**
8719
+ * Creates the native conversation an admission reserved: project readiness first (outside the
8720
+ * creation's control budget), then the durable dispatch mark, then `session.create` under the
8721
+ * reserved id and generation. A failure before the child could have taken the creation leaves the
8722
+ * conversation `pending` (the next admission to it, or the next child generation, tries again);
8723
+ * one after leaves it `uncertain` until the next generation's recovery reads the native catalog.
8724
+ * The admitted messages are never held or resent by this: they stay queued for the conversation.
8725
+ */
8726
+ private async materializeFlexAdmissionConversation(conversationArg: IFlexAdmissionConversationDocument): Promise<void> {
8727
+ const { projectId } = conversationArg;
8728
+ const sessionId = conversationArg.content.sessionId;
8729
+ const key = this.sessionStateMutationKey(projectId, sessionId);
8730
+ const store = this.requireAuthStore();
8731
+ const submissions = store.requireFlexSubmissions();
8732
+ const release = this.reserveHarnessSubmissionAdmission(projectId, sessionId);
8733
+ let dispatched = false;
8734
+ try {
8735
+ const current = await submissions.conversation(projectId, sessionId);
8736
+ if (!current || current.content.creation !== 'pending') return;
8737
+ const { content } = current;
8738
+ const obligation = await store.getSessionCreationObligation({ projectIdentityId: projectId, runtimeId: sessionId });
8739
+ if (!obligation || obligation.state !== 'pending') {
8740
+ throw new FlexSubmissionError('outcome_unknown', 'The reserved Flex conversation has no pending creation.');
8741
+ }
8742
+ const supervisor = this.requireFlexSupervisor();
8743
+ const signal = this.operationAbortController.signal;
8744
+ await supervisor.waitForProjectReady(projectId, signal);
8745
+ const authority = this.requireFlexRuntimeExitAuthority(supervisor);
8746
+ this.assertSessionMutationAdmission(projectId, sessionId);
8747
+ if (obligation.dispatchStartedAt === undefined) {
8748
+ await store.markManagedSessionCreationDispatched({
8749
+ projectIdentityId: projectId,
8750
+ runtimeId: sessionId,
8751
+ operationId: obligation.operationId,
8752
+ dispatchStartedAt: new Date(),
8753
+ });
8754
+ }
8755
+ dispatched = true;
8756
+ const raw = await supervisor.request('session.create', {
8757
+ scopeId: projectId,
8758
+ options: {
8759
+ sessionId: sessionId.nativeId,
8760
+ sessionGenerationId: content.sessionGenerationId,
8761
+ ...(content.title === undefined ? {} : { title: content.title }),
8762
+ ...(content.configurationRevision === undefined ? {} : { configurationRef: content.configurationRevision }),
8763
+ },
8764
+ }, AbortSignal.any([signal, authority.signal]));
8765
+ this.assertFlexSessionIdentityGenerationCurrent(supervisor, authority);
8766
+ if (
8767
+ raw.sessionId !== sessionId.nativeId
8768
+ || raw.sessionGenerationId !== content.sessionGenerationId
8769
+ || raw.configurationRef !== content.configurationRevision
8770
+ ) throw new Error('Flex created another conversation than the admission reserved.');
8771
+ const generation = requireFlexSessionGeneration(raw);
8772
+ await this.configurationAuthority?.captureFlexSessionRevision({
8773
+ projectId,
8774
+ sessionId: raw.sessionId,
8775
+ ...generation,
8776
+ revision: raw.configurationRef ?? null,
8777
+ });
8778
+ const managed = await store.completeManagedSessionCreationAdmission({
8779
+ projectIdentityId: projectId,
8780
+ runtimeId: sessionId,
8781
+ operationId: obligation.operationId,
8782
+ supervisorGeneration: authority.sessionIdentityGeneration,
8783
+ providerSessionGeneration: requireFlexSessionProviderGeneration(raw),
8784
+ ...generation,
8785
+ terminalAt: new Date(),
8786
+ signal,
8787
+ });
8788
+ this.setManagedSessionAuthority(projectId, sessionId, 'managed', managed.identity.sessionIdentityId);
8789
+ await submissions.setCreation(projectId, sessionId, 'ready', {
8790
+ ...generation,
8791
+ sessionIdentityId: managed.identity.sessionIdentityId,
8792
+ });
8793
+ await this.trackCreatedConversation(projectId, this.toFlexSession(raw), managed.identity.sessionIdentityId);
8794
+ this.flexAdmissionCreationPending.delete(key);
8795
+ this.invalidateHarnessSessionEnumeration(projectId);
8796
+ this.queueFlexControllerEvent({ type: 'sessions.changed', harnessId: 'flex', projectId, timestamp: Date.now() });
8797
+ this.flexPromptQueue.schedule(projectId, sessionId);
8798
+ } catch (errorArg) {
8799
+ // The child may have created the conversation once the request could have reached it.
8800
+ if (dispatched && flexStartFailureHeldReason({ started: true, accepted: false }, errorArg) === 'uncertain') {
8801
+ await submissions.setCreation(projectId, sessionId, 'uncertain');
8802
+ }
8803
+ this.queueHarnessSessionError(projectId, sessionId);
8804
+ throw errorArg;
8805
+ } finally {
8806
+ release();
8807
+ }
8808
+ }
8809
+
8557
8810
  private async createSessionForPrincipal(
8558
8811
  principalArg: TControllerOperationPrincipal,
8559
8812
  peerIdArg: string,
@@ -8610,7 +8863,11 @@ export class OpenCodeController {
8610
8863
  });
8611
8864
  let dispatchStarted = false;
8612
8865
  try {
8613
- if (harnessId === 'flex') signalArg.throwIfAborted();
8866
+ if (harnessId === 'flex') {
8867
+ // The project's preparation can outlast the creation's control budget: wait for it first.
8868
+ await this.requireFlexSupervisor().waitForProjectReady(projectId, signalArg);
8869
+ signalArg.throwIfAborted();
8870
+ }
8614
8871
  const dispatchStartedAt = new Date();
8615
8872
  await this.requireAuthStore().markManagedSessionCreationDispatched({
8616
8873
  projectIdentityId: projectId,
@@ -10967,6 +11224,10 @@ export class OpenCodeController {
10967
11224
  this.attachmentStore = await ControllerAttachmentStore.open(await objectStorage.start());
10968
11225
  this.assertStartActive();
10969
11226
  const pendingPromptStore = authStore.requirePendingPrompts();
11227
+ this.flexAdmissionCreationPending.clear();
11228
+ for (const intent of await authStore.requireFlexSubmissions().listConversations()) {
11229
+ if (intent.content.creation !== 'ready' && intent.content.creation !== 'retired') this.flexAdmissionCreationPending.add(this.sessionStateMutationKey(intent.projectId, intent.content.sessionId));
11230
+ }
10970
11231
  await pendingPromptStore.load((projectIdArg, sessionIdArg) => (
10971
11232
  armedFlexHolds.has(this.sessionStateMutationKey(projectIdArg, sessionIdArg))
10972
11233
  ));
@@ -12630,7 +12891,7 @@ export class OpenCodeController {
12630
12891
  || cleanupRoot.sessionId !== obligation.runtimeId.nativeId
12631
12892
  || cleanupRoot.providerSessionGeneration !== obligation.providerSessionGeneration
12632
12893
  ) throw new Error('The Flex deletion obligation has no exact cleanup cohort.');
12633
- await supervisorArg.request('session.delete', {
12894
+ const answer = await supervisorArg.request('session.delete', {
12634
12895
  scopeId: projectArg.id,
12635
12896
  root: {
12636
12897
  sessionId: cleanupRoot.sessionId,
@@ -12643,16 +12904,71 @@ export class OpenCodeController {
12643
12904
  sessionGenerationSequence: entry.sessionGenerationSequence,
12644
12905
  })),
12645
12906
  }, signalArg);
12646
- await this.completeRecoveredManagedSessionDeletion(projectArg, obligation, signalArg);
12907
+ const settlement = await this.settleFlexSessionDeletionAnswer(projectArg.id, obligation.runtimeId, {
12908
+ sessionGenerationId: cleanupRoot.sessionGenerationId,
12909
+ sessionGenerationSequence: cleanupRoot.sessionGenerationSequence,
12910
+ }, answer);
12911
+ await this.completeRecoveredManagedSessionDeletion(projectArg, obligation, signalArg, false, settlement);
12647
12912
  }
12648
12913
  }
12649
12914
 
12915
+ /**
12916
+ * What AGL ends of a Flex session's records after FlexHarness answered its generation-fenced
12917
+ * deletion of `obligationGenerationArg` (ruling 2026-11-18): `matched` ends them as before, and
12918
+ * FlexHarness's deletion already ended a document whose project-management record it held;
12919
+ * `absent` ends the session state in one mutation (`settleAbsentFlexSessionState`) unless a live
12920
+ * record of another generation holds the id; `superseded`, or that record, retires the obligation
12921
+ * with nothing keyed by the id touched, named in the controller log with both generations.
12922
+ */
12923
+ private async settleFlexSessionDeletionAnswer(
12924
+ projectIdArg: string,
12925
+ sessionIdArg: IControllerRuntimeId,
12926
+ obligationGenerationArg: TFlexSessionGeneration,
12927
+ answerArg: TFlexSessionDeletionResult,
12928
+ ): Promise<TFlexDeletionSettlement> {
12929
+ if (answerArg.matched) return 'complete';
12930
+ let holder: TFlexSessionGeneration;
12931
+ if (answerArg.reason === 'superseded') {
12932
+ holder = answerArg.current;
12933
+ } else {
12934
+ const settled = await this.requireAuthStore().settleAbsentFlexSessionState(
12935
+ projectIdArg,
12936
+ sessionIdArg,
12937
+ obligationGenerationArg,
12938
+ );
12939
+ if (settled.outcome === 'ended') return 'complete';
12940
+ holder = settled.generation;
12941
+ }
12942
+ const name = (generationArg: TFlexSessionGeneration): string => (
12943
+ `${JSON.stringify(generationArg.sessionGenerationId)}#${generationArg.sessionGenerationSequence}`
12944
+ );
12945
+ console.error(`The deletion of Flex session ${JSON.stringify(sessionIdArg.nativeId)} in project ${
12946
+ JSON.stringify(projectIdArg)} for generation ${name(obligationGenerationArg)} met generation ${
12947
+ name(holder)}, which holds the id now; the deletion is retired and that generation is left as it is.`);
12948
+ return 'retire';
12949
+ }
12950
+
12650
12951
  private async completeRecoveredManagedSessionDeletion(
12651
12952
  projectArg: IControllerProjectDocument,
12652
12953
  obligationArg: IControllerManagedSessionDeletionObligation,
12653
12954
  signalArg: AbortSignal,
12654
12955
  projectRemovalArg = false,
12956
+ settlementArg: TFlexDeletionSettlement = 'complete',
12655
12957
  ): Promise<void> {
12958
+ if (settlementArg === 'retire') {
12959
+ // Another generation holds the session id: the obligation retires and nothing keyed by the
12960
+ // id (state, layout, harness operations, pending messages) is touched.
12961
+ const retire = projectRemovalArg
12962
+ ? this.requireAuthStore().completeManagedSessionDeletionForProjectRemoval.bind(this.requireAuthStore())
12963
+ : this.requireAuthStore().completeManagedSessionDeletion.bind(this.requireAuthStore());
12964
+ await retire({
12965
+ projectIdentityId: projectArg.id,
12966
+ runtimeId: obligationArg.runtimeId,
12967
+ operationId: obligationArg.operationId,
12968
+ retiredAt: new Date(),
12969
+ });
12970
+ return;
12971
+ }
12656
12972
  const cleanupObligations = await this.requireAuthStore().getSessionIntelligenceCleanupObligations(
12657
12973
  projectArg.id,
12658
12974
  obligationArg.runtimeId,
@@ -12786,37 +13102,52 @@ export class OpenCodeController {
12786
13102
  }
12787
13103
  }
12788
13104
 
13105
+ /**
13106
+ * Settles the project's Flex creations a child generation left unfinished, from the native
13107
+ * catalog (`session.identities`, metadata only). A creation without admitted messages completes
13108
+ * when its conversation exists with the expected generation and retires otherwise. One that
13109
+ * admitted messages own is never retired here: it completes when the conversation exists; when it
13110
+ * does not, the creation never took effect (an earlier generation's request is over), so it is
13111
+ * `pending` again and the next creation attempt sends it under the same id and generation. A
13112
+ * conversation that exists under another generation stays `uncertain` for the user to inspect.
13113
+ */
12789
13114
  private async recoverFlexManagedSessionCreations(
12790
13115
  projectArg: IControllerProjectDocument,
12791
13116
  supervisorArg: FlexSupervisor,
12792
13117
  supervisorGenerationArg: string,
12793
13118
  signalArg: AbortSignal,
12794
13119
  ): Promise<void> {
12795
- const obligations = await this.requireAuthStore().listPendingSessionCreationObligations({
13120
+ const store = this.requireAuthStore();
13121
+ const obligations = await store.listPendingSessionCreationObligations({
12796
13122
  projectIdentityId: projectArg.id,
12797
13123
  harnessId: 'flex',
12798
13124
  signal: signalArg,
12799
13125
  });
13126
+ const identities = obligations.some((obligation) => obligation.dispatchStartedAt !== undefined)
13127
+ ? (await supervisorArg.request('session.identities', { scopeId: projectArg.id }, signalArg)).sessions
13128
+ : [];
13129
+ if (obligations.length === 0) return;
13130
+ const submissions = store.requireFlexSubmissions();
12800
13131
  for (const obligation of obligations) {
12801
13132
  signalArg.throwIfAborted();
12802
- let current: TFlexSession | undefined;
12803
- if (obligation.dispatchStartedAt !== undefined) {
12804
- try {
12805
- current = await supervisorArg.request('session.get', {
12806
- scopeId: projectArg.id,
12807
- sessionId: obligation.runtimeId.nativeId,
12808
- }, signalArg);
12809
- } catch (errorArg) {
12810
- if (!(errorArg instanceof FlexServiceError) || errorArg.code !== 'NOT_FOUND') throw errorArg;
13133
+ const key = this.sessionStateMutationKey(projectArg.id, obligation.runtimeId);
13134
+ // A creation in flight in this generation owns its own outcome.
13135
+ if (this.flexAdmissionCreationTasks.has(key)) continue;
13136
+ const intent = await submissions.conversation(projectArg.id, obligation.runtimeId);
13137
+ const admitted = intent !== undefined && intent.content.creation !== 'retired';
13138
+ const current = obligation.dispatchStartedAt === undefined
13139
+ ? undefined
13140
+ : identities.find((identity) => identity.sessionId === obligation.runtimeId.nativeId);
13141
+ const created = current !== undefined
13142
+ && obligation.expectedFlexSessionGenerationId !== undefined
13143
+ && current.sessionGenerationId === obligation.expectedFlexSessionGenerationId;
13144
+ if (!created) {
13145
+ if (admitted) {
13146
+ await submissions.setCreation(projectArg.id, obligation.runtimeId, current === undefined ? 'pending' : 'uncertain');
13147
+ this.flexAdmissionCreationPending.add(key);
13148
+ continue;
12811
13149
  }
12812
- }
12813
- if (
12814
- !current
12815
- || obligation.dispatchStartedAt === undefined
12816
- || obligation.expectedFlexSessionGenerationId === undefined
12817
- || current.sessionGenerationId !== obligation.expectedFlexSessionGenerationId
12818
- ) {
12819
- await this.requireAuthStore().retireManagedSessionCreation({
13150
+ await store.retireManagedSessionCreation({
12820
13151
  projectIdentityId: projectArg.id,
12821
13152
  runtimeId: obligation.runtimeId,
12822
13153
  operationId: obligation.operationId,
@@ -12825,26 +13156,46 @@ export class OpenCodeController {
12825
13156
  this.deleteManagedSessionAuthorityCacheEntry(projectArg.id, obligation.runtimeId);
12826
13157
  continue;
12827
13158
  }
12828
- const observation = await this.requireAuthStore().completeManagedSessionCreationAdmission({
13159
+ const generation = {
13160
+ sessionGenerationId: current.sessionGenerationId,
13161
+ sessionGenerationSequence: current.sessionGenerationSequence,
13162
+ };
13163
+ const observation = await store.completeManagedSessionCreationAdmission({
12829
13164
  projectIdentityId: projectArg.id,
12830
13165
  runtimeId: obligation.runtimeId,
12831
13166
  operationId: obligation.operationId,
12832
13167
  supervisorGeneration: supervisorGenerationArg,
12833
- providerSessionGeneration: requireFlexSessionProviderGeneration(current),
12834
- sessionGenerationId: current.sessionGenerationId,
12835
- sessionGenerationSequence: current.sessionGenerationSequence,
13168
+ providerSessionGeneration: flexSessionProviderGeneration(generation.sessionGenerationId, generation.sessionGenerationSequence),
13169
+ ...generation,
12836
13170
  terminalAt: new Date(),
12837
13171
  signal: signalArg,
12838
13172
  });
12839
- this.setManagedSessionAuthority(
13173
+ this.setManagedSessionAuthority(projectArg.id, obligation.runtimeId, 'managed', observation.identity.sessionIdentityId);
13174
+ if (!admitted) continue;
13175
+ const ready = { ...generation, sessionIdentityId: observation.identity.sessionIdentityId };
13176
+ await submissions.setCreation(projectArg.id, obligation.runtimeId, 'ready', ready);
13177
+ this.flexAdmissionCreationPending.delete(key);
13178
+ await this.trackCreatedConversation(
12840
13179
  projectArg.id,
12841
- obligation.runtimeId,
12842
- 'managed',
13180
+ this.provisionalFlexSession({ ...intent, content: { ...intent.content, creation: 'ready', ...ready } }),
12843
13181
  observation.identity.sessionIdentityId,
12844
13182
  );
12845
13183
  }
12846
13184
  }
12847
13185
 
13186
+ /**
13187
+ * Once a project's session authority is reconciled, starts every admitted conversation creation
13188
+ * still `pending`. Conversations recovery found created are scheduled with the project's other
13189
+ * queues (`reconcileFlexPromptActivity`).
13190
+ */
13191
+ private resumeFlexAdmissionCreations(projectIdArg: string): void {
13192
+ void this.trackOperationPromise((async () => {
13193
+ for (const conversation of await this.listUnfinishedFlexAdmissions(projectIdArg)) {
13194
+ if (conversation.content.creation === 'pending') this.scheduleFlexAdmissionCreation(conversation);
13195
+ }
13196
+ })()).catch((errorArg) => console.error('Resuming admitted Flex conversation creations failed.', errorArg));
13197
+ }
13198
+
12848
13199
  private async ensureFlexProjectionReader(): Promise<void> {
12849
13200
  if (this.flexProjectionReader) {
12850
13201
  if (this.flexProjectionReaderReady) return;
@@ -16506,6 +16857,7 @@ export class OpenCodeController {
16506
16857
  const executeFlex = async (
16507
16858
  flexModel: IFlexModelChoice,
16508
16859
  ): Promise<IReq_ControllerSlashExecute['response']> => {
16860
+ await this.requireFlexSupervisor().waitForProjectReady(projectId, signalArg);
16509
16861
  this.harnessOperationManager.assertCurrentHarnessAdmission(reservedOperation);
16510
16862
  submissionStarted = true;
16511
16863
  const result = await this.requireFlexSupervisor().request('slash.execute', {
@@ -17714,6 +18066,20 @@ export class OpenCodeController {
17714
18066
  },
17715
18067
  );
17716
18068
 
18069
+ protectedRouterArg.addHandler<IReq_ControllerFlexSubmissionAdmit>('controller.flex.submission.admit', async (requestArg, toolsArg) => {
18070
+ const input = validateRequest(() => assertFlexSubmissionAdmitRequest(requestArg));
18071
+ const peer = peerFromLocalData(toolsArg?.localData);
18072
+ return this.runOperation(peer, signal => this.runAudited({ type: 'session.send', peerId: peer.id }, () => this.admitFlexSubmission(input, signal)));
18073
+ });
18074
+ protectedRouterArg.addHandler<IReq_ControllerFlexSubmissionGet>('controller.flex.submission.get', async (requestArg, toolsArg) => {
18075
+ const input = validateRequest(() => assertFlexSubmissionGetRequest(requestArg));
18076
+ const peer = peerFromLocalData(toolsArg?.localData);
18077
+ return this.runOperation(peer, async () => {
18078
+ await this.resolveProject(input.projectId);
18079
+ return { version: 1, receipt: await this.requireAuthStore().requireFlexSubmissions().get(input.projectId, input.clientMessageId) };
18080
+ });
18081
+ });
18082
+
17717
18083
  protectedRouterArg.addHandler<IReq_ControllerSessionSend>(
17718
18084
  'controller.session.send',
17719
18085
  async (requestArg, toolsArg) => {
@@ -20923,6 +21289,7 @@ export class OpenCodeController {
20923
21289
  signalArg,
20924
21290
  );
20925
21291
  let dispatchedObligation = obligation;
21292
+ let settlement: TFlexDeletionSettlement = 'complete';
20926
21293
  if (obligation.runtimeId.harnessId !== 'flex') {
20927
21294
  if (obligation.dispatchStartedAt === undefined) {
20928
21295
  dispatchedObligation = await this.requireAuthStore()
@@ -20955,7 +21322,7 @@ export class OpenCodeController {
20955
21322
  throw new Error('A managed Flex root was absent from project cleanup authority.');
20956
21323
  }
20957
21324
  } else {
20958
- await this.requireFlexSupervisor().request('session.delete', {
21325
+ const answer = await this.requireFlexSupervisor().request('session.delete', {
20959
21326
  scopeId: projectArg.id,
20960
21327
  root: {
20961
21328
  sessionId: cleanupRoot.sessionId,
@@ -20968,6 +21335,10 @@ export class OpenCodeController {
20968
21335
  sessionGenerationSequence: entry.sessionGenerationSequence,
20969
21336
  })),
20970
21337
  }, signalArg);
21338
+ settlement = await this.settleFlexSessionDeletionAnswer(projectArg.id, dispatchedObligation.runtimeId, {
21339
+ sessionGenerationId: cleanupRoot.sessionGenerationId,
21340
+ sessionGenerationSequence: cleanupRoot.sessionGenerationSequence,
21341
+ }, answer);
20971
21342
  }
20972
21343
  }
20973
21344
  await this.completeRecoveredManagedSessionDeletion(
@@ -20975,6 +21346,7 @@ export class OpenCodeController {
20975
21346
  dispatchedObligation,
20976
21347
  signalArg,
20977
21348
  true,
21349
+ settlement,
20978
21350
  );
20979
21351
  }
20980
21352
  const [remainingCreations, remainingDeletions] = await Promise.all([
@@ -21152,6 +21524,7 @@ export class OpenCodeController {
21152
21524
  );
21153
21525
  this.flexProjectIdentityRecoveryPending.delete(current.id);
21154
21526
  this.reconcileFlexPromptActivity(current.id);
21527
+ this.resumeFlexAdmissionCreations(current.id);
21155
21528
  }
21156
21529
  return { projects, availableProjects, flexSynchronized: true };
21157
21530
  } catch (errorArg) {
@@ -21347,11 +21720,13 @@ export class OpenCodeController {
21347
21720
  }
21348
21721
  await this.retireProjectSessionIntelligence(project.id, signalArg);
21349
21722
  if (removeMetadataOnly) {
21350
- // Retire controller metadata, but retain artifacts scoped to the untrusted path.
21723
+ // Retire controller metadata, but retain artifacts scoped to the untrusted path; a live
21724
+ // Flex project-management record stays FlexHarness's, so only AGL's own fields go.
21351
21725
  await this.requireAuthStore().retireProjectSessionStates(
21352
21726
  project.id,
21353
21727
  async () => undefined,
21354
21728
  signalArg,
21729
+ 'metadata-only',
21355
21730
  );
21356
21731
  } else {
21357
21732
  await this.requireAuthStore().retireProjectSessionStates(
@@ -21379,6 +21754,8 @@ export class OpenCodeController {
21379
21754
  gitReversion.unregisterProject(project.id);
21380
21755
  }
21381
21756
  await this.harnessOperationManager.purgeProject(project.id);
21757
+ // Receipts and conversation intents live as long as their project and go with it.
21758
+ await this.requireAuthStore().requireFlexSubmissions().purgeProject(project.id);
21382
21759
  for (const setId of await this.openPendingPromptStore()?.purgeProject(project.id) ?? []) {
21383
21760
  await this.collectAttachmentSet(setId);
21384
21761
  }
@@ -23077,7 +23454,9 @@ export class OpenCodeController {
23077
23454
  : sessionArg.status === 'failed'
23078
23455
  ? 'error'
23079
23456
  : 'idle';
23457
+ const managed = this.managedSessionAuthorities.get(this.managedSessionAuthorityKey(sessionArg.scopeId, flexRuntimeId(sessionArg.sessionId)));
23080
23458
  return {
23459
+ ...(managed?.state === 'managed' ? { sessionIdentityId: managed.sessionIdentityId } : {}),
23081
23460
  id: flexRuntimeId(sessionArg.sessionId),
23082
23461
  // FlexHarness's preview, the first prompt, names a session nobody titled.
23083
23462
  title: sessionArg.title || sessionArg.preview || 'Untitled session',
@@ -23452,18 +23831,20 @@ export class OpenCodeController {
23452
23831
  });
23453
23832
  }
23454
23833
 
23834
+ /** `durableAdmissionArg`: a durable Flex admission, which a Flex reconciliation does not refuse. */
23455
23835
  private reserveHarnessSubmissionAdmission(
23456
23836
  projectIdArg: string,
23457
23837
  sessionIdArg: IControllerRuntimeId,
23838
+ durableAdmissionArg = false,
23458
23839
  ): () => void {
23459
- this.assertSessionMutationAdmission(projectIdArg, sessionIdArg);
23840
+ this.assertSessionMutationAdmission(projectIdArg, sessionIdArg, durableAdmissionArg);
23460
23841
  const projectRelease = this.reserveAdmissionEntry(
23461
23842
  this.projectHarnessSubmissionAdmissions,
23462
23843
  projectIdArg,
23463
23844
  );
23464
23845
  const sessionKey = this.sessionStateMutationKey(projectIdArg, sessionIdArg);
23465
23846
  try {
23466
- this.assertSessionMutationAdmission(projectIdArg, sessionIdArg);
23847
+ this.assertSessionMutationAdmission(projectIdArg, sessionIdArg, durableAdmissionArg);
23467
23848
  } catch (errorArg) {
23468
23849
  projectRelease();
23469
23850
  throw errorArg;
@@ -23473,7 +23854,7 @@ export class OpenCodeController {
23473
23854
  sessionKey,
23474
23855
  );
23475
23856
  try {
23476
- this.assertSessionMutationAdmission(projectIdArg, sessionIdArg);
23857
+ this.assertSessionMutationAdmission(projectIdArg, sessionIdArg, durableAdmissionArg);
23477
23858
  } catch (errorArg) {
23478
23859
  sessionRelease();
23479
23860
  projectRelease();
@@ -23621,9 +24002,14 @@ export class OpenCodeController {
23621
24002
  await this.waitForAdmissionDrain(this.projectArchiveAdmissions.get(projectIdArg)?.drained, signalArg);
23622
24003
  }
23623
24004
 
24005
+ /**
24006
+ * `durableAdmissionArg`: a durable Flex admission only commits records, so a Flex reconciliation
24007
+ * does not refuse it; the queue dispatches it once the reconciliation finished.
24008
+ */
23624
24009
  private assertSessionMutationAdmission(
23625
24010
  projectIdArg: string,
23626
24011
  sessionIdArg: IControllerRuntimeId,
24012
+ durableAdmissionArg = false,
23627
24013
  ): void {
23628
24014
  if (sessionIdArg.harnessId === 'codex') this.requireCodexClient(sessionIdArg.nativeId);
23629
24015
  if (sessionIdArg.harnessId === 'claude') this.requireClaudeHarness();
@@ -23633,7 +24019,7 @@ export class OpenCodeController {
23633
24019
  { code: 'project_not_found' },
23634
24020
  );
23635
24021
  }
23636
- if (this.flexProjectIdentityRecoveryPending.has(projectIdArg)) {
24022
+ if (!durableAdmissionArg && this.flexProjectIdentityRecoveryPending.has(projectIdArg)) {
23637
24023
  throw new plugins.typedrequest.TypedResponseError(
23638
24024
  'The requested Flex project is reconciling session authority.',
23639
24025
  { code: 'concurrent_change' },
@@ -26686,6 +27072,16 @@ export class OpenCodeController {
26686
27072
  ));
26687
27073
  const queueId = running?.flexQueueId;
26688
27074
  if (queueId === undefined) return false;
27075
+ // A steer joins the running turn only on that turn's model; another model starts its own turn.
27076
+ if (submissionArg.model && submissionArg.providerConnectionId && running?.flexModel
27077
+ && !plugins.util.isDeepStrictEqual(this.toFlexModelChoice(submissionArg.model, submissionArg.providerConnectionId), running.flexModel)) return false;
27078
+ await this.requireFlexSupervisor().waitForProjectReady(projectId, signalArg);
27079
+ // Input the controller admitted durably is marked handed over before the child can see it.
27080
+ if (this.harnessOperationManager.getOperation(operation)?.inputAccepted) {
27081
+ const pending = this.openPendingPromptStore();
27082
+ if (!pending) throw new Error('Durable Flex input has no pending owner.');
27083
+ await pending.recordHandOver(projectId, sessionId, [operation.operationId]);
27084
+ }
26689
27085
  this.harnessOperationManager.assertCurrentHarnessAdmission(operation);
26690
27086
  // Bound first, so a steer whose answer is lost still settles with its run.
26691
27087
  this.harnessOperationManager.bindFlexSteer(operation, queueId, running!.flexRunId!);
@@ -28501,7 +28897,8 @@ export class OpenCodeController {
28501
28897
  return sessionIdArg.harnessId === 'flex'
28502
28898
  && this.sessionPromptQueueIsOpen(projectIdArg, sessionIdArg)
28503
28899
  && this.flexIsOperational()
28504
- && !this.flexProjectIdentityRecoveryPending.has(projectIdArg);
28900
+ && !this.flexProjectIdentityRecoveryPending.has(projectIdArg)
28901
+ && !this.flexAdmissionCreationPending.has(this.sessionStateMutationKey(projectIdArg, sessionIdArg));
28505
28902
  }
28506
28903
 
28507
28904
  private scheduleQueuedOpenCodePrompt(
@@ -28735,10 +29132,10 @@ export class OpenCodeController {
28735
29132
  snapshotArg: Pick<IControllerHarnessOperationSnapshot, 'reservation' | 'handedOver'>,
28736
29133
  ): IPendingPromptRecord {
28737
29134
  const { reservation } = snapshotArg;
28738
- const model = reservation.source === 'direct' ? reservation.direct.model : undefined;
28739
- const providerConnectionId = reservation.source === 'direct'
29135
+ const model = reservation.selection?.model ?? (reservation.source === 'direct' ? reservation.direct.model : undefined);
29136
+ const providerConnectionId = reservation.selection?.providerConnectionId ?? (reservation.source === 'direct'
28740
29137
  ? reservation.direct.providerConnectionId
28741
- : undefined;
29138
+ : undefined);
28742
29139
  const sender = reservation.source === 'direct' ? reservation.direct.sender : undefined;
28743
29140
  // A message is accepted only once its files are stored, so its record names them by their set.
28744
29141
  if (harnessOperationAttachments(reservation).length > 0 && reservation.attachmentSet === undefined) {
@@ -31380,6 +31777,8 @@ export class OpenCodeController {
31380
31777
  }, eventArg);
31381
31778
  return;
31382
31779
  }
31780
+ // The supervisor keeps project preparation for its readiness waits; it never reaches here.
31781
+ if (eventArg.type === 'project.preparation') return;
31383
31782
 
31384
31783
  const jobKey = controllerRuntimeIdKey(flexRuntimeId(eventArg.jobId));
31385
31784
  const cached = this.flexRefreshJobs.get(jobKey);
@@ -34278,6 +34677,43 @@ export class OpenCodeController {
34278
34677
  );
34279
34678
  job?.abortController.abort(new Error('The source session was deleted.'));
34280
34679
  if (job?.task) await Promise.allSettled([job.task]);
34680
+ // An admitted conversation FlexHarness never created has nothing native to delete.
34681
+ if (sessionIdArg.harnessId === 'flex' && this.flexAdmissionCreationPending.has(sessionKey)) {
34682
+ const store = this.requireAuthStore();
34683
+ const flexSessionId = flexRuntimeId(sessionIdArg.nativeId);
34684
+ const intent = await store.requireFlexSubmissions().conversation(projectIdArg, flexSessionId);
34685
+ const obligation = intent && intent.content.creation !== 'ready'
34686
+ ? await store.getSessionCreationObligation({ projectIdentityId: projectIdArg, runtimeId: flexSessionId }) : undefined;
34687
+ if (intent && intent.content.creation !== 'ready' && obligation && obligation.dispatchStartedAt === undefined) {
34688
+ // A live project-management record means FlexHarness knew a session under this id: the
34689
+ // conversation was not "never created", so FlexHarness's deletion of that record's
34690
+ // generation decides what ends, never a tombstone of AGL's.
34691
+ const recordGeneration = await store.liveFlexProjectManagementGeneration(projectIdArg, sessionIdArg);
34692
+ if (recordGeneration) {
34693
+ const answer = await this.requireFlexSupervisor().request('session.delete', {
34694
+ scopeId: projectIdArg,
34695
+ root: { sessionId: sessionIdArg.nativeId, ...recordGeneration },
34696
+ authorizedCohort: [{ sessionId: sessionIdArg.nativeId, ...recordGeneration }],
34697
+ }, signalArg);
34698
+ if (await this.settleFlexSessionDeletionAnswer(projectIdArg, sessionIdArg, recordGeneration, answer) === 'retire') {
34699
+ throw new plugins.typedrequest.TypedResponseError(
34700
+ 'Another generation of this Flex conversation holds its id; nothing was deleted.',
34701
+ { code: 'concurrent_change' },
34702
+ );
34703
+ }
34704
+ }
34705
+ if (obligation.state === 'pending') await store.retireManagedSessionCreation({ projectIdentityId: projectIdArg, runtimeId: flexSessionId, operationId: obligation.operationId, terminalAt: new Date() });
34706
+ await store.requireFlexSubmissions().setCreation(projectIdArg, sessionIdArg, 'retired');
34707
+ await this.harnessOperationManager.purgeSession(projectIdArg, sessionIdArg);
34708
+ for (const setId of await this.openPendingPromptStore()?.purgeSession(projectIdArg, sessionIdArg) ?? []) await this.collectAttachmentSet(setId);
34709
+ await store.tombstoneSessionState(projectIdArg, sessionIdArg);
34710
+ this.flexAdmissionCreationPending.delete(sessionKey);
34711
+ await this.pruneSessionFromLayout(projectIdArg, sessionIdArg);
34712
+ this.queueFlexControllerEvent({ type: 'sessions.changed', harnessId: 'flex', projectId: projectIdArg, timestamp: Date.now() });
34713
+ durableDeletionCompleted = true;
34714
+ return true;
34715
+ }
34716
+ }
34281
34717
  try {
34282
34718
  const deleted = await this.requireResourceCoordinator().withSessionDeletion(
34283
34719
  projectIdArg,
@@ -34348,7 +34784,7 @@ export class OpenCodeController {
34348
34784
  if (!cleanupCohort || !cleanupRoot) {
34349
34785
  throw new Error('The Flex deletion obligation has no exact cleanup cohort.');
34350
34786
  }
34351
- await this.requireFlexSupervisor().request('session.delete', {
34787
+ const answer = await this.requireFlexSupervisor().request('session.delete', {
34352
34788
  scopeId: projectIdArg,
34353
34789
  root: {
34354
34790
  sessionId: cleanupRoot.sessionId,
@@ -34361,6 +34797,24 @@ export class OpenCodeController {
34361
34797
  sessionGenerationSequence: entry.sessionGenerationSequence,
34362
34798
  })),
34363
34799
  }, signalArg);
34800
+ const settlement = await this.settleFlexSessionDeletionAnswer(projectIdArg, sessionIdArg, {
34801
+ sessionGenerationId: cleanupRoot.sessionGenerationId,
34802
+ sessionGenerationSequence: cleanupRoot.sessionGenerationSequence,
34803
+ }, answer);
34804
+ if (settlement === 'retire') {
34805
+ // Another generation holds the session id: the obligation retires and nothing keyed by
34806
+ // the id (state, layout, harness operations, pending messages) is touched.
34807
+ await this.requireAuthStore().completeManagedSessionDeletion({
34808
+ projectIdentityId: projectIdArg,
34809
+ runtimeId: requireManagedRuntimeId(sessionIdArg),
34810
+ operationId: operationIdArg,
34811
+ retiredAt: new Date(),
34812
+ });
34813
+ durableDeletionCompleted = true;
34814
+ this.invalidateHarnessSessionEnumeration(projectIdArg);
34815
+ this.queueFlexControllerEvent({ type: 'sessions.changed', harnessId: 'flex', projectId: projectIdArg, timestamp: Date.now() });
34816
+ return true;
34817
+ }
34364
34818
  }
34365
34819
  if (!alreadyTombstoned) {
34366
34820
  await this.requireAuthStore().tombstoneSessionState(projectIdArg, sessionIdArg);
@@ -34403,6 +34857,10 @@ export class OpenCodeController {
34403
34857
  } catch (errorArg) {
34404
34858
  console.error('Untracking the deleted conversation failed.', errorArg);
34405
34859
  }
34860
+ if (sessionIdArg.harnessId === 'flex') {
34861
+ await this.requireAuthStore().requireFlexSubmissions().setCreation(projectIdArg, sessionIdArg, 'retired');
34862
+ this.flexAdmissionCreationPending.delete(sessionKey);
34863
+ }
34406
34864
  durableDeletionCompleted = true;
34407
34865
  this.forgetFlexSessionRuntimeState(projectIdArg, sessionIdArg);
34408
34866
  retiredAuthorityToken = this.markRetiredSessionAuthority(