@modelprofile.com/flexharness 9.4.0 → 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;
@@ -1134,6 +1255,7 @@ export interface IFlexHarnessOptions<TScope> {
1134
1255
  callbackLimits?: IFlexCallbackLimits;
1135
1256
  promptQueueLimits?: IFlexPromptQueueLimits;
1136
1257
  reversionLimits?: IFlexReversionLimits;
1258
+ sessionImportLimits?: IFlexSessionImportLimits;
1137
1259
  /**
1138
1260
  * Bounds each turn-reversion maintenance operation. Falls back to
1139
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',
@@ -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:
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,
@@ -0,0 +1,327 @@
1
+ import { FlexHarnessValidationError } from './errors.js';
2
+ import {
3
+ FLEX_PROJECT_MANAGEMENT_LIMITS,
4
+ FLEX_SESSION_IMPORT_DEFAULT_LIMITS,
5
+ FLEX_SESSION_IMPORT_MAXIMUM_LIMITS,
6
+ FLEX_SESSION_IMPORT_MAX_DETAILS_BYTES,
7
+ FLEX_SESSION_IMPORT_MAX_MESSAGE_BYTES,
8
+ } from './interfaces.js';
9
+ import type {
10
+ IFlexBeginSessionImportOptions,
11
+ IFlexImportedRun,
12
+ IFlexMessage,
13
+ IFlexSessionImportHandle,
14
+ IFlexSessionImportLimits,
15
+ IFlexSessionImportParent,
16
+ IFlexSessionImportPart,
17
+ IFlexSessionImportSource,
18
+ IJsonObject,
19
+ } from './interfaces.js';
20
+ import { maxSubagentNameBytes } from './utils.harnessoptions.js';
21
+ import { assertFlexMessageRecord, assertJsonSerializable, cloneSerializable } from './utils.json.js';
22
+ import {
23
+ createBoundedTransferMessage,
24
+ jsonBytes,
25
+ maxTransferIdentifierBytes,
26
+ requireTransferIdentifier,
27
+ } from './utils.transfer.js';
28
+ import { validateIdentifier, validateUtf8String } from './utils.validation.js';
29
+
30
+ const maxSourceBytes = 128;
31
+ const maxDigestBytes = 256;
32
+ const maxImportParts = 1024;
33
+ const controlCharacterPattern = /[\u0000-\u001f\u007f]/u;
34
+
35
+ export interface INormalizedSessionImportOptions {
36
+ sessionId: string;
37
+ title?: string;
38
+ createdAt: string;
39
+ updatedAt: string;
40
+ origin: IFlexSessionImportSource;
41
+ parent?: IFlexSessionImportParent;
42
+ }
43
+
44
+ export interface INormalizedImportedRunPage {
45
+ runs: IFlexImportedRun[];
46
+ bytes: number;
47
+ }
48
+
49
+ export function resolveSessionImportLimits(
50
+ limits: IFlexSessionImportLimits = {},
51
+ ): Required<IFlexSessionImportLimits> {
52
+ const resolved = {
53
+ maxOpenImports: limits.maxOpenImports ?? FLEX_SESSION_IMPORT_DEFAULT_LIMITS.maxOpenImports,
54
+ maxMessagesPerSession: limits.maxMessagesPerSession
55
+ ?? FLEX_SESSION_IMPORT_DEFAULT_LIMITS.maxMessagesPerSession,
56
+ maxSessionBytes: limits.maxSessionBytes ?? FLEX_SESSION_IMPORT_DEFAULT_LIMITS.maxSessionBytes,
57
+ maxPageBytes: limits.maxPageBytes ?? FLEX_SESSION_IMPORT_DEFAULT_LIMITS.maxPageBytes,
58
+ stagedImportIdleTimeoutMs: limits.stagedImportIdleTimeoutMs
59
+ ?? FLEX_SESSION_IMPORT_DEFAULT_LIMITS.stagedImportIdleTimeoutMs,
60
+ };
61
+ for (const [name, value] of Object.entries(resolved)) {
62
+ const maximum = FLEX_SESSION_IMPORT_MAXIMUM_LIMITS[name as keyof IFlexSessionImportLimits];
63
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
64
+ throw new FlexHarnessValidationError(
65
+ `sessionImportLimits.${name} must be an integer from 1 through ${maximum}.`,
66
+ );
67
+ }
68
+ }
69
+ return resolved;
70
+ }
71
+
72
+ function requirePlainRecord(value: unknown, name: string): Record<string, unknown> {
73
+ if (
74
+ !value
75
+ || typeof value !== 'object'
76
+ || Array.isArray(value)
77
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))
78
+ ) {
79
+ throw new FlexHarnessValidationError(`${name} must be a plain object.`);
80
+ }
81
+ return value as Record<string, unknown>;
82
+ }
83
+
84
+ function requireKnownKeys(
85
+ record: Record<string, unknown>,
86
+ allowedKeys: readonly string[],
87
+ name: string,
88
+ ): void {
89
+ const unsupported = Reflect.ownKeys(record).find((key) =>
90
+ typeof key !== 'string' || !allowedKeys.includes(key));
91
+ if (unsupported !== undefined) {
92
+ throw new FlexHarnessValidationError(`${name} does not support "${String(unsupported)}".`);
93
+ }
94
+ }
95
+
96
+ function requireBoundedText(value: unknown, name: string, maxBytes: number): string {
97
+ validateUtf8String(value, name, maxBytes, true);
98
+ if (controlCharacterPattern.test(value)) {
99
+ throw new FlexHarnessValidationError(`${name} must not contain control characters.`);
100
+ }
101
+ return value;
102
+ }
103
+
104
+ /** A timestamp exactly as `Date.prototype.toISOString()` renders it. */
105
+ export function requireCanonicalTimestamp(value: unknown, name: string): string {
106
+ if (typeof value !== 'string' || value.length > 64) {
107
+ throw new FlexHarnessValidationError(`${name} must be an ISO 8601 timestamp.`);
108
+ }
109
+ const time = Date.parse(value);
110
+ if (!Number.isFinite(time) || new Date(time).toISOString() !== value) {
111
+ throw new FlexHarnessValidationError(
112
+ `${name} must be an ISO 8601 timestamp as Date.prototype.toISOString() renders it.`,
113
+ );
114
+ }
115
+ return value;
116
+ }
117
+
118
+ function normalizeImportPart(value: unknown): IFlexSessionImportPart {
119
+ const part = requirePlainRecord(value, 'origin.part');
120
+ requireKnownKeys(part, ['index', 'count'], 'origin.part');
121
+ const { index, count } = part;
122
+ if (
123
+ !Number.isSafeInteger(count)
124
+ || Number(count) < 1
125
+ || Number(count) > maxImportParts
126
+ || !Number.isSafeInteger(index)
127
+ || Number(index) < 0
128
+ || Number(index) >= Number(count)
129
+ ) {
130
+ throw new FlexHarnessValidationError(
131
+ `origin.part must have a count from 1 through ${maxImportParts} and a zero-based index below it.`,
132
+ );
133
+ }
134
+ return { index: index as number, count: count as number };
135
+ }
136
+
137
+ function normalizeImportDetails(value: unknown): IJsonObject {
138
+ requirePlainRecord(value, 'origin.details');
139
+ try {
140
+ assertJsonSerializable(value, 'origin.details');
141
+ } catch (error) {
142
+ throw new FlexHarnessValidationError('origin.details must be a JSON object.', { cause: error });
143
+ }
144
+ if (jsonBytes(value) > FLEX_SESSION_IMPORT_MAX_DETAILS_BYTES) {
145
+ throw new FlexHarnessValidationError(
146
+ `origin.details must be at most ${FLEX_SESSION_IMPORT_MAX_DETAILS_BYTES} JSON bytes.`,
147
+ );
148
+ }
149
+ return cloneSerializable(value as IJsonObject);
150
+ }
151
+
152
+ function normalizeImportSource(value: unknown): IFlexSessionImportSource {
153
+ const origin = requirePlainRecord(value, 'origin');
154
+ requireKnownKeys(origin, ['source', 'sourceId', 'digest', 'part', 'details'], 'origin');
155
+ return {
156
+ source: requireBoundedText(origin.source, 'origin.source', maxSourceBytes),
157
+ sourceId: requireBoundedText(origin.sourceId, 'origin.sourceId', maxTransferIdentifierBytes),
158
+ digest: requireBoundedText(origin.digest, 'origin.digest', maxDigestBytes),
159
+ ...(origin.part === undefined ? {} : { part: normalizeImportPart(origin.part) }),
160
+ ...(origin.details === undefined ? {} : { details: normalizeImportDetails(origin.details) }),
161
+ };
162
+ }
163
+
164
+ function normalizeImportParent(value: unknown): IFlexSessionImportParent {
165
+ const parent = requirePlainRecord(value, 'parent');
166
+ requireKnownKeys(parent, ['sessionId', 'runId', 'toolCallId', 'agent'], 'parent');
167
+ return {
168
+ sessionId: requireBoundedText(parent.sessionId, 'parent.sessionId', maxTransferIdentifierBytes),
169
+ runId: requireBoundedText(parent.runId, 'parent.runId', maxTransferIdentifierBytes),
170
+ toolCallId: requireBoundedText(parent.toolCallId, 'parent.toolCallId', maxTransferIdentifierBytes),
171
+ agent: requireBoundedText(parent.agent, 'parent.agent', maxSubagentNameBytes),
172
+ };
173
+ }
174
+
175
+ export function normalizeBeginSessionImportOptions(
176
+ options: IFlexBeginSessionImportOptions,
177
+ ): INormalizedSessionImportOptions {
178
+ const record = requirePlainRecord(options, 'beginSessionImport options');
179
+ requireKnownKeys(
180
+ record,
181
+ ['sessionId', 'title', 'createdAt', 'updatedAt', 'origin', 'parent'],
182
+ 'beginSessionImport options',
183
+ );
184
+ const sessionId = record.sessionId as string;
185
+ validateIdentifier(sessionId, 'sessionId');
186
+ requireTransferIdentifier(sessionId, 'sessionId');
187
+ if (record.title !== undefined) {
188
+ validateUtf8String(record.title, 'title', FLEX_PROJECT_MANAGEMENT_LIMITS.maxTitleBytes, true);
189
+ }
190
+ const createdAt = requireCanonicalTimestamp(record.createdAt, 'createdAt');
191
+ const updatedAt = record.updatedAt === undefined
192
+ ? createdAt
193
+ : requireCanonicalTimestamp(record.updatedAt, 'updatedAt');
194
+ if (Date.parse(updatedAt) < Date.parse(createdAt)) {
195
+ throw new FlexHarnessValidationError('updatedAt must not be earlier than createdAt.');
196
+ }
197
+ const parent = record.parent === undefined ? undefined : normalizeImportParent(record.parent);
198
+ if (parent?.sessionId === sessionId) {
199
+ throw new FlexHarnessValidationError('An imported session cannot be its own parent.');
200
+ }
201
+ return {
202
+ sessionId,
203
+ ...(record.title === undefined ? {} : { title: record.title as string }),
204
+ createdAt,
205
+ updatedAt,
206
+ origin: normalizeImportSource(record.origin),
207
+ ...(parent === undefined ? {} : { parent }),
208
+ };
209
+ }
210
+
211
+ /** The identity an import is idempotent by: its source, source id and part. */
212
+ export function sessionImportIdentity(
213
+ origin: Pick<IFlexSessionImportSource, 'source' | 'sourceId' | 'part'>,
214
+ ): string {
215
+ return JSON.stringify([origin.source, origin.sourceId, origin.part?.index ?? null]);
216
+ }
217
+
218
+ function normalizeImportedMessage(
219
+ value: unknown,
220
+ path: string,
221
+ role: IFlexMessage['role'],
222
+ sessionId: string,
223
+ ): { message: IFlexMessage; bytes: number } {
224
+ try {
225
+ assertFlexMessageRecord(value, path);
226
+ } catch (error) {
227
+ throw new FlexHarnessValidationError(
228
+ `${path} is not a valid message: ${error instanceof Error ? error.message : String(error)}`,
229
+ { cause: error },
230
+ );
231
+ }
232
+ const message = cloneSerializable(value as IFlexMessage);
233
+ if (message.role !== role) {
234
+ throw new FlexHarnessValidationError(`${path}.role must be "${role}".`);
235
+ }
236
+ if (message.sessionId !== sessionId) {
237
+ throw new FlexHarnessValidationError(`${path}.sessionId must be the imported session "${sessionId}".`);
238
+ }
239
+ if (message.status === 'streaming') {
240
+ throw new FlexHarnessValidationError(`${path}.status must be completed, failed or cancelled.`);
241
+ }
242
+ requireCanonicalTimestamp(message.createdAt, `${path}.createdAt`);
243
+ if (message.completedAt !== undefined) {
244
+ requireCanonicalTimestamp(message.completedAt, `${path}.completedAt`);
245
+ }
246
+ for (const [index, part] of message.parts.entries()) {
247
+ if (part.type !== 'reasoning' && part.type !== 'tool') continue;
248
+ if (part.status === 'running') {
249
+ throw new FlexHarnessValidationError(`${path}.parts[${index}] must not be running.`);
250
+ }
251
+ }
252
+ const bytes = jsonBytes(message);
253
+ if (bytes > FLEX_SESSION_IMPORT_MAX_MESSAGE_BYTES) {
254
+ throw new FlexHarnessValidationError(
255
+ `${path} exceeds ${FLEX_SESSION_IMPORT_MAX_MESSAGE_BYTES} JSON bytes.`,
256
+ );
257
+ }
258
+ try {
259
+ createBoundedTransferMessage(message);
260
+ } catch (error) {
261
+ throw new FlexHarnessValidationError(`${path} cannot be read back within the transfer limits.`, {
262
+ cause: error,
263
+ });
264
+ }
265
+ return { message, bytes };
266
+ }
267
+
268
+ /**
269
+ * Validates one page of imported runs. Every message must belong to `sessionId`, be terminal and
270
+ * fit the transfer limits; a run's user and assistant message share its run id and status.
271
+ */
272
+ export function normalizeImportedRunPage(
273
+ runs: readonly IFlexImportedRun[],
274
+ sessionId: string,
275
+ maxPageBytes: number,
276
+ ): INormalizedImportedRunPage {
277
+ if (!Array.isArray(runs) || runs.length === 0) {
278
+ throw new FlexHarnessValidationError('Imported runs must be a non-empty array.');
279
+ }
280
+ let pageBytes: number;
281
+ try {
282
+ assertJsonSerializable(runs, 'runs');
283
+ pageBytes = jsonBytes(runs);
284
+ } catch (error) {
285
+ throw new FlexHarnessValidationError('Imported runs must be JSON-safe.', { cause: error });
286
+ }
287
+ if (pageBytes > maxPageBytes) {
288
+ throw new FlexHarnessValidationError(`Imported runs exceed the page limit of ${maxPageBytes} JSON bytes.`);
289
+ }
290
+ const normalized: IFlexImportedRun[] = [];
291
+ let bytes = 0;
292
+ for (const [index, value] of runs.entries()) {
293
+ const path = `runs[${index}]`;
294
+ const run = requirePlainRecord(value, path);
295
+ requireKnownKeys(run, ['user', 'assistant'], path);
296
+ const user = normalizeImportedMessage(run.user, `${path}.user`, 'user', sessionId);
297
+ const assistant = normalizeImportedMessage(run.assistant, `${path}.assistant`, 'assistant', sessionId);
298
+ if (user.message.runId !== assistant.message.runId) {
299
+ throw new FlexHarnessValidationError(`${path} user and assistant messages must share one runId.`);
300
+ }
301
+ if (user.message.messageId === assistant.message.messageId) {
302
+ throw new FlexHarnessValidationError(`${path} user and assistant messages must have distinct ids.`);
303
+ }
304
+ if (user.message.status !== assistant.message.status) {
305
+ throw new FlexHarnessValidationError(`${path} user and assistant messages must share one status.`);
306
+ }
307
+ normalized.push({ user: user.message, assistant: assistant.message });
308
+ bytes += user.bytes + assistant.bytes;
309
+ }
310
+ return { runs: normalized, bytes };
311
+ }
312
+
313
+ /** Validates the shape of a handle `beginSessionImport()` returned. */
314
+ export function validateSessionImportHandle(handle: IFlexSessionImportHandle): IFlexSessionImportHandle {
315
+ const record = requirePlainRecord(handle, 'Session import handle');
316
+ requireKnownKeys(record, ['importId', 'scopeId', 'sessionId'], 'Session import handle');
317
+ for (const key of ['importId', 'scopeId', 'sessionId'] as const) {
318
+ if (typeof record[key] !== 'string' || record[key] === '') {
319
+ throw new FlexHarnessValidationError(`Session import handle ${key} must be a non-empty string.`);
320
+ }
321
+ }
322
+ return {
323
+ importId: record.importId as string,
324
+ scopeId: record.scopeId as string,
325
+ sessionId: record.sessionId as string,
326
+ };
327
+ }