@modelprofile.com/flexharness 16.0.1 → 16.1.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.
package/readme.md CHANGED
@@ -697,7 +697,11 @@ await harness.retireScope(scopeId);
697
697
  await harness.dispose();
698
698
  ```
699
699
 
700
- Only one run may be active in a session. Additional prompts enter a bounded FIFO owned by FlexHarness, while different sessions can run concurrently. `enqueuePrompt()` resolves with `{ queueId, completion }` after the immutable prompt and options have been accepted into that runtime queue and `prompt.queued` has been emitted. `startPrompt()` keeps its durable-admission behavior: it waits for its FIFO turn and resolves with `{ queueId, runId, completion }` only after the canonical generation claim, run ID, and initial public audit messages have been durably reserved and the corresponding start events have been emitted. `prompt()` preserves the simpler behavior by awaiting completion internally.
700
+ `getSession()` returns the session as saved after every queued write that may change it; it does not wait for queued writes of the scope's other sessions, so a slow save of one session never holds a read of another. `listSessions()` waits for every queued write.
701
+
702
+ Only one run may be active in a session. Additional prompts enter a bounded FIFO owned by FlexHarness, while different sessions can run concurrently. `enqueuePrompt()` resolves with `{ queueId, generation, completion }` after the immutable prompt and options have been accepted into that runtime queue and `prompt.queued` has been emitted. `startPrompt()` keeps its durable-admission behavior: it waits for its FIFO turn and resolves with `{ queueId, generation, runId, completion }` only after the canonical generation claim, run ID, and initial public audit messages have been durably reserved and the corresponding start events have been emitted. `prompt()` preserves the simpler behavior by awaiting completion internally.
703
+
704
+ Every admission names the session generation that admitted it: `generation` (`IFlexPromptAdmissionGeneration`) holds `sessionGenerationId`, `sessionGenerationSequence`, `depth` (0 for a root session, also a legacy root that stored none) and `configurationRef` when the session has one, as `getSession()` reports them. None of them changes while the generation lives, and the prompt only ever runs on that generation. The harness reads it from the session in memory, so a caller that needs it for the run it started does not call `getSession()`: that read waits for the session's queued writes, which queue behind every other session's write queued before them in the scope's one write FIFO.
701
705
 
702
706
  Queue entries expose `queued`, `starting`, `scheduled`, `running`, `completed`, `failed`, and `cancelled` status through `getPromptQueueEntry()` and `listPromptQueueEntries()`. The list is ordered by process-local `queueSequence`. `getPromptQueueEntry()` throws `FlexHarnessNotFoundError` for an unknown or evicted ID. `cancelPrompt()` cancels one exact queue ID: a waiting entry leaves the FIFO and releases capacity immediately but remains queryable as `cancelled` until terminal retention evicts it; a promoted entry uses the canonical run cancellation path and is stopped with the same `FlexHarnessAbortError` ("The run was aborted.") as `abort()`; only a waiting entry is rejected with "The queued prompt was cancelled.". A cancelled run, whether stopped or found interrupted on reload, puts its `error` on the assistant message only; its user message is `cancelled` without an `error`, while a failed run marks both messages. Cancelling a terminal entry returns `false`, while an unknown ID throws. `abort()` remains scoped to the currently active run.
703
707
 
@@ -740,7 +744,7 @@ no `prompt` or `promptId`: continuation creates a new run and an assistant messa
740
744
  without appending or modifying a user message. Its result has the prompt result's
741
745
  fields except `userMessage`. Explicit steers still become user messages normally.
742
746
 
743
- Admission returns `{ queueId, completion }` once queued, like `enqueuePrompt()`.
747
+ Admission returns `{ queueId, generation, completion }` once queued, like `enqueuePrompt()`.
744
748
  The entry and its `prompt.*` events carry `continuation: true`. Inspect its `runId`
745
749
  after `prompt.started`, or read it through `getPromptQueueEntry()`. Use the same
746
750
  `cancelPrompt()`, `cancelScheduledPrompt()`, `abort()` and `steerPrompt()` methods.
@@ -872,7 +876,7 @@ Two horizons bound undo. Retention pruning removes the oldest complete visible u
872
876
 
873
877
  Session metadata archival through `updateSession(..., { archived: true })` only sets `archivedAt`. It does not archive Agent events, retire captures, or remove undo history.
874
878
 
875
- `executeSlashCommand()` is the authoritative parser and lookup boundary. Its result distinguishes `not-command`, `malformed`, `unknown`, completed `operation`, bounded `handler-result`, and `prompt-admission`. A prompt admission contains the normal `{ queueId, runId, completion }`; await `admission.completion` for the model result. Unknown commands are never admitted as literal prompts. Known unavailable commands and invalid arguments throw typed FlexHarness errors. Options accept `promptId`, `modelHint`, `system`, `maxSteps`, and `signal`; commands do not accept attachments. For templates and `/init`, `promptId` follows the normal prompt contract: a non-empty string of at most 512 UTF-8 bytes, recorded on the queue entry and native user message (including exact transcript reads after restart or with `includeUndone`), with duplicate outstanding ids refused by `FlexHarnessDuplicatePromptError`. Results that admit no prompt (`operation`, `handler-result`, `unknown`, `not-command`, `malformed`) ignore `promptId` without recording or reserving it. `/compact` uses `modelHint` and `signal` and refuses `system` and `maxSteps` with `FlexHarnessValidationError`. Aborting a template or `init` execution cancels its exact queued or started prompt without affecting another queue entry.
879
+ `executeSlashCommand()` is the authoritative parser and lookup boundary. Its result distinguishes `not-command`, `malformed`, `unknown`, completed `operation`, bounded `handler-result`, and `prompt-admission`. A prompt admission contains the normal `{ queueId, generation, runId, completion }`; await `admission.completion` for the model result. Unknown commands are never admitted as literal prompts. Known unavailable commands and invalid arguments throw typed FlexHarness errors. Options accept `promptId`, `modelHint`, `system`, `maxSteps`, and `signal`; commands do not accept attachments. For templates and `/init`, `promptId` follows the normal prompt contract: a non-empty string of at most 512 UTF-8 bytes, recorded on the queue entry and native user message (including exact transcript reads after restart or with `includeUndone`), with duplicate outstanding ids refused by `FlexHarnessDuplicatePromptError`. Results that admit no prompt (`operation`, `handler-result`, `unknown`, `not-command`, `malformed`) ignore `promptId` without recording or reserving it. `/compact` uses `modelHint` and `signal` and refuses `system` and `maxSteps` with `FlexHarnessValidationError`. Aborting a template or `init` execution cancels its exact queued or started prompt without affecting another queue entry.
876
880
 
877
881
  Templates replace every `$ARGUMENTS` with untouched raw argument text. `$1` through the highest referenced positional placeholder use tokenized arguments, with the highest position receiving all remaining tokens joined by spaces. Missing positions become empty. A template with no placeholders appends non-empty raw arguments after a blank line. `/init` uses the OpenCode 1.18.15 `AGENTS.md` initialization prompt with provider-neutral active-workspace wording.
878
882
 
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@modelprofile.com/flexharness',
6
- version: '16.0.1',
6
+ version: '16.1.0',
7
7
  description: 'The FlexHarness toolbox source repository and shared dependency catalog.'
8
8
  }
@@ -31,6 +31,7 @@ import type {
31
31
  IFlexScopeSnapshot,
32
32
  IFlexSession,
33
33
  IFlexSessionImportLimits,
34
+ IFlexSessionTombstone,
34
35
  IFlexSubagentDefinition,
35
36
  IFlexTerminalProjection,
36
37
  IFlexToolCatalogOptions,
@@ -47,6 +48,7 @@ import { InMemoryFlexHarnessStores } from './classes.stores.js';
47
48
  import { FlexCodeSandbox } from './classes.codesandbox.js';
48
49
  import {
49
50
  assertJsonSerializable,
51
+ canonicalJson,
50
52
  cloneSerializable,
51
53
  deepFreeze,
52
54
  resolveJsonLimits,
@@ -434,6 +436,8 @@ export class FlexHarnessCore<TScope> {
434
436
  pendingPermissions: new Map(),
435
437
  publications: new Map(),
436
438
  scopeQueue: Promise.resolve(),
439
+ wholeScopeQueue: Promise.resolve(),
440
+ sessionScopeQueues: new Map(),
437
441
  lifecycle: 'active',
438
442
  fenceInProgress: false,
439
443
  fenceAdditionalErrors: [],
@@ -1203,10 +1207,11 @@ export class FlexHarnessCore<TScope> {
1203
1207
  this.assertStateAcceptingWork(state);
1204
1208
  return operation();
1205
1209
  });
1206
- state.scopeQueue = owned.then(() => undefined, () => undefined);
1210
+ this.enqueueScopeTail(state, owned);
1207
1211
  return owned;
1208
1212
  }
1209
1213
 
1214
+ /** Runs a scope mutation that may change any session, after every mutation queued before it. */
1210
1215
  public mutateScope<TValue>(
1211
1216
  state: IStorageState,
1212
1217
  mutation: () => TValue,
@@ -1216,13 +1221,57 @@ export class FlexHarnessCore<TScope> {
1216
1221
  if (!allowDuringDrain) this.assertStateAcceptingWork(state);
1217
1222
  return this.mutateScopeOwned(state, mutation);
1218
1223
  });
1219
- state.scopeQueue = operation.then(() => undefined, () => undefined);
1224
+ this.enqueueScopeTail(state, operation);
1220
1225
  return operation;
1221
1226
  }
1222
1227
 
1228
+ /**
1229
+ * Runs a scope mutation that changes only the session `sessionId`, in the same order as every
1230
+ * other scope mutation. A read of another session does not wait for it (`sessionReadBarrier`).
1231
+ * A mutation that changes another session anyway is rolled back and fails.
1232
+ */
1233
+ public mutateSessionScope<TValue>(
1234
+ state: IStorageState,
1235
+ sessionId: string,
1236
+ mutation: () => TValue,
1237
+ allowDuringDrain = false,
1238
+ ): Promise<TValue> {
1239
+ const operation = state.scopeQueue.then(() => {
1240
+ if (!allowDuringDrain) this.assertStateAcceptingWork(state);
1241
+ return this.mutateScopeOwned(state, mutation, sessionId);
1242
+ });
1243
+ this.enqueueScopeTail(state, operation, sessionId);
1244
+ return operation;
1245
+ }
1246
+
1247
+ /**
1248
+ * Settles once every scope mutation queued so far that may change `sessionId` has settled: those
1249
+ * naming it and those that may change any session. Mutations of other sessions are not waited for.
1250
+ */
1251
+ public sessionReadBarrier(state: IStorageState, sessionId: string): Promise<void> {
1252
+ const sessionQueue = state.sessionScopeQueues.get(sessionId);
1253
+ return sessionQueue === undefined
1254
+ ? state.wholeScopeQueue
1255
+ : Promise.all([state.wholeScopeQueue, sessionQueue]).then(() => undefined);
1256
+ }
1257
+
1258
+ private enqueueScopeTail(state: IStorageState, operation: Promise<unknown>, sessionId?: string): void {
1259
+ const tail = operation.then(() => undefined, () => undefined);
1260
+ state.scopeQueue = tail;
1261
+ if (sessionId === undefined) {
1262
+ state.wholeScopeQueue = tail;
1263
+ return;
1264
+ }
1265
+ state.sessionScopeQueues.set(sessionId, tail);
1266
+ void tail.then(() => {
1267
+ if (state.sessionScopeQueues.get(sessionId) === tail) state.sessionScopeQueues.delete(sessionId);
1268
+ });
1269
+ }
1270
+
1223
1271
  public async mutateScopeOwned<TValue>(
1224
1272
  state: IStorageState,
1225
1273
  mutation: () => TValue,
1274
+ onlySessionId?: string,
1226
1275
  ): Promise<TValue> {
1227
1276
  const beforeRevision = state.revision;
1228
1277
  const beforeSessions = new Map([...state.sessions].map(([id, stored]) => [id, {
@@ -1259,6 +1308,9 @@ export class FlexHarnessCore<TScope> {
1259
1308
  let result: TValue;
1260
1309
  try {
1261
1310
  result = mutation();
1311
+ if (onlySessionId !== undefined) {
1312
+ this.assertOnlySessionChanged(state, onlySessionId, beforeSessions, beforeTombstones, beforeRetainedCleanups);
1313
+ }
1262
1314
  } catch (error) {
1263
1315
  restore();
1264
1316
  throw error;
@@ -1304,6 +1356,37 @@ export class FlexHarnessCore<TScope> {
1304
1356
  }
1305
1357
  }
1306
1358
 
1359
+ /** Holds a mutation declared for one session to that session: no other session, tombstone or cleanup changed. */
1360
+ private assertOnlySessionChanged(
1361
+ state: IStorageState,
1362
+ sessionId: string,
1363
+ beforeSessions: ReadonlyMap<string, { stored: IStoredSessionState; metadata: IFlexSession }>,
1364
+ beforeTombstones: ReadonlyMap<string, IFlexSessionTombstone>,
1365
+ beforeRetainedCleanups: ReadonlyMap<string, unknown>,
1366
+ ): void {
1367
+ const changed = (id: string) => {
1368
+ if (id === sessionId) return false;
1369
+ const before = beforeSessions.get(id);
1370
+ const stored = state.sessions.get(id);
1371
+ if (before?.stored !== stored) return true;
1372
+ if (before && canonicalJson(before.stored.session) !== canonicalJson(before.metadata)) return true;
1373
+ if (canonicalJson(beforeTombstones.get(id)) !== canonicalJson(state.tombstones.get(id))) return true;
1374
+ return beforeRetainedCleanups.get(id) !== state.retainedSessionCleanups.get(id);
1375
+ };
1376
+ const ids = new Set([
1377
+ ...beforeSessions.keys(), ...state.sessions.keys(),
1378
+ ...beforeTombstones.keys(), ...state.tombstones.keys(),
1379
+ ...beforeRetainedCleanups.keys(), ...state.retainedSessionCleanups.keys(),
1380
+ ]);
1381
+ for (const id of ids) {
1382
+ if (changed(id)) {
1383
+ throw this.trustInternalError(new Error(
1384
+ `A scope mutation declared for session "${sessionId}" changed session "${id}".`,
1385
+ ));
1386
+ }
1387
+ }
1388
+ }
1389
+
1307
1390
  public mutateProjection<TValue>(
1308
1391
  state: IStorageState,
1309
1392
  stored: IStoredSessionState,
@@ -159,7 +159,7 @@ export class FlexHarnessPermissions<TScope> {
159
159
  run.pendingPermissionIds.add(request.permissionId);
160
160
  run.controller.signal.addEventListener('abort', abortListener, { once: true });
161
161
  try {
162
- await this.core.mutateScope(state, () => {
162
+ await this.core.mutateSessionScope(state, run.sessionId, () => {
163
163
  if (state.sessions.get(run.sessionId) !== run.stored) {
164
164
  throw new FlexHarnessAbortError('The session was deleted while permission was pending.');
165
165
  }
@@ -274,7 +274,7 @@ export class FlexHarnessPermissions<TScope> {
274
274
  stored.rememberedPermissionKeys.add(rememberKey);
275
275
  });
276
276
  }
277
- await this.core.mutateScope(state, () => {
277
+ await this.core.mutateSessionScope(state, pending.request.sessionId, () => {
278
278
  if (state.sessions.get(pending.request.sessionId) !== stored) {
279
279
  throw new FlexHarnessAbortError('The session was deleted while permission was resolving.');
280
280
  }
@@ -299,7 +299,7 @@ export class FlexHarnessPermissions<TScope> {
299
299
  && stored.session.status !== 'waiting_permission'
300
300
  ) {
301
301
  try {
302
- await this.core.mutateScope(state, () => {
302
+ await this.core.mutateSessionScope(state, pending.request.sessionId, () => {
303
303
  stored.session.status = 'waiting_permission';
304
304
  stored.session.activity.status = 'waiting_permission';
305
305
  stored.session.updatedAt = new Date().toISOString();
@@ -19,6 +19,7 @@ import type {
19
19
  IFlexSteerAdmission,
20
20
  IFlexSteerInput,
21
21
  IFlexPromptAdmission,
22
+ IFlexPromptAdmissionGeneration,
22
23
  IFlexPromptQueueAdmission,
23
24
  IFlexPromptQueueEntry,
24
25
  IFlexPromptOptions,
@@ -27,6 +28,7 @@ import type {
27
28
  IFlexSchedulePromptOptions,
28
29
  TFlexPrompt,
29
30
  TFlexAgentPrompt,
31
+ IFlexSession,
30
32
  } from './interfaces.js';
31
33
  import { cloneSerializable } from './utils.json.js';
32
34
  import { normalizeFlexPrompt, type INormalizedFlexPrompt } from './utils.prompt.js';
@@ -42,12 +44,21 @@ import type {
42
44
  IPendingPromptAdmission,
43
45
  IAdmittedSteer,
44
46
  } from './interfaces.flexharness.js';
45
- import { combineErrors, isAbortError } from './utils.flexharness.js';
47
+ import { combineErrors, isAbortError, requireSessionGeneration } from './utils.flexharness.js';
46
48
  import { sessionPreview } from './utils.sessionpreview.js';
47
49
  import type { FlexHarnessCore } from './classes.flexharness.core.js';
48
50
 
49
51
  const maxScheduleDebounceMs = 24 * 60 * 60 * 1000;
50
52
 
53
+ /** The generation an admission reports, read from the session in memory, never from the store. */
54
+ function promptAdmissionGeneration(session: Readonly<IFlexSession>): IFlexPromptAdmissionGeneration {
55
+ return Object.freeze({
56
+ ...requireSessionGeneration(session),
57
+ depth: session.depth ?? 0,
58
+ ...(session.configurationRef === undefined ? {} : { configurationRef: session.configurationRef }),
59
+ });
60
+ }
61
+
51
62
  function containsStoreCommitUncertainty(error: unknown, seen = new Set<unknown>()): boolean {
52
63
  if (error instanceof FlexHarnessStoreCommitUncertainError) return true;
53
64
  if (!(error instanceof Error) || seen.has(error)) return false;
@@ -565,7 +576,11 @@ export class FlexHarnessPromptQueue<TScope> {
565
576
  this.schedulePromptQueueDrain(state, stored);
566
577
  return {
567
578
  // The input determines whether the completed run has a user message.
568
- admission: Object.freeze({ queueId: queued.queueId, completion }) as IFlexPromptQueueAdmission<
579
+ admission: Object.freeze({
580
+ queueId: queued.queueId,
581
+ generation: promptAdmissionGeneration(stored.session),
582
+ completion,
583
+ }) as IFlexPromptQueueAdmission<
569
584
  TPrompt extends undefined ? IFlexContinuePromptResult : IFlexPromptResult
570
585
  >,
571
586
  started: started as Promise<IFlexPromptAdmission<
@@ -766,7 +781,7 @@ export class FlexHarnessPromptQueue<TScope> {
766
781
  if (reservation.userMessage) run.reservedUserMessage = publicSnapshot(reservation.userMessage);
767
782
  run.reservedAssistantMessage = publicSnapshot(reservation.assistantMessage);
768
783
  this.assertPromptPromotion(queued, run);
769
- await this.core.mutateScope(run.state, () => {
784
+ await this.core.mutateSessionScope(run.state, run.sessionId, () => {
770
785
  if (run.controller.signal.aborted) {
771
786
  throw run.controller.signal.reason ?? new FlexHarnessAbortError();
772
787
  }
@@ -854,6 +869,7 @@ export class FlexHarnessPromptQueue<TScope> {
854
869
  }
855
870
  queued.resolveStarted(Object.freeze({
856
871
  queueId: queued.queueId,
872
+ generation: promptAdmissionGeneration(run.stored.session),
857
873
  runId: run.runId,
858
874
  completion: queued.completion,
859
875
  }));
@@ -693,7 +693,7 @@ export class FlexHarnessRuns<TScope> {
693
693
  true,
694
694
  );
695
695
  let session!: IFlexSession;
696
- await this.core.mutateScope(run.state, () => {
696
+ await this.core.mutateSessionScope(run.state, run.sessionId, () => {
697
697
  if (run.state.sessions.get(run.sessionId) !== run.stored) {
698
698
  throw new FlexHarnessNotFoundError('Session', run.sessionId);
699
699
  }
@@ -1016,7 +1016,7 @@ export class FlexHarnessRuns<TScope> {
1016
1016
  run.stored.stagedTerminals = run.stored.stagedTerminals.filter((entry) => entry.runId !== run.runId);
1017
1017
  }, true);
1018
1018
  if (!this.core.isTombstoned(run) && !run.cacheWarm) {
1019
- await this.core.mutateScope(run.state, () => {
1019
+ await this.core.mutateSessionScope(run.state, run.sessionId, () => {
1020
1020
  if (run.state.sessions.get(run.sessionId) !== run.stored) return;
1021
1021
  const timestamp = terminal.assistantMessage.completedAt!;
1022
1022
  run.stored.session.status = 'idle';
@@ -1041,7 +1041,7 @@ export class FlexHarnessRuns<TScope> {
1041
1041
  }, true);
1042
1042
  // A failed cache-warm turn reports through `cache.warm.stopped`; the session keeps its state.
1043
1043
  if (run.cacheWarm) return;
1044
- await this.core.mutateScope(run.state, () => {
1044
+ await this.core.mutateSessionScope(run.state, run.sessionId, () => {
1045
1045
  if (run.state.sessions.get(run.sessionId) !== run.stored) return;
1046
1046
  const timestamp = terminal.assistantMessage.completedAt!;
1047
1047
  const activityStatus = terminal.status === 'completed' ? 'idle' : terminal.status;
@@ -1297,7 +1297,7 @@ export class FlexHarnessRuns<TScope> {
1297
1297
  }
1298
1298
  if (run.state.sessions.get(run.sessionId) === run.stored && run.stored.session.activity.runId === run.runId) {
1299
1299
  try {
1300
- await this.core.mutateScope(run.state, () => {
1300
+ await this.core.mutateSessionScope(run.state, run.sessionId, () => {
1301
1301
  run.stored.session.status = 'idle';
1302
1302
  run.stored.session.activity = { status: 'idle' };
1303
1303
  run.stored.session.updatedAt = new Date().toISOString();
@@ -262,7 +262,8 @@ export class FlexHarnessSessions<TScope> {
262
262
 
263
263
  public async getSession(scopeId: string, sessionId: string): Promise<IFlexSession> {
264
264
  const { state } = await this.core.resolveState(scopeId);
265
- await state.scopeQueue;
265
+ // Waits for the queued changes of this session only, never for another session's save.
266
+ await this.core.sessionReadBarrier(state, sessionId);
266
267
  this.core.assertStateAcceptingWork(state);
267
268
  return publicSnapshot(this.core.requireSession(state, sessionId).session);
268
269
  }
@@ -284,7 +285,7 @@ export class FlexHarnessSessions<TScope> {
284
285
  validateUpdateSessionOptions(options, this.core.agentSessionPolicy.contextCompactor !== undefined);
285
286
  const { state } = await this.core.resolveState(scopeId);
286
287
  let result!: IFlexSession;
287
- await this.core.mutateScope(state, () => {
288
+ await this.core.mutateSessionScope(state, sessionId, () => {
288
289
  const stored = Object.prototype.hasOwnProperty.call(options, 'archived')
289
290
  ? this.core.requireMutableSession(state, sessionId)
290
291
  : this.core.requireSession(state, sessionId);
@@ -209,7 +209,12 @@ export interface IStorageState {
209
209
  * describing it. A view waits until none is open, so it never shows a change without its event.
210
210
  */
211
211
  publications: Map<string, Set<Promise<void>>>;
212
+ /** Settles once every scope mutation queued so far has settled. */
212
213
  scopeQueue: Promise<void>;
214
+ /** Settles once every scope mutation that may change any session, queued so far, has settled. */
215
+ wholeScopeQueue: Promise<void>;
216
+ /** Per session, settles once every mutation queued so far that names only it has settled. */
217
+ sessionScopeQueues: Map<string, Promise<void>>;
213
218
  lifecycle: 'active' | 'retiring' | 'fenced' | 'retired';
214
219
  fenceInProgress: boolean;
215
220
  fenceAdditionalErrors: unknown[];
package/ts/interfaces.ts CHANGED
@@ -655,8 +655,25 @@ export interface IFlexSteerAdmission {
655
655
  runId: string;
656
656
  }
657
657
 
658
+ /**
659
+ * The session generation a prompt was admitted to, with the facts bound to it, as `getSession()`
660
+ * reports them. None of them changes while the generation lives, and a prompt only ever runs on
661
+ * the generation that admitted it.
662
+ */
663
+ export interface IFlexPromptAdmissionGeneration extends IFlexSessionGeneration {
664
+ /** 0 for a root session, also for a legacy root whose stored record omits it. */
665
+ depth: number;
666
+ /** The configuration revision bound to the generation; absent when the session has none. */
667
+ configurationRef?: string;
668
+ }
669
+
658
670
  export interface IFlexPromptQueueAdmission<TResult extends IFlexContinuePromptResult = IFlexPromptResult> {
659
671
  queueId: string;
672
+ /**
673
+ * The session generation that admitted the prompt. A caller needs no `getSession()` for it,
674
+ * which would wait for the session's queued writes.
675
+ */
676
+ generation: IFlexPromptAdmissionGeneration;
660
677
  completion: Promise<TResult>;
661
678
  }
662
679
 
package/ts/readme.md CHANGED
@@ -697,7 +697,11 @@ await harness.retireScope(scopeId);
697
697
  await harness.dispose();
698
698
  ```
699
699
 
700
- Only one run may be active in a session. Additional prompts enter a bounded FIFO owned by FlexHarness, while different sessions can run concurrently. `enqueuePrompt()` resolves with `{ queueId, completion }` after the immutable prompt and options have been accepted into that runtime queue and `prompt.queued` has been emitted. `startPrompt()` keeps its durable-admission behavior: it waits for its FIFO turn and resolves with `{ queueId, runId, completion }` only after the canonical generation claim, run ID, and initial public audit messages have been durably reserved and the corresponding start events have been emitted. `prompt()` preserves the simpler behavior by awaiting completion internally.
700
+ `getSession()` returns the session as saved after every queued write that may change it; it does not wait for queued writes of the scope's other sessions, so a slow save of one session never holds a read of another. `listSessions()` waits for every queued write.
701
+
702
+ Only one run may be active in a session. Additional prompts enter a bounded FIFO owned by FlexHarness, while different sessions can run concurrently. `enqueuePrompt()` resolves with `{ queueId, generation, completion }` after the immutable prompt and options have been accepted into that runtime queue and `prompt.queued` has been emitted. `startPrompt()` keeps its durable-admission behavior: it waits for its FIFO turn and resolves with `{ queueId, generation, runId, completion }` only after the canonical generation claim, run ID, and initial public audit messages have been durably reserved and the corresponding start events have been emitted. `prompt()` preserves the simpler behavior by awaiting completion internally.
703
+
704
+ Every admission names the session generation that admitted it: `generation` (`IFlexPromptAdmissionGeneration`) holds `sessionGenerationId`, `sessionGenerationSequence`, `depth` (0 for a root session, also a legacy root that stored none) and `configurationRef` when the session has one, as `getSession()` reports them. None of them changes while the generation lives, and the prompt only ever runs on that generation. The harness reads it from the session in memory, so a caller that needs it for the run it started does not call `getSession()`: that read waits for the session's queued writes, which queue behind every other session's write queued before them in the scope's one write FIFO.
701
705
 
702
706
  Queue entries expose `queued`, `starting`, `scheduled`, `running`, `completed`, `failed`, and `cancelled` status through `getPromptQueueEntry()` and `listPromptQueueEntries()`. The list is ordered by process-local `queueSequence`. `getPromptQueueEntry()` throws `FlexHarnessNotFoundError` for an unknown or evicted ID. `cancelPrompt()` cancels one exact queue ID: a waiting entry leaves the FIFO and releases capacity immediately but remains queryable as `cancelled` until terminal retention evicts it; a promoted entry uses the canonical run cancellation path and is stopped with the same `FlexHarnessAbortError` ("The run was aborted.") as `abort()`; only a waiting entry is rejected with "The queued prompt was cancelled.". A cancelled run, whether stopped or found interrupted on reload, puts its `error` on the assistant message only; its user message is `cancelled` without an `error`, while a failed run marks both messages. Cancelling a terminal entry returns `false`, while an unknown ID throws. `abort()` remains scoped to the currently active run.
703
707
 
@@ -740,7 +744,7 @@ no `prompt` or `promptId`: continuation creates a new run and an assistant messa
740
744
  without appending or modifying a user message. Its result has the prompt result's
741
745
  fields except `userMessage`. Explicit steers still become user messages normally.
742
746
 
743
- Admission returns `{ queueId, completion }` once queued, like `enqueuePrompt()`.
747
+ Admission returns `{ queueId, generation, completion }` once queued, like `enqueuePrompt()`.
744
748
  The entry and its `prompt.*` events carry `continuation: true`. Inspect its `runId`
745
749
  after `prompt.started`, or read it through `getPromptQueueEntry()`. Use the same
746
750
  `cancelPrompt()`, `cancelScheduledPrompt()`, `abort()` and `steerPrompt()` methods.
@@ -872,7 +876,7 @@ Two horizons bound undo. Retention pruning removes the oldest complete visible u
872
876
 
873
877
  Session metadata archival through `updateSession(..., { archived: true })` only sets `archivedAt`. It does not archive Agent events, retire captures, or remove undo history.
874
878
 
875
- `executeSlashCommand()` is the authoritative parser and lookup boundary. Its result distinguishes `not-command`, `malformed`, `unknown`, completed `operation`, bounded `handler-result`, and `prompt-admission`. A prompt admission contains the normal `{ queueId, runId, completion }`; await `admission.completion` for the model result. Unknown commands are never admitted as literal prompts. Known unavailable commands and invalid arguments throw typed FlexHarness errors. Options accept `promptId`, `modelHint`, `system`, `maxSteps`, and `signal`; commands do not accept attachments. For templates and `/init`, `promptId` follows the normal prompt contract: a non-empty string of at most 512 UTF-8 bytes, recorded on the queue entry and native user message (including exact transcript reads after restart or with `includeUndone`), with duplicate outstanding ids refused by `FlexHarnessDuplicatePromptError`. Results that admit no prompt (`operation`, `handler-result`, `unknown`, `not-command`, `malformed`) ignore `promptId` without recording or reserving it. `/compact` uses `modelHint` and `signal` and refuses `system` and `maxSteps` with `FlexHarnessValidationError`. Aborting a template or `init` execution cancels its exact queued or started prompt without affecting another queue entry.
879
+ `executeSlashCommand()` is the authoritative parser and lookup boundary. Its result distinguishes `not-command`, `malformed`, `unknown`, completed `operation`, bounded `handler-result`, and `prompt-admission`. A prompt admission contains the normal `{ queueId, generation, runId, completion }`; await `admission.completion` for the model result. Unknown commands are never admitted as literal prompts. Known unavailable commands and invalid arguments throw typed FlexHarness errors. Options accept `promptId`, `modelHint`, `system`, `maxSteps`, and `signal`; commands do not accept attachments. For templates and `/init`, `promptId` follows the normal prompt contract: a non-empty string of at most 512 UTF-8 bytes, recorded on the queue entry and native user message (including exact transcript reads after restart or with `includeUndone`), with duplicate outstanding ids refused by `FlexHarnessDuplicatePromptError`. Results that admit no prompt (`operation`, `handler-result`, `unknown`, `not-command`, `malformed`) ignore `promptId` without recording or reserving it. `/compact` uses `modelHint` and `signal` and refuses `system` and `maxSteps` with `FlexHarnessValidationError`. Aborting a template or `init` execution cancels its exact queued or started prompt without affecting another queue entry.
876
880
 
877
881
  Templates replace every `$ARGUMENTS` with untouched raw argument text. `$1` through the highest referenced positional placeholder use tokenized arguments, with the highest position receiving all remaining tokens joined by spaces. Missing positions become empty. A template with no placeholders appends non-empty raw arguments after a blank line. `/init` uses the OpenCode 1.18.15 `AGENTS.md` initialization prompt with provider-neutral active-workspace wording.
878
882