@modelprofile.com/flexharness 9.3.1 → 9.5.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/ts/errors.ts CHANGED
@@ -44,6 +44,17 @@ export class FlexHarnessSessionBusyError extends FlexHarnessError {
44
44
  }
45
45
  }
46
46
 
47
+ /** An operation would change the history or model context of an imported, read-only session. */
48
+ export class FlexHarnessImportedSessionError extends FlexHarnessError {
49
+ public readonly sessionId: string;
50
+
51
+ constructor(sessionId: string) {
52
+ super('FLEX_SESSION_READ_ONLY', `Session "${sessionId}" is an imported conversation and is read-only.`);
53
+ this.name = 'FlexHarnessImportedSessionError';
54
+ this.sessionId = sessionId;
55
+ }
56
+ }
57
+
47
58
  export class FlexHarnessSlashCommandUnavailableError extends FlexHarnessError {
48
59
  public readonly commandName: string;
49
60
  public readonly unavailableReason: string;
package/ts/interfaces.ts CHANGED
@@ -169,8 +169,129 @@ export interface IFlexSession {
169
169
  parentToolCallId?: string;
170
170
  agent?: string;
171
171
  depth?: number;
172
+ /** Set only on a session the staged session import created; such a session is read-only. */
173
+ origin?: IFlexSessionOrigin;
172
174
  }
173
175
 
176
+ /** The position of an imported session when one source conversation was split into several sessions. */
177
+ export interface IFlexSessionImportPart {
178
+ /** Zero-based position of this session among the parts. */
179
+ index: number;
180
+ /** The number of parts the source was split into. */
181
+ count: number;
182
+ }
183
+
184
+ /** What an import caller states about the source of the history it imports. */
185
+ export interface IFlexSessionImportSource {
186
+ /** The kind of source, for example `claude-code-transcript`. */
187
+ source: string;
188
+ /** The source's own identifier of the conversation. */
189
+ sourceId: string;
190
+ /** The caller's digest of the source content; a changed source has a changed digest. */
191
+ digest: string;
192
+ part?: IFlexSessionImportPart;
193
+ /** Source-specific metadata, for example the source working directory or what the conversion lost. */
194
+ details?: IJsonObject;
195
+ }
196
+
197
+ /** Where an imported session's history came from. */
198
+ export interface IFlexSessionOrigin extends IFlexSessionImportSource {
199
+ kind: 'import';
200
+ /** When FlexHarness committed the import. */
201
+ importedAt: string;
202
+ }
203
+
204
+ /** The imported parent session, run and tool call an imported child session belongs to. */
205
+ export interface IFlexSessionImportParent {
206
+ sessionId: string;
207
+ runId: string;
208
+ toolCallId: string;
209
+ agent: string;
210
+ }
211
+
212
+ export interface IFlexBeginSessionImportOptions {
213
+ /** Caller-chosen and deterministic, so a repeated import finds the earlier one. */
214
+ sessionId: string;
215
+ title?: string;
216
+ /** When the source conversation started, as `Date.prototype.toISOString()` renders it. */
217
+ createdAt: string;
218
+ /** When the source conversation last changed; defaults to `createdAt`. */
219
+ updatedAt?: string;
220
+ origin: IFlexSessionImportSource;
221
+ parent?: IFlexSessionImportParent;
222
+ }
223
+
224
+ export interface IFlexSessionImportHandle {
225
+ importId: string;
226
+ scopeId: string;
227
+ sessionId: string;
228
+ }
229
+
230
+ export interface IFlexSessionImportStarted {
231
+ status: 'started';
232
+ handle: IFlexSessionImportHandle;
233
+ }
234
+
235
+ /**
236
+ * A session with the same source, source id and part already exists. `already_imported` means its
237
+ * digest equals the requested one; `digest_mismatch` means the source changed since that import.
238
+ */
239
+ export interface IFlexSessionImportExisting {
240
+ status: 'already_imported' | 'digest_mismatch';
241
+ session: IFlexSession;
242
+ }
243
+
244
+ export type TFlexBeginSessionImportResult = IFlexSessionImportStarted | IFlexSessionImportExisting;
245
+
246
+ /** One imported run: a user message and the assistant message that answered it. */
247
+ export interface IFlexImportedRun {
248
+ user: IFlexMessage;
249
+ assistant: IFlexMessage;
250
+ }
251
+
252
+ export interface IFlexSessionImportProgress {
253
+ runs: number;
254
+ messages: number;
255
+ bytes: number;
256
+ }
257
+
258
+ export interface IFlexSessionImportLimits {
259
+ /** Staged imports open at once in one FlexHarness. */
260
+ maxOpenImports?: number;
261
+ /** Messages in one imported session, two per run. */
262
+ maxMessagesPerSession?: number;
263
+ /** JSON bytes of all messages of one imported session. */
264
+ maxSessionBytes?: number;
265
+ /** JSON bytes of the runs one `appendImportedRuns()` call carries. */
266
+ maxPageBytes?: number;
267
+ /**
268
+ * Milliseconds a staged import may stay without an `appendImportedRuns()` call. An expired
269
+ * import is discarded as if it were aborted, which frees its slot and its staged memory.
270
+ */
271
+ stagedImportIdleTimeoutMs?: number;
272
+ }
273
+
274
+ /** JSON bytes of one imported message; a larger message could not be read back whole. */
275
+ export const FLEX_SESSION_IMPORT_MAX_MESSAGE_BYTES = 480 * 1024;
276
+ export const FLEX_SESSION_IMPORT_MAX_DETAILS_BYTES = 16 * 1024;
277
+ export const FLEX_SESSION_IMPORT_MAX_DEPTH = 8;
278
+
279
+ export const FLEX_SESSION_IMPORT_DEFAULT_LIMITS = Object.freeze({
280
+ maxOpenImports: 2,
281
+ maxMessagesPerSession: 2048,
282
+ maxSessionBytes: 64 * 1024 * 1024,
283
+ maxPageBytes: 1024 * 1024,
284
+ stagedImportIdleTimeoutMs: 5 * 60 * 1000,
285
+ });
286
+
287
+ export const FLEX_SESSION_IMPORT_MAXIMUM_LIMITS = Object.freeze({
288
+ maxOpenImports: 64,
289
+ maxMessagesPerSession: 20_000,
290
+ maxSessionBytes: 256 * 1024 * 1024,
291
+ maxPageBytes: 1536 * 1024,
292
+ stagedImportIdleTimeoutMs: 60 * 60 * 1000,
293
+ });
294
+
174
295
  export interface IFlexCreateSessionOptions {
175
296
  sessionId?: string;
176
297
  sessionGenerationId?: string;
@@ -1059,8 +1180,31 @@ export interface IFlexAgentContextInvocation<TScope = unknown> {
1059
1180
  readonly sessionId: string;
1060
1181
  }
1061
1182
 
1183
+ /**
1184
+ * The options a `contextCompactor` receives. `resolvedModel` and `modelHint` state the model the
1185
+ * compacted work was dispatched on; when both are absent nothing dispatched states one and the
1186
+ * host chooses the compaction model.
1187
+ */
1062
1188
  export interface IFlexAgentContextCompactionOptions<TScope = unknown>
1063
- extends plugins.IAgentContextCompactionOptions, IFlexAgentContextInvocation<TScope> {}
1189
+ extends plugins.IAgentContextCompactionOptions, IFlexAgentContextInvocation<TScope> {
1190
+ /**
1191
+ * Set when `reason` is `'context-overflow'`: the model the run whose context overflowed resolved
1192
+ * and generates with, as `IFlexModelResolver.resolveModel()` returned it for that run. A
1193
+ * delegated run's overflow carries the delegated run's own model.
1194
+ */
1195
+ readonly resolvedModel?: Readonly<IFlexResolvedModel>;
1196
+ /**
1197
+ * Set when `reason` is `'manual'` and the compaction was requested with a model hint: the
1198
+ * `modelHint` of the `/compact` slash command's execution options or of `compactSession()`.
1199
+ * Resolve it as the model resolver resolves a prompt's `modelHint`.
1200
+ */
1201
+ readonly modelHint?: string;
1202
+ }
1203
+
1204
+ export interface IFlexCompactSessionOptions {
1205
+ /** The model hint the compactor receives as `modelHint`. */
1206
+ modelHint?: string;
1207
+ }
1064
1208
 
1065
1209
  export type TFlexAgentContextCompactor<TScope = unknown> = (
1066
1210
  messages: Parameters<plugins.TAgentContextCompactor>[0],
@@ -1111,6 +1255,7 @@ export interface IFlexHarnessOptions<TScope> {
1111
1255
  callbackLimits?: IFlexCallbackLimits;
1112
1256
  promptQueueLimits?: IFlexPromptQueueLimits;
1113
1257
  reversionLimits?: IFlexReversionLimits;
1258
+ sessionImportLimits?: IFlexSessionImportLimits;
1114
1259
  /**
1115
1260
  * Bounds each turn-reversion maintenance operation. Falls back to
1116
1261
  * agentSessionPolicy.generationLeaseCleanupTimeoutMs, then 30 seconds.
package/ts/readme.md CHANGED
@@ -235,6 +235,13 @@ const harness = new FlexHarness<IProjectScope>({
235
235
  maxExcludedRunIds: 1000,
236
236
  maxPendingReversionReleases: 1000,
237
237
  },
238
+ sessionImportLimits: {
239
+ maxOpenImports: 2,
240
+ maxMessagesPerSession: 2048,
241
+ maxSessionBytes: 64 * 1024 * 1024,
242
+ maxPageBytes: 1024 * 1024,
243
+ stagedImportIdleTimeoutMs: 5 * 60 * 1000,
244
+ },
238
245
  subagents: [
239
246
  {
240
247
  name: 'researcher',
@@ -580,7 +587,7 @@ const undone = await harness.undoSession(scopeId, sessionId);
580
587
  console.log(undone.revertedRunId);
581
588
  const redone = await harness.redoSession(scopeId, sessionId);
582
589
  console.log(redone.restoredRunId);
583
- await harness.compactSession(scopeId, sessionId);
590
+ await harness.compactSession(scopeId, sessionId, { modelHint: 'summary-model' });
584
591
  await harness.archiveSessionEvents(scopeId, sessionId, compactionEventId);
585
592
  await harness.listBackgroundExecutions(scopeId, sessionId);
586
593
  await harness.getBackgroundExecution(scopeId, sessionId, executionId);
@@ -667,7 +674,7 @@ Two horizons bound undo. Retention pruning removes the oldest complete visible u
667
674
 
668
675
  Session metadata archival through `updateSession(..., { archived: true })` only sets `archivedAt`. It does not archive Agent events, retire captures, or remove undo history.
669
676
 
670
- `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 `modelHint`, `system`, `maxSteps`, and `signal`; commands do not accept attachments. Aborting a template or `init` execution cancels its exact queued or started prompt without affecting another queue entry.
677
+ `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 `modelHint`, `system`, `maxSteps`, and `signal`; commands do not accept attachments. `/compact` takes `modelHint` and `signal` only 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.
671
678
 
672
679
  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.
673
680
 
@@ -805,6 +812,82 @@ Public audit history is safe to send to controllers: attachment parts contain so
805
812
 
806
813
  Sessions expose `idle`, `scheduled`, `running`, `waiting_permission`, `failed`, and `cancelled` status. Persisted non-terminal activity is repaired from canonical Agent generation outcomes after process restart; incomplete messages and parts normalize to `cancelled` unless an accepted hidden terminal stage can be promoted.
807
814
 
815
+ ## Conversation Import
816
+
817
+ A finished conversation from another tool can be imported as an archived, read-only session. The import is staged in three steps, so a large conversation crosses a process boundary in bounded pages. Turning a source format into Flex messages is the importer's job; the core validates, bounds, persists and protects the result.
818
+
819
+ ```typescript
820
+ const started = await harness.beginSessionImport('project:billing', {
821
+ sessionId: 'claude-7f3c2a',
822
+ title: 'Fix the billing export',
823
+ createdAt: '2026-09-01T09:00:00.000Z',
824
+ updatedAt: '2026-09-01T11:00:00.000Z',
825
+ origin: {
826
+ source: 'claude-code-transcript',
827
+ sourceId: '7f3c2a',
828
+ digest: 'sha256:9b1d…',
829
+ details: { cwd: '/workspace' },
830
+ },
831
+ });
832
+
833
+ if (started.status === 'started') {
834
+ try {
835
+ for (const page of pages) {
836
+ await harness.appendImportedRuns(started.handle, page);
837
+ }
838
+ const session = await harness.commitSessionImport(started.handle);
839
+ } finally {
840
+ await harness.abortSessionImport(started.handle);
841
+ }
842
+ }
843
+ ```
844
+
845
+ - **`beginSessionImport(scopeId, options)`** validates the options and reserves the caller-chosen `sessionId`. Choose a deterministic id, derived from the source. The result is one of three:
846
+ - `started`, with a handle `{ importId, scopeId, sessionId }`;
847
+ - `already_imported`, with the existing session;
848
+ - `digest_mismatch`, with the existing session.
849
+
850
+ A scope holds at most one import per `origin.source`, `origin.sourceId` and `origin.part.index`, whatever its session id. `already_imported` means that session has the same `origin.digest`, so the caller skips it. `digest_mismatch` means the source changed since; the caller deletes that session and imports again. A staged import of the same session id or source identity throws `FlexHarnessSessionBusyError`. Until the commit completes, `listSessions()` omits the session and `createSession()` refuses its id. While the import is staged, `getSession()` throws `FlexHarnessSessionBusyError`. While its commit runs, `getSession()` throws `FlexHarnessNotFoundError`, because a deletion tombstone reserves the id.
851
+ - **`appendImportedRuns(handle, runs)`** stages one page of runs, in order. A run is `{ user, assistant }`, two messages of the exact `IFlexMessage` shape. Both belong to the imported session, share one `runId` and one terminal status (`completed`, `failed` or `cancelled`), and have no `running` reasoning or tool part. Timestamps are ISO 8601 as `Date.prototype.toISOString()` renders them. Run ids and message ids are unique within the import. A page that breaks a rule or a bound stages nothing, and the import stays open. The result reports the staged `runs`, `messages` and `bytes`.
852
+ - **`commitSessionImport(handle)`** persists the runs and publishes the session, with one `session.created` event:
853
+ - `origin` is `{ kind: 'import', source, sourceId, digest, part?, details?, importedAt }`, and `archivedAt` equals `importedAt`;
854
+ - `createdAt` and `updatedAt` are the ones passed to `beginSessionImport()`, and the status is `idle`.
855
+
856
+ The commit first persists a deletion tombstone for the id, then writes the projection, then replaces the tombstone with the session in one scope save. A failed commit removes what it persisted through the normal tombstone cleanup. After a crash, or a save whose outcome is uncertain, the next load of the namespace resolves it: a surviving tombstone is cleaned up, and a published session is kept. A commit needs at least one run.
857
+ - **`abortSessionImport(handle)`** discards a staged import. Nothing of it was persisted. An unknown or finished handle is ignored, so the call is safe in a `finally`. A staged import that receives no `appendImportedRuns()` call for `stagedImportIdleTimeoutMs` expires and is discarded the same way; its handle then reports `FlexHarnessNotFoundError`.
858
+ - **Child sessions.** `parent: { sessionId, runId, toolCallId, agent }` imports a child session, such as a subagent's conversation. The parent must be a committed imported session in the same scope. Its assistant message of `runId` must hold the tool call `toolCallId` whose `childSessionId` names the child. No other session may claim that tool call. The child gets `depth` one below its parent, at most `FLEX_SESSION_IMPORT_MAX_DEPTH` (8). Deleting the parent deletes its children.
859
+
860
+ **Read-only.** An imported session never runs, and nothing writes model context for it: it has no Agent events and no tool jobs. Every operation that would change its history or model context throws `FlexHarnessImportedSessionError` (code `FLEX_SESSION_READ_ONLY`):
861
+
862
+ - `prompt`, `startPrompt`, `enqueuePrompt` and `schedulePrompt`;
863
+ - `executeSlashCommand` and `compactSession`;
864
+ - `undoSession` and `redoSession`;
865
+ - `pushRuntimeEvent`, `reconcileToolExecution` and `archiveSessionEvents`;
866
+ - the project-management writes: tasks, goal and scratchpad.
867
+
868
+ `listSlashCommands()` reports every command unavailable with the reason `Session is an imported conversation and is read-only.` Reads work: sessions, messages, message pages, reversion info and project state. So do `updateSession()` (title and archived flag), `deleteSession()` and `deleteSessionGenerationCohort()`. A load never repairs an imported session's runs from Agent generation outcomes, because it has none.
869
+
870
+ **Bounds.** `sessionImportLimits` sets the bounds; each must be an integer from 1 through its maximum:
871
+
872
+ | Limit | Default | Maximum |
873
+ |---|---|---|
874
+ | `maxOpenImports` (staged imports at once, per harness) | 2 | 64 |
875
+ | `maxMessagesPerSession` | 2048 | 20000 |
876
+ | `maxSessionBytes` (JSON bytes of all messages) | 64 MiB | 256 MiB |
877
+ | `maxPageBytes` (JSON bytes of one `appendImportedRuns()` page) | 1 MiB | 1.5 MiB |
878
+ | `stagedImportIdleTimeoutMs` (idle time before a staged import expires) | 5 minutes | 1 hour |
879
+
880
+ Some bounds are fixed:
881
+
882
+ - one message is at most `FLEX_SESSION_IMPORT_MAX_MESSAGE_BYTES` (480 KiB), and must read back through the message transfer limits;
883
+ - `origin.details` is a JSON object of at most `FLEX_SESSION_IMPORT_MAX_DETAILS_BYTES` (16 KiB);
884
+ - `origin.source` is at most 128 UTF-8 bytes, `origin.sourceId` 512 and `origin.digest` 256, none with control characters;
885
+ - `origin.part` has a `count` from 1 through 1024 and a zero-based `index` below it.
886
+
887
+ Staged runs are held in memory until the commit, so the memory of open imports is bounded by `maxOpenImports` × `maxSessionBytes`. Retiring the scope, disposing the harness or the idle expiry discards staged imports. The expiry timer does not keep the process alive.
888
+
889
+ **Stores.** The import adds no store method. Scope snapshots carry the optional session `origin`, and a store that validates session keys exactly must accept it. The commit writes the whole projection in one save at revision 1. FlexHarness versions before 9.5.0 reject the new key under their strict reader, so a downgrade over imported sessions is unsupported.
890
+
808
891
  ## Permissions
809
892
 
810
893
  Tools request permission through the run-scoped provider context:
@@ -851,6 +934,28 @@ Transactional tool calls persist an execution intent before the tool side effect
851
934
 
852
935
  `executionContextProvider` can construct a AgentSession execution context for each session. FlexHarness supplies the resolved scope, storage key, and the session's private job store. The public background APIs expose only execution ID, type, state, exit code, and timestamps; command payloads, stdout, and stderr remain private. The provider's optional `close()` is owned by session deletion, scope retirement, and harness disposal.
853
936
 
937
+ ### Context Compaction Model
938
+
939
+ A `contextCompactor` states which model to compact with from the model the compacted work was dispatched on, never from a host default that may name another account:
940
+
941
+ | `reason` | Compaction | Model members |
942
+ | --- | --- | --- |
943
+ | `context-overflow` | A run's context overflowed, including a delegated run's | `resolvedModel`: the `IFlexResolvedModel` the model resolver returned for that run, frozen; a delegated run's overflow carries the delegated run's own model |
944
+ | `manual` | `/compact` or `compactSession()` | `modelHint`: the `modelHint` of the `/compact` execution options or of `compactSession(scopeId, sessionId, { modelHint })`, when one was passed |
945
+ | `retention` | Event retention | none |
946
+
947
+ A compactor uses `resolvedModel.model` directly, and resolves `modelHint` the way its model resolver resolves a prompt's `modelHint`. Only when neither member is present, because nothing dispatched states a model, does the host choose the compaction model itself.
948
+
949
+ ```typescript
950
+ agentSessionPolicy: {
951
+ contextCompactor: async (messages, _events, options) => {
952
+ const model = options.resolvedModel?.model
953
+ ?? await resolveHostModel(options.scopeId, options.modelHint);
954
+ return compactMessages(model, messages, options);
955
+ },
956
+ },
957
+ ```
958
+
854
959
  ## Events
855
960
 
856
961
  ```typescript
package/ts/utils.json.ts CHANGED
@@ -494,10 +494,12 @@ function validateSession(value: unknown, path: string): IValidatedSessionIdentit
494
494
  'parentToolCallId',
495
495
  'agent',
496
496
  'depth',
497
+ 'origin',
497
498
  ],
498
499
  path,
499
500
  );
500
501
  requireString(session.scopeId, `${path}.scopeId`);
502
+ if (session.origin !== undefined) validateSessionOrigin(session.origin, `${path}.origin`);
501
503
  const sessionId = requireString(session.sessionId, `${path}.sessionId`);
502
504
  const generation = validateOptionalSessionGeneration(session, path);
503
505
  requireOptionalString(session.title, `${path}.title`);
@@ -555,6 +557,41 @@ function validateSession(value: unknown, path: string): IValidatedSessionIdentit
555
557
  };
556
558
  }
557
559
 
560
+ function validateSessionOrigin(value: unknown, path: string): void {
561
+ const origin = requireRecord(value, path);
562
+ requireOnlyKeys(
563
+ origin,
564
+ ['kind', 'source', 'sourceId', 'digest', 'importedAt', 'part', 'details'],
565
+ path,
566
+ );
567
+ if (origin.kind !== 'import') {
568
+ throw new FlexHarnessStoreFormatError(`${path}.kind is invalid.`);
569
+ }
570
+ requireString(origin.source, `${path}.source`);
571
+ requireString(origin.sourceId, `${path}.sourceId`);
572
+ requireString(origin.digest, `${path}.digest`);
573
+ requireString(origin.importedAt, `${path}.importedAt`);
574
+ if (origin.part !== undefined) {
575
+ const part = requireRecord(origin.part, `${path}.part`);
576
+ requireOnlyKeys(part, ['index', 'count'], `${path}.part`);
577
+ requireNonNegativeInteger(part.index, `${path}.part.index`);
578
+ requireNonNegativeInteger(part.count, `${path}.part.count`);
579
+ if (Number(part.index) >= Number(part.count)) {
580
+ throw new FlexHarnessStoreFormatError(`${path}.part.index must be below part.count.`);
581
+ }
582
+ }
583
+ if (origin.details !== undefined) requireRecord(origin.details, `${path}.details`);
584
+ }
585
+
586
+ /**
587
+ * Asserts the exact stored shape of one public message: its keys, part kinds and field types.
588
+ * Throws `FlexHarnessStoreFormatError`.
589
+ */
590
+ export function assertFlexMessageRecord(value: unknown, path: string): void {
591
+ assertJsonSerializable(value, path);
592
+ validateMessage(value, path);
593
+ }
594
+
558
595
  function validateSubagentProvenance(
559
596
  value: unknown,
560
597
  path: string,