@niwa-labs/harness-mcode 0.0.0-stage → 0.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.
@@ -0,0 +1,445 @@
1
+ /**
2
+ * The durable history of a MiniMax Code installation: `<home>/durable-history/sessions.g1.db`, a
3
+ * sqlite database (WAL) the harness writes to as a session goes, message by message. A new
4
+ * session's `messages.jsonl` stays empty until the session is adopted; its history is only here.
5
+ *
6
+ * Layout: `entries(entry_id, seq, ordinal, batch_id)` points at `batches(batch_id, payload)`. A
7
+ * payload is `"MZS2"`, a codec byte (1 zstd, 2 gzip), two 8-byte lengths, and from byte 21 the
8
+ * frame, which holds a JSON array of `{id, parentId, kind, payload}`; `ordinal` is the place of the
9
+ * entry in that array. The entries of a session have ids that start with `<native id>|`.
10
+ *
11
+ * Two kinds carry the conversation: `history.v1.full` (`reason` seed or adopt, `envelopes[]`) states
12
+ * it whole, `history.v1.append` (`envelopes[]`) adds to it. An envelope is `{message_id, turn_id,
13
+ * message}`: the line of a journal. The active view is the last `full` and the appends after it,
14
+ * a message once. Other kinds (the offloads of tool output) are not conversation.
15
+ *
16
+ * The database is only ever opened read-only; this module writes nothing.
17
+ */
18
+
19
+ import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
20
+ import * as zlib from "node:zlib";
21
+ import { basename, dirname, join } from "node:path";
22
+
23
+ import { Database } from "bun:sqlite";
24
+ import { z } from "zod";
25
+
26
+ import { parseNativeRecord } from "./format.ts";
27
+ import type { McodeRecord } from "./format.ts";
28
+
29
+ const MAGIC = "MZS2";
30
+ const HEADER_BYTES = 21;
31
+ const CODEC_ZSTD = 1;
32
+ const CODEC_GZIP = 2;
33
+
34
+ const FULL = "history.v1.full";
35
+ const APPEND = "history.v1.append";
36
+
37
+ export const DURABLE_DIR = "durable-history";
38
+ export const DURABLE_NAME = "sessions.g1.db";
39
+
40
+ /** The database of an installation. */
41
+ export function durablePathOf(home: string): string {
42
+ return join(home, DURABLE_DIR, DURABLE_NAME);
43
+ }
44
+
45
+ // Match the producer's safeHistoryPathSegment. This encoding is not injective.
46
+ function sessionSegment(native: string): string {
47
+ return native.replace(/[<>:"/\\|?*\x00-\x1f]/gu, "-").replace(/^\.+/u, "").slice(0, 180) || "snapshot";
48
+ }
49
+
50
+ function checkedDirectory(root: string, components: string[]): string | undefined {
51
+ let directory = root;
52
+ for (const component of components) {
53
+ directory = join(directory, component);
54
+ const info = lstatSync(directory, { throwIfNoEntry: false });
55
+ if (info === undefined) return undefined;
56
+ if (!info.isDirectory()) throw new Error(`ncode: expected a session history directory at ${directory}`);
57
+ }
58
+ return directory;
59
+ }
60
+
61
+ /** The newest generation of Ncode's session log. Only the configured home may be a symlink. */
62
+ export function sessionDurablePath(home: string, native: string): string | undefined {
63
+ const directory = checkedDirectory(home, [DURABLE_DIR, "sessions", sessionSegment(native)]);
64
+ if (directory === undefined) return undefined;
65
+ let generation = 0;
66
+ for (const name of readdirSync(directory)) {
67
+ const match = /^sessions\.g([1-9]\d*)\.db$/.exec(name);
68
+ if (match === null) continue;
69
+ const value = Number(match[1]);
70
+ if (Number.isSafeInteger(value) && value > generation) generation = value;
71
+ }
72
+ if (generation === 0) return undefined;
73
+ const path = join(directory, `sessions.g${generation}.db`);
74
+ for (const suffix of ["", "-wal", "-shm", "-journal"]) {
75
+ const entry = lstatSync(path + suffix, { throwIfNoEntry: false });
76
+ if (entry !== undefined && !entry.isFile()) throw new Error(`ncode: invalid session history file at ${path + suffix}`);
77
+ }
78
+ return path;
79
+ }
80
+
81
+ /** One message of the active view, with where it was found. */
82
+ export interface DurableTurn {
83
+ /** The seq of the entry that carried the message. */
84
+ readonly seq: number;
85
+ /** The place of that entry in its batch. */
86
+ readonly ordinal: number;
87
+ /** The place of the envelope in that entry. */
88
+ readonly index: number;
89
+ /** The `message_id` of the envelope, when it has one. */
90
+ readonly messageId: string | undefined;
91
+ /** The envelope as the harness wrote it: what `raw` gives back. */
92
+ readonly raw: unknown;
93
+ /** The envelope read as a record of a journal; `null` when it is not one. */
94
+ readonly record: McodeRecord | null;
95
+ }
96
+
97
+ /**
98
+ * What one batch may inflate to. The database is the harness's own, but a batch that claims (or
99
+ * turns out to be) hundreds of megabytes is not conversation: it is refused, and the session reads
100
+ * as it did without the database, instead of the reader running out of memory.
101
+ */
102
+ export const MAX_BATCH_BYTES = 256 * 1024 * 1024;
103
+
104
+ /**
105
+ * The frame of a batch, inflated by the decoder of `node:zlib` with the cap given to it: the output
106
+ * is bounded while it is produced. Bun's own `zstdDecompressSync` has no bound, so it is never used;
107
+ * a runtime that has no bounded zstd decoder cannot read the batch.
108
+ */
109
+ function inflate(codec: number, frame: Uint8Array): Buffer {
110
+ const bounded = { maxOutputLength: MAX_BATCH_BYTES };
111
+ try {
112
+ if (codec === CODEC_GZIP) return zlib.gunzipSync(frame, bounded);
113
+ const zstd = (zlib as { zstdDecompressSync?: (input: Uint8Array, options: typeof bounded) => Buffer }).zstdDecompressSync;
114
+ if (typeof zstd !== "function") {
115
+ throw new Error("mcode: this runtime has no zstd decoder with a bound, a batch of the durable history cannot be read");
116
+ }
117
+ return zstd(frame, bounded);
118
+ } catch (error) {
119
+ if ((error as { code?: unknown }).code === "ERR_BUFFER_TOO_LARGE") {
120
+ throw new Error("mcode: a batch of the durable history is larger than it may be");
121
+ }
122
+ throw error;
123
+ }
124
+ }
125
+
126
+ /** The frame of a batch payload, decoded. */
127
+ export function decodeBatch(payload: Uint8Array): unknown[] {
128
+ const bytes = Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
129
+ if (bytes.length < HEADER_BYTES || bytes.subarray(0, 4).toString("latin1") !== MAGIC) {
130
+ throw new Error("mcode: a batch of the durable history has no MZS2 header");
131
+ }
132
+ if (bytes.readBigUInt64BE(5) > BigInt(MAX_BATCH_BYTES)) {
133
+ throw new Error("mcode: a batch of the durable history is larger than it may be");
134
+ }
135
+ const codec = bytes[4];
136
+ if (codec !== CODEC_ZSTD && codec !== CODEC_GZIP) {
137
+ throw new Error(`mcode: a batch of the durable history has an unknown codec ${String(codec)}`);
138
+ }
139
+ const text = inflate(codec, bytes.subarray(HEADER_BYTES));
140
+ const parsed: unknown = JSON.parse(text.toString("utf8"));
141
+ if (!Array.isArray(parsed)) throw new Error("mcode: a batch of the durable history is not an array");
142
+ return parsed;
143
+ }
144
+
145
+ /** The entries of a session lie between these two ids: `|` is followed by `}` in ASCII. */
146
+ function rangeOf(native: string): [string, string] {
147
+ return [`${native}|`, `${native}}`];
148
+ }
149
+
150
+ /**
151
+ * The database, read-only: no write lock is ever taken. A short busy timeout lets a read ride out
152
+ * the moment the harness's writer checkpoints, instead of failing at once.
153
+ */
154
+ function open(path: string): Database {
155
+ const db = new Database(path, { readonly: true });
156
+ try {
157
+ db.run("pragma busy_timeout = 250");
158
+ } catch (error) {
159
+ db.close();
160
+ throw error;
161
+ }
162
+ return db;
163
+ }
164
+
165
+ /**
166
+ * The durable history is an addition of a fork of the harness: with the regular harness there is
167
+ * no such file, and a file that is there but cannot be read must not break the reading side. A
168
+ * problem is told once per database, and the caller goes on as if the database had nothing.
169
+ */
170
+ const told = new Set<string>();
171
+
172
+ function tellOnce(path: string, error: unknown): void {
173
+ if (told.has(path)) return;
174
+ told.add(path);
175
+ const reason = error instanceof Error ? error.message : String(error);
176
+ console.warn(`mcode: the durable history ${path} cannot be read, it is ignored: ${reason}`);
177
+ }
178
+
179
+ /**
180
+ * Does the database hold any entry of this session? A database that is not there holds none;
181
+ * `null` when it is there and cannot be asked.
182
+ */
183
+ export function durableHasSession(path: string, native: string): boolean | null {
184
+ if (!existsSync(path)) return false;
185
+ try {
186
+ const db = open(path);
187
+ try {
188
+ const [low, high] = rangeOf(native);
189
+ return db.query("select 1 from entries where entry_id >= ? and entry_id < ? limit 1").get(low, high) !== null;
190
+ } finally {
191
+ db.close();
192
+ }
193
+ } catch (error) {
194
+ tellOnce(path, error);
195
+ return null;
196
+ }
197
+ }
198
+
199
+ /** The ids of the sessions the database holds. */
200
+ export function durableSessions(path: string): string[] {
201
+ if (!existsSync(path)) return [];
202
+ try {
203
+ const db = open(path);
204
+ try {
205
+ const rows = db
206
+ .query(
207
+ "select distinct substr(entry_id, 1, instr(entry_id, '|') - 1) as id from entries where entry_id >= 'mvs_' and entry_id < 'mvs`' and instr(entry_id, '|') > 0",
208
+ )
209
+ .all() as Array<{ id: string }>;
210
+ return rows.map((row) => row.id);
211
+ } finally {
212
+ db.close();
213
+ }
214
+ } catch (error) {
215
+ tellOnce(path, error);
216
+ return [];
217
+ }
218
+ }
219
+
220
+ /** Discover native identities only inside the fork's canonical per-session stores. */
221
+ export function* sessionStoreIds(home: string, wanted: Set<string> | undefined, listed: Set<string>): Generator<string> {
222
+ const root = checkedDirectory(home, [DURABLE_DIR, "sessions"]);
223
+ if (root === undefined) return;
224
+ const segments = wanted === undefined
225
+ ? readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name)
226
+ : new Set(Array.from(wanted, sessionSegment));
227
+ for (const segment of segments) {
228
+ if (segment !== sessionSegment(segment)) continue;
229
+ try {
230
+ const path = sessionDurablePath(home, segment);
231
+ if (path === undefined) continue;
232
+ const db = open(path);
233
+ try {
234
+ db.run("begin");
235
+ const rows = db.query<{ id: string }, []>(
236
+ "select distinct substr(entry_id, 1, instr(entry_id, '|') - 1) as id from entries where instr(entry_id, '|') > 1",
237
+ ).all();
238
+ for (const { id } of rows) {
239
+ if (sessionSegment(id) !== segment || listed.has(id) || (wanted && !wanted.has(id))) continue;
240
+ if (checkpointOf(db, path, id) || !entriesOf(db, id, true).next().done) yield id;
241
+ }
242
+ } finally {
243
+ db.close();
244
+ }
245
+ } catch (error) {
246
+ tellOnce(join(root, segment), error);
247
+ }
248
+ }
249
+ }
250
+
251
+ /**
252
+ * The active view of a session: the last full history and the appends after it, a message once.
253
+ * `null` when the database cannot be read (missing tables, an unknown codec, a decode error, a
254
+ * locked file): the caller falls back to what it did before the database was there.
255
+ */
256
+ export function readDurableSession(path: string, native: string): DurableTurn[] | null {
257
+ try {
258
+ return readView(path, native);
259
+ } catch (error) {
260
+ tellOnce(path, error);
261
+ return null;
262
+ }
263
+ }
264
+
265
+ /** One conversation entry of a session: where it lies and what it carries. */
266
+ interface Located {
267
+ readonly seq: number;
268
+ readonly ordinal: number;
269
+ readonly kind: typeof FULL | typeof APPEND;
270
+ readonly envelopes: unknown[];
271
+ }
272
+
273
+ /**
274
+ * The conversation entries of a session in the order they were written, one batch decoded at a
275
+ * time and only as far as the caller goes. The listing is built on the first of them; a batch is
276
+ * not decoded for an entry that is not conversation. Runs in one read transaction: a snapshot.
277
+ */
278
+ function* entriesOf(db: Database, native: string, sessionFile = false, afterSeq = -1): Generator<Located> {
279
+ const [low, high] = rangeOf(native);
280
+ const rows = db
281
+ .query(
282
+ "select entry_id, seq, ordinal, batch_id from entries where entry_id >= ? and entry_id < ? and seq > ? order by seq, ordinal",
283
+ )
284
+ .all(low, high, afterSeq) as Array<{ entry_id: string; seq: number; ordinal: number; batch_id: number }>;
285
+ const payload = db.query("select payload from batches where batch_id = ?");
286
+ // Entries of one batch lie together, so the last decoded batch is the one that is asked again.
287
+ let cached: { id: number; batch: unknown[] } | undefined;
288
+ for (const row of rows) {
289
+ if (cached?.id !== row.batch_id) {
290
+ const found = payload.get(row.batch_id) as { payload: Uint8Array } | null;
291
+ if (found === null) {
292
+ if (sessionFile) throw new Error("ncode: missing session history batch");
293
+ continue;
294
+ }
295
+ cached = { id: row.batch_id, batch: decodeBatch(found.payload) };
296
+ }
297
+ const entry = cached.batch[row.ordinal];
298
+ if (typeof entry !== "object" || entry === null) {
299
+ if (sessionFile) throw new Error("ncode: missing session history entry");
300
+ continue;
301
+ }
302
+ const { kind, payload: body } = entry as { kind?: unknown; payload?: unknown };
303
+ if (typeof kind !== "string" || !kind.startsWith("history.")) continue;
304
+ if (sessionFile && ((entry as { id?: unknown }).id !== row.entry_id ||
305
+ (body as { sessionId?: unknown } | null)?.sessionId !== native)) {
306
+ throw new Error("ncode: session history entry identity mismatch");
307
+ }
308
+ const envelopes = (body as { envelopes?: unknown } | null | undefined)?.envelopes;
309
+ if (sessionFile && kind === "history.v2.tombstone") {
310
+ yield { seq: row.seq, ordinal: row.ordinal, kind: FULL, envelopes: [] };
311
+ } else if (sessionFile && kind === "history.v2.replace" && Array.isArray(envelopes)) {
312
+ yield { seq: row.seq, ordinal: row.ordinal, kind: FULL, envelopes };
313
+ } else if (kind === FULL || kind === APPEND) {
314
+ if (sessionFile && !Array.isArray(envelopes)) throw new Error("ncode: missing session history envelopes");
315
+ yield { seq: row.seq, ordinal: row.ordinal, kind, envelopes: Array.isArray(envelopes) ? envelopes : [] };
316
+ } else if (sessionFile) {
317
+ throw new Error(`ncode: cannot materialize the active view for ${kind}`);
318
+ }
319
+ }
320
+ }
321
+
322
+ const checkpointSchema = z.object({
323
+ schema: z.literal(1),
324
+ sessionId: z.string(),
325
+ backendDirectory: z.string(),
326
+ backendGeneration: z.int().positive(),
327
+ backendSeq: z.int().nonnegative(),
328
+ fold: z.object({
329
+ lastEntryId: z.string(),
330
+ segmentCounts: z.array(z.int().nonnegative()),
331
+ segmentSeqs: z.array(z.int().nonnegative()),
332
+ envelopes: z.array(z.object({ message_id: z.string().min(1), turn_id: z.string(), message: z.looseObject({}) }).passthrough()),
333
+ }),
334
+ });
335
+
336
+ /** Ncode's disposable materialized fold. Validate its carrier and anchor in this read transaction. */
337
+ function checkpointOf(db: Database, path: string, native: string): Located | undefined {
338
+ const carrier = dirname(path);
339
+ const cache = join(dirname(dirname(carrier)), "fold-cache");
340
+ const file = join(cache, basename(carrier) + ".json");
341
+ if (!lstatSync(cache, { throwIfNoEntry: false })?.isDirectory()) return undefined;
342
+ const info = lstatSync(file, { throwIfNoEntry: false });
343
+ if (!info?.isFile() || info.size > MAX_BATCH_BYTES) return undefined;
344
+ try {
345
+ const parsed = checkpointSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
346
+ if (!parsed.success) return undefined;
347
+ const { sessionId, backendDirectory, backendGeneration, backendSeq, fold } = parsed.data;
348
+ if (sessionId !== native || backendDirectory !== carrier || basename(path) !== `sessions.g${backendGeneration}.db`) return undefined;
349
+ if (fold.segmentCounts.length !== fold.segmentSeqs.length ||
350
+ fold.segmentCounts.reduce((sum, count) => sum + count, 0) !== fold.envelopes.length ||
351
+ !fold.lastEntryId.startsWith(native + "|")) return undefined;
352
+ if (db.query("select 1 from entries where seq >= ? limit 1").get(backendSeq) === null) return undefined;
353
+ const [low, high] = rangeOf(native);
354
+ const anchor = db.query(
355
+ "select entry_id from entries where entry_id >= ? and entry_id < ? and seq <= ? order by seq desc, ordinal desc limit 1",
356
+ ).get(low, high, backendSeq) as { entry_id: string } | null;
357
+ if (anchor?.entry_id !== fold.lastEntryId) return undefined;
358
+ return { kind: FULL, seq: backendSeq, ordinal: 0, envelopes: fold.envelopes };
359
+ } catch {
360
+ return undefined;
361
+ }
362
+ }
363
+
364
+ function* activeEntries(db: Database, path: string, native: string, sessionFile: boolean): Generator<Located> {
365
+ const checkpoint = sessionFile ? checkpointOf(db, path, native) : undefined;
366
+ if (checkpoint !== undefined) yield checkpoint;
367
+ yield* entriesOf(db, native, sessionFile, checkpoint?.seq);
368
+ }
369
+
370
+ export function readView(path: string, native: string, sessionFile = false): DurableTurn[] {
371
+ if (!sessionFile && !existsSync(path)) return [];
372
+ const db = open(path);
373
+ try {
374
+ db.run("begin");
375
+ let view: DurableTurn[] = [];
376
+ const seen = new Set<string>();
377
+ for (const entry of activeEntries(db, path, native, sessionFile)) {
378
+ if (entry.kind === FULL) {
379
+ view = [];
380
+ seen.clear();
381
+ }
382
+ for (const [index, raw] of entry.envelopes.entries()) {
383
+ const messageId = messageIdOf(raw);
384
+ if (messageId !== undefined) {
385
+ if (seen.has(messageId)) continue;
386
+ seen.add(messageId);
387
+ }
388
+ view.push({ seq: entry.seq, ordinal: entry.ordinal, index, messageId, raw, record: parseNativeRecord(raw) });
389
+ }
390
+ }
391
+ return view;
392
+ } finally {
393
+ db.close();
394
+ }
395
+ }
396
+
397
+ /** What `durableFirst`'s `pick` answers to say that nothing further is to be looked at. */
398
+ export const STOP = Symbol("stop");
399
+
400
+ /**
401
+ * The first thing `pick` takes out of the envelopes of a session, in the order they were written,
402
+ * and no further: the listing wants a working directory from the head of a history, not the
403
+ * history. `pick` answers `undefined` to go on and `STOP` to end the look without a result.
404
+ * `undefined` when nothing was taken, `null` when the database cannot be read.
405
+ */
406
+ export function durableFirst<T>(
407
+ path: string,
408
+ native: string,
409
+ pick: (turn: DurableTurn) => T | undefined | typeof STOP,
410
+ ): T | undefined | null {
411
+ try {
412
+ if (!existsSync(path)) return undefined;
413
+ const db = open(path);
414
+ try {
415
+ db.run("begin");
416
+ for (const entry of entriesOf(db, native)) {
417
+ for (const [index, raw] of entry.envelopes.entries()) {
418
+ const taken = pick({
419
+ seq: entry.seq,
420
+ ordinal: entry.ordinal,
421
+ index,
422
+ messageId: messageIdOf(raw),
423
+ raw,
424
+ record: parseNativeRecord(raw),
425
+ });
426
+ if (taken === STOP) return undefined;
427
+ if (taken !== undefined) return taken;
428
+ }
429
+ }
430
+ return undefined;
431
+ } finally {
432
+ db.close();
433
+ }
434
+ } catch (error) {
435
+ tellOnce(path, error);
436
+ return null;
437
+ }
438
+ }
439
+
440
+ /** The `message_id` of an envelope, when it has one. */
441
+ export function messageIdOf(raw: unknown): string | undefined {
442
+ if (typeof raw !== "object" || raw === null) return undefined;
443
+ const id = (raw as { message_id?: unknown }).message_id;
444
+ return typeof id === "string" && id.length > 0 ? id : undefined;
445
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The fixtures of the conformance suite for MiniMax Code: the four scenarios written the way the
3
+ * harness writes them (format.ts, paths.ts). `home` is the directory the reading side is opened on.
4
+ */
5
+
6
+ import { appendFile, mkdir, rm, writeFile } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+
9
+ import type { FixtureResult, FixtureWriter, Scenario } from "@niwa-labs/harness";
10
+ import { harnessId, sessionId } from "@niwa-labs/harness";
11
+
12
+ import { LOG_NAME, MANIFEST_NAME, encodeNativeId } from "./paths.ts";
13
+
14
+ /** The installation id the fixtures are written for; the suite opens its reading side with it. */
15
+ export const FIXTURE_HARNESS = harnessId("mcode");
16
+
17
+ const line = (message: object): string => `${JSON.stringify({ message_id: "m", message })}\n`;
18
+ const user = (text: string): string => line({ role: "user", timestamp: 1000, content: text });
19
+ const answer = (text: string): string =>
20
+ line({ role: "assistant", timestamp: 2000, model: "mcode-1", content: [{ type: "text", text }] });
21
+
22
+ /** The half-written line is cut inside a string: not parseable until the rest arrives. */
23
+ const FINAL_ANSWER = answer("the finished answer");
24
+ const CUT = FINAL_ANSWER.length - 12;
25
+
26
+ export const writeMcodeFixtures: FixtureWriter = async (home, scenario) => {
27
+ const native = `mvs_${scenario}`;
28
+ const dir = join(
29
+ home,
30
+ "v2",
31
+ "sessions",
32
+ "2026",
33
+ "10",
34
+ "07",
35
+ `12-00-00-000-session_${encodeNativeId(native)}`,
36
+ );
37
+ await mkdir(dir, { recursive: true });
38
+ await writeFile(
39
+ join(dir, MANIFEST_NAME),
40
+ JSON.stringify({ sessionId: native, createdAtMs: 1000, updatedAtMs: 2000 }),
41
+ );
42
+ const log = join(dir, LOG_NAME);
43
+ const body = bodyOf(scenario);
44
+ await writeFile(log, body.text);
45
+
46
+ const result: FixtureResult = {
47
+ session: sessionId(FIXTURE_HARNESS, native),
48
+ ...(body.child === undefined ? {} : { child: sessionId(FIXTURE_HARNESS, body.child) }),
49
+ ...(body.summary === undefined ? {} : { summary: body.summary }),
50
+ ...(scenario === "running"
51
+ ? { finish: () => appendFile(log, FINAL_ANSWER.slice(CUT)) }
52
+ : {}),
53
+ makeUnreadable: async () => {
54
+ await rm(log);
55
+ await mkdir(log);
56
+ },
57
+ remove: () => rm(dir, { recursive: true, force: true }),
58
+ };
59
+ return result;
60
+ };
61
+
62
+ function bodyOf(scenario: Scenario): { text: string; child?: string; summary?: string } {
63
+ const start = user("hello") + answer("hi there");
64
+ switch (scenario) {
65
+ case "running":
66
+ return { text: start + FINAL_ANSWER.slice(0, CUT) };
67
+ case "nested":
68
+ return {
69
+ text:
70
+ start +
71
+ line({
72
+ role: "assistant",
73
+ timestamp: 3000,
74
+ content: [{ type: "toolCall", id: "call_1", name: "task", arguments: { prompt: "work" } }],
75
+ }) +
76
+ line({
77
+ role: "toolResult",
78
+ timestamp: 4000,
79
+ toolCallId: "call_1",
80
+ toolName: "task",
81
+ content: [{ type: "text", text: 'started session_id="mvs_child"' }],
82
+ }),
83
+ child: "mvs_child",
84
+ };
85
+ case "compaction":
86
+ return {
87
+ text: start + line({ role: "compactionSummary", timestamp: 3000, summary: "what happened so far" }),
88
+ summary: "what happened so far",
89
+ };
90
+ case "broken":
91
+ return { text: `${start}{"unfamiliar":"shape"}\nnot json at all\n` };
92
+ }
93
+ }