agl 43.14.0 → 44.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/changelog.md +22 -0
  2. package/dist_serve/bundle.js +4473 -4235
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +29 -29
  5. package/dist_serve/bundle.js.third-party-notices.txt +29 -29
  6. package/dist_ts/00_commitinfo_data.js +2 -2
  7. package/dist_ts/aglapi/aglapisurface.document.js +37 -4
  8. package/dist_ts/classes.authstore.d.ts +60 -3
  9. package/dist_ts/classes.authstore.js +161 -13
  10. package/dist_ts/classes.controller.d.ts +63 -0
  11. package/dist_ts/classes.controller.js +502 -43
  12. package/dist_ts/classes.embeddeddb.js +7 -2
  13. package/dist_ts/classes.flexmodels.private.d.ts +39 -0
  14. package/dist_ts/classes.flexmodels.private.js +127 -1
  15. package/dist_ts/classes.flexprojectpreparation.d.ts +21 -0
  16. package/dist_ts/classes.flexprojectpreparation.js +69 -0
  17. package/dist_ts/classes.flexpromptqueue.d.ts +21 -1
  18. package/dist_ts/classes.flexpromptqueue.js +67 -7
  19. package/dist_ts/classes.flexrequestqueue.d.ts +11 -0
  20. package/dist_ts/classes.flexrequestqueue.js +40 -0
  21. package/dist_ts/classes.flexservice.d.ts +46 -14
  22. package/dist_ts/classes.flexservice.js +179 -55
  23. package/dist_ts/classes.flexstore.d.ts +68 -3
  24. package/dist_ts/classes.flexstore.js +277 -11
  25. package/dist_ts/classes.flexsubmissionmodels.d.ts +58 -0
  26. package/dist_ts/classes.flexsubmissionmodels.js +162 -0
  27. package/dist_ts/classes.flexsubmissionstore.d.ts +70 -0
  28. package/dist_ts/classes.flexsubmissionstore.js +323 -0
  29. package/dist_ts/classes.flexsupervisor.d.ts +10 -0
  30. package/dist_ts/classes.flexsupervisor.js +27 -1
  31. package/dist_ts/classes.harnessoperationmanager.d.ts +31 -0
  32. package/dist_ts/classes.harnessoperationmanager.js +69 -7
  33. package/dist_ts/classes.pendingpromptstore.d.ts +11 -3
  34. package/dist_ts/classes.pendingpromptstore.js +66 -10
  35. package/dist_ts/classes.sessionidentityservice.d.ts +18 -1
  36. package/dist_ts/classes.sessionidentityservice.js +34 -4
  37. package/dist_ts/classes.validation.d.ts +3 -0
  38. package/dist_ts/classes.validation.js +50 -1
  39. package/dist_ts/functions.deviceapi.js +3 -1
  40. package/dist_ts/interfaces.auth.d.ts +3 -1
  41. package/dist_ts/interfaces.auth.js +1 -1
  42. package/dist_ts/interfaces.flexipc.d.ts +29 -5
  43. package/dist_ts/interfaces.flexipc.js +13 -4
  44. package/dist_ts_authswitch/classes.authoritydatabase.d.ts +1 -0
  45. package/dist_ts_authswitch/classes.authoritydatabase.js +17 -5
  46. package/dist_ts_interfaces/flexadmission.d.ts +69 -0
  47. package/dist_ts_interfaces/flexadmission.js +2 -0
  48. package/dist_ts_interfaces/index.d.ts +1 -0
  49. package/dist_ts_interfaces/index.js +2 -1
  50. package/dist_ts_interfaces/interfaces.d.ts +10 -1
  51. package/dist_ts_interfaces/interfaces.js +2 -2
  52. package/dist_ts_interfaces/requests.d.ts +2 -1
  53. package/dist_ts_interfaces/requests.js +1 -1
  54. package/dist_ts_migration/v10_flexharnessv3migration.js +4 -1
  55. package/docs/nosqldb11-migration.md +59 -0
  56. package/package.json +10 -9
  57. package/readme.md +5 -1
  58. package/ts/00_commitinfo_data.ts +1 -1
  59. package/ts/aglapi/aglapisurface.document.ts +36 -3
  60. package/ts/classes.authstore.ts +179 -11
  61. package/ts/classes.controller.ts +498 -40
  62. package/ts/classes.embeddeddb.ts +6 -1
  63. package/ts/classes.flexmodels.private.ts +109 -0
  64. package/ts/classes.flexprojectpreparation.ts +69 -0
  65. package/ts/classes.flexpromptqueue.ts +69 -6
  66. package/ts/classes.flexrequestqueue.ts +47 -0
  67. package/ts/classes.flexservice.ts +187 -51
  68. package/ts/classes.flexstore.ts +352 -10
  69. package/ts/classes.flexsubmissionmodels.ts +89 -0
  70. package/ts/classes.flexsubmissionstore.ts +312 -0
  71. package/ts/classes.flexsupervisor.ts +26 -0
  72. package/ts/classes.harnessoperationmanager.ts +79 -6
  73. package/ts/classes.pendingpromptstore.ts +55 -6
  74. package/ts/classes.sessionidentityservice.ts +33 -2
  75. package/ts/classes.validation.ts +42 -0
  76. package/ts/functions.deviceapi.ts +2 -0
  77. package/ts/interfaces.auth.ts +3 -1
  78. package/ts/interfaces.flexipc.ts +38 -4
  79. package/ts_authswitch/classes.authoritydatabase.ts +19 -5
  80. package/ts_interfaces/flexadmission.ts +52 -0
  81. package/ts_interfaces/index.ts +2 -0
  82. package/ts_interfaces/interfaces.ts +10 -1
  83. package/ts_interfaces/requests.ts +3 -0
  84. package/ts_migration/v10_flexharnessv3migration.ts +3 -0
  85. package/ts_web/00_commitinfo_data.ts +1 -1
  86. package/ts_web/classes.browsersubmissions.ts +279 -0
  87. package/ts_web/classes.sessiondraftsync.ts +64 -1
  88. package/ts_web/elements.harnesscontrollerapp.ts +340 -5
  89. package/ts_web/functions.flexsubmissions.ts +88 -0
@@ -0,0 +1,312 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { IControllerFlexSubmissionInput, IControllerFlexSubmissionReceipt, IControllerRuntimeId } from '../ts_interfaces/index.js';
3
+ import { ControllerFlexAdmissionConversationModel, ControllerFlexSubmissionModel, type IFlexAdmissionConversationContent, type IFlexAdmissionConversationDocument, type IFlexSubmissionDocument } from './classes.flexsubmissionmodels.js';
4
+ import { ControllerPendingPromptModel, ControllerProjectModel, ControllerSessionStateModel, controllerSessionStateId } from './classes.authmodels.js';
5
+ import type { ControllerPendingPromptStore, IPendingPromptRecord } from './classes.pendingpromptstore.js';
6
+ import type { ControllerSessionIdentityService } from './classes.sessionidentityservice.js';
7
+
8
+ export class FlexSubmissionError extends Error {
9
+ constructor(
10
+ public readonly code: 'concurrent_change' | 'outcome_unknown' | 'project_not_found' | 'invalid_request',
11
+ messageArg: string,
12
+ optionsArg?: ErrorOptions,
13
+ ) {
14
+ super(messageArg, optionsArg);
15
+ this.name = 'FlexSubmissionError';
16
+ }
17
+ }
18
+
19
+ /** Aborts an admission transaction that met its own identity already committed. */
20
+ class FlexSubmissionDuplicate extends Error {
21
+ constructor() {
22
+ super('The submission identity is already admitted.');
23
+ this.name = 'FlexSubmissionDuplicate';
24
+ }
25
+ }
26
+
27
+ /** An admission either committed now or found the same submission committed before. */
28
+ export type TFlexSubmissionAdmission =
29
+ | { status: 'admitted'; receipt: IControllerFlexSubmissionReceipt }
30
+ | { status: 'duplicate'; receipt: IControllerFlexSubmissionReceipt };
31
+
32
+ /** Receipts and conversation intents a project removal deletes per page, through their project index. */
33
+ export const flexSubmissionPurgePageSize = 100;
34
+
35
+ const hash = (valuesArg: readonly unknown[]): string => plugins.crypto.createHash('sha256').update(JSON.stringify(valuesArg)).digest('base64url');
36
+ const conversationId = (controllerIdArg: string, projectIdArg: string, nativeIdArg: string): string => hash(['flex-admission-conversation-v1', controllerIdArg, projectIdArg, nativeIdArg]);
37
+ const submissionId = (controllerIdArg: string, projectIdArg: string, clientMessageIdArg: string): string => hash(['flex-submission-v1', controllerIdArg, projectIdArg, clientMessageIdArg]);
38
+ /** Keys in UTF-16 code-unit order: a persisted digest never depends on a locale or an ICU version. */
39
+ const stable = (valueArg: unknown): unknown => {
40
+ if (Array.isArray(valueArg)) return valueArg.map(stable);
41
+ if (valueArg && typeof valueArg === 'object') return Object.fromEntries(Object.entries(valueArg).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)).map(([key, value]) => [key, stable(value)]));
42
+ return valueArg;
43
+ };
44
+ export const flexSubmissionDigest = (inputArg: IControllerFlexSubmissionInput): string => plugins.crypto.createHash('sha256').update(JSON.stringify(stable(inputArg))).digest('hex');
45
+
46
+ /**
47
+ * Idempotency/intent sidecars of the existing pending ledger, not another dispatch queue. The
48
+ * pending owner, receipt, sequence, initial metadata and managed creation obligation commit once
49
+ * together. Native work is never done inside this transaction, and a duplicate only reads.
50
+ */
51
+ export class ControllerFlexSubmissionStore {
52
+ /** A commit that could not be read back may not be turned into a new admission in this process. */
53
+ private readonly uncertain = new Set<string>();
54
+
55
+ constructor(private readonly controllerId: string, private readonly issuerId: string,
56
+ private readonly database: plugins.nosqldb.SmartdataDb, private readonly identities: ControllerSessionIdentityService,
57
+ private readonly pending: ControllerPendingPromptStore) {}
58
+
59
+ public async existing(inputArg: IControllerFlexSubmissionInput): Promise<IControllerFlexSubmissionReceipt | undefined> {
60
+ const id = submissionId(this.controllerId, inputArg.projectId, inputArg.clientMessageId);
61
+ const stored = await ControllerFlexSubmissionModel.exact.findStoredOne({ id });
62
+ if (!stored) {
63
+ if (this.uncertain.has(id)) throw new FlexSubmissionError('outcome_unknown', 'The admission outcome remains unknown. Inspect its receipt; do not resend it.');
64
+ return undefined;
65
+ }
66
+ // A readable receipt settles an unknown outcome: the identity was admitted.
67
+ this.uncertain.delete(id);
68
+ return this.matchingReceipt(ControllerFlexSubmissionModel.exact.toPersisted(stored), inputArg);
69
+ }
70
+
71
+ /**
72
+ * The receipt of a submission of a registered project, or null when none was admitted. A project
73
+ * that is being removed or was removed answers `project_not_found`, never null: its receipts are
74
+ * deleted only after its removal started, so the project is read after the receipt.
75
+ */
76
+ public async get(projectIdArg: string, clientMessageIdArg: string): Promise<IControllerFlexSubmissionReceipt | null> {
77
+ const stored = await ControllerFlexSubmissionModel.exact.findStoredOne({ id: submissionId(this.controllerId, projectIdArg, clientMessageIdArg) });
78
+ await this.requireRegisteredProject(projectIdArg);
79
+ return stored ? this.receiptOf(ControllerFlexSubmissionModel.exact.toPersisted(stored)) : null;
80
+ }
81
+
82
+ /**
83
+ * Deletes the project's receipts and conversation intents, a bounded page at a time through
84
+ * their project index, until a page finds none. Only a project removal calls this, after its
85
+ * durable start and before it completes: no admission commits to a project that is being removed.
86
+ */
87
+ public async purgeProject(projectIdArg: string): Promise<void> {
88
+ const filter = { controllerId: this.controllerId, projectId: projectIdArg };
89
+ const sort = { controllerId: 1, projectId: 1, id: 1 } as const;
90
+ for (;;) {
91
+ const page = await ControllerFlexSubmissionModel.exact.findStored({ filter, sort, limit: flexSubmissionPurgePageSize });
92
+ if (page.length === 0) break;
93
+ // A page member that changed meanwhile is read again on the next page.
94
+ for (const current of page) await ControllerFlexSubmissionModel.exact.delete({ current });
95
+ }
96
+ for (;;) {
97
+ const page = await ControllerFlexAdmissionConversationModel.exact.findStored({ filter, sort, limit: flexSubmissionPurgePageSize });
98
+ if (page.length === 0) break;
99
+ for (const current of page) await ControllerFlexAdmissionConversationModel.exact.delete({ current });
100
+ }
101
+ }
102
+
103
+ public async resolve(inputArg: IControllerFlexSubmissionInput, configurationRevisionArg?: string): Promise<IFlexAdmissionConversationDocument> {
104
+ let content: IFlexAdmissionConversationContent;
105
+ const target = inputArg.conversation;
106
+ if (target.kind === 'new') {
107
+ const seed = [this.issuerId, this.controllerId, inputArg.projectId, target.clientConversationId];
108
+ const nativeId = `hcon_${hash(['flex-intent-native-v1', ...seed])}`;
109
+ content = { version: 1, sessionId: { harnessId: 'flex', nativeId }, sessionGenerationId: hash(['flex-intent-generation-v1', ...seed]),
110
+ clientConversationId: target.clientConversationId, sequence: 0, creation: 'pending',
111
+ creationOperationId: Buffer.from(hash(['flex-intent-creation-v1', ...seed]), 'base64url').subarray(0, 24).toString('base64url'),
112
+ creationRequestedAt: Date.now(), ...(target.title === undefined ? {} : { title: target.title }), ...(target.scratchpad === undefined ? {} : { scratchpad: target.scratchpad }),
113
+ ...(configurationRevisionArg === undefined ? {} : { configurationRevision: configurationRevisionArg }) };
114
+ } else {
115
+ const identity = await this.identities.flexSubmissionIdentity({ projectIdentityId: inputArg.projectId, runtimeId: target.sessionId, sessionIdentityId: target.sessionIdentityId });
116
+ content = { version: 1, sessionId: { ...target.sessionId }, ...identity, sequence: 0, creation: 'ready' };
117
+ }
118
+ const id = conversationId(this.controllerId, inputArg.projectId, content.sessionId.nativeId);
119
+ const stored = await ControllerFlexAdmissionConversationModel.exact.findStoredOne({ id });
120
+ if (stored) {
121
+ const document = ControllerFlexAdmissionConversationModel.exact.toPersisted(stored);
122
+ if (document.content.creation === 'retired' || document.content.sessionGenerationId !== content.sessionGenerationId
123
+ || (target.kind === 'existing' && document.content.sessionIdentityId !== target.sessionIdentityId)
124
+ || (target.kind === 'new' && (document.content.clientConversationId !== target.clientConversationId
125
+ || document.content.title !== target.title || document.content.scratchpad !== target.scratchpad))) {
126
+ throw new FlexSubmissionError('concurrent_change', 'The conversation intent changed or was retired.');
127
+ }
128
+ return document;
129
+ }
130
+ return { id, controllerId: this.controllerId, projectId: inputArg.projectId, content };
131
+ }
132
+
133
+ /**
134
+ * Commits the pending owner, the receipt, the conversation's next sequence and, for a new
135
+ * conversation, its creation obligation and initial metadata in one transaction. A submission
136
+ * already admitted under this identity aborts it and answers with its stored receipt
137
+ * (`duplicate`), or refuses different input under that identity; it is never `concurrent_change`.
138
+ */
139
+ public async admit(inputArg: IControllerFlexSubmissionInput, conversationArg: IFlexAdmissionConversationDocument, recordArg: IPendingPromptRecord,
140
+ assertAdmissionArg: () => void, signalArg?: AbortSignal): Promise<TFlexSubmissionAdmission> {
141
+ const id = submissionId(this.controllerId, inputArg.projectId, inputArg.clientMessageId);
142
+ if (this.uncertain.has(id)) {
143
+ // The receipt is read before the fence: once readable, it answers (digest-checked) and ends
144
+ // the fence. Without it the outcome stays unknown; the admission is never tried again.
145
+ const stored = await ControllerFlexSubmissionModel.exact.findStoredOne({ id });
146
+ if (!stored) throw new FlexSubmissionError('outcome_unknown', 'This admission has an unknown outcome. Inspect its receipt; do not resend it.');
147
+ this.uncertain.delete(id);
148
+ return { status: 'duplicate', receipt: await this.matchingReceipt(ControllerFlexSubmissionModel.exact.toPersisted(stored), inputArg) };
149
+ }
150
+ let candidate: IFlexSubmissionDocument | undefined;
151
+ try {
152
+ await this.commitAdmission(id, inputArg, conversationArg, recordArg, assertAdmissionArg, (candidateArg) => { candidate = candidateArg; }, signalArg);
153
+ } catch (errorArg) {
154
+ if (!(errorArg instanceof FlexSubmissionDuplicate)) throw errorArg;
155
+ // Nothing of this transaction committed; the earlier admission's receipt is the answer.
156
+ const stored = await ControllerFlexSubmissionModel.exact.findStoredOne({ id });
157
+ if (!stored) throw new FlexSubmissionError('outcome_unknown', 'The admitted submission could not be read back. Inspect its receipt; do not resend it.', { cause: errorArg });
158
+ return { status: 'duplicate', receipt: await this.matchingReceipt(ControllerFlexSubmissionModel.exact.toPersisted(stored), inputArg) };
159
+ }
160
+ if (!candidate) throw new Error('The Flex admission committed without a receipt.');
161
+ return { status: 'admitted', receipt: structuredClone(candidate.content.receipt) };
162
+ }
163
+
164
+ private async commitAdmission(id: string, inputArg: IControllerFlexSubmissionInput, conversationArg: IFlexAdmissionConversationDocument,
165
+ recordArg: IPendingPromptRecord, assertAdmissionArg: () => void, onCandidateArg: (candidateArg: IFlexSubmissionDocument) => void,
166
+ signalArg?: AbortSignal): Promise<void> {
167
+ let candidate: IFlexSubmissionDocument | undefined;
168
+ await this.pending.admit(recordArg, async pendingDocumentArg => {
169
+ const transaction = this.database.createSession();
170
+ try {
171
+ await transaction.withTransaction(async session => {
172
+ const options = { session };
173
+ // Single writer: only the controller process that owns the database engine writes
174
+ // projects, locators and managed sessions, each under the auth store's project mutation
175
+ // lane (`withFlexSubmissionAdmission` holds it here), so the project and identity
176
+ // documents read below cannot change before this commits. Admissions to one conversation
177
+ // are ordered by the write-write conflict on its conversation document.
178
+ const projectStored = await ControllerProjectModel.exact.findStoredOne({ id: inputArg.projectId }, options);
179
+ const project = projectStored ? ControllerProjectModel.exact.toPersisted(projectStored) : undefined;
180
+ if (!project || project.controllerId !== this.controllerId || project.removalStartedAt || project.removedAt) {
181
+ throw new FlexSubmissionError('project_not_found', 'The requested project is being removed.');
182
+ }
183
+ if (await ControllerFlexSubmissionModel.exact.findStoredOne({ id }, options)) throw new FlexSubmissionDuplicate();
184
+ const current = await ControllerFlexAdmissionConversationModel.exact.findStoredOne({ id: conversationArg.id }, options);
185
+ const conversation = current ? ControllerFlexAdmissionConversationModel.exact.toPersisted(current) : structuredClone(conversationArg);
186
+ if (conversation.content.creation === 'retired' || conversation.content.sessionGenerationId !== conversationArg.content.sessionGenerationId) throw new FlexSubmissionError('concurrent_change', 'The conversation intent changed.');
187
+ if (inputArg.conversation.kind === 'existing') {
188
+ await this.identities.flexSubmissionIdentity({ projectIdentityId: inputArg.projectId, runtimeId: inputArg.conversation.sessionId, sessionIdentityId: inputArg.conversation.sessionIdentityId }, session);
189
+ }
190
+ const nextSequence = conversation.content.sequence + 1;
191
+ if (!Number.isSafeInteger(nextSequence)) throw new FlexSubmissionError('concurrent_change', 'The conversation admission sequence is exhausted.');
192
+ conversation.content.sequence = nextSequence;
193
+ if (!current && conversation.content.creation === 'pending') {
194
+ await this.identities.beginManagedSessionCreation({ projectIdentityId: inputArg.projectId, runtimeId: conversation.content.sessionId,
195
+ operationId: conversation.content.creationOperationId!, requestedAt: new Date(conversation.content.creationRequestedAt!), expectedFlexSessionGenerationId: conversation.content.sessionGenerationId }, session);
196
+ const state = await ControllerSessionStateModel.exact.insert({ id: controllerSessionStateId(this.controllerId, inputArg.projectId, conversation.content.sessionId),
197
+ controllerId: this.controllerId, projectId: inputArg.projectId, sessionId: conversation.content.sessionId,
198
+ scratchpad: { text: conversation.content.scratchpad ?? '', revision: conversation.content.scratchpad ? 1 : 0 }, intelligenceExchanges: [],
199
+ modelChoice: inputArg.model, providerConnectionId: inputArg.providerConnectionId, updateId: plugins.crypto.randomBytes(32).toString('base64url') }, options);
200
+ if (state.status !== 'inserted') throw new FlexSubmissionError('concurrent_change', 'Initial conversation metadata already exists.');
201
+ }
202
+ if (current) {
203
+ const changed = await ControllerFlexAdmissionConversationModel.exact.transition({ current, change: model => { model.content = conversation.content; } }, options);
204
+ if (changed.status !== 'transitioned') throw new FlexSubmissionError('concurrent_change', 'The conversation admission sequence changed.');
205
+ } else {
206
+ const inserted = await ControllerFlexAdmissionConversationModel.exact.insert(conversation, options);
207
+ if (inserted.status !== 'inserted') throw new FlexSubmissionError('concurrent_change', 'The conversation intent changed.');
208
+ }
209
+ const receipt: IControllerFlexSubmissionReceipt = { version: 1, clientMessageId: inputArg.clientMessageId, operationId: recordArg.promptId, projectId: inputArg.projectId,
210
+ sessionId: conversation.content.sessionId, sessionGenerationId: conversation.content.sessionGenerationId,
211
+ ...(conversation.content.sessionGenerationSequence === undefined ? {} : { sessionGenerationSequence: conversation.content.sessionGenerationSequence }),
212
+ ...(conversation.content.sessionIdentityId === undefined ? {} : { sessionIdentityId: conversation.content.sessionIdentityId }),
213
+ ...(conversation.content.clientConversationId === undefined ? {} : { clientConversationId: conversation.content.clientConversationId }),
214
+ serverSequence: nextSequence, acceptedAt: recordArg.createdAt, state: 'waiting', creation: conversation.content.creation };
215
+ candidate = { id, controllerId: this.controllerId, projectId: inputArg.projectId, content: { version: 1, digest: flexSubmissionDigest(inputArg), receipt } };
216
+ const pending = await ControllerPendingPromptModel.exact.insert(pendingDocumentArg, options);
217
+ if (pending.status !== 'inserted') throw new FlexSubmissionError('concurrent_change', 'This operation identity is already accepted.');
218
+ const inserted = await ControllerFlexSubmissionModel.exact.insert(candidate, options);
219
+ if (inserted.status !== 'inserted') throw new FlexSubmissionDuplicate();
220
+ assertAdmissionArg();
221
+ }, { timeoutMS: 20_000, ...(signalArg ? { signal: signalArg } : {}) });
222
+ } catch (errorArg) {
223
+ if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) === 'not_committed') throw errorArg;
224
+ this.uncertain.add(id);
225
+ // Only an exact immutable receipt proves this transaction committed. Absence or a failed
226
+ // read leaves the fence; neither retries the admission nor starts native work.
227
+ try {
228
+ const stored = await ControllerFlexSubmissionModel.exact.findStoredOne({ id });
229
+ if (stored && candidate && plugins.util.isDeepStrictEqual(ControllerFlexSubmissionModel.exact.toPersisted(stored), candidate)) {
230
+ this.uncertain.delete(id);
231
+ return;
232
+ }
233
+ } catch { /* Preserve the original unknown outcome with a fixed public refusal. */ }
234
+ throw new FlexSubmissionError('outcome_unknown', 'The admission outcome is unknown. Inspect its receipt; do not resend it.', { cause: errorArg });
235
+ } finally {
236
+ await transaction.close().catch(errorArg => console.error('Closing a Flex admission transaction failed.', errorArg));
237
+ }
238
+ });
239
+ if (candidate) onCandidateArg(candidate);
240
+ }
241
+
242
+ /** The stored receipt for this exact input; the same identity with different input is refused. */
243
+ private async matchingReceipt(documentArg: IFlexSubmissionDocument, inputArg: IControllerFlexSubmissionInput): Promise<IControllerFlexSubmissionReceipt> {
244
+ if (documentArg.content.digest !== flexSubmissionDigest(inputArg)) {
245
+ throw new FlexSubmissionError('invalid_request', 'This message identity already names different input. Nothing was admitted.');
246
+ }
247
+ return this.receiptOf(documentArg);
248
+ }
249
+
250
+ private async requireRegisteredProject(projectIdArg: string): Promise<void> {
251
+ const stored = await ControllerProjectModel.exact.findStoredOne({ id: projectIdArg });
252
+ const project = stored ? ControllerProjectModel.exact.toPersisted(stored) : undefined;
253
+ if (!project || project.controllerId !== this.controllerId || project.removalStartedAt || project.removedAt) {
254
+ throw new FlexSubmissionError('project_not_found', 'The requested project is not registered.');
255
+ }
256
+ }
257
+
258
+ private async receiptOf(documentArg: IFlexSubmissionDocument): Promise<IControllerFlexSubmissionReceipt> {
259
+ const receipt = structuredClone(documentArg.content.receipt);
260
+ const [pendingStored, conversationStored, stateStored] = await Promise.all([
261
+ ControllerPendingPromptModel.exact.findStoredOne({ id: receipt.operationId }),
262
+ ControllerFlexAdmissionConversationModel.exact.findStoredOne({ id: conversationId(this.controllerId, receipt.projectId, receipt.sessionId.nativeId) }),
263
+ ControllerSessionStateModel.exact.findStoredOne({ id: controllerSessionStateId(this.controllerId, receipt.projectId, receipt.sessionId) }),
264
+ ]);
265
+ if (conversationStored) {
266
+ const conversation = ControllerFlexAdmissionConversationModel.exact.toPersisted(conversationStored).content;
267
+ receipt.creation = conversation.creation;
268
+ if (conversation.sessionIdentityId !== undefined) receipt.sessionIdentityId = conversation.sessionIdentityId;
269
+ if (conversation.sessionGenerationSequence !== undefined) receipt.sessionGenerationSequence = conversation.sessionGenerationSequence;
270
+ }
271
+ const pending = pendingStored ? ControllerPendingPromptModel.exact.toPersisted(pendingStored) : undefined;
272
+ const hold = stateStored ? ControllerSessionStateModel.exact.toPersisted(stateStored).flexLimitResume?.hold : undefined;
273
+ receipt.state = pending?.heldReason ? 'held' : pending?.dispatch === 'waiting' ? 'waiting' : pending ? 'handedOver'
274
+ : hold?.state === 'armed' ? 'waiting' : 'settled';
275
+ if (pending?.heldReason) receipt.heldReason = pending.heldReason;
276
+ return receipt;
277
+ }
278
+
279
+ public async conversation(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<IFlexAdmissionConversationDocument | undefined> {
280
+ const stored = await ControllerFlexAdmissionConversationModel.exact.findStoredOne({ id: conversationId(this.controllerId, projectIdArg, sessionIdArg.nativeId) });
281
+ return stored ? ControllerFlexAdmissionConversationModel.exact.toPersisted(stored) : undefined;
282
+ }
283
+
284
+ /** The admitted conversations whose native creation is not finished (`pending` or `uncertain`). */
285
+ public async listUnfinishedConversations(projectIdArg?: string): Promise<IFlexAdmissionConversationDocument[]> {
286
+ return (await this.listConversations(projectIdArg)).filter((conversation) => (
287
+ conversation.content.creation === 'pending' || conversation.content.creation === 'uncertain'
288
+ ));
289
+ }
290
+
291
+ public async listConversations(projectIdArg?: string): Promise<IFlexAdmissionConversationDocument[]> {
292
+ return (await ControllerFlexAdmissionConversationModel.exact.findStored({ filter: { controllerId: this.controllerId, ...(projectIdArg === undefined ? {} : { projectId: projectIdArg }) } }))
293
+ .map(stored => ControllerFlexAdmissionConversationModel.exact.toPersisted(stored));
294
+ }
295
+
296
+ public async setCreation(projectIdArg: string, sessionIdArg: IControllerRuntimeId, creationArg: IControllerFlexSubmissionReceipt['creation'],
297
+ nativeArg?: { sessionGenerationId: string; sessionGenerationSequence: number; sessionIdentityId: string }): Promise<void> {
298
+ const current = await ControllerFlexAdmissionConversationModel.exact.findStoredOne({ id: conversationId(this.controllerId, projectIdArg, sessionIdArg.nativeId) });
299
+ if (!current) return;
300
+ const before = ControllerFlexAdmissionConversationModel.exact.toPersisted(current);
301
+ if (nativeArg && nativeArg.sessionGenerationId !== before.content.sessionGenerationId) throw new FlexSubmissionError('concurrent_change', 'Native creation returned another reserved generation.');
302
+ const candidate = { ...before, content: { ...before.content, creation: creationArg, ...(nativeArg ?? {}) } };
303
+ try {
304
+ const changed = await ControllerFlexAdmissionConversationModel.exact.transition({ current, change: model => { model.content = candidate.content; } });
305
+ if (changed.status !== 'transitioned') throw new FlexSubmissionError('concurrent_change', 'Conversation creation changed concurrently.');
306
+ } catch (errorArg) {
307
+ if (!(errorArg instanceof plugins.nosqldb.SmartdataExactPersistenceError) || errorArg.code !== 'ambiguous_write') throw errorArg;
308
+ const written = await ControllerFlexAdmissionConversationModel.exact.findStoredOne({ id: before.id });
309
+ if (!written || !plugins.util.isDeepStrictEqual(ControllerFlexAdmissionConversationModel.exact.toPersisted(written), candidate)) throw errorArg;
310
+ }
311
+ }
312
+ }
@@ -1,6 +1,7 @@
1
1
  import * as plugins from './plugins.js';
2
2
  import { commitinfo } from './00_commitinfo_data.js';
3
3
  import { FlexFramedTransport, FlexIpcNotSentError } from './classes.flexframedtransport.js';
4
+ import { FlexProjectPreparation } from './classes.flexprojectpreparation.js';
4
5
  import {
5
6
  GitReversionConflictError,
6
7
  GitReversionDirtyWorktreeError,
@@ -367,6 +368,8 @@ export class FlexSupervisor {
367
368
  private generationWriterId?: string;
368
369
  /** Writers of earlier generations whose exit was confirmed, oldest first. */
369
370
  private readonly retiredWriterIds: string[] = [];
371
+ /** Each project's preparation in the current child generation; every generation end resets it. */
372
+ private readonly projectPreparation = new FlexProjectPreparation();
370
373
 
371
374
  constructor(private readonly options: IFlexSupervisorOptions = {}) {
372
375
  this.writeControllerLog = options.writeControllerLog ?? ((lineArg) => console.error(lineArg));
@@ -434,6 +437,21 @@ export class FlexSupervisor {
434
437
  : this.ownsHostPeer(peerIdArg);
435
438
  }
436
439
 
440
+ /**
441
+ * Resolves once the current child generation reported the project ready
442
+ * (`project.preparation`). Every mutating request of a project awaits it first, outside that
443
+ * request's control budget: a ready child is not a prepared project. Refused with `NOT_READY`
444
+ * when no child is ready, when the project's preparation failed and when the generation ends,
445
+ * and with the signal's reason when it aborts. It sends nothing to the child.
446
+ */
447
+ public waitForProjectReady(projectIdArg: string, signalArg: AbortSignal): Promise<void> {
448
+ if (signalArg.aborted) return Promise.reject(signalArg.reason);
449
+ if (!this.status.ready) {
450
+ return Promise.reject(new FlexServiceError(this.status.state === 'unsupported' ? 'UNSUPPORTED_RUNTIME' : 'NOT_READY'));
451
+ }
452
+ return this.projectPreparation.wait(projectIdArg, signalArg);
453
+ }
454
+
437
455
  public subscribe(listenerArg: (eventArg: TFlexChildEvent) => void): () => void {
438
456
  this.eventListeners.add(listenerArg);
439
457
  return () => this.eventListeners.delete(listenerArg);
@@ -543,6 +561,7 @@ export class FlexSupervisor {
543
561
  signalArg?: AbortSignal,
544
562
  ): Promise<IFlexSupervisorStatus> {
545
563
  this.status = { state: 'starting', ready: false };
564
+ this.projectPreparation.reset();
546
565
  this.settledHostRequestIds.clear();
547
566
  this.browserChannelGenerations.clear();
548
567
  signalArg?.throwIfAborted();
@@ -696,6 +715,11 @@ export class FlexSupervisor {
696
715
  return;
697
716
  }
698
717
  if (messageArg.type === 'event') {
718
+ // Project preparation belongs to this generation's readiness, not to the controller's events.
719
+ if (messageArg.event.type === 'project.preparation') {
720
+ this.projectPreparation.changed(messageArg.event.scopeId, messageArg.event.state);
721
+ return;
722
+ }
699
723
  for (const listener of [...this.eventListeners]) {
700
724
  try {
701
725
  listener(messageArg.event);
@@ -1595,6 +1619,8 @@ export class FlexSupervisor {
1595
1619
  }
1596
1620
 
1597
1621
  private rejectPending(errorArg: Error): void {
1622
+ // The generation ended: no project of it is prepared any more.
1623
+ this.projectPreparation.reset();
1598
1624
  for (const [requestId, pending] of this.pendingRequests) {
1599
1625
  this.clearPendingRequest(requestId, pending);
1600
1626
  pending.reject(
@@ -66,6 +66,8 @@ interface IControllerHarnessOperationReservationBase {
66
66
  messageId?: IControllerRuntimeId;
67
67
  /** Where the operation's files are stored durably; set before its input can be accepted. */
68
68
  attachmentSet?: IControllerAttachmentSetDocument;
69
+ /** Immutable effective selection captured before durable admission. */
70
+ selection?: Readonly<{ model?: TControllerModelChoice; providerConnectionId?: string }>;
69
71
  }
70
72
 
71
73
  export interface IControllerDraftHarnessOperationReservation
@@ -213,6 +215,11 @@ interface IActiveHarnessOperation {
213
215
  harnessAdmissionGeneration: number;
214
216
  state: TControllerHarnessOperationState;
215
217
  inputAccepted: boolean;
218
+ /**
219
+ * The controller committed the input's pending owner before any native dispatch (`admitInput`):
220
+ * a later queue or runtime acceptance finds the input accepted already and takes it as it is.
221
+ */
222
+ durablyAdmitted?: true;
216
223
  observedTerminal: boolean;
217
224
  messageReplacement?: { settled: Promise<void> };
218
225
  /** Survives a failed run returning to the queue: input once handed to Flex cannot be edited. */
@@ -505,6 +512,8 @@ export class ControllerHarnessOperationManager {
505
512
  attachmentSet?: IControllerAttachmentSetDocument;
506
513
  /** The message is one the conversation already accepted, delivered now: no count refuses it. */
507
514
  deliversAccepted?: true;
515
+ /** Durable controller input is admitted independently of a native runtime restart. */
516
+ durableAdmission?: true;
508
517
  },
509
518
  deliveryArg: TControllerHarnessOperationDelivery,
510
519
  identityArg?: Readonly<{ operationId: string; createdAt: number }>,
@@ -527,13 +536,13 @@ export class ControllerHarnessOperationManager {
527
536
  assertDeliverySupported('send', sessionIdArg, deliveryArg);
528
537
  const harnessId = sessionIdArg.harnessId;
529
538
  const harnessAdmissionGeneration = this.currentHarnessAdmissionGeneration(harnessId);
530
- this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration);
539
+ messageArg.durableAdmission ? this.assertDurableInputAdmission(harnessId, harnessAdmissionGeneration) : this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration);
531
540
  const key = this.sessionKey(projectIdArg, sessionIdArg);
532
541
  if (this.pendingUploadCleanups.size > 0 && messageArg.attachments.length > 0) {
533
542
  await this.retryPendingUploadCleanups().catch(() => undefined);
534
543
  }
535
544
  if (this.closed) throw new Error('The harness operation manager is closed.');
536
- this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration);
545
+ messageArg.durableAdmission ? this.assertDurableInputAdmission(harnessId, harnessAdmissionGeneration) : this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration);
537
546
  const operations = this.operationsBySession.get(key) ?? [];
538
547
  this.assertOperationCapacity(
539
548
  operations.length,
@@ -585,7 +594,7 @@ export class ControllerHarnessOperationManager {
585
594
  if (this.closed || !this.operationsBySession.get(key)?.includes(active)) {
586
595
  throw new Error('The harness operation reservation closed during upload materialization.');
587
596
  }
588
- this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration);
597
+ messageArg.durableAdmission ? this.assertDurableInputAdmission(harnessId, harnessAdmissionGeneration) : this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration);
589
598
  if (upload) {
590
599
  reservation.promptSuffix = upload.promptSuffix;
591
600
  reservation.uploadDirectory = upload.directory;
@@ -597,6 +606,26 @@ export class ControllerHarnessOperationManager {
597
606
  }
598
607
  }
599
608
 
609
+ public bindPromptSelection(reservationArg: TControllerHarnessOperationReservation, modelArg?: TControllerModelChoice, providerConnectionIdArg?: string): TControllerHarnessOperationReservation {
610
+ const active = this.requireSubmitting(reservationArg);
611
+ if (active.inputAccepted) throw new Error('Accepted input selection is immutable.');
612
+ active.reservation.selection = Object.freeze({ ...(modelArg ? { model: Object.freeze({ ...modelArg }) } : {}), ...(providerConnectionIdArg ? { providerConnectionId: providerConnectionIdArg } : {}) });
613
+ return cloneReservation(active.reservation);
614
+ }
615
+
616
+ /**
617
+ * Records that the input's pending owner is durably committed, before any native dispatch:
618
+ * controller acceptance, not native acceptance. The operation keeps submitting and is not
619
+ * handed over; the queue or runtime acceptance that follows takes the input as accepted.
620
+ */
621
+ public admitInput(reservationArg: TControllerHarnessOperationReservation): void {
622
+ const active = this.requireSubmitting(reservationArg);
623
+ if (active.inputAccepted) throw new Error('The harness operation input was already accepted.');
624
+ if (reservationArg.source === 'draft') this.clearReservationDraft(reservationArg);
625
+ active.inputAccepted = true;
626
+ active.durablyAdmitted = true;
627
+ }
628
+
600
629
  public accept(
601
630
  reservationArg: IControllerDraftHarnessOperationReservation,
602
631
  ): IControllerSessionDraft;
@@ -738,7 +767,8 @@ export class ControllerHarnessOperationManager {
738
767
  /** The run refused the steer before it reached it; the message is the next turn's input. */
739
768
  public unbindFlexSteer(reservationArg: TControllerHarnessOperationReservation): void {
740
769
  const active = this.requireActive(reservationArg);
741
- if (active.state !== 'submitting' || active.inputAccepted) {
770
+ // Input the controller admitted durably is still being handed over until its runtime accepts it.
771
+ if (active.state !== 'submitting' || (active.inputAccepted && !active.durablyAdmitted)) {
742
772
  throw new Error('Only a steer that is still being handed over can be refused.');
743
773
  }
744
774
  delete active.flexSteerQueueId;
@@ -843,7 +873,11 @@ export class ControllerHarnessOperationManager {
843
873
  reservationArg: TControllerHarnessOperationReservation,
844
874
  ): IControllerSessionDraft | undefined {
845
875
  if (activeArg.inputAccepted) {
846
- throw new Error('The harness operation input was already accepted.');
876
+ // Input the controller admitted durably was accepted, and its draft cleared, at admission.
877
+ if (!activeArg.durablyAdmitted) throw new Error('The harness operation input was already accepted.');
878
+ return reservationArg.source === 'draft'
879
+ ? this.getDraft(reservationArg.projectId, reservationArg.sessionId)
880
+ : undefined;
847
881
  }
848
882
  const draft = reservationArg.source === 'draft'
849
883
  ? this.clearReservationDraft(reservationArg)
@@ -967,6 +1001,17 @@ export class ControllerHarnessOperationManager {
967
1001
  }));
968
1002
  }
969
1003
 
1004
+ /** Claim the earliest queued steer beside a running Flex turn; all native effects still await its durable mark. */
1005
+ public beginQueuedSteerSubmission(reservationArg: TControllerHarnessOperationReservation): void {
1006
+ const active = this.requireActive(reservationArg);
1007
+ const operations = this.operationsBySession.get(this.sessionKey(reservationArg.projectId, reservationArg.sessionId)) ?? [];
1008
+ const firstQueuedSteer = operations.find(operation => operation.state === 'queued' && operation.reservation.delivery === 'steer');
1009
+ if (reservationArg.sessionId.harnessId !== 'flex' || firstQueuedSteer !== active || active.releasePromise) throw new Error('The Flex steer is not claimable.');
1010
+ active.state = 'submitting';
1011
+ active.handedOver = true;
1012
+ delete active.queueClass;
1013
+ }
1014
+
970
1015
  public beginQueuedSubmission(reservationArg: TControllerHarnessOperationReservation): void {
971
1016
  const active = this.requireActive(reservationArg);
972
1017
  const operations = this.operationsBySession.get(
@@ -1068,6 +1113,23 @@ export class ControllerHarnessOperationManager {
1068
1113
  return result.draft;
1069
1114
  }
1070
1115
 
1116
+ /**
1117
+ * Clears the shared draft after a durably admitted send, only while it is still at the revision
1118
+ * the send captured and holds exactly the sent content: later edits are a newer revision and stay.
1119
+ */
1120
+ public clearCapturedDraft(
1121
+ projectIdArg: string,
1122
+ sessionIdArg: IControllerRuntimeId,
1123
+ revisionArg: number,
1124
+ sentArg: Readonly<{ text: string; attachments: readonly IControllerDraftAttachment[] }>,
1125
+ ): void {
1126
+ const draft = this.getDraft(projectIdArg, sessionIdArg);
1127
+ if (draft.revision !== revisionArg || draft.text !== sentArg.text
1128
+ || !plugins.util.isDeepStrictEqual(draft.attachments, sentArg.attachments)) return;
1129
+ const result = this.drafts.clearExact(this.sessionKey(projectIdArg, sessionIdArg), revisionArg);
1130
+ if (result.update) this.options.onDraftChanged(projectIdArg, sessionIdArg, result.update);
1131
+ }
1132
+
1071
1133
  public markOutcomeUnknown(reservationArg: TControllerHarnessOperationReservation): boolean {
1072
1134
  const active = this.findActive(reservationArg);
1073
1135
  if (!active) return false;
@@ -1119,7 +1181,7 @@ export class ControllerHarnessOperationManager {
1119
1181
 
1120
1182
  public clearTurnResourceOwner(reservationArg: TControllerHarnessOperationReservation): void {
1121
1183
  const active = this.requireActive(reservationArg);
1122
- if (active.inputAccepted || active.state !== 'submitting') throw new Error('Only undispatched input may drop its native turn binding.');
1184
+ if ((active.inputAccepted && !active.durablyAdmitted) || active.state !== 'submitting') throw new Error('Only undispatched input may drop its native turn binding.');
1123
1185
  active.turnOwner = undefined;
1124
1186
  }
1125
1187
 
@@ -1768,6 +1830,17 @@ export class ControllerHarnessOperationManager {
1768
1830
  return this.harnessAdmissionGenerations.get(harnessIdArg) ?? 0;
1769
1831
  }
1770
1832
 
1833
+ public assertDurableAdmissionCurrent(reservationArg: TControllerHarnessOperationReservation): void {
1834
+ const active = this.requireActive(reservationArg);
1835
+ this.assertDurableInputAdmission(reservationArg.sessionId.harnessId as TControllerSessionHarnessId, active.harnessAdmissionGeneration);
1836
+ }
1837
+
1838
+ private assertDurableInputAdmission(harnessIdArg: TControllerSessionHarnessId, generationArg: number): void {
1839
+ if (this.closed) throw new ControllerHarnessOperationConflictError('Harness prompt admission is closed.');
1840
+ this.assertHarnessGeneration(harnessIdArg, generationArg);
1841
+ if (this.upgradeAdmissionSealed()) throw new ControllerHarnessOperationConflictError('Harness prompt admission is temporarily sealed.');
1842
+ }
1843
+
1771
1844
  private assertHarnessAdmission(
1772
1845
  harnessIdArg: TControllerSessionHarnessId,
1773
1846
  expectedGenerationArg: number,
@@ -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 {