@nextclaw/kernel 0.19.4 → 0.19.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. package/dist/app/worker/index.d.ts +1 -1
  2. package/dist/app/worker/index.js +2 -2
  3. package/dist/index.d.ts +2 -2
  4. package/dist/index.js +15 -32
  5. package/dist/index.js.map +1 -1
  6. package/dist/{ncp-agent-session-journal-entry.utils-Dh0Ck_oW.js → ncp-agent-session-journal-entry.utils-oYJG8jpX.js} +2 -2
  7. package/dist/{ncp-agent-session-journal-entry.utils-Dh0Ck_oW.js.map → ncp-agent-session-journal-entry.utils-oYJG8jpX.js.map} +1 -1
  8. package/dist/{ncp-agent-session-journal.utils-B7a_PKCq.js → ncp-agent-session-journal.utils-CkymaYrF.js} +15 -11
  9. package/dist/ncp-agent-session-journal.utils-CkymaYrF.js.map +1 -0
  10. package/dist/{ncp-agent-session-message-projection-tail.store-5sjmoFxv.js → ncp-agent-session-message-projection-tail.store-_7hsonM_.js} +3 -3
  11. package/dist/{ncp-agent-session-message-projection-tail.store-5sjmoFxv.js.map → ncp-agent-session-message-projection-tail.store-_7hsonM_.js.map} +1 -1
  12. package/dist/{nextclaw-harness.manager-j0JHST4g.d.ts → nextclaw-harness.manager-CHnoMH-B.d.ts} +5 -3
  13. package/dist/nextclaw-harness.manager-CHnoMH-B.d.ts.map +1 -0
  14. package/dist/{nextclaw-harness.manager-mJToWeCB.js → nextclaw-harness.manager-ajpoljL-.js} +13 -4
  15. package/dist/{nextclaw-harness.manager-mJToWeCB.js.map → nextclaw-harness.manager-ajpoljL-.js.map} +1 -1
  16. package/dist/{session-journal-maintenance.store-DrZMlaxf.js → session-journal-maintenance.store-B9HFTpW5.js} +32 -27
  17. package/dist/session-journal-maintenance.store-B9HFTpW5.js.map +1 -0
  18. package/package.json +9 -9
  19. package/dist/ncp-agent-session-journal.utils-B7a_PKCq.js.map +0 -1
  20. package/dist/nextclaw-harness.manager-j0JHST4g.d.ts.map +0 -1
  21. package/dist/session-journal-maintenance.store-DrZMlaxf.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { c as isRecord$1, d as safeNcpSessionFilename, f as toIsoString, l as normalizeNcpAgentId, m as SessionEventReplayer, o as createNcpAgentSessionJournalMetadataEntry, u as normalizeNcpSessionId, v as SessionReplaySupersessionTracker } from "./ncp-agent-session-journal.utils-B7a_PKCq.js";
1
+ import { c as isRecord$1, d as safeNcpSessionFilename, f as toIsoString, l as normalizeNcpAgentId, m as SessionEventReplayer, o as createNcpAgentSessionJournalMetadataEntry, u as normalizeNcpSessionId, v as SessionReplaySupersessionTracker } from "./ncp-agent-session-journal.utils-CkymaYrF.js";
2
2
  import { i as isSessionJournalDelta, n as canCoalesceSessionJournalDeltas, r as coalesceSessionJournalDeltas } from "./session-journal-delta-coalescer.utils-CI-N-Zpj.js";
3
- import { t as scanSessionJournal } from "./ncp-agent-session-journal-entry.utils-Dh0Ck_oW.js";
3
+ import { t as scanSessionJournal } from "./ncp-agent-session-journal-entry.utils-oYJG8jpX.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { createHash, randomUUID } from "node:crypto";
6
6
  import { join } from "node:path";
@@ -279,6 +279,27 @@ var SessionJournalLoaderStore = class {
279
279
  };
280
280
  };
281
281
  //#endregion
282
+ //#region src/utils/session-journal-durability.utils.ts
283
+ /** Node cannot flush a Windows directory handle; source and intent files are still flushed. */
284
+ async function syncSessionJournalDirectory(path) {
285
+ if (process.platform === "win32") return;
286
+ const handle = await open(path, "r");
287
+ try {
288
+ await handle.sync();
289
+ } finally {
290
+ await handle.close();
291
+ }
292
+ }
293
+ /** FlushFileBuffers requires a writable handle on Windows, including copied backup files. */
294
+ async function syncSessionJournalFile(path) {
295
+ const handle = await open(path, process.platform === "win32" ? "r+" : "r");
296
+ try {
297
+ await handle.sync();
298
+ } finally {
299
+ await handle.close();
300
+ }
301
+ }
302
+ //#endregion
282
303
  //#region src/stores/session-journal-maintenance.store.ts
283
304
  var session_journal_maintenance_store_exports = /* @__PURE__ */ __exportAll({
284
305
  assertSessionJournalTailComplete: () => assertSessionJournalTailComplete,
@@ -300,22 +321,6 @@ function paths(journalDir, sessionId) {
300
321
  projection: join(journalDir, ".message-projections", basename)
301
322
  };
302
323
  }
303
- async function syncDirectory(path) {
304
- const handle = await open(path, "r");
305
- try {
306
- await handle.sync();
307
- } finally {
308
- await handle.close();
309
- }
310
- }
311
- async function syncFile(path) {
312
- const handle = await open(path, "r");
313
- try {
314
- await handle.sync();
315
- } finally {
316
- await handle.close();
317
- }
318
- }
319
324
  async function hashFile(path) {
320
325
  const hash = createHash("sha256");
321
326
  for await (const chunk of createReadStream(path)) hash.update(chunk);
@@ -409,7 +414,7 @@ async function invalidateDerivedState(journalDir, sessionId, projection) {
409
414
  } finally {
410
415
  database.close();
411
416
  }
412
- await syncDirectory(journalDir);
417
+ await syncSessionJournalDirectory(journalDir);
413
418
  }
414
419
  /** Runs before the catalog opens. An interrupted switch always rolls back to the untouched backup. */
415
420
  async function recoverSessionJournalMaintenance(journalDir) {
@@ -431,7 +436,7 @@ async function recoverSessionJournalMaintenance(journalDir) {
431
436
  if (marker.snapshot?.hadSource === false) await rm(source, { force: true });
432
437
  else {
433
438
  await copyFile(backup, restore);
434
- await syncFile(restore);
439
+ await syncSessionJournalFile(restore);
435
440
  await rename(restore, source);
436
441
  }
437
442
  if (marker.snapshot) {
@@ -445,7 +450,7 @@ async function recoverSessionJournalMaintenance(journalDir) {
445
450
  await invalidateDerivedState(journalDir, sessionId, join(journalDir, ".message-projections", name.slice(0, -(".jsonl" + suffix).length)));
446
451
  await rm(`${source}.pending`, { force: true });
447
452
  await rm(join(journalDir, name));
448
- await syncDirectory(journalDir);
453
+ await syncSessionJournalDirectory(journalDir);
449
454
  if (marker.snapshot) await rm(backup, { force: true });
450
455
  }
451
456
  }
@@ -511,22 +516,22 @@ async function writeMaintenanceMarker(journalDir, target, sessionId) {
511
516
  await marker.close();
512
517
  }
513
518
  await rename(target.markerDraft, target.marker);
514
- await syncDirectory(journalDir);
519
+ await syncSessionJournalDirectory(journalDir);
515
520
  }
516
521
  async function activateCompactedJournal(journalDir, sessionId, target, sourceStat) {
517
522
  let renamed = false;
518
523
  try {
519
524
  await copyFile(target.source, target.backup, constants.COPYFILE_EXCL);
520
- await syncFile(target.backup);
525
+ await syncSessionJournalFile(target.backup);
521
526
  await assertSourceUnchanged(target.source, sourceStat);
522
527
  await writeMaintenanceMarker(journalDir, target, sessionId);
523
528
  await assertSourceUnchanged(target.source, sourceStat);
524
529
  await rename(target.pending, target.source);
525
530
  renamed = true;
526
- await syncDirectory(journalDir);
531
+ await syncSessionJournalDirectory(journalDir);
527
532
  await invalidateDerivedState(journalDir, sessionId, target.projection);
528
533
  await rm(target.marker);
529
- await syncDirectory(journalDir);
534
+ await syncSessionJournalDirectory(journalDir);
530
535
  } catch (error) {
531
536
  if (renamed) await recoverSessionJournalMaintenance(journalDir);
532
537
  else {
@@ -616,6 +621,6 @@ async function compactSessionJournal(input) {
616
621
  }
617
622
  }
618
623
  //#endregion
619
- export { restoreSessionJournalBackup as a, NcpAgentSessionMetadataStore as c, recoverSessionJournalTornTail as i, openSqliteDatabase as l, compactSessionJournal as n, session_journal_maintenance_store_exports as o, recoverSessionJournalMaintenance as r, SessionJournalLoaderStore as s, assertSessionJournalTailComplete as t, runSqliteTransaction as u };
624
+ export { restoreSessionJournalBackup as a, syncSessionJournalFile as c, openSqliteDatabase as d, runSqliteTransaction as f, recoverSessionJournalTornTail as i, SessionJournalLoaderStore as l, compactSessionJournal as n, session_journal_maintenance_store_exports as o, recoverSessionJournalMaintenance as r, syncSessionJournalDirectory as s, assertSessionJournalTailComplete as t, NcpAgentSessionMetadataStore as u };
620
625
 
621
- //# sourceMappingURL=session-journal-maintenance.store-DrZMlaxf.js.map
626
+ //# sourceMappingURL=session-journal-maintenance.store-B9HFTpW5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-journal-maintenance.store-B9HFTpW5.js","names":["isRecord","syncDirectory","syncFile"],"sources":["../src/stores/sqlite-database.store.ts","../src/stores/ncp-agent-session-metadata.store.ts","../src/stores/session-journal-loader.store.ts","../src/utils/session-journal-durability.utils.ts","../src/stores/session-journal-maintenance.store.ts"],"sourcesContent":["import { existsSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Database, SqlJsStatic, Statement } from \"sql.js\";\n\nexport type SqliteStatement = {\n all: (...params: unknown[]) => unknown[];\n get: (...params: unknown[]) => unknown;\n run: (...params: unknown[]) => unknown;\n};\n\nexport type SqliteDatabase = {\n /** Hosts whose atomic transaction blocks timers can supply a microtask yield. */\n transactionYield?: () => Promise<void>;\n close: () => void;\n exec: (sql: string) => void;\n prepare: (sql: string) => SqliteStatement;\n};\n\nconst require = createRequire(import.meta.url);\nconst portableDatabases = new Map<string, Promise<PortableSqliteDatabase>>();\n\nexport async function openSqliteDatabase(\n databasePath: string,\n options: { incremental?: boolean } = {},\n): Promise<SqliteDatabase> {\n try {\n const native = require(\"node:sqlite\") as {\n DatabaseSync: new (path: string) => SqliteDatabase;\n };\n return new native.DatabaseSync(databasePath);\n } catch (error) {\n if (!isMissingNodeSqlite(error)) throw error;\n if (options.incremental) {\n const { default: Database } = await import(\"libsql\");\n return new Database(databasePath) as unknown as SqliteDatabase;\n }\n return await openPortableDatabase(databasePath);\n }\n}\n\nexport function runSqliteTransaction<T>(\n database: SqliteDatabase,\n operation: () => T,\n mode: \"DEFERRED\" | \"IMMEDIATE\" = \"DEFERRED\",\n): T {\n database.exec(`BEGIN ${mode}`);\n try {\n const result = operation();\n database.exec(\"COMMIT\");\n return result;\n } catch (error) {\n database.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\nfunction isMissingNodeSqlite(error: unknown): boolean {\n const code =\n typeof error === \"object\" && error !== null\n ? (error as { code?: unknown }).code\n : undefined;\n return code === \"ERR_UNKNOWN_BUILTIN_MODULE\" || code === \"MODULE_NOT_FOUND\";\n}\n\nasync function openPortableDatabase(\n databasePath: string,\n): Promise<SqliteDatabase> {\n const existing = portableDatabases.get(databasePath);\n if (existing) return (await existing).acquire();\n const opening = createPortableDatabase(databasePath).catch((error) => {\n portableDatabases.delete(databasePath);\n throw error;\n });\n portableDatabases.set(databasePath, opening);\n return (await opening).acquire();\n}\n\nasync function createPortableDatabase(\n databasePath: string,\n): Promise<PortableSqliteDatabase> {\n const imported = await import(\"sql.js\");\n const initialize = imported.default as unknown as (params: {\n locateFile: (file: string) => string;\n }) => Promise<SqlJsStatic>;\n const sqlite = await initialize({\n locateFile: resolveSqlJsAsset,\n });\n const database = existsSync(databasePath)\n ? new sqlite.Database(readFileSync(databasePath))\n : new sqlite.Database();\n return new PortableSqliteDatabase(databasePath, database);\n}\n\nfunction resolveSqlJsAsset(file: string): string {\n try {\n return require.resolve(`sql.js/dist/${file}`);\n } catch (error) {\n const bundledAssetPath = fileURLToPath(new URL(file, import.meta.url));\n if (file === \"sql-wasm.wasm\" && existsSync(bundledAssetPath)) {\n return bundledAssetPath;\n }\n throw error;\n }\n}\n\nclass PortableSqliteDatabase {\n private inTransaction = false;\n private dirty = false;\n private leaseCount = 0;\n\n constructor(\n private readonly databasePath: string,\n private readonly database: Database,\n ) {}\n\n acquire = (): SqliteDatabase => {\n this.leaseCount += 1;\n return new PortableSqliteLease(this);\n };\n\n exec = (sql: string): void => {\n const command = sql.trim().toUpperCase();\n this.database.run(sql);\n if (command.startsWith(\"BEGIN\")) {\n this.inTransaction = true;\n return;\n }\n if (command.startsWith(\"ROLLBACK\")) {\n this.inTransaction = false;\n this.dirty = false;\n return;\n }\n if (command.startsWith(\"COMMIT\")) {\n this.inTransaction = false;\n this.persistIfDirty();\n return;\n }\n if (!command.startsWith(\"PRAGMA\")) this.markDirty();\n };\n\n prepare = (sql: string): SqliteStatement =>\n new PortableSqliteStatement(this, sql);\n\n release = (): void => {\n this.leaseCount -= 1;\n if (this.leaseCount > 0) return;\n this.persistIfDirty();\n this.database.close();\n portableDatabases.delete(this.databasePath);\n };\n\n run = (sql: string, params: unknown[]): void => {\n this.database.run(\n sql,\n normalizeParams(params) as Parameters<Database[\"run\"]>[1],\n );\n this.markDirty();\n };\n\n readRows = (sql: string, params: unknown[]): unknown[] => {\n const statement = this.database.prepare(sql);\n try {\n bindStatement(statement, params);\n const rows: unknown[] = [];\n while (statement.step()) rows.push(statement.getAsObject());\n return rows;\n } finally {\n statement.free();\n }\n };\n\n private markDirty = (): void => {\n this.dirty = true;\n if (!this.inTransaction) this.persistIfDirty();\n };\n\n private persistIfDirty = (): void => {\n if (!this.dirty) return;\n const temporaryPath = `${this.databasePath}.tmp`;\n writeFileSync(temporaryPath, this.database.export());\n renameSync(temporaryPath, this.databasePath);\n this.dirty = false;\n };\n}\n\nclass PortableSqliteLease implements SqliteDatabase {\n private closed = false;\n\n constructor(private readonly owner: PortableSqliteDatabase) {}\n\n close = (): void => {\n if (this.closed) return;\n this.closed = true;\n this.owner.release();\n };\n\n exec = (sql: string): void => this.owner.exec(sql);\n\n prepare = (sql: string): SqliteStatement => this.owner.prepare(sql);\n}\n\nclass PortableSqliteStatement implements SqliteStatement {\n constructor(\n private readonly database: PortableSqliteDatabase,\n private readonly sql: string,\n ) {}\n\n all = (...params: unknown[]): unknown[] =>\n this.database.readRows(this.sql, params);\n\n get = (...params: unknown[]): unknown => this.all(...params)[0];\n\n run = (...params: unknown[]): unknown => {\n this.database.run(this.sql, params);\n return {};\n };\n}\n\nfunction bindStatement(statement: Statement, params: unknown[]): void {\n const normalized = normalizeParams(params);\n if (Array.isArray(normalized) && normalized.length === 0) return;\n statement.bind(normalized as Parameters<Statement[\"bind\"]>[0]);\n}\n\nfunction normalizeParams(\n params: unknown[],\n): unknown[] | Record<string, unknown> {\n if (params.length !== 1 || !isRecord(params[0])) return params;\n return Object.fromEntries(\n Object.entries(params[0]).map(([key, value]) => [`@${key}`, value]),\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, open, readFile, rename, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { AgentSessionEventRecord } from \"@nextclaw/ncp-toolkit\";\nimport {\n createNcpAgentSessionJournalMetadataEntry,\n isRecord,\n normalizeNcpAgentId,\n safeNcpSessionFilename,\n toIsoString,\n} from \"@kernel/utils/ncp-agent-session-journal.utils.js\";\n\nexport type NcpAgentSessionActivitySnapshot = {\n metadata: Record<string, unknown>;\n agentId?: string;\n createdAt: string;\n updatedAt: string;\n};\n\nexport class NcpAgentSessionMetadataStore {\n constructor(private readonly journalDir: string) {}\n\n write = async (record: AgentSessionEventRecord): Promise<void> => {\n await mkdir(this.journalDir, { recursive: true });\n const targetPath = this.metadataPath(record.sessionId);\n const tempPath = `${targetPath}.${process.pid}.${randomUUID()}.tmp`;\n try {\n const output = await open(tempPath, \"wx\");\n try { await output.writeFile(`${JSON.stringify(createNcpAgentSessionJournalMetadataEntry(record))}\\n`, \"utf-8\"); await output.sync(); }\n finally { await output.close(); }\n await rename(tempPath, targetPath);\n } catch (error) {\n await rm(tempPath, { force: true });\n throw error;\n }\n };\n\n read = async (\n sessionId: string,\n activitySnapshot: NcpAgentSessionActivitySnapshot,\n ): Promise<NcpAgentSessionActivitySnapshot> => {\n try {\n const parsed = JSON.parse(await readFile(this.metadataPath(sessionId), \"utf-8\")) as unknown;\n if (!isRecord(parsed) || parsed._type !== \"metadata\" || !isRecord(parsed.metadata)) {\n throw new Error(`invalid ncp agent session metadata sidecar: ${sessionId}`);\n }\n const createdAt = toIsoString(parsed.created_at, activitySnapshot.createdAt);\n const sidecarUpdatedAt = toIsoString(parsed.updated_at, activitySnapshot.updatedAt);\n const updatedAt = Date.parse(sidecarUpdatedAt) > Date.parse(activitySnapshot.updatedAt)\n ? sidecarUpdatedAt\n : activitySnapshot.updatedAt;\n const agentId = normalizeNcpAgentId(typeof parsed.agent_id === \"string\" ? parsed.agent_id : undefined);\n return {\n metadata: structuredClone(parsed.metadata),\n ...(agentId ? { agentId } : {}),\n createdAt,\n updatedAt,\n };\n } catch (error) {\n const code = error && typeof error === \"object\" && \"code\" in error ? error.code : undefined;\n if (code === \"ENOENT\") {\n return activitySnapshot;\n }\n throw error;\n }\n };\n\n delete = async (sessionId: string): Promise<void> => {\n await rm(this.metadataPath(sessionId), { force: true });\n };\n\n private metadataPath = (sessionId: string): string => {\n return join(this.journalDir, `${safeNcpSessionFilename(sessionId.replace(/:/g, \"_\"))}.metadata.json`);\n };\n}\n","import { stat } from \"node:fs/promises\";\nimport type { AgentSessionRecord } from \"@nextclaw/ncp-toolkit\";\nimport type { LoadedNcpAgentJournalSession } from \"@kernel/utils/ncp-agent-session-journal.utils.js\";\nimport { scanSessionJournal } from \"@kernel/utils/ncp-agent-session-journal-entry.utils.js\";\nimport { SessionEventReplayer } from \"@kernel/utils/ncp-agent-session-replay.utils.js\";\nimport { SessionReplaySupersessionTracker } from \"@kernel/utils/ncp-agent-session-replay-event.utils.js\";\nimport type { NcpAgentSessionMetadataStore } from \"./ncp-agent-session-metadata.store.js\";\n\n/** Explicit full-record operations read the source, never the bounded display projection. */\nexport class SessionJournalLoaderStore {\n constructor(private readonly metadataStore: NcpAgentSessionMetadataStore) {}\n\n load = async (sessionId: string, path: string): Promise<LoadedNcpAgentJournalSession | null> => {\n let journalStat: Awaited<ReturnType<typeof stat>>;\n try { journalStat = await stat(path); } catch { return null; }\n const journalOffset = journalStat.size;\n const supersessionTracker = new SessionReplaySupersessionTracker();\n const parsedJournal = await scanSessionJournal({\n path, endOffset: journalOffset,\n onEvent: (event, eventIndex) => supersessionTracker.observe(event, eventIndex),\n });\n const { agentId, createdAt, updatedAt, metadata } = await this.metadataStore.read(sessionId, {\n ...parsedJournal,\n createdAt: Date.parse(parsedJournal.createdAt) > journalStat.birthtimeMs ? journalStat.birthtime.toISOString() : parsedJournal.createdAt,\n updatedAt: Date.parse(parsedJournal.updatedAt) > journalStat.mtimeMs ? parsedJournal.updatedAt : journalStat.mtime.toISOString(),\n });\n const replayer = await SessionEventReplayer.create();\n const supersededSyntheticRecoveryIndexes = supersessionTracker.finish();\n await scanSessionJournal({ path, endOffset: journalOffset, onEvent: async (event, eventIndex) => {\n await replayer.append(event, eventIndex, supersededSyntheticRecoveryIndexes);\n } });\n const record: AgentSessionRecord = { sessionId, ...(agentId ? { agentId } : {}), messages: replayer.finish(), createdAt, updatedAt, metadata };\n return { record, nextSeq: parsedJournal.nextSeq, journalOffset, projectedJournalOffset: parsedJournal.projectedJournalOffset };\n };\n}\n","import { open } from \"node:fs/promises\";\n\n/** Node cannot flush a Windows directory handle; source and intent files are still flushed. */\nexport async function syncSessionJournalDirectory(path: string): Promise<void> {\n if (process.platform === \"win32\") return;\n const handle = await open(path, \"r\");\n try { await handle.sync(); } finally { await handle.close(); }\n}\n\n/** FlushFileBuffers requires a writable handle on Windows, including copied backup files. */\nexport async function syncSessionJournalFile(path: string): Promise<void> {\n const handle = await open(path, process.platform === \"win32\" ? \"r+\" : \"r\");\n try { await handle.sync(); } finally { await handle.close(); }\n}\n","import { createReadStream } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { createInterface } from \"node:readline\";\nimport { copyFile, open, readFile, readdir, rename, rm, stat } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { join } from \"node:path\";\nimport type { NcpEndpointEvent } from \"@nextclaw/ncp\";\nimport {\n NCP_AGENT_SESSION_JOURNAL_ENTRY_VERSION,\n normalizeNcpSessionId,\n safeNcpSessionFilename,\n} from \"@kernel/utils/ncp-agent-session-journal.utils.js\";\nimport {\n canCoalesceSessionJournalDeltas,\n coalesceSessionJournalDeltas,\n isSessionJournalDelta,\n SESSION_JOURNAL_DELTA_MAX_BYTES,\n} from \"@kernel/utils/session-journal-delta-coalescer.utils.js\";\nimport { NcpAgentSessionMetadataStore } from \"./ncp-agent-session-metadata.store.js\";\nimport { SessionJournalLoaderStore } from \"./session-journal-loader.store.js\";\nimport { openSqliteDatabase, runSqliteTransaction } from \"./sqlite-database.store.js\";\nimport { syncSessionJournalDirectory as syncDirectory, syncSessionJournalFile as syncFile } from \"@kernel/utils/session-journal-durability.utils.js\";\n\ntype JournalEntry = {\n _type: string;\n version?: number;\n seq?: number;\n timestamp?: string;\n event?: NcpEndpointEvent;\n};\n\nexport type SessionJournalCompactionResult = {\n sessionId: string;\n applied: boolean;\n inputBytes: number;\n outputBytes: number;\n inputLines: number;\n outputLines: number;\n};\n\nconst CATALOG_FILE = \".ncp-agent-session-catalog.sqlite\";\n\nfunction paths(journalDir: string, sessionId: string) {\n const basename = safeNcpSessionFilename(sessionId.replace(/:/g, \"_\"));\n const source = join(journalDir, `${basename}.jsonl`);\n return {\n source,\n backup: `${source}.backup`,\n pending: `${source}.pending`,\n marker: `${source}.maintenance`,\n markerDraft: `${source}.maintenance.tmp`,\n projection: join(journalDir, \".message-projections\", basename),\n };\n}\n\nasync function hashFile(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(path)) hash.update(chunk);\n return hash.digest(\"hex\");\n}\n\nasync function assertSourceUnchanged(source: string, expected: Awaited<ReturnType<typeof stat>>): Promise<void> {\n const current = await stat(source);\n if (current.size !== expected.size || current.mtimeMs !== expected.mtimeMs || current.ino !== expected.ino)\n throw new Error(\"Journal changed during compaction; refusing activation.\");\n}\n\n/** Refuse to append after a partial write: another JSONL entry would hide the torn tail. */\nexport async function assertSessionJournalTailComplete(source: string): Promise<void> {\n let handle: Awaited<ReturnType<typeof open>>;\n try { handle = await open(source, \"r\"); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n try {\n const size = (await handle.stat()).size;\n if (size === 0) return;\n const suffix = Buffer.alloc(1);\n await handle.read(suffix, 0, 1, size - 1);\n if (suffix[0] !== 10) throw new Error(\"Journal has an incomplete tail line; refusing further writes.\");\n } finally { await handle.close(); }\n}\n\n/** Maintenance only: preserve a crash-torn suffix before restoring the last committed newline. */\nexport async function recoverSessionJournalTornTail(source: string, signal?: AbortSignal): Promise<void> {\n const file = await open(source, \"r+\");\n try {\n const original = await file.stat();\n if (!original.size) return;\n const buffer = Buffer.alloc(64 * 1024);\n await file.read(buffer, 0, 1, original.size - 1);\n if (buffer[0] === 10) return;\n let boundary = 0;\n for (let end = original.size; end > 0;) {\n signal?.throwIfAborted();\n const start = Math.max(0, end - buffer.length);\n const { bytesRead } = await file.read(buffer, 0, end - start, start);\n const newline = buffer.subarray(0, bytesRead).lastIndexOf(10);\n if (newline >= 0) { boundary = start + newline + 1; break; }\n end = start;\n await new Promise<void>(resolve => setImmediate(resolve));\n }\n const quarantine = await open(`${source}.torn-${original.size}-${Math.floor(original.mtimeMs)}`, \"w\");\n try {\n for (let offset = boundary; offset < original.size;) {\n signal?.throwIfAborted();\n const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, original.size - offset), offset);\n if (!bytesRead) throw new Error(\"Torn journal preservation made no progress.\");\n await quarantine.writeFile(buffer.subarray(0, bytesRead));\n offset += bytesRead;\n }\n await quarantine.sync();\n } finally { await quarantine.close(); }\n signal?.throwIfAborted();\n await assertSourceUnchanged(source, original);\n await file.truncate(boundary);\n await file.sync();\n } finally { await file.close(); }\n}\n\nasync function invalidateDerivedState(journalDir: string, sessionId: string, projection: string): Promise<void> {\n await rm(projection, { recursive: true, force: true });\n const catalogPath = join(journalDir, CATALOG_FILE);\n try { await stat(catalogPath); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n const database = await openSqliteDatabase(catalogPath);\n try {\n database.exec(\"PRAGMA busy_timeout = 10000; PRAGMA synchronous = FULL; PRAGMA foreign_keys = ON;\");\n runSqliteTransaction(database, () => {\n database.prepare(\"DELETE FROM run_recovery WHERE session_id = ?\").run(sessionId);\n database.prepare(\"DELETE FROM sessions WHERE session_id = ? AND deleted_at IS NULL\").run(sessionId);\n }, \"IMMEDIATE\");\n } finally { database.close(); }\n await syncDirectory(journalDir);\n}\n\n/** Runs before the catalog opens. An interrupted switch always rolls back to the untouched backup. */\nexport async function recoverSessionJournalMaintenance(journalDir: string): Promise<void> {\n let names: string[];\n try { names = await readdir(journalDir); } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n for (const name of names.filter((item) => item.endsWith(\".jsonl.maintenance\") || item.endsWith(\".jsonl.import-maintenance\"))) {\n const marker = JSON.parse(await readFile(join(journalDir, name), \"utf8\")) as { sessionId?: string; snapshot?: {\n hadSource: boolean; metadata: Parameters<NcpAgentSessionMetadataStore[\"write\"]>[0];\n } };\n const sessionId = normalizeNcpSessionId(marker.sessionId ?? \"\");\n const suffix = name.endsWith(\".import-maintenance\") ? \".import-maintenance\" : \".maintenance\";\n if (!sessionId || `${safeNcpSessionFilename(sessionId.replace(/:/g, \"_\"))}.jsonl${suffix}` !== name\n || (suffix === \".import-maintenance\" && !marker.snapshot))\n throw new Error(`Invalid journal maintenance marker: ${name}`);\n const source = join(journalDir, name.slice(0, -suffix.length));\n const backup = `${source}${marker.snapshot ? \".import-backup\" : \".backup\"}`;\n const restore = `${source}.restore`;\n if (marker.snapshot?.hadSource === false) await rm(source, { force: true });\n else { await copyFile(backup, restore); await syncFile(restore); await rename(restore, source); }\n if (marker.snapshot) {\n const metadataStore = new NcpAgentSessionMetadataStore(journalDir);\n if (marker.snapshot.hadSource) await metadataStore.write({ ...marker.snapshot.metadata, sessionId });\n else await metadataStore.delete(sessionId);\n }\n const basename = name.slice(0, -(\".jsonl\" + suffix).length);\n await invalidateDerivedState(journalDir, sessionId, join(journalDir, \".message-projections\", basename));\n await rm(`${source}.pending`, { force: true });\n await rm(join(journalDir, name));\n await syncDirectory(journalDir);\n if (marker.snapshot) await rm(backup, { force: true });\n }\n}\n\nasync function validateColdReplay(journalDir: string, sessionId: string, source: string, candidate: string): Promise<void> {\n const loader = new SessionJournalLoaderStore(\n new NcpAgentSessionMetadataStore(journalDir),\n );\n const original = await loader.load(sessionId, source);\n const compacted = await loader.load(sessionId, candidate);\n if (!original || !compacted || !isDeepStrictEqual(original.record.messages, compacted.record.messages)) {\n throw new Error(\"Session journal compaction changed cold-replayed messages.\");\n }\n}\n\nasync function writeCoalescedJournal(source: string, pending: string): Promise<{ inputLines: number; outputLines: number }> {\n const output = await open(pending, \"wx\");\n let inputLines = 0;\n let outputLines = 0;\n let nextSeq = 1;\n let pendingEntry: JournalEntry | null = null;\n const flush = async () => {\n if (!pendingEntry) return;\n if (pendingEntry._type === \"event\") pendingEntry.seq = nextSeq++;\n await output.writeFile(`${JSON.stringify(pendingEntry)}\\n`);\n outputLines++;\n pendingEntry = null;\n };\n try {\n const lines = createInterface({ input: createReadStream(source), crlfDelay: Infinity });\n for await (const line of lines) {\n if (!line) throw new Error(\"Journal contains a blank line; compaction requires a valid complete source.\");\n inputLines++;\n const entry = JSON.parse(line) as JournalEntry;\n if (!entry || typeof entry !== \"object\" || ![\"event\", \"metadata\"].includes(entry._type)) {\n throw new Error(`Invalid journal entry at line ${inputLines}.`);\n }\n if (entry.version !== undefined && entry.version !== NCP_AGENT_SESSION_JOURNAL_ENTRY_VERSION)\n throw new Error(`Unsupported journal entry version at line ${inputLines}.`);\n if (entry._type === \"event\") {\n if (!Number.isSafeInteger(entry.seq) || entry.seq! < 1 || !entry.event?.type || !(\"payload\" in entry.event)) {\n throw new Error(`Invalid journal sequence or event at line ${inputLines}.`);\n }\n }\n if (pendingEntry?._type === \"event\" && entry._type === \"event\" && pendingEntry.event && entry.event &&\n canCoalesceSessionJournalDeltas(pendingEntry.event, entry.event) &&\n isSessionJournalDelta(pendingEntry.event) && isSessionJournalDelta(entry.event)) {\n const merged = coalesceSessionJournalDeltas(pendingEntry.event, entry.event);\n if (Buffer.byteLength(merged.payload.delta, \"utf8\") <= SESSION_JOURNAL_DELTA_MAX_BYTES) {\n pendingEntry.event = merged;\n continue;\n }\n }\n await flush();\n pendingEntry = entry;\n }\n await flush();\n await output.sync();\n } finally {\n await output.close();\n }\n return { inputLines, outputLines };\n}\n\nasync function writeMaintenanceMarker(journalDir: string, target: ReturnType<typeof paths>, sessionId: string): Promise<void> {\n const marker = await open(target.markerDraft, \"wx\");\n try {\n await marker.writeFile(`${JSON.stringify({ sessionId })}\\n`);\n await marker.sync();\n } finally {\n await marker.close();\n }\n await rename(target.markerDraft, target.marker);\n await syncDirectory(journalDir);\n}\n\nasync function activateCompactedJournal(\n journalDir: string,\n sessionId: string,\n target: ReturnType<typeof paths>,\n sourceStat: Awaited<ReturnType<typeof stat>>,\n): Promise<void> {\n let renamed = false;\n try {\n await copyFile(target.source, target.backup, constants.COPYFILE_EXCL);\n await syncFile(target.backup);\n await assertSourceUnchanged(target.source, sourceStat);\n await writeMaintenanceMarker(journalDir, target, sessionId);\n await assertSourceUnchanged(target.source, sourceStat);\n await rename(target.pending, target.source);\n renamed = true;\n await syncDirectory(journalDir);\n await invalidateDerivedState(journalDir, sessionId, target.projection);\n await rm(target.marker);\n await syncDirectory(journalDir);\n } catch (error) {\n if (renamed) await recoverSessionJournalMaintenance(journalDir);\n else {\n await rm(target.markerDraft, { force: true });\n await rm(target.marker, { force: true });\n await rm(target.backup, { force: true });\n }\n throw error;\n }\n}\n\n/** Restores the original v1 journal after a successful offline compaction. All writers must be stopped. */\nexport async function restoreSessionJournalBackup(input: {\n journalDir: string;\n sessionId: string;\n writersStopped?: true;\n}): Promise<{ sessionId: string; restored: true }> {\n const sessionId = normalizeNcpSessionId(input.sessionId);\n if (!sessionId || input.writersStopped !== true)\n throw new Error(\"Stop all writers and explicitly acknowledge it before restoring a journal backup.\");\n const target = paths(input.journalDir, sessionId);\n await stat(target.backup);\n for (const candidate of [target.pending, target.marker, target.markerDraft]) {\n try { await stat(candidate); throw new Error(`Unresolved journal maintenance file: ${candidate}`); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n }\n const sourceStat = await stat(target.source);\n let recoveryStarted = false;\n try {\n await writeCoalescedJournal(target.backup, target.pending);\n const expected = await stat(target.pending);\n if (sourceStat.size !== expected.size || await hashFile(target.source) !== await hashFile(target.pending))\n throw new Error(\"Journal changed since compaction; refusing restore to protect later events.\");\n await assertSourceUnchanged(target.source, sourceStat);\n await writeMaintenanceMarker(input.journalDir, target, sessionId);\n await assertSourceUnchanged(target.source, sourceStat);\n recoveryStarted = true;\n await recoverSessionJournalMaintenance(input.journalDir);\n } catch (error) {\n await rm(target.markerDraft, { force: true });\n if (!recoveryStarted) await rm(target.marker, { force: true });\n throw error;\n } finally {\n await rm(target.pending, { force: true });\n }\n return { sessionId, restored: true };\n}\n\n/** Explicit offline operation. The caller must stop every writer for this HOME before apply. */\nexport async function compactSessionJournal(input: {\n journalDir: string;\n sessionId: string;\n apply: boolean;\n writersStopped?: true;\n}): Promise<SessionJournalCompactionResult> {\n const sessionId = normalizeNcpSessionId(input.sessionId);\n if (!sessionId) throw new Error(\"A session ID is required.\");\n if (input.apply && input.writersStopped !== true) throw new Error(\"Stop all writers and explicitly acknowledge it before applying compaction.\");\n const target = paths(input.journalDir, sessionId);\n for (const candidate of [target.backup, target.pending, target.marker, target.markerDraft]) {\n try { await stat(candidate); throw new Error(`Unresolved journal maintenance file: ${candidate}`); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n }\n const before = await stat(target.source);\n await assertSessionJournalTailComplete(target.source);\n try {\n const { inputLines, outputLines } = await writeCoalescedJournal(target.source, target.pending);\n await validateColdReplay(input.journalDir, sessionId, target.source, target.pending);\n await assertSourceUnchanged(target.source, before);\n const outputBytes = (await stat(target.pending)).size;\n const result = { sessionId, applied: input.apply, inputBytes: before.size, outputBytes, inputLines, outputLines };\n if (!input.apply) return result;\n await activateCompactedJournal(input.journalDir, sessionId, target, before);\n return result;\n } finally {\n await rm(target.pending, { force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM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A;CAC1C,MAAM,YAAY,sBAAsB,MAAM,UAAU;AACxD,KAAI,CAAC,UAAW,OAAM,IAAI,MAAM,4BAA4B;AAC5D,KAAI,MAAM,SAAS,MAAM,mBAAmB,KAAM,OAAM,IAAI,MAAM,6EAA6E;CAC/I,MAAM,SAAS,MAAM,MAAM,YAAY,UAAU;AACjD,MAAK,MAAM,aAAa;EAAC,OAAO;EAAQ,OAAO;EAAS,OAAO;EAAQ,OAAO;EAAY,CACxF,KAAI;AAAE,QAAM,KAAK,UAAU;AAAE,QAAM,IAAI,MAAM,wCAAwC,YAAY;UAC1F,OAAO;AAAE,MAAK,MAAgC,SAAS,SAAU,OAAM;;CAEhF,MAAM,SAAS,MAAM,KAAK,OAAO,OAAO;AACxC,OAAM,iCAAiC,OAAO,OAAO;AACrD,KAAI;EACF,MAAM,EAAE,YAAY,gBAAgB,MAAM,sBAAsB,OAAO,QAAQ,OAAO,QAAQ;AAC9F,QAAM,mBAAmB,MAAM,YAAY,WAAW,OAAO,QAAQ,OAAO,QAAQ;AACpF,QAAM,sBAAsB,OAAO,QAAQ,OAAO;EAClD,MAAM,eAAe,MAAM,KAAK,OAAO,QAAQ,EAAE;EACjD,MAAM,SAAS;GAAE;GAAW,SAAS,MAAM;GAAO,YAAY,OAAO;GAAM;GAAa;GAAY;GAAa;AACjH,MAAI,CAAC,MAAM,MAAO,QAAO;AACzB,QAAM,yBAAyB,MAAM,YAAY,WAAW,QAAQ,OAAO;AAC3E,SAAO;WACC;AACR,QAAM,GAAG,OAAO,SAAS,EAAE,OAAO,MAAM,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nextclaw/kernel",
3
- "version": "0.19.4",
3
+ "version": "0.19.6",
4
4
  "private": false,
5
5
  "description": "NextClaw product kernel skeleton for agents, tasks, sessions, context, tools, skills, providers, automation, and channels.",
6
6
  "type": "module",
@@ -35,19 +35,19 @@
35
35
  "rxjs": "^7.8.2",
36
36
  "sql.js": "^1.14.2",
37
37
  "stream-json": "1.9.1",
38
- "@nextclaw/app-runtime": "0.16.11",
39
38
  "@nextclaw/channel-extension-feishu": "0.2.42",
40
- "@nextclaw/mcp": "0.3.58",
41
39
  "@nextclaw/channel-extension-weixin": "0.2.42",
42
- "@nextclaw/core": "0.18.8",
40
+ "@nextclaw/core": "0.18.9",
41
+ "@nextclaw/app-runtime": "0.16.11",
43
42
  "@nextclaw/ncp": "0.11.3",
44
- "@nextclaw/ncp-agent-runtime-next": "0.1.31",
43
+ "@nextclaw/mcp": "0.3.59",
45
44
  "@nextclaw/ncp-agent-runtime": "0.4.28",
46
- "@nextclaw/ncp-mcp": "0.2.58",
47
- "@nextclaw/nextclaw-ncp-runtime-http-client": "0.3.27",
48
- "@nextclaw/nextclaw-ncp-runtime-stdio-client": "0.3.58",
45
+ "@nextclaw/ncp-agent-runtime-next": "0.1.31",
49
46
  "@nextclaw/ncp-toolkit": "0.6.28",
50
- "@nextclaw/runtime": "0.4.57",
47
+ "@nextclaw/ncp-mcp": "0.2.59",
48
+ "@nextclaw/nextclaw-ncp-runtime-http-client": "0.3.27",
49
+ "@nextclaw/runtime": "0.4.58",
50
+ "@nextclaw/nextclaw-ncp-runtime-stdio-client": "0.3.59",
51
51
  "@nextclaw/shared": "0.8.4"
52
52
  },
53
53
  "devDependencies": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"ncp-agent-session-journal.utils-B7a_PKCq.js","names":["readOptionalString","readCompressedContextCompactionCheckpoint","ContextWindowBudgetService","readCompressedContextCompactionCheckpoint","CONTEXT_COMPACTION_METADATA_KEY","readMessageFromSummaryEvent","isRecord","readMessageFromSummaryEvent","readMessageFromSummaryEvent"],"sources":["../src/tools/structured-result.tools.ts","../src/utils/agent-peer-session.utils.ts","../src/utils/ncp-agent-session-label.utils.ts","../src/features/context-compaction/services/context-compaction-journal-recovery.service.ts","../src/tools/tool-schema.tools.ts","../src/utils/agent-model-input-budget.utils.ts","../src/utils/context-compaction-summary-source.utils.ts","../src/utils/context-compaction-summary-input.utils.ts","../src/features/context-compaction/services/context-compaction-summary-generation.service.ts","../src/features/context-compaction/utils/context-compaction.utils.ts","../src/features/context-compaction/services/context-compaction-preflight.service.ts","../src/utils/ncp-agent-session-replay-event.utils.ts","../src/utils/ncp-agent-session-replay-tool-ownership.utils.ts","../src/utils/ncp-agent-session-replay.utils.ts","../src/utils/ncp-agent-session-journal.utils.ts"],"sourcesContent":["import { validateToolArgs } from \"@nextclaw/ncp-agent-runtime\";\nimport type { NcpTool } from \"@nextclaw/ncp\";\n\nexport const STRUCTURED_RESULT_TOOL_NAME = \"nextclaw_submit_result\";\n\nexport type StructuredResultContract = {\n requestId: string;\n schema: Record<string, unknown>;\n toolName: typeof STRUCTURED_RESULT_TOOL_NAME;\n};\n\nexport class StructuredResultSubmitTool implements NcpTool {\n readonly name = STRUCTURED_RESULT_TOOL_NAME;\n readonly description = \"Submit the structured object result for this request.\";\n\n constructor(private readonly contract: StructuredResultContract) {}\n\n get parameters(): Record<string, unknown> {\n return this.contract.schema;\n }\n\n validateArgs = (args: Record<string, unknown>): string[] =>\n validateToolArgs(args, this.contract.schema);\n\n execute = async (args: Record<string, unknown>): Promise<unknown> => args;\n}\n","import { createHash } from \"node:crypto\";\nimport { BUILTIN_MAIN_AGENT_ID } from \"@nextclaw/core\";\n\nexport const AGENT_RUN_PEER_ID_METADATA_KEY = \"agent_peer_id\";\nexport const AGENT_RUN_PEER_SCOPE_METADATA_KEY = \"agent_peer_scope\";\n\nexport type AgentPeerSessionIdentity = {\n metadata: Record<string, unknown>;\n sessionId: string;\n};\n\nexport function createAgentPeerSessionIdentity(params: {\n agentId?: string;\n channel?: string;\n metadata?: Record<string, unknown>;\n peerId: string;\n}): AgentPeerSessionIdentity {\n const scope = resolveAgentPeerScope(params);\n return {\n metadata: {\n [AGENT_RUN_PEER_ID_METADATA_KEY]: params.peerId,\n [AGENT_RUN_PEER_SCOPE_METADATA_KEY]: scope,\n },\n sessionId: `agent-peer-${createHash(\"sha256\")\n .update(`${scope}\\0${params.peerId}`)\n .digest(\"hex\")\n .slice(0, 32)}`,\n };\n}\n\nfunction resolveAgentPeerScope(params: {\n agentId?: string;\n channel?: string;\n metadata?: Record<string, unknown>;\n}): string {\n const metadata = params.metadata ?? {};\n const explicitScope =\n readOptionalString(metadata[AGENT_RUN_PEER_SCOPE_METADATA_KEY]) ??\n readOptionalString(metadata.agentPeerScope);\n if (explicitScope) {\n return explicitScope;\n }\n const agentId = readOptionalString(params.agentId) ?? BUILTIN_MAIN_AGENT_ID;\n const channel =\n readOptionalString(params.channel) ??\n readOptionalString(metadata.channel) ??\n \"agent-run\";\n const accountId =\n readOptionalString(metadata.accountId) ??\n readOptionalString(metadata.account_id) ??\n \"default\";\n return `agent:${agentId}:${channel}:${accountId}`;\n}\n\nfunction readOptionalString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n","import type { NcpMessage } from \"@nextclaw/ncp\";\n\nconst AUTO_SESSION_LABEL_MAX_LENGTH = 64;\n\nexport function resolveNcpAgentSessionLabel(\n messages: readonly NcpMessage[],\n): string | null {\n for (const message of messages) {\n if (message.role !== \"user\") {\n continue;\n }\n for (const part of message.parts) {\n if (part.type !== \"text\" && part.type !== \"rich-text\") {\n continue;\n }\n const text = typeof part.text === \"string\" ? part.text.trim() : \"\";\n if (text) {\n return truncateLabel(text);\n }\n }\n }\n return null;\n}\n\nfunction truncateLabel(value: string): string {\n const chars = Array.from(value);\n return chars.length <= AUTO_SESSION_LABEL_MAX_LENGTH\n ? value\n : `${chars.slice(0, AUTO_SESSION_LABEL_MAX_LENGTH).join(\"\")}...`;\n}\n","import { NcpEventType, type NcpEndpointEvent, type NcpMessage } from \"@nextclaw/ncp\";\n\ntype RecoveredCompactionTerminal = {\n status: \"cancelled\" | \"failed\";\n updatedAt: string;\n};\n\nexport class ContextCompactionJournalRecoveryService {\n private readonly pendingMessageIds = new Set<string>();\n private readonly pendingCheckpoints = new Map<string, Record<string, unknown>>();\n private readonly recoveredTerminals = new Map<string, RecoveredCompactionTerminal>();\n private readonly terminalMessages = new Map<string, RecoveredCompactionTerminal>();\n\n seed = (messages: readonly NcpMessage[]): void => {\n for (const message of messages) {\n if (\n message.role === \"assistant\" &&\n (message.status === \"final\" || message.status === \"error\")\n ) {\n this.terminalMessages.set(message.id, {\n status: \"failed\",\n updatedAt: message.lifecycle?.endedAt ?? message.timestamp,\n });\n }\n const checkpoint = this.readCheckpoint(message);\n if (!checkpoint) {\n continue;\n }\n if (checkpoint.status === \"compressing\") {\n this.pendingMessageIds.add(message.id);\n this.pendingCheckpoints.set(message.id, structuredClone(checkpoint));\n } else {\n this.pendingMessageIds.delete(message.id);\n this.pendingCheckpoints.delete(message.id);\n this.recoveredTerminals.delete(message.id);\n }\n }\n };\n\n track = (event: NcpEndpointEvent): void => {\n if (event.type === NcpEventType.MessageSent) {\n this.trackMessageSent(event);\n return;\n }\n this.trackTerminalEvent(event);\n };\n\n private trackMessageSent = (\n event: Extract<NcpEndpointEvent, { type: NcpEventType.MessageSent }>,\n ): void => {\n const checkpoint = this.readCheckpoint(event.payload.message);\n if (!checkpoint) {\n return;\n }\n if (checkpoint.status === \"compressing\") {\n this.pendingMessageIds.add(event.payload.message.id);\n this.pendingCheckpoints.set(event.payload.message.id, structuredClone(checkpoint));\n const continuationMessageId = this.readContinuationMessageId(checkpoint);\n const terminal = continuationMessageId\n ? this.terminalMessages.get(continuationMessageId)\n : undefined;\n if (terminal) {\n this.recoveredTerminals.set(event.payload.message.id, terminal);\n }\n return;\n }\n this.pendingMessageIds.delete(event.payload.message.id);\n this.pendingCheckpoints.delete(event.payload.message.id);\n this.recoveredTerminals.delete(event.payload.message.id);\n };\n\n private trackTerminalEvent = (event: NcpEndpointEvent): void => {\n const terminalStatus = event.type === NcpEventType.MessageAbort\n ? \"cancelled\"\n : event.type === NcpEventType.RunError || event.type === NcpEventType.RunFinished\n ? \"failed\"\n : null;\n if (!terminalStatus) {\n return;\n }\n const updatedAt = event.occurredAt ?? new Date(0).toISOString();\n const terminal = { status: terminalStatus, updatedAt } satisfies RecoveredCompactionTerminal;\n const eventMessageId = this.readEventMessageId(event);\n if (eventMessageId) {\n this.terminalMessages.set(eventMessageId, terminal);\n }\n if (this.pendingMessageIds.size === 0) {\n return;\n }\n const pendingMessageIds = [...this.pendingMessageIds];\n const targetedMessageIds = eventMessageId\n ? pendingMessageIds.filter((messageId) => {\n const checkpoint = this.readCheckpointByMessageId(messageId);\n return this.readContinuationMessageId(checkpoint) === eventMessageId;\n })\n : [];\n const legacyMessageIds = pendingMessageIds.filter((messageId) =>\n this.readContinuationMessageId(this.readCheckpointByMessageId(messageId)) === null,\n );\n const messageIds = targetedMessageIds.length > 0\n ? [...targetedMessageIds, ...legacyMessageIds]\n : eventMessageId && legacyMessageIds.length < pendingMessageIds.length\n ? legacyMessageIds\n : pendingMessageIds;\n for (const messageId of messageIds) {\n this.recoveredTerminals.set(messageId, terminal);\n this.pendingMessageIds.delete(messageId);\n this.pendingCheckpoints.delete(messageId);\n }\n };\n\n terminalize = (message: NcpMessage): NcpMessage => {\n const terminal = this.recoveredTerminals.get(message.id);\n if (!terminal) {\n return structuredClone(message);\n }\n const checkpoint = this.readCheckpoint(message);\n if (!checkpoint || checkpoint.status !== \"compressing\") {\n return structuredClone(message);\n }\n return {\n ...structuredClone(message),\n parts: [{\n type: \"text\",\n text: terminal.status === \"cancelled\"\n ? \"Context compaction was cancelled\"\n : \"Context compaction failed\"\n }],\n metadata: {\n ...structuredClone(message.metadata ?? {}),\n checkpoint: {\n ...structuredClone(checkpoint),\n status: terminal.status,\n updatedAt: terminal.updatedAt\n }\n }\n };\n };\n\n private readCheckpoint = (message: NcpMessage): Record<string, unknown> | null => {\n const metadata = message.metadata;\n const checkpoint = metadata?.checkpoint;\n return metadata?.nextclaw_timeline_kind === \"context_compaction\"\n && checkpoint\n && typeof checkpoint === \"object\"\n && !Array.isArray(checkpoint)\n ? checkpoint as Record<string, unknown>\n : null;\n };\n\n private readCheckpointByMessageId = (messageId: string): Record<string, unknown> | null => {\n const checkpoint = this.pendingCheckpoints.get(messageId);\n return checkpoint ? structuredClone(checkpoint) : null;\n };\n\n private readContinuationMessageId = (checkpoint: Record<string, unknown> | null): string | null => {\n const value = checkpoint?.continuationMessageId;\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n };\n\n private readEventMessageId = (event: NcpEndpointEvent): string | null => {\n if (event.type === NcpEventType.MessageAbort || event.type === NcpEventType.RunError || event.type === NcpEventType.RunFinished) {\n const messageId = event.payload.messageId;\n return typeof messageId === \"string\" && messageId.trim() ? messageId.trim() : null;\n }\n return null;\n };\n}\n","import type { NcpTool } from \"@nextclaw/ncp\";\nimport { STRUCTURED_RESULT_TOOL_NAME } from \"./structured-result.tools.js\";\n\nexport const TOOL_SCHEMA_NAME = \"tool_schema\";\nconst EAGER_TOOL_NAMES = new Set([\n TOOL_SCHEMA_NAME, STRUCTURED_RESULT_TOOL_NAME, \"node_repl\",\n \"read_file\", \"write_file\", \"edit_file\", \"list_dir\", \"exec\", \"web_search\", \"web_fetch\", \"view_image\",\n \"memory_search\", \"memory_get\",\n]);\n\n/** Model-facing disclosure only; execution continues to validate the original schema. */\nexport function selectToolModelParameters(tool: NcpTool): NcpTool[\"parameters\"] {\n const parameters = tool.modelParameters ?? tool.parameters;\n return EAGER_TOOL_NAMES.has(tool.name) || !parameters || JSON.stringify(parameters).length <= 160\n ? parameters : { type: \"object\" };\n}\n\nexport class ToolSchemaTool implements NcpTool {\n readonly name = TOOL_SCHEMA_NAME;\n readonly description = \"Read full parameters for an available tool. Before first using a tool whose object schema has no properties field, query its exact name here, then call the original tool with the returned parameter shape.\";\n readonly parameters = {\n type: \"object\",\n properties: { name: { type: \"string\", minLength: 1 } },\n required: [\"name\"],\n additionalProperties: false,\n };\n\n readonly modelParameters?: NcpTool[\"parameters\"];\n readonly validateArgs?: (value: Record<string, unknown>) => string[];\n\n constructor(private readonly readTools: () => readonly NcpTool[], portableValidation = false) {\n if (portableValidation) {\n this.modelParameters = this.parameters;\n this.validateArgs = (value) => [\n ...(typeof value.name === \"string\" && value.name.length >= 1 ? [] : [\"name must be a nonempty string\"]),\n ...Object.keys(value).filter((key) => key !== \"name\").map((key) => `${key} is not allowed`),\n ];\n }\n }\n\n execute = async (args: unknown): Promise<unknown> => {\n const name = args && typeof args === \"object\" && \"name\" in args ? args.name : null;\n if (typeof name !== \"string\" || !name.trim()) throw new Error(\"Tool name is required.\");\n const tool = this.readTools().find((candidate) => candidate.name === name.trim());\n if (!tool) throw new Error(`Tool is not in the current allowed catalog: ${name}`);\n return structuredClone({ name: tool.name, description: tool.description, parameters: tool.modelParameters ?? tool.parameters });\n };\n}\n\n/** Build one run-scoped catalog from host-provided tools, with the same duplicate and schema rules on every host. */\nexport function composeAgentToolCatalog(\n groups: readonly (readonly NcpTool[])[],\n options: {\n allowedNames?: ReadonlySet<string> | null;\n includeSchemaTool?: boolean;\n portableValidation?: boolean;\n wrapTool?: (tool: NcpTool) => NcpTool;\n } = {},\n): NcpTool[] {\n const tools: NcpTool[] = [];\n const seen = new Set<string>();\n const allowed = options.allowedNames ?? null;\n const isAllowed = (name: string) => allowed === null || allowed.has(name);\n if (options.includeSchemaTool !== false && isAllowed(TOOL_SCHEMA_NAME)) {\n const lookup = new ToolSchemaTool(() => tools, options.portableValidation);\n tools.push(options.wrapTool?.(lookup) ?? lookup);\n seen.add(TOOL_SCHEMA_NAME);\n }\n for (const group of groups) {\n for (const tool of group) {\n if (!isAllowed(tool.name)) continue;\n if (seen.has(tool.name)) {\n if (allowed !== null) throw new Error(`Restricted tool catalog has a duplicate name: ${tool.name}`);\n continue;\n }\n seen.add(tool.name);\n tools.push(options.wrapTool?.(tool) ?? tool);\n }\n }\n return tools;\n}\n","import { estimateInputTokens } from \"@nextclaw/core/model-input-budget\";\nimport type { NcpTool, OpenAITool } from \"@nextclaw/ncp\";\nimport { buildOpenAiFunctionTool } from \"@nextclaw/ncp-agent-runtime\";\nimport { TOOL_SCHEMA_NAME, selectToolModelParameters } from \"@kernel/tools/tool-schema.tools.js\";\n\nexport function buildContextBlockInputMessages(\n contextBlocks: readonly string[] = [],\n): Record<string, unknown>[] {\n const contextContent = contextBlocks\n .map((block) => block.trim())\n .filter(Boolean)\n .join(\"\\n\\n\");\n return contextContent ? [{ role: \"system\", content: contextContent }] : [];\n}\n\nexport function buildProviderTools(tools: readonly NcpTool[]): OpenAITool[] {\n const hasSchemaLookup = tools.some((tool) => tool.name === TOOL_SCHEMA_NAME);\n return tools.map((tool): OpenAITool => buildOpenAiFunctionTool({\n name: tool.name,\n description: tool.description,\n parameters: hasSchemaLookup ? selectToolModelParameters(tool) : tool.modelParameters ?? tool.parameters,\n }));\n}\n\nexport function estimateToolInputTokens(tools: readonly NcpTool[]): number {\n return estimateInputTokens(buildProviderTools(tools));\n}\n","type RuntimeMessage = Record<string, unknown>;\n\nconst SOURCE_FIELDS = [\"role\", \"content\", \"reasoning_content\", \"name\", \"tool_calls\", \"tool_call_id\",\n \"timestamp\", \"ncp_message_id\", \"ncp_part_start\", \"ncp_part_end\"] as const;\nconst IDENTITY_FIELDS = new Set([\"role\", \"name\", \"id\", \"type\", \"tool_call_id\", \"ncp_message_id\", \"timestamp\"]);\nconst MIN_SOURCE_TEXT_CHARS = 128;\n\nexport function truncateSummarySourceString(value: unknown, maxChars: number): unknown {\n if (typeof value !== \"string\" || value.length <= maxChars) return value;\n const marker = `[${value.length - maxChars} chars omitted]`;\n const kept = Math.max(0, maxChars - marker.length - 2);\n const head = Math.ceil(kept / 2);\n return `${value.slice(0, head).trimEnd()}\\n${marker}\\n${kept > head ? value.slice(-(kept - head)).trimStart() : \"\"}`;\n}\n\nfunction sourceMessages(messages: readonly RuntimeMessage[]): RuntimeMessage[] {\n return messages.map((message) => Object.fromEntries(SOURCE_FIELDS\n .filter((field) => message[field] !== undefined)\n .map((field) => [field, message[field]])));\n}\n\nfunction serializeSource(messages: readonly RuntimeMessage[], textChars: number): { text: string; truncated: boolean } {\n const summaries = new Set(messages.filter((message) =>\n (message.role === \"system\" || message.role === \"service\") && typeof message.content === \"string\"\n ).map((message) => message.content));\n let truncated = false;\n const text = JSON.stringify(sourceMessages(messages), (key, value) => {\n const fitted = IDENTITY_FIELDS.has(key) || summaries.has(value) ? value : truncateSummarySourceString(value, textChars);\n if (fitted !== value) truncated = true;\n return fitted;\n });\n return { text, truncated };\n}\n\n/** Shrink verbose fields, never discard a message or break the outer JSON. */\nexport function stringifyCompactionSource(messages: readonly RuntimeMessage[], maxChars: number, report?: (truncated: boolean) => void): string {\n if (messages.length === 0) return \"[]\";\n const minimal = serializeSource(messages, MIN_SOURCE_TEXT_CHARS);\n if (minimal.text.length > maxChars) {\n throw new Error(\"Compaction source identities exceed the input budget; split the source before summarizing.\");\n }\n let fitted = minimal;\n let lower = MIN_SOURCE_TEXT_CHARS;\n let upper = maxChars;\n while (lower <= upper) {\n const limit = Math.floor((lower + upper) / 2);\n const candidate = serializeSource(messages, limit);\n if (candidate.text.length <= maxChars) { fitted = candidate; lower = limit + 1; }\n else upper = limit - 1;\n }\n report?.(fitted.truncated);\n return fitted.text;\n}\n\n/** Bound identity overhead before fitting text; every source record belongs to one batch. */\nexport function splitCompactionSource(messages: readonly RuntimeMessage[], maxChars: number): RuntimeMessage[][] {\n const batches: RuntimeMessage[][] = [];\n let batch: RuntimeMessage[] = [];\n let size = 2;\n for (const message of messages) {\n const messageSize = serializeSource([message], MIN_SOURCE_TEXT_CHARS).text.length;\n if (messageSize > maxChars) throw new Error(\"A compaction source record exceeds the minimum safe input budget.\");\n if (batch.length > 0 && size + messageSize > maxChars) {\n batches.push(batch); batch = []; size = 2;\n }\n batch.push(message); size += messageSize;\n }\n if (batch.length > 0) batches.push(batch);\n return batches.length > 0 ? batches : [[]];\n}\n","import { estimateInputTokens } from \"@nextclaw/core/model-input-budget\";\nimport { normalizeAssistantText } from \"@nextclaw/ncp\";\nimport { stringifyCompactionSource, truncateSummarySourceString } from \"./context-compaction-summary-source.utils.js\";\n\nconst SUMMARY_SOURCE_MAX_CHARS = 120_000;\nconst SUMMARY_HEADING = \"# Compressed Working Context\";\nexport const SUMMARY_CONTINUATION_HEADING = \"## Continuation Contract\";\nexport const SUMMARY_ESSENTIAL_COMPLETE_MARKER = \"<!-- nextclaw-essential-context-complete -->\";\nconst SUMMARY_ESSENTIAL_SECTIONS = [\n \"Active Request\",\n \"Current Work State\",\n \"Safety and User Constraints\",\n \"Continuation Contract\",\n] as const;\nconst SUMMARY_OPTIONAL_SECTIONS = [\n [\"Critical Technical Context\", \"critical-technical-context\"],\n [\"Evidence and Verification\", \"evidence-and-verification\"],\n [\"Recent High-Fidelity Context\", \"recent-high-fidelity-context\"],\n [\"Older Relevant Context\", \"older-relevant-context\"],\n] as const;\nconst SUMMARY_SYSTEM_PROMPT = [\n \"Summarize facts as Markdown starting '# Compressed Working Context'.\",\n \"Describe Active Request, Current Work State, Safety and User Constraints, and Continuation Contract. These are content priorities, not a machine-readable protocol.\",\n \"Include latest intent, decisions, constraints, changed files, evidence and next step. Distinguish Done/In Progress/Blocked/Failed; keep command/file identities and outcomes. Attempted calls alone are not completion.\",\n \"Update any previous summary: carry completed work and constraints forward, replace stale next steps. Completed requests are history. Repeat reads only for freshness/verification; recover uncertain side-effect status before repeating. A greeting does not erase the prior task or restart onboarding.\",\n \"Include technical context and verification evidence when relevant. State uncertainty explicitly; never invent completion or missing constraints. Finish naturally within the output budget.\",\n].join(\"\\n\");\n\nfunction buildSummaryProviderMessages(params: {\n essentialOnly: boolean;\n messages: readonly Record<string, unknown>[];\n sourceMaxChars: number;\n targetSummaryTokens: number;\n}): { messages: Record<string, unknown>[]; sourceTruncated: boolean } {\n const { essentialOnly, messages, sourceMaxChars, targetSummaryTokens } = params;\n let sourceTruncated = false;\n const source = stringifyCompactionSource(messages, sourceMaxChars, truncated => { sourceTruncated = truncated; });\n return { sourceTruncated, messages: [\n {\n role: \"system\",\n content: essentialOnly\n ? `${SUMMARY_SYSTEM_PROMPT}\\nThis is the final recovery attempt. Stop immediately after the essential completion marker and do not output optional sections.`\n : SUMMARY_SYSTEM_PROMPT,\n },\n {\n role: \"user\",\n content: [\n \"Compress these runtime messages into a reusable working context.\",\n `Keep the visible Markdown summary within ${targetSummaryTokens} tokens. Use the output budget for the summary, not for hidden reasoning.`,\n essentialOnly\n ? \"Output the four essential sections only, then stop after the essential completion marker.\"\n : \"Prioritize the active task, constraints, verified outcomes and next step. Finish naturally.\",\n \"\",\n \"Messages JSON:\",\n source,\n ].join(\"\\n\"),\n },\n ] };\n}\n\nexport function fitContextCompactionSummaryInput(params: {\n essentialOnly?: boolean;\n maxInputTokens: number;\n messages: readonly Record<string, unknown>[];\n targetSummaryTokens: number;\n sourceMaxChars?: number;\n}): { messages: Record<string, unknown>[]; sourceTruncated: boolean } {\n const {\n essentialOnly = false,\n maxInputTokens,\n messages,\n sourceMaxChars = SUMMARY_SOURCE_MAX_CHARS,\n targetSummaryTokens,\n } = params;\n const empty = buildSummaryProviderMessages({\n essentialOnly,\n messages: [],\n sourceMaxChars: 0,\n targetSummaryTokens,\n });\n const fixedTokens = estimateInputTokens(empty.messages);\n if (fixedTokens > maxInputTokens) {\n throw new Error(\n `Context compaction summary prompt needs more than ${maxInputTokens} input tokens. Increase the agent contextTokens setting.`,\n );\n }\n // Allocate conservatively once. The source owner already fits strings; a second\n // binary search around it repeatedly serialized the same working window.\n const fitted = buildSummaryProviderMessages({ essentialOnly, messages, targetSummaryTokens,\n sourceMaxChars: Math.min(sourceMaxChars, Math.max(0, (maxInputTokens - fixedTokens - 8) * 3)) });\n if (estimateInputTokens(fitted.messages) > maxInputTokens) throw new Error(\"Compaction source cannot fit without dropping message identities.\");\n return fitted;\n}\n\nexport function normalizeContextCompactionSummary(content: string): string {\n return normalizeAssistantText(content, \"think-tags\").text.trim();\n}\n\ntype ParsedSummarySection = {\n heading: string;\n body: string;\n complete: boolean;\n marker: string;\n};\n\nexport type ContextCompactionSummaryValidation = {\n essentialComplete: boolean;\n missingEssentialSections: string[];\n summary: string | null;\n};\n\nfunction parseSummarySections(summary: string): ParsedSummarySection[] | null {\n if (!summary.startsWith(SUMMARY_HEADING)) {\n return null;\n }\n const headingPattern = /^## ([^\\n]+)$/gm;\n const headings = [...summary.matchAll(headingPattern)];\n if (headings.length === 0) {\n return null;\n }\n return headings.map((headingMatch, index) => {\n const heading = headingMatch[1]?.trim() ?? \"\";\n const start = (headingMatch.index ?? 0) + headingMatch[0].length;\n const end = headings[index + 1]?.index ?? summary.length;\n const body = summary.slice(start, end).trim();\n const optional = SUMMARY_OPTIONAL_SECTIONS.find(([name]) => name === heading);\n const marker = heading === SUMMARY_CONTINUATION_HEADING.slice(3)\n ? SUMMARY_ESSENTIAL_COMPLETE_MARKER\n : optional\n ? `<!-- nextclaw-section-complete:${optional[1]} -->`\n : \"\";\n const complete = optional\n ? body.endsWith(marker)\n : heading === SUMMARY_CONTINUATION_HEADING.slice(3)\n ? body.endsWith(marker)\n : Boolean(body);\n return {\n heading,\n body,\n complete,\n marker,\n };\n });\n}\n\n/**\n * Validate the priority-prefix protocol and return only complete sections.\n * A truncated optional tail is deliberately discarded as a unit.\n */\nexport function validateContextCompactionSummary(params: {\n summary: string;\n}): ContextCompactionSummaryValidation {\n const essentialMarkerCount = params.summary.split(SUMMARY_ESSENTIAL_COMPLETE_MARKER).length - 1;\n if (essentialMarkerCount !== 1) {\n return {\n essentialComplete: false,\n missingEssentialSections: [\"Continuation Contract\"],\n summary: null,\n };\n }\n const sections = parseSummarySections(params.summary);\n if (!sections) {\n return {\n essentialComplete: false,\n missingEssentialSections: [...SUMMARY_ESSENTIAL_SECTIONS],\n summary: null,\n };\n }\n const required = sections.slice(0, SUMMARY_ESSENTIAL_SECTIONS.length);\n const missingEssentialSections = SUMMARY_ESSENTIAL_SECTIONS.filter((heading, index) => {\n const section = required[index];\n return section?.heading !== heading || !section.body || !section.complete;\n });\n if (missingEssentialSections.length > 0) {\n return { essentialComplete: false, missingEssentialSections, summary: null };\n }\n\n const retained: string[] = [\n SUMMARY_HEADING,\n ...required.map((section) => `## ${section.heading}\\n\\n${section.body}`),\n ];\n const optionalStart = SUMMARY_ESSENTIAL_SECTIONS.length;\n for (let index = optionalStart; index < sections.length; index += 1) {\n const section = sections[index];\n const expectedOptional = SUMMARY_OPTIONAL_SECTIONS[index - optionalStart];\n if (\n !section ||\n !section.marker ||\n !section.complete ||\n !expectedOptional ||\n section.heading !== expectedOptional[0]\n ) {\n break;\n }\n retained.push(`## ${section.heading}\\n\\n${section.body}`);\n }\n return {\n essentialComplete: true,\n missingEssentialSections: [],\n summary: retained.join(\"\\n\\n\"),\n };\n}\n\nexport function fitContextCompactionSummaryOutput(params: {\n maxInstallableSummaryTokens: number;\n summary: string;\n}): string | null {\n const { maxInstallableSummaryTokens, summary } = params;\n const validation = validateContextCompactionSummary({ summary });\n if (!validation.summary) {\n return null;\n }\n const fittedSummary = validation.summary;\n if (estimateInputTokens(fittedSummary) <= maxInstallableSummaryTokens) {\n return fittedSummary;\n }\n const sections = parseSummarySections(fittedSummary);\n if (!sections) {\n return null;\n }\n const essentialSections = sections.slice(0, SUMMARY_ESSENTIAL_SECTIONS.length);\n const composeEssential = (): string => [\n SUMMARY_HEADING,\n ...essentialSections.map((section) => `## ${section.heading}\\n\\n${section.body}`),\n ].join(\"\\n\\n\");\n\n // Optional sections are a lower-priority tail: discard them before touching\n // the essential prefix. This is the normal hard-budget path for a length\n // response that completed the required protocol.\n const essentialOnly = composeEssential();\n if (estimateInputTokens(essentialOnly) <= maxInstallableSummaryTokens) {\n return essentialOnly;\n }\n return null;\n}\n\n/**\n * Last-resort checkpoint used after bounded semantic generation failures.\n * It deliberately preserves exact recent source instead of inventing a\n * natural-language summary, and explicitly marks older execution status unknown.\n */\nexport function buildContextCompactionEmergencySummary(params: {\n maxInstallableSummaryTokens: number;\n messages: readonly Record<string, unknown>[];\n}): string | null {\n const { maxInstallableSummaryTokens, messages } = params;\n const build = (sourceMaxChars: number): string => {\n let source = \"\";\n try { source = stringifyCompactionSource(messages.slice(-2), sourceMaxChars); } catch { /* Explicit degraded recovery may have no source. */ }\n const quotedSource = source\n ? source.split(\"\\n\").map((line) => `> ${line}`).join(\"\\n\")\n : \"> No recent source text fit the emergency checkpoint budget.\";\n return [\n SUMMARY_HEADING,\n \"## Active Request\\n\\nContinue the latest raw user request retained after this checkpoint. If no raw user request follows, continue the active run from the exact recent source below.\",\n `## Current Work State\\n\\nModel-based compaction did not produce a safe summary. Exact retained recent source:\\n\\n${quotedSource}`,\n \"## Safety and User Constraints\\n\\nHonor the retained system, service, and user constraints verbatim. Treat dropped older context as unknown and do not invent it.\",\n `## Continuation Contract\\n\\nContinue from the exact recent source and following raw messages. Older execution state is unknown: recover evidence before repeating any side effect. Do not repeat work unless the retained evidence says it is incomplete.\\n${SUMMARY_ESSENTIAL_COMPLETE_MARKER}`,\n ].join(\"\\n\\n\");\n };\n\n let lower = 0;\n let upper = SUMMARY_SOURCE_MAX_CHARS;\n let fitted = build(0);\n if (estimateInputTokens(fitted) > maxInstallableSummaryTokens) {\n return null;\n }\n while (lower <= upper) {\n const sourceMaxChars = Math.floor((lower + upper) / 2);\n const candidate = build(sourceMaxChars);\n if (estimateInputTokens(candidate) <= maxInstallableSummaryTokens) {\n fitted = candidate;\n lower = sourceMaxChars + 1;\n } else {\n upper = sourceMaxChars - 1;\n }\n }\n return fitted;\n}\n\n/** Build a deterministic, smaller source for semantic compaction retries. */\nexport function selectContextCompactionAttemptMessages(\n messages: readonly Record<string, unknown>[],\n attempt: number,\n): Record<string, unknown>[] {\n if (attempt <= 1) {\n return messages.map((message) => structuredClone(message));\n }\n const contentRatio = attempt >= 3 ? 0.25 : 0.5;\n return messages.map((message) => {\n const copy = structuredClone(message);\n if ((copy.role === \"system\" || copy.role === \"service\") && typeof copy.content === \"string\" && copy.content.includes(\"# Compressed Working Context\")) return copy;\n if (typeof copy.content === \"string\" && copy.content.length > 32) {\n const maxChars = Math.max(16, Math.floor(copy.content.length * contentRatio));\n copy.content = truncateSummarySourceString(copy.content, maxChars);\n }\n return copy;\n });\n}\n","import { estimateInputTokens } from \"@nextclaw/core/model-input-budget\";\nimport type { ContextCompactionCheckpoint } from \"@nextclaw/core/context-compaction\";\nimport {\n fitContextCompactionSummaryInput,\n normalizeContextCompactionSummary,\n} from \"@kernel/utils/context-compaction-summary-input.utils.js\";\n\nexport type GeneratedCompactionSummary = {\n diagnostics: NonNullable<ContextCompactionCheckpoint[\"summaryDiagnostics\"]>;\n summary: string;\n};\n\nexport type CompactionSummaryProvider = {\n chat(input: {\n model: string;\n maxTokens: number;\n messages: Record<string, unknown>[];\n requestId: string;\n sessionId: string;\n signal?: AbortSignal;\n thinkingLevel: \"off\";\n }): Promise<{ content: string | null; finishReason: string; usage: Record<string, number>; toolCalls?: readonly unknown[] }>;\n};\n\ntype SummaryGenerationRequest = {\n maxInputTokens: number;\n maxInstallableSummaryTokens: number;\n maxTokens: number;\n messages: Record<string, unknown>[];\n model: string;\n requestId: string;\n sessionId: string;\n signal?: AbortSignal;\n targetSummaryTokens: number;\n};\n\nconst NATURAL_FINISH_REASONS = new Set([\"completed\", \"end_turn\", \"stop\"]);\nconst SUMMARY_TIMEOUT_MS = 60_000;\nclass UnusableCompactionSummary extends Error {}\n// Code owns this notice. It never claims that omitted history was summarized.\nexport const COMPACTION_RECOVERY_NOTICE = [\n \"Earlier conversation is archived, not reliably summarized. Its constraints and action outcomes remain unresolved.\",\n \"Read the original session history before relying on old facts. Do not repeat actions or infer completion.\",\n \"Only read-only recovery is permitted. If required business conditions cannot be verified, ask a specific clarification.\",\n].join(\"\\n\");\n\nexport class ContextCompactionSummaryGenerationService {\n constructor(private readonly providerManager?: CompactionSummaryProvider) {}\n\n generate = async (params: SummaryGenerationRequest): Promise<GeneratedCompactionSummary> => {\n params.signal?.throwIfAborted();\n let inputTokens = 0;\n let attemptCount = 0;\n let finishReason = \"not-called\";\n let rawSummaryTokens = 0;\n let providerUsage: Record<string, number> = {};\n let summary = \"\";\n let failure: string | undefined;\n let sourceTruncated = false;\n const controller = new AbortController();\n const abort = () => controller.abort(params.signal?.reason);\n params.signal?.addEventListener(\"abort\", abort, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n if (!this.providerManager) throw new Error(\"Summary provider unavailable\");\n let messages: Record<string, unknown>[];\n try { const fitted = fitContextCompactionSummaryInput({\n maxInputTokens: params.maxInputTokens, messages: params.messages,\n sourceMaxChars: Math.min(512 * 1024, params.maxInputTokens * 3),\n targetSummaryTokens: params.targetSummaryTokens,\n }); messages = fitted.messages; sourceTruncated = fitted.sourceTruncated;\n } catch (error) { throw new UnusableCompactionSummary(error instanceof Error ? error.message : String(error)); }\n inputTokens = estimateInputTokens(messages);\n attemptCount = 1;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new UnusableCompactionSummary(\"Compaction summary deadline exceeded\");\n controller.abort(error);\n reject(error);\n }, SUMMARY_TIMEOUT_MS);\n });\n const cancelled = new Promise<never>((_, reject) => {\n controller.signal.addEventListener(\"abort\", () => reject(controller.signal.reason), { once: true });\n });\n const response = await Promise.race([\n this.providerManager.chat({\n model: params.model, maxTokens: params.maxTokens, messages,\n requestId: params.requestId, sessionId: params.sessionId,\n signal: controller.signal, thinkingLevel: \"off\",\n }), timeout, cancelled,\n ]);\n providerUsage = response.usage;\n finishReason = response.finishReason;\n summary = response.content ? normalizeContextCompactionSummary(response.content) : \"\";\n rawSummaryTokens = summary ? estimateInputTokens(summary) : 0;\n if (response.toolCalls?.length) throw new UnusableCompactionSummary(\"Unexpected summary tool calls\");\n if (!NATURAL_FINISH_REASONS.has(finishReason.trim().toLowerCase())) {\n throw new UnusableCompactionSummary(`Incomplete summary: finishReason=${finishReason}`);\n }\n if (!summary) throw new UnusableCompactionSummary(\"Empty visible summary\");\n if (rawSummaryTokens > Math.min(params.targetSummaryTokens, params.maxInstallableSummaryTokens)) {\n throw new UnusableCompactionSummary(\"Summary exceeds the installable budget\");\n }\n } catch (error) {\n params.signal?.throwIfAborted();\n if (!(error instanceof UnusableCompactionSummary)) throw error;\n failure = error instanceof Error ? error.message : String(error);\n summary = COMPACTION_RECOVERY_NOTICE;\n if (estimateInputTokens(summary) > params.maxInstallableSummaryTokens) {\n throw new Error(`Recovery notice cannot fit the model input budget: ${failure}`);\n }\n } finally {\n if (timer) clearTimeout(timer);\n params.signal?.removeEventListener(\"abort\", abort);\n }\n params.signal?.throwIfAborted();\n return { summary, diagnostics: {\n attemptCount, degraded: failure !== undefined || sourceTruncated, finishReason, sourceTruncated,\n installedSummaryTokens: estimateInputTokens(summary), providerInputTokens: inputTokens,\n providerMaxOutputTokens: params.maxTokens, providerUsage, rawSummaryTokens,\n recovery: failure ? \"deterministic-recent-context\" : \"provider-summary\",\n targetSummaryTokens: params.targetSummaryTokens, sourceBatchCount: 1,\n ...(failure ? { failure } : {}),\n } };\n };\n}\n","import {\n type NcpEndpointEvent,\n type NcpMessage,\n NcpEventType,\n} from \"@nextclaw/ncp\";\nimport { readCompressedContextCompactionCheckpoint, type ContextCompactionCheckpoint } from \"@nextclaw/core/context-compaction-checkpoint\";\nimport { MODEL_ROUND_PART_OFFSETS } from \"@nextclaw/ncp-agent-runtime\";\nimport { COMPACTION_RECOVERY_NOTICE } from \"../services/context-compaction-summary-generation.service.js\";\n\nexport const NEXTCLAW_TIMELINE_KIND_METADATA_KEY = \"nextclaw_timeline_kind\";\nexport const CONTEXT_COMPACTION_TIMELINE_KIND = \"context_compaction\";\nexport const CONTEXT_COMPACTION_PROJECTION_METADATA_KEY = \"nextclaw_context_projection\";\nexport const CONTEXT_COMPACTION_PROJECTION_KIND = \"compressed_context\";\nexport const CONTEXT_COMPACTION_PART_START = \"nextclaw_compaction_part_start\";\nexport const CONTEXT_COMPACTION_CONTINUATION_TEXT = \"Continue the active run from the compressed working context. Do not repeat completed tool calls; proceed with the next required action.\";\nexport const CONTEXT_COMPACTION_SYSTEM_PREAMBLE = [\n \"Compressed working context for this session. Original messages and recorded tool outcomes remain authoritative; verify uncertain constraints and effects using session history.\",\n \"Continue from this context and any following messages. Do not restart onboarding or treat missing profile fields as a new-session trigger unless the compressed context says onboarding is the active user task.\",\n].join(\"\\n\");\nexport const CONTEXT_COMPACTION_RECOVERY_PREAMBLE = \"Unresolved archived history: read original session history to verify old constraints and action outcomes. Only read-only recovery is permitted; ask a specific business clarification if required facts remain unknown.\";\n\nexport type ContextCompactionTimelineCheckpoint = ContextCompactionCheckpoint;\n\nfunction readCheckpointTimelineText(checkpoint: ContextCompactionTimelineCheckpoint): string {\n if (checkpoint.status === \"compressing\") {\n return \"Compressing earlier context\";\n }\n return checkpoint.status === \"compressed\"\n ? \"Earlier context was auto-compacted\"\n : \"Context compaction failed\";\n}\n\nfunction buildCompressedContextSystemText(checkpoint: ContextCompactionCheckpoint): string {\n return [\n CONTEXT_COMPACTION_SYSTEM_PREAMBLE,\n \"\",\n !checkpoint.recovery && checkpoint.summary === COMPACTION_RECOVERY_NOTICE\n ? \"Earlier conversation remains archived. Follow the latest human-confirmed task conditions and read original history for any older facts needed.\"\n : checkpoint.summary,\n ...(checkpoint.recovery ? [\n CONTEXT_COMPACTION_RECOVERY_PREAMBLE,\n ] : []),\n ].join(\"\\n\");\n}\n\nexport function readContextRecoveryState(messages: readonly NcpMessage[], fallback?: ContextCompactionCheckpoint | null): { required: boolean; checkpointId?: string; unresolvedArchive: boolean } {\n const checkpoint = readLatestContextCompactionCheckpoint(messages) ?? fallback;\n const unresolvedArchive = messages.some(message => message.metadata?.nextclaw_archived_body === true\n && (!checkpoint?.recovery || Date.parse(message.timestamp) > Date.parse(checkpoint.recovery.archiveThrough)));\n if (!checkpoint?.recovery) return { required: unresolvedArchive, unresolvedArchive };\n const checkpointId = checkpoint.recovery.checkpointId ?? checkpoint.id;\n const acknowledged = messages.some(message => message.role === \"user\"\n && message.metadata?.nextclaw_context_recovery_ack === checkpointId);\n return { required: !acknowledged || unresolvedArchive, checkpointId, unresolvedArchive };\n}\n\nexport function readContextCompactionCheckpoint(message: NcpMessage): ContextCompactionCheckpoint | null {\n const metadata = message.metadata;\n return metadata?.[NEXTCLAW_TIMELINE_KIND_METADATA_KEY] === CONTEXT_COMPACTION_TIMELINE_KIND\n ? readCompressedContextCompactionCheckpoint(metadata.checkpoint)\n : null;\n}\n\nfunction readLatestContextCompactionMarker(sessionMessages: readonly NcpMessage[]) {\n return sessionMessages.reduce<{ checkpoint: ContextCompactionCheckpoint } | null>((marker, message) => {\n const candidateCheckpoint = readContextCompactionCheckpoint(message);\n return candidateCheckpoint && (!marker || Date.parse(candidateCheckpoint.updatedAt) >= Date.parse(marker.checkpoint.updatedAt))\n ? { checkpoint: candidateCheckpoint }\n : marker;\n }, null);\n}\n\nfunction buildContextCompactionSummaryMessage(params: {\n checkpoint: ContextCompactionCheckpoint;\n sessionId: string;\n}): NcpMessage {\n const { checkpoint, sessionId } = params;\n return {\n id: `${sessionId}:context-compaction-summary:${checkpoint.id}:${checkpoint.updatedAt}`,\n sessionId,\n role: \"service\",\n status: \"final\",\n timestamp: checkpoint.updatedAt,\n parts: [{ type: \"text\", text: buildCompressedContextSystemText(checkpoint) }],\n metadata: {\n [CONTEXT_COMPACTION_PROJECTION_METADATA_KEY]: CONTEXT_COMPACTION_PROJECTION_KIND,\n ...(checkpoint.recovery ? { nextclaw_context_recovery: checkpoint.recovery } : {}),\n },\n };\n}\n\nfunction buildMidRunContinuationMessage(params: {\n checkpoint: ContextCompactionCheckpoint;\n sessionId: string;\n}): NcpMessage {\n const { checkpoint, sessionId } = params;\n return {\n id: `${sessionId}:context-compaction-continuation:${checkpoint.id}:${checkpoint.updatedAt}`,\n sessionId,\n role: \"user\",\n status: \"final\",\n timestamp: checkpoint.updatedAt,\n parts: [{\n type: \"text\",\n text: CONTEXT_COMPACTION_CONTINUATION_TEXT,\n }],\n };\n}\n\nfunction sliceMessageParts(message: NcpMessage, start: number, end?: number): NcpMessage {\n const base = Number(message.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0);\n const physicalEnd = base + message.parts.length;\n end ??= physicalEnd;\n if (!Number.isInteger(start) || start < 0 || start > end || !Number.isInteger(end)) {\n throw new Error(\"Invalid compacted message part boundary\");\n }\n if (!message.metadata?.nextclaw_partial_projection && (start < base || end > physicalEnd)) throw new Error(\"Invalid compacted message part boundary\");\n const localStart = Math.max(0, start - base);\n const localEnd = Math.min(message.parts.length, end - base);\n const projected = { ...message, parts: message.parts.slice(localStart, Math.max(localStart, localEnd)).map(part => structuredClone(part)), metadata: structuredClone(message.metadata ?? {}) };\n projected.metadata = { ...projected.metadata, [CONTEXT_COMPACTION_PART_START]: start };\n const offsets = projected.metadata?.[MODEL_ROUND_PART_OFFSETS];\n if (Array.isArray(offsets)) {\n projected.metadata = { ...projected.metadata, [MODEL_ROUND_PART_OFFSETS]:\n offsets.filter((offset) => offset > localStart && offset < localEnd).map((offset) => offset - localStart) };\n }\n return projected;\n}\n\nfunction projectMessageAfterCheckpoint(\n message: NcpMessage,\n checkpoint: ContextCompactionCheckpoint,\n): NcpMessage | null {\n const retainedEnd = checkpoint.retainedMessagePartEnds?.[message.id];\n const physicalEnd = Number(message.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0) + message.parts.length;\n if (typeof retainedEnd === \"number\") {\n return physicalEnd > retainedEnd ? sliceMessageParts(message, retainedEnd) : null;\n }\n const coveredPartCount = checkpoint.continuationMessageCoveredPartCount;\n if (\n message.id === checkpoint.continuationMessageId &&\n typeof coveredPartCount === \"number\" &&\n Number.isInteger(coveredPartCount) &&\n coveredPartCount >= 0\n ) {\n return physicalEnd > coveredPartCount\n ? sliceMessageParts(message, coveredPartCount)\n : null;\n }\n return Date.parse(message.timestamp) > Date.parse(readCheckpointCoveredUntil(checkpoint))\n ? structuredClone(message)\n : null;\n}\n\nfunction readCheckpointMessageIds(value: unknown): Set<string> {\n return new Set(\n Array.isArray(value)\n ? value.filter((messageId): messageId is string =>\n typeof messageId === \"string\" && messageId.length > 0,\n )\n : [],\n );\n}\n\nfunction projectPreservedUserMessage(\n message: NcpMessage,\n checkpoint: ContextCompactionCheckpoint,\n): NcpMessage {\n const truncated = checkpoint.truncatedPreservedUserMessage;\n if (\n truncated?.messageId === message.id &&\n typeof truncated.text === \"string\" &&\n truncated.text.length > 0\n ) {\n return {\n ...structuredClone(message),\n parts: [{ type: \"text\", text: truncated.text }],\n };\n }\n return structuredClone(message);\n}\n\nfunction readCheckpointCoveredUntil(checkpoint: ContextCompactionCheckpoint): string {\n return checkpoint.coveredUntil ?? checkpoint.updatedAt;\n}\n\nexport function createContextCompactionMessageId(): string {\n return `context-compaction-message-${crypto.randomUUID()}`;\n}\n\nexport function buildContextCompactionTimelineNcpMessage(params: {\n messageId: string;\n sessionId: string;\n checkpoint: ContextCompactionTimelineCheckpoint;\n}): NcpMessage {\n const { checkpoint, messageId, sessionId } = params;\n const text = readCheckpointTimelineText(checkpoint);\n return {\n id: messageId,\n sessionId,\n role: \"service\",\n status: \"final\",\n timestamp: checkpoint.updatedAt,\n parts: [{ type: \"text\", text }],\n metadata: {\n [NEXTCLAW_TIMELINE_KIND_METADATA_KEY]: CONTEXT_COMPACTION_TIMELINE_KIND,\n checkpoint,\n },\n };\n}\n\nexport function isContextCompactionTimelineMessage(message: { metadata?: Record<string, unknown> | undefined } | null | undefined): boolean {\n return message?.metadata?.[NEXTCLAW_TIMELINE_KIND_METADATA_KEY] === CONTEXT_COMPACTION_TIMELINE_KIND;\n}\n\nexport function isContextCompactionProjectionMessage(message: { metadata?: Record<string, unknown> | undefined } | null | undefined): boolean {\n return message?.metadata?.[CONTEXT_COMPACTION_PROJECTION_METADATA_KEY] === CONTEXT_COMPACTION_PROJECTION_KIND;\n}\n\nexport function readLatestContextCompactionCheckpoint(sessionMessages: readonly NcpMessage[]): ContextCompactionCheckpoint | null {\n return readLatestContextCompactionMarker(sessionMessages)?.checkpoint ?? null;\n}\n\nexport type ContextCompactionModelProjection = {\n messages: NcpMessage[];\n stablePrefixMessageCount: number;\n};\n\nexport function buildContextCompactionModelProjection(params: {\n sessionId: string;\n sessionMessages: readonly NcpMessage[];\n}): ContextCompactionModelProjection {\n const { sessionId, sessionMessages } = params;\n const marker = readLatestContextCompactionMarker(sessionMessages);\n const regularMessages = sessionMessages.filter((message) => !readContextCompactionCheckpoint(message));\n if (!marker) {\n return {\n messages: regularMessages.map((message) => structuredClone(message)),\n stablePrefixMessageCount: 0,\n };\n }\n const { checkpoint: storedCheckpoint } = marker;\n const checkpoint = readContextRecoveryState(sessionMessages).required ? storedCheckpoint : { ...storedCheckpoint, recovery: undefined };\n const preservedUserMessageIds = readCheckpointMessageIds(checkpoint.preservedUserMessageIds);\n const retainedMessageIds = readCheckpointMessageIds(checkpoint.retainedMessageIds);\n const preservedUserMessages = regularMessages\n .filter((message) => message.role === \"user\" && preservedUserMessageIds.has(message.id))\n .map((message) => projectPreservedUserMessage(message, checkpoint))\n .sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp));\n const retainedMessages = regularMessages\n .filter((message) => retainedMessageIds.has(message.id))\n .map((message) => sliceMessageParts(message, checkpoint.retainedMessagePartStarts?.[message.id] ?? Number(message.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0),\n checkpoint.retainedMessagePartEnds?.[message.id] ?? Number(message.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0) + message.parts.length))\n .sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp));\n const projectedRegularMessages = regularMessages\n .filter((message) =>\n !preservedUserMessageIds.has(message.id) && (!retainedMessageIds.has(message.id)\n || checkpoint.retainedMessagePartEnds?.[message.id] !== undefined),\n )\n .map((message) => projectMessageAfterCheckpoint(message, checkpoint))\n .filter((message): message is NcpMessage => Boolean(message))\n .sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp));\n const stablePrefixMessages = [\n buildContextCompactionSummaryMessage({ checkpoint, sessionId }),\n ...preservedUserMessages,\n ...(checkpoint.phase === \"mid-run\"\n ? [buildMidRunContinuationMessage({ checkpoint, sessionId })]\n : []),\n ...retainedMessages,\n ].map((message) => structuredClone(message));\n return {\n messages: [\n ...stablePrefixMessages,\n ...projectedRegularMessages.map((message) => structuredClone(message)),\n ],\n stablePrefixMessageCount: stablePrefixMessages.length,\n };\n}\n\nexport function readContextWindowEventSessionId(event: NcpEndpointEvent): string | null {\n const payload = \"payload\" in event ? event.payload : null;\n if (!payload || typeof payload !== \"object\") {\n return null;\n }\n return \"sessionId\" in payload && typeof payload.sessionId === \"string\"\n ? payload.sessionId.trim() || null\n : null;\n}\n\nexport function isContextWindowSnapshot(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function createContextWindowSignature(value: Record<string, unknown>): string {\n return JSON.stringify(value);\n}\n\nexport function shouldRefreshContextWindowDuringStream(event: NcpEndpointEvent): boolean {\n switch (event.type) {\n case NcpEventType.MessageTextStart:\n case NcpEventType.MessageTextDelta:\n case NcpEventType.MessageTextEnd:\n case NcpEventType.MessageReasoningStart:\n case NcpEventType.MessageReasoningDelta:\n case NcpEventType.MessageReasoningEnd:\n case NcpEventType.MessageToolCallStart:\n case NcpEventType.MessageToolCallArgs:\n case NcpEventType.MessageToolCallArgsDelta:\n case NcpEventType.MessageToolCallEnd:\n case NcpEventType.MessageToolCallResult:\n return true;\n default:\n return false;\n }\n}\n\nexport function shouldRefreshContextWindowImmediately(event: NcpEndpointEvent): boolean {\n switch (event.type) {\n case NcpEventType.MessageSent:\n case NcpEventType.MessageCompleted:\n case NcpEventType.MessageFailed:\n case NcpEventType.MessageAbort:\n case NcpEventType.RunFinished:\n case NcpEventType.RunError:\n return true;\n default:\n return false;\n }\n}\n","import {\n CONTEXT_COMPACTION_METADATA_KEY,\n ContextCompactionService,\n ContextWindowBudgetService,\n buildCompressingCompactionCheckpoint,\n buildContextWindowSnapshot,\n readCompressedContextCompactionCheckpoint,\n type ContextCompactionCheckpoint,\n type ContextCompactionPhase,\n type ContextCompactionPlan,\n type ContextWindowBudgetEvaluation,\n type ContextWindowSnapshot,\n} from \"@nextclaw/core/context-compaction\";\nimport { estimateInputTokens } from \"@nextclaw/core/model-input-budget\";\nimport { type NcpMessage, type NcpTool } from \"@nextclaw/ncp\";\nimport {\n ncpMessageToOpenAiMessageGroups,\n type LocalAssetStore,\n} from \"@nextclaw/ncp-agent-runtime\";\nimport { CHAT_CONTINUATION_TARGET_MESSAGE_METADATA_KEY } from \"@nextclaw/shared\";\nimport {\n buildContextBlockInputMessages,\n estimateToolInputTokens,\n} from \"@kernel/utils/agent-model-input-budget.utils.js\";\nimport { ContextCompactionSummaryGenerationService, type CompactionSummaryProvider } from \"./context-compaction-summary-generation.service.js\";\n\nexport type CompactionProfileResolver = {\n resolveAgentProfileForRun(input: {\n requestMetadata: Record<string, unknown>;\n storedAgentId?: string;\n }): { contextTokens: number; reservedContextTokens: number };\n};\nexport type { CompactionSummaryProvider } from \"./context-compaction-summary-generation.service.js\";\nimport {\n buildContextCompactionModelProjection,\n buildContextCompactionTimelineNcpMessage,\n CONTEXT_COMPACTION_CONTINUATION_TEXT,\n CONTEXT_COMPACTION_PART_START,\n CONTEXT_COMPACTION_SYSTEM_PREAMBLE,\n CONTEXT_COMPACTION_RECOVERY_PREAMBLE,\n createContextCompactionMessageId,\n isContextCompactionProjectionMessage,\n isContextCompactionTimelineMessage,\n readLatestContextCompactionCheckpoint,\n readContextRecoveryState,\n} from \"@kernel/features/context-compaction/utils/context-compaction.utils.js\";\n\nexport type ContextCompactionPreflightResult = {\n contextWindow: ContextWindowSnapshot;\n sessionMessages: NcpMessage[];\n timelineMessage: NcpMessage | null;\n};\n\nexport type ContextCompactionPreflightBeginResult = {\n contextWindow: ContextWindowSnapshot;\n sessionMessages: NcpMessage[];\n pendingCompaction: ContextCompactionPendingWork | null;\n};\n\nexport type ContextCompactionTrigger = \"automatic\" | \"manual\";\n\ntype ContinuationMessageBoundary = {\n messageId: string;\n coveredPartCount: number;\n};\n\ntype ContextCompactionPendingWork = {\n overflow: boolean;\n originalBudget: ContextWindowBudgetEvaluation;\n priorCheckpoint: ContextCompactionCheckpoint | null;\n checkpoint: ReturnType<typeof buildCompressingCompactionCheckpoint>;\n contextBlockMessages: Record<string, unknown>[];\n continuationMessageBoundary: ContinuationMessageBoundary | null;\n contextTokens: number;\n phase: ContextCompactionPhase;\n serviceMessageId: string;\n model: string;\n plan: ContextCompactionPlan;\n reservedContextTokens: number;\n snapshotFixedInputTokens: number;\n sessionId: string;\n sessionMessages: NcpMessage[];\n};\n\ntype ResolvedCompactionProfile = {\n contextTokens: number;\n reservedContextTokens: number;\n};\n\nfunction toCompactionModelMessages(\n messages: readonly NcpMessage[],\n assetStore: LocalAssetStore | null,\n): Record<string, unknown>[] {\n return messages.flatMap((message) =>\n ncpMessageToOpenAiMessageGroups(message, { assetStore }).flatMap((group, index, groups) => group.messages.map((providerMessage) => ({\n ...providerMessage,\n ncp_message_id: message.id,\n ncp_part_start: group.partStart + Number(message.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0),\n ncp_part_end: (groups[index + 1]?.partStart ?? message.parts.length)\n + Number(message.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0),\n timestamp: message.timestamp,\n }))),\n );\n}\n\nfunction estimateCompactionProjectionOverhead(phase: ContextCompactionPhase): number {\n const summaryPlanOverhead = estimateInputTokens({ role: \"user\", content: \"\" });\n const summaryProjectionOverhead = estimateInputTokens({\n role: \"system\",\n content: `${CONTEXT_COMPACTION_SYSTEM_PREAMBLE}\\n\\n${CONTEXT_COMPACTION_RECOVERY_PREAMBLE}\\n\\n`,\n });\n const continuationTokens = phase === \"mid-run\"\n ? estimateInputTokens({ role: \"user\", content: CONTEXT_COMPACTION_CONTINUATION_TEXT })\n : 0;\n return Math.max(0, summaryProjectionOverhead - summaryPlanOverhead) + continuationTokens;\n}\n\nfunction mergeInputMessages(params: {\n inputMessages: readonly NcpMessage[];\n sessionMessages: readonly NcpMessage[];\n}): NcpMessage[] {\n const messages = params.sessionMessages.map((message) => structuredClone(message));\n const seen = new Set(messages.map((message) => message.id));\n for (const message of params.inputMessages) {\n if (seen.has(message.id)) {\n continue;\n }\n messages.push(structuredClone(message));\n }\n return messages;\n}\n\nfunction readContinuationMessageBoundary(\n messages: readonly NcpMessage[],\n): ContinuationMessageBoundary | null {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (\n message?.role === \"assistant\" &&\n (message.status === \"pending\" || message.status === \"streaming\")\n ) {\n return {\n messageId: message.id,\n coveredPartCount: Number(message.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0) + message.parts.length,\n };\n }\n }\n return null;\n}\n\nfunction readPreRunContinuationBoundary(\n messages: readonly NcpMessage[],\n): ContinuationMessageBoundary | null {\n const continuationPrompt = messages.at(-1);\n const targetMessageId = continuationPrompt?.metadata?.[\n CHAT_CONTINUATION_TARGET_MESSAGE_METADATA_KEY\n ];\n if (typeof targetMessageId !== \"string\" || !targetMessageId.trim()) {\n return null;\n }\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const target = messages[index];\n if (target?.id === targetMessageId && target.role === \"assistant\") {\n return { messageId: target.id, coveredPartCount: Number(target.metadata?.[CONTEXT_COMPACTION_PART_START] ?? 0) + target.parts.length };\n }\n }\n return null;\n}\n\nfunction buildContextWindowSnapshotFromBudget(params: {\n budget: ContextWindowBudgetEvaluation;\n checkpoint: ContextCompactionCheckpoint | null;\n completeInputBudget: boolean;\n fixedInputTokens: number;\n reservedContextTokens: number;\n totalContextTokens: number;\n}): ContextWindowSnapshot {\n const {\n budget,\n checkpoint,\n completeInputBudget,\n fixedInputTokens,\n reservedContextTokens,\n totalContextTokens,\n } = params;\n return buildContextWindowSnapshot({\n usedContextTokens: budget.estimatedTokens,\n completeInputBudget,\n totalContextTokens,\n fixedInputTokens,\n reservedContextTokens,\n triggerContextTokens: budget.triggerTokens,\n prunedUsedContextTokens: budget.estimatedTokens,\n droppedHistoryCount: budget.droppedHistoryCount,\n truncatedToolResultCount: budget.truncatedToolResultCount,\n truncatedSystemPrompt: budget.truncatedSystemPrompt,\n truncatedUserMessage: budget.truncatedUserMessage,\n checkpoint,\n compactedUsedContextTokens: checkpoint ? budget.estimatedTokens : undefined,\n });\n}\n\nexport class ContextCompactionPreflightService {\n private readonly deferredAttempts = new Map<string, { model: string; tokens: number }>();\n private readonly compactionService = new ContextCompactionService();\n private readonly contextWindowBudgetService = new ContextWindowBudgetService();\n private readonly summaryGenerationService: ContextCompactionSummaryGenerationService;\n\n constructor(\n private readonly agentManager: CompactionProfileResolver,\n providerManager?: CompactionSummaryProvider,\n private readonly assetStore: LocalAssetStore | null = null,\n ) {\n this.summaryGenerationService = new ContextCompactionSummaryGenerationService(providerManager);\n }\n\n preview = (params: {\n completeInputBudget?: boolean;\n contextBlocks?: readonly string[];\n fixedInputTokens?: number;\n requestMetadata: Record<string, unknown>;\n sessionId: string;\n sessionMessages: readonly NcpMessage[];\n storedAgentId?: string;\n storedMetadata: Record<string, unknown>;\n tools?: readonly NcpTool[];\n }): ContextWindowSnapshot | null => {\n const {\n completeInputBudget = false,\n contextBlocks = [],\n fixedInputTokens,\n requestMetadata,\n sessionId,\n sessionMessages,\n storedAgentId,\n storedMetadata,\n tools = [],\n } = params;\n const profile = this.resolveCompactionProfile({\n requestMetadata,\n storedAgentId,\n });\n const existingCheckpoint = readCompressedContextCompactionCheckpoint(\n storedMetadata[CONTEXT_COMPACTION_METADATA_KEY],\n ) ?? readLatestContextCompactionCheckpoint(sessionMessages);\n const projectedMessages = existingCheckpoint\n ? buildContextCompactionModelProjection({\n sessionId,\n sessionMessages,\n }).messages\n : sessionMessages.filter((message) => !isContextCompactionTimelineMessage(message));\n const contextBlockMessages = buildContextBlockInputMessages(contextBlocks);\n const contextBlockInputTokens = estimateInputTokens(contextBlockMessages);\n const toolInputTokens = estimateToolInputTokens(tools);\n const snapshotFixedInputTokens = fixedInputTokens\n ?? contextBlockInputTokens + toolInputTokens;\n const messages = [\n ...(fixedInputTokens === undefined ? contextBlockMessages : []),\n ...toCompactionModelMessages(projectedMessages, this.assetStore),\n ];\n const budget = this.contextWindowBudgetService.evaluate({\n messages,\n contextTokens: profile.contextTokens,\n fixedInputTokens: fixedInputTokens\n ?? toolInputTokens,\n reservedContextTokens: profile.reservedContextTokens,\n });\n return buildContextWindowSnapshotFromBudget({\n budget,\n checkpoint: existingCheckpoint,\n completeInputBudget,\n fixedInputTokens: snapshotFixedInputTokens,\n reservedContextTokens: profile.reservedContextTokens,\n totalContextTokens: profile.contextTokens,\n });\n };\n\n begin = (params: {\n contextBlocks?: readonly string[];\n inputMessages: readonly NcpMessage[];\n model: string;\n phase?: ContextCompactionPhase;\n requestMetadata: Record<string, unknown>;\n sessionId: string;\n sessionMessages: readonly NcpMessage[];\n storedAgentId?: string;\n storedMetadata: Record<string, unknown>;\n tools?: readonly NcpTool[];\n trigger?: ContextCompactionTrigger;\n overflow?: boolean;\n maxOutputTokens?: number;\n }): ContextCompactionPreflightBeginResult => {\n const {\n contextBlocks = [],\n inputMessages,\n model,\n phase = \"pre-run\",\n requestMetadata,\n sessionId,\n sessionMessages,\n storedAgentId,\n storedMetadata,\n tools = [],\n trigger = \"automatic\",\n } = params;\n const profile = this.resolveCompactionProfile({\n requestMetadata,\n storedAgentId,\n });\n const contextTokens = profile.contextTokens;\n const reservedContextTokens = Math.max(profile.reservedContextTokens, params.maxOutputTokens ?? 0);\n const ncpMessages = mergeInputMessages({\n inputMessages,\n sessionMessages,\n });\n const continuationMessageBoundary = phase === \"mid-run\"\n ? readContinuationMessageBoundary(ncpMessages)\n : readPreRunContinuationBoundary(ncpMessages);\n const existingCheckpoint = readCompressedContextCompactionCheckpoint(\n storedMetadata[CONTEXT_COMPACTION_METADATA_KEY],\n ) ?? readLatestContextCompactionCheckpoint(ncpMessages);\n const projectedMessages = existingCheckpoint\n ? buildContextCompactionModelProjection({\n sessionId,\n sessionMessages: ncpMessages,\n }).messages\n : ncpMessages.filter((message) => !isContextCompactionTimelineMessage(message));\n const contextBlockMessages = buildContextBlockInputMessages(contextBlocks);\n const messages = [\n ...contextBlockMessages,\n ...toCompactionModelMessages(projectedMessages, this.assetStore),\n ];\n const preservableUserMessageIds = ncpMessages.flatMap((message) =>\n message.role === \"user\" ? [message.id] : [],\n );\n const fixedInputTokens = estimateToolInputTokens(tools);\n const snapshotFixedInputTokens = estimateInputTokens(contextBlockMessages) + fixedInputTokens;\n const budget = this.contextWindowBudgetService.evaluate({\n messages,\n contextTokens,\n fixedInputTokens,\n reservedContextTokens,\n });\n const hardInputLimit = contextTokens - reservedContextTokens;\n const archivePressure = readContextRecoveryState(ncpMessages, existingCheckpoint).unresolvedArchive;\n const structuralPressure = archivePressure || ncpMessages.length > 256 || ncpMessages.reduce((count, message) => count + message.parts.length, 0) > 1_024;\n const deferred = this.deferredAttempts.get(sessionId);\n const retryGrowth = Math.max(1, Math.floor((hardInputLimit - budget.triggerTokens) / 2));\n const throttled = !params.overflow && trigger === \"automatic\" && budget.estimatedTokens <= hardInputLimit\n && deferred?.model === model && budget.estimatedTokens < deferred.tokens + retryGrowth;\n const plan = trigger === \"automatic\" && ((!budget.shouldCompact && !params.overflow && !structuralPressure) || (throttled && !structuralPressure))\n ? null\n : this.compactionService.prepareForModelInput({\n messages,\n coverLeadingSystemMessage:\n contextBlockMessages.length === 0\n && isContextCompactionProjectionMessage(projectedMessages[0]),\n contextTokens,\n compactionThresholdTokens: trigger === \"manual\" || params.overflow || structuralPressure ? 0 : budget.triggerTokens,\n fixedInputTokens,\n preservableUserMessageIds,\n projectedTokenLimit: Math.max(1, Math.min(hardInputLimit,\n params.overflow ? Math.floor(budget.estimatedTokens * 0.7) : Math.max(budget.triggerTokens, snapshotFixedInputTokens + 1_024)) - (\n estimateCompactionProjectionOverhead(phase)\n )),\n retainLatestMessage: phase === \"pre-run\",\n retainRecentTokens: 20_000,\n });\n const coveredSessionMessageCount = plan\n ? (existingCheckpoint?.coveredSessionMessageCount ?? 0) + plan.coveredMessages.length - (existingCheckpoint ? 1 : 0)\n : 0;\n const serviceMessageId = createContextCompactionMessageId();\n const checkpoint = plan\n ? {\n ...buildCompressingCompactionCheckpoint(\n storedMetadata[CONTEXT_COMPACTION_METADATA_KEY],\n ),\n phase,\n continuationMessageId: continuationMessageBoundary?.messageId,\n continuationMessageCoveredPartCount:\n continuationMessageBoundary?.coveredPartCount,\n coveredMessageCount: coveredSessionMessageCount,\n coveredSessionMessageCount,\n originalEstimatedTokens: plan.originalEstimatedTokens,\n projectedEstimatedTokens: budget.estimatedTokens,\n }\n : existingCheckpoint;\n\n const contextWindow = buildContextWindowSnapshotFromBudget({\n budget,\n checkpoint,\n completeInputBudget: true,\n fixedInputTokens: snapshotFixedInputTokens,\n reservedContextTokens,\n totalContextTokens: contextTokens,\n });\n return {\n contextWindow,\n sessionMessages: ncpMessages,\n pendingCompaction: plan && checkpoint\n ? {\n originalBudget: budget,\n overflow: params.overflow === true,\n priorCheckpoint: existingCheckpoint,\n checkpoint,\n contextBlockMessages,\n continuationMessageBoundary,\n contextTokens,\n phase,\n serviceMessageId,\n model,\n plan,\n reservedContextTokens,\n snapshotFixedInputTokens,\n sessionId,\n sessionMessages: ncpMessages,\n }\n : null,\n };\n };\n\n finish = async (\n pending: ContextCompactionPendingWork,\n signal?: AbortSignal,\n ): Promise<ContextCompactionPreflightResult> => {\n let summaryDiagnostics: ContextCompactionCheckpoint[\"summaryDiagnostics\"];\n const compacted = await this.compactionService.compactPreparedForModelInput({\n contextTokens: pending.contextTokens,\n plan: pending.plan,\n generateSummary: async ({\n maxInputTokens,\n maxInstallableSummaryTokens,\n maxTokens,\n messages,\n targetSummaryTokens,\n }) => {\n const generated = await this.summaryGenerationService.generate({\n maxInputTokens,\n maxInstallableSummaryTokens,\n maxTokens,\n messages,\n model: pending.model,\n requestId: pending.serviceMessageId,\n sessionId: pending.sessionId,\n signal,\n targetSummaryTokens,\n });\n summaryDiagnostics = generated.diagnostics;\n return generated.summary;\n },\n });\n const generatedCheckpoint = compacted.checkpoint;\n if (!generatedCheckpoint) {\n throw new Error(\"context compaction pending work did not produce a checkpoint\");\n }\n signal?.throwIfAborted();\n if ((summaryDiagnostics?.recovery === \"deterministic-recent-context\" || summaryDiagnostics?.sourceTruncated)\n && !pending.overflow && !pending.sessionMessages.some(message => message.metadata?.nextclaw_archived_body)\n && pending.originalBudget.estimatedTokens <= pending.contextTokens - pending.reservedContextTokens) {\n // Discard the candidate; nothing from an unsuccessful summary replaces the old view.\n this.deferredAttempts.delete(pending.sessionId);\n this.deferredAttempts.set(pending.sessionId, { model: pending.model, tokens: pending.originalBudget.estimatedTokens });\n if (this.deferredAttempts.size > 512) this.deferredAttempts.delete(this.deferredAttempts.keys().next().value!);\n return {\n contextWindow: buildContextWindowSnapshotFromBudget({\n budget: pending.originalBudget, checkpoint: pending.priorCheckpoint,\n completeInputBudget: true, fixedInputTokens: pending.snapshotFixedInputTokens,\n reservedContextTokens: pending.reservedContextTokens, totalContextTokens: pending.contextTokens,\n }),\n sessionMessages: pending.sessionMessages,\n timelineMessage: buildContextCompactionTimelineNcpMessage({\n messageId: pending.serviceMessageId, sessionId: pending.sessionId,\n checkpoint: { ...pending.checkpoint, status: \"failed\", summaryDiagnostics, updatedAt: new Date().toISOString() },\n }),\n };\n }\n this.deferredAttempts.delete(pending.sessionId);\n const checkpoint: ContextCompactionCheckpoint = {\n ...generatedCheckpoint,\n id: pending.checkpoint.id,\n createdAt: pending.checkpoint.createdAt,\n phase: pending.phase,\n continuationMessageId: pending.continuationMessageBoundary?.messageId,\n continuationMessageCoveredPartCount:\n pending.continuationMessageBoundary?.coveredPartCount,\n coveredMessageCount: pending.checkpoint.coveredMessageCount,\n coveredSessionMessageCount: pending.checkpoint.coveredSessionMessageCount,\n summaryDiagnostics: summaryDiagnostics!,\n status: \"compressed\" as const,\n ...(summaryDiagnostics?.recovery === \"deterministic-recent-context\" || summaryDiagnostics?.sourceTruncated || readContextRecoveryState(pending.sessionMessages, pending.priorCheckpoint).required\n ? { recovery: {\n required: true as const,\n reason: summaryDiagnostics?.recovery === \"deterministic-recent-context\"\n ? \"summary-unavailable\" as const : \"unresolved-archive\" as const,\n archiveThrough: pending.sessionMessages.reduce((latest, message) => Date.parse(message.timestamp) > Date.parse(latest) ? message.timestamp : latest,\n generatedCheckpoint.coveredUntil ?? generatedCheckpoint.updatedAt),\n checkpointId: summaryDiagnostics?.recovery === \"deterministic-recent-context\" || summaryDiagnostics?.sourceTruncated\n || readContextRecoveryState(pending.sessionMessages, pending.priorCheckpoint).unresolvedArchive ? pending.checkpoint.id\n : pending.priorCheckpoint?.recovery?.checkpointId ?? pending.priorCheckpoint?.id ?? pending.checkpoint.id,\n } } : {}),\n };\n const timelineMessage = buildContextCompactionTimelineNcpMessage({\n messageId: pending.serviceMessageId,\n sessionId: pending.sessionId,\n checkpoint,\n });\n const projectedMessages = buildContextCompactionModelProjection({\n sessionId: pending.sessionId,\n sessionMessages: [...pending.sessionMessages, timelineMessage],\n }).messages;\n const budget = this.contextWindowBudgetService.evaluate({\n messages: [\n ...pending.contextBlockMessages,\n ...toCompactionModelMessages(projectedMessages, this.assetStore),\n ],\n contextTokens: pending.contextTokens,\n fixedInputTokens: pending.plan.fixedInputTokens,\n reservedContextTokens: pending.reservedContextTokens,\n });\n if (budget.estimatedTokens > pending.contextTokens - pending.reservedContextTokens) {\n throw new Error(\n `Context compaction checkpoint does not fit the final provider input surface: ${budget.estimatedTokens} estimated tokens exceeds ${budget.triggerTokens}. The previous checkpoint was kept unchanged.`,\n );\n }\n const contextWindow = buildContextWindowSnapshotFromBudget({\n budget,\n checkpoint,\n completeInputBudget: true,\n fixedInputTokens: pending.snapshotFixedInputTokens,\n reservedContextTokens: pending.reservedContextTokens,\n totalContextTokens: pending.contextTokens,\n });\n return {\n contextWindow,\n sessionMessages: pending.sessionMessages,\n timelineMessage,\n };\n };\n\n private resolveCompactionProfile = (params: {\n requestMetadata: Record<string, unknown>;\n storedAgentId?: string;\n }): ResolvedCompactionProfile => {\n const profile = this.agentManager.resolveAgentProfileForRun({\n requestMetadata: params.requestMetadata,\n storedAgentId: params.storedAgentId,\n });\n return {\n contextTokens: profile.contextTokens,\n reservedContextTokens: profile.reservedContextTokens,\n };\n };\n}\n","import { mergeToolExecutionTiming } from \"@nextclaw/ncp-toolkit\";\nimport {\n type NcpEndpointEvent,\n NcpEventType,\n type NcpMessage,\n} from \"@nextclaw/ncp\";\nimport {\n NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE,\n NCP_SESSION_REQUEST_ACCEPTED_EVENT_TYPE,\n NCP_SESSION_REQUEST_COMPLETED_EVENT_TYPE,\n NCP_SESSION_REQUEST_FAILED_EVENT_TYPE,\n type NcpAgentSessionJournalReplayEvent,\n type NcpSessionRequestJournalEvent,\n} from \"./ncp-agent-session-journal.utils.js\";\n\nexport type NcpAgentSessionReplayableEvent = Exclude<\n NcpAgentSessionJournalReplayEvent,\n NcpSessionRequestJournalEvent\n>;\ntype NcpToolCallResultReplayPayload = Extract<\n NcpEndpointEvent,\n { type: NcpEventType.MessageToolCallResult }\n>[\"payload\"];\n\nexport function readSupersededSyntheticRecoveryIndexes(\n events: readonly NcpAgentSessionJournalReplayEvent[],\n): Set<number> {\n const superseded = new Set<number>();\n const futureMessageIds = new Set<string>();\n const futureRunIds = new Set<string>();\n const futureToolCallMessageIds = new Map<string, string>();\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (\n event.type === NcpEventType.RunError &&\n event.payload.interrupted === true &&\n ((event.payload.messageId && futureMessageIds.has(event.payload.messageId)) ||\n (event.payload.runId && futureRunIds.has(event.payload.runId)))\n ) {\n superseded.add(index);\n }\n const toolCallId = readEventToolCallId(event);\n const mappedToolMessageId = toolCallId\n ? futureToolCallMessageIds.get(toolCallId)\n : undefined;\n if (mappedToolMessageId) {\n futureMessageIds.add(mappedToolMessageId);\n }\n if (isReplayContinuationEvent(event)) {\n const messageId = readEventMessageId(event);\n const runId = readEventRunId(event);\n if (messageId) futureMessageIds.add(messageId);\n if (runId) futureRunIds.add(runId);\n if (toolCallId && messageId) {\n futureToolCallMessageIds.set(toolCallId, messageId);\n }\n }\n }\n return superseded;\n}\n\nexport class SessionReplaySupersessionTracker {\n private readonly interrupted: Array<{ index: number; messageId: string | null; runId: string | null }> = [];\n private readonly lastContinuationByMessageId = new Map<string, number>();\n private readonly lastContinuationByRunId = new Map<string, number>();\n private readonly toolOwners = new Map<string, string>();\n\n observe = (event: NcpAgentSessionJournalReplayEvent, index: number): void => {\n const messageId = readEventMessageId(event);\n const runId = readEventRunId(event);\n const toolCallId = readEventToolCallId(event);\n if (toolCallId && messageId) this.toolOwners.set(toolCallId, messageId);\n if (event.type === NcpEventType.RunError && event.payload.interrupted === true) {\n this.interrupted.push({ index, messageId, runId });\n }\n if (!isReplayContinuationEvent(event)) return;\n const ownerMessageId = messageId ?? (toolCallId ? this.toolOwners.get(toolCallId) ?? null : null);\n if (ownerMessageId) this.lastContinuationByMessageId.set(ownerMessageId, index);\n if (runId) this.lastContinuationByRunId.set(runId, index);\n };\n\n finish = (): Set<number> => new Set(this.interrupted\n .filter(({ index, messageId, runId }) =>\n (messageId ? (this.lastContinuationByMessageId.get(messageId) ?? -1) > index : false) ||\n (runId ? (this.lastContinuationByRunId.get(runId) ?? -1) > index : false))\n .map(({ index }) => index));\n}\n\nexport function isReplayContinuationEvent(event: NcpAgentSessionJournalReplayEvent): boolean {\n if (isJournalOnlyEvent(event)) {\n return false;\n }\n if (event.type === NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE) {\n return true;\n }\n return (\n readStreamingMessageId(event) !== null ||\n event.type === NcpEventType.MessageCompleted ||\n event.type === NcpEventType.RunFinished\n );\n}\n\nexport function isStreamingMessageCreationEvent(event: NcpEndpointEvent): boolean {\n return event.type === NcpEventType.MessageTextStart || event.type === NcpEventType.MessageReasoningStart;\n}\n\nexport function readEventMessageId(event: NcpAgentSessionJournalReplayEvent): string | null {\n if (isJournalOnlyEvent(event)) {\n return null;\n }\n const message = readMessageFromSummaryEvent(event);\n if (message?.id) {\n return message.id;\n }\n if (event.type === NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE) {\n return null;\n }\n const streamingMessageId = readStreamingMessageId(event);\n if (streamingMessageId) {\n return streamingMessageId;\n }\n const payload = \"payload\" in event && isRecord(event.payload)\n ? event.payload as Record<string, unknown>\n : null;\n const messageId = payload?.messageId;\n if (typeof messageId === \"string\" && messageId.trim()) {\n return messageId.trim();\n }\n return null;\n}\n\nexport function readEventRunId(event: NcpAgentSessionJournalReplayEvent): string | null {\n if (isJournalOnlyEvent(event)) {\n return null;\n }\n if (event.type === NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE) {\n return null;\n }\n const payload = \"payload\" in event && isRecord(event.payload)\n ? event.payload as Record<string, unknown>\n : null;\n const runId = payload?.runId;\n if (typeof runId === \"string\" && runId.trim()) {\n return runId.trim();\n }\n return null;\n}\n\nexport function readEventToolCallId(event: NcpAgentSessionJournalReplayEvent): string | null {\n if (isJournalOnlyEvent(event)) {\n return null;\n }\n const payload = \"payload\" in event && isRecord(event.payload)\n ? event.payload as Record<string, unknown>\n : null;\n const toolCallId = payload?.toolCallId;\n return typeof toolCallId === \"string\" && toolCallId.trim() ? toolCallId.trim() : null;\n}\n\nexport function createReplayEvent(\n event: NcpAgentSessionReplayableEvent,\n toolResultsByCallId: ReadonlyMap<string, NcpToolCallResultReplayPayload>\n): NcpEndpointEvent {\n const replayEvent = structuredClone(event);\n const occurredAt = readReplayEventOccurredAt(replayEvent);\n const replayMessage = readMessageFromSummaryEvent(replayEvent);\n const legacyCompactionMessageId = readLegacyContextCompactionMessageId(replayMessage);\n if (replayMessage && legacyCompactionMessageId) {\n replayMessage.id = legacyCompactionMessageId;\n }\n // A persisted draft is a checkpoint, not evidence that its run completed.\n if (replayMessage && replayEvent.type === NcpEventType.MessageCompleted) {\n replayMessage.status = \"final\";\n }\n if (\n replayEvent.type === NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE ||\n replayEvent.type === NcpEventType.MessageCompleted\n ) {\n replayEvent.payload.message = mergeReplayCompletedToolResults(replayEvent.payload.message, toolResultsByCallId);\n return {\n occurredAt,\n type: NcpEventType.MessageSent,\n payload: replayEvent.payload\n };\n }\n return replayEvent;\n}\n\nfunction readReplayEventOccurredAt(event: NcpAgentSessionReplayableEvent): string | undefined {\n if (!(\"occurredAt\" in event) || typeof event.occurredAt !== \"string\") {\n return undefined;\n }\n return event.occurredAt;\n}\n\nfunction mergeReplayCompletedToolResults(\n message: NcpMessage,\n toolResultsByCallId: ReadonlyMap<string, NcpToolCallResultReplayPayload>\n): NcpMessage {\n let changed = false;\n const parts = message.parts.map((part) => {\n if (part.type !== \"tool-invocation\" || !part.toolCallId) {\n return part;\n }\n const result = toolResultsByCallId.get(part.toolCallId);\n if (!result) {\n return part;\n }\n changed = true;\n return {\n ...part,\n state: \"result\" as const,\n result: result.content,\n ...(result.contentItems ? { resultContentItems: result.contentItems } : {}),\n ...(result.execution\n ? {\n execution: mergeToolExecutionTiming(result.execution, part.execution) ?? result.execution\n }\n : {})\n };\n });\n return changed ? { ...message, parts } : message;\n}\n\nfunction readLegacyContextCompactionMessageId(message: NcpMessage | undefined): string | null {\n const checkpoint = isRecord(message?.metadata?.checkpoint) ? message.metadata.checkpoint : null;\n const checkpointId = typeof checkpoint?.id === \"string\" ? checkpoint.id : \"\";\n const coveredCount = checkpoint?.coveredSessionMessageCount;\n const legacyId = `${message?.sessionId}:service:context-compaction:${checkpointId}`;\n return typeof coveredCount === \"number\" && message?.id === legacyId ? `${legacyId}:${coveredCount}` : null;\n}\n\nexport function createReplayStreamingBootstrapEvent(\n event: NcpEndpointEvent,\n knownMessageIds: Set<string>\n): { event: NcpEndpointEvent; messageId: string } | null {\n const messageId = readStreamingMessageId(event);\n if (!messageId || knownMessageIds.has(messageId)) {\n return null;\n }\n return {\n messageId,\n event: {\n occurredAt: event.occurredAt,\n type: NcpEventType.MessageSent,\n payload: {\n sessionId: readEventSessionId(event),\n message: {\n id: messageId,\n sessionId: readEventSessionId(event),\n role: \"assistant\",\n status: \"streaming\",\n parts: [],\n timestamp: readReplayPayloadTimestamp(event) ?? new Date().toISOString()\n }\n }\n }\n };\n}\n\nexport function readReplayMessageId(event: NcpEndpointEvent): string | null {\n const message = readMessageFromSummaryEvent(event);\n return message?.id ?? null;\n}\n\nfunction readEventSessionId(event: NcpEndpointEvent): string {\n const payload: Record<string, unknown> | null = \"payload\" in event && isRecord(event.payload) ? event.payload : null;\n const sessionId = payload?.sessionId;\n return typeof sessionId === \"string\" ? sessionId : \"\";\n}\n\nfunction readReplayPayloadTimestamp(event: NcpEndpointEvent): string | null {\n const payload: Record<string, unknown> | null = \"payload\" in event && isRecord(event.payload) ? event.payload : null;\n const timestamp = typeof payload?.timestamp === \"string\" ? payload.timestamp : \"\";\n return Number.isFinite(Date.parse(timestamp)) ? new Date(timestamp).toISOString() : null;\n}\n\nexport function readStreamingMessageId(event: NcpEndpointEvent): string | null {\n switch (event.type) {\n case NcpEventType.MessageTextStart:\n case NcpEventType.MessageTextDelta:\n case NcpEventType.MessageTextEnd:\n case NcpEventType.MessageReasoningStart:\n case NcpEventType.MessageReasoningDelta:\n case NcpEventType.MessageReasoningEnd:\n case NcpEventType.MessageToolCallStart:\n case NcpEventType.MessageToolCallArgsDelta:\n case NcpEventType.MessageToolExecutionStarted:\n return event.payload.messageId?.trim() || null;\n default:\n return null;\n }\n}\n\nexport function isJournalOnlyEvent(event: NcpAgentSessionJournalReplayEvent): event is NcpSessionRequestJournalEvent {\n return (\n event.type === NCP_SESSION_REQUEST_ACCEPTED_EVENT_TYPE ||\n event.type === NCP_SESSION_REQUEST_COMPLETED_EVENT_TYPE ||\n event.type === NCP_SESSION_REQUEST_FAILED_EVENT_TYPE\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function readMessageFromSummaryEvent(event: NcpAgentSessionJournalReplayEvent): NcpMessage | undefined {\n if (\n event.type === NcpEventType.MessageSent ||\n event.type === NcpEventType.MessageCompleted ||\n event.type === NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE\n ) {\n return event.payload.message;\n }\n return undefined;\n}\n","import { NcpEventType, type NcpMessage } from \"@nextclaw/ncp\";\nimport type { NcpAgentSessionJournalReplayEvent } from \"./ncp-agent-session-journal.utils.js\";\nimport { readEventToolCallId, readMessageFromSummaryEvent, readEventMessageId } from \"./ncp-agent-session-replay-event.utils.js\";\n\nexport function seedReplayToolOwners(messages: readonly NcpMessage[]): Map<string, string> {\n const owners = new Map<string, string>();\n for (const message of messages) {\n for (const part of message.parts) {\n if (part.type === \"tool-invocation\" && part.toolCallId) owners.set(part.toolCallId, message.id);\n }\n }\n return owners;\n}\n\nexport function readReplayToolOwners(event: NcpAgentSessionJournalReplayEvent): Map<string, string> {\n const message = readMessageFromSummaryEvent(event);\n const owners = seedReplayToolOwners(message ? [message] : []);\n if (event.type === NcpEventType.MessageToolCallStart && event.payload.messageId) {\n owners.set(event.payload.toolCallId, event.payload.messageId);\n }\n return owners;\n}\n\n// A result for an older message can arrive after its checkpoint was settled.\n// In that case the active seed alone cannot prove ownership: read the journal.\nexport function needsReplayToolHistory(\n events: readonly NcpAgentSessionJournalReplayEvent[],\n seeds: readonly NcpMessage[],\n): boolean {\n return readMissingReplayToolCallIds(events, seeds).size > 0;\n}\n\nexport function readMissingReplayToolCallIds(\n events: readonly NcpAgentSessionJournalReplayEvent[],\n seeds: readonly NcpMessage[],\n): Set<string> {\n const owners = seedReplayToolOwners(seeds);\n const missing = new Set<string>();\n for (const event of events) {\n const toolCallId = readEventToolCallId(event);\n if (toolCallId && !readEventMessageId(event) && !owners.has(toolCallId)) missing.add(toolCallId);\n for (const [callId, messageId] of readReplayToolOwners(event)) owners.set(callId, messageId);\n }\n return missing;\n}\n","import {\n DefaultNcpAgentConversationStateManager,\n insertMessageByTimeline,\n} from \"@nextclaw/ncp-toolkit\";\nimport {\n type NcpEndpointEvent,\n NcpEventType,\n type NcpMessage,\n} from \"@nextclaw/ncp\";\nimport { ContextCompactionJournalRecoveryService } from \"@kernel/features/context-compaction/index.js\";\nimport {\n type NcpAgentSessionJournalReplayEvent,\n} from \"./ncp-agent-session-journal.utils.js\";\nimport {\n createReplayEvent,\n createReplayStreamingBootstrapEvent,\n isJournalOnlyEvent,\n isStreamingMessageCreationEvent,\n readEventMessageId,\n readEventRunId,\n readEventToolCallId,\n readMessageFromSummaryEvent,\n readReplayMessageId,\n readStreamingMessageId,\n readSupersededSyntheticRecoveryIndexes,\n type NcpAgentSessionReplayableEvent,\n} from \"./ncp-agent-session-replay-event.utils.js\";\nimport { seedReplayToolOwners, readReplayToolOwners } from \"./ncp-agent-session-replay-tool-ownership.utils.js\";\nimport { MODEL_ROUND_PART_OFFSETS } from \"@nextclaw/ncp-agent-runtime\";\n\nexport function mergePartialSessionMessage(message: NcpMessage, original: NcpMessage | null): NcpMessage {\n if (message.role !== \"assistant\" || message.metadata?.nextclaw_partial_projection !== true) return message;\n if (!original) throw new Error(\"Partial session projection has no original message to preserve.\");\n const source = message.metadata.nextclaw_source as { partIndices?: number[]; partCount?: number } | undefined;\n const indices = source?.partIndices ?? [];\n const incoming = message.metadata[MODEL_ROUND_PART_OFFSETS];\n const old = original.metadata?.[MODEL_ROUND_PART_OFFSETS];\n const mapped = Array.isArray(incoming) ? incoming.filter(Number.isInteger).map(offset =>\n indices[offset] ?? (source?.partCount ?? original.parts.length) + offset - indices.length) : [];\n const metadata: Record<string, unknown> = { ...original.metadata, ...message.metadata,\n [MODEL_ROUND_PART_OFFSETS]: [...new Set([...(Array.isArray(old) ? old.filter(Number.isInteger) : []), ...mapped])].sort((left, right) => left - right) };\n delete metadata.nextclaw_partial_projection; delete metadata.nextclaw_source;\n delete metadata.nextclaw_compaction_part_start; delete metadata.nextclaw_archived_body;\n return { ...message, parts: original.parts, metadata };\n}\n\ntype NcpToolCallResultReplayPayload = Extract<\n NcpEndpointEvent,\n { type: NcpEventType.MessageToolCallResult }\n>[\"payload\"];\n\nclass ReplayContext {\n readonly knownMessageIds: Set<string>;\n readonly terminalMessageIds: Set<string>;\n readonly toolResultsByCallId = new Map<string, NcpToolCallResultReplayPayload>();\n readonly compactionRecovery = new ContextCompactionJournalRecoveryService();\n readonly activeTailRunIds = new Set<string>();\n readonly toolOwners: Map<string, string>;\n\n constructor(readonly stateManager: DefaultNcpAgentConversationStateManager, seeds: readonly NcpMessage[]) {\n this.knownMessageIds = new Set(seeds.map(message => message.id));\n this.terminalMessageIds = new Set(seeds.filter(message => message.role === \"assistant\" && (message.status === \"final\" || message.status === \"error\")).map(message => message.id));\n this.toolOwners = seedReplayToolOwners(seeds);\n this.compactionRecovery.seed(seeds);\n }\n\n recordEvent = (event: NcpEndpointEvent, activeMessageId?: string): void => {\n for (const [callId, messageId] of readReplayToolOwners(event)) this.toolOwners.set(callId, messageId);\n const message = readMessageFromSummaryEvent(event);\n if (message?.role === \"assistant\" && (message.status === \"final\" || message.status === \"error\")) {\n this.terminalMessageIds.add(message.id);\n }\n if (event.type === NcpEventType.RunError || event.type === NcpEventType.RunFinished || event.type === NcpEventType.MessageAbort) {\n const messageId = readEventMessageId(event) ?? activeMessageId;\n if (messageId) this.terminalMessageIds.add(messageId);\n }\n };\n}\n\nexport async function replayNcpAgentSessionEvents(\n events: readonly NcpAgentSessionJournalReplayEvent[],\n seedMessages: readonly NcpMessage[] = [],\n activeMessageId?: string | null,\n allowUnknownStreamingBootstrap = true,\n): Promise<NcpMessage[]> {\n const replayer = await SessionEventReplayer.create(seedMessages, activeMessageId, allowUnknownStreamingBootstrap);\n const supersededSyntheticRecoveryIndexes = readSupersededSyntheticRecoveryIndexes(events);\n for (const [eventIndex, event] of events.entries()) {\n await replayer.append(event, eventIndex, supersededSyntheticRecoveryIndexes);\n }\n return replayer.finish();\n}\n\nexport class SessionEventReplayer {\n private constructor(\n private readonly context: ReplayContext,\n private readonly allowUnknownStreamingBootstrap: boolean,\n ) {}\n\n static create = async (\n seedMessages: readonly NcpMessage[] = [],\n activeMessageId?: string | null,\n allowUnknownStreamingBootstrap = true,\n ): Promise<SessionEventReplayer> => new SessionEventReplayer(\n await createReplayContext(seedMessages, activeMessageId),\n allowUnknownStreamingBootstrap,\n );\n\n append = async (\n event: NcpAgentSessionJournalReplayEvent,\n eventIndex: number,\n supersededSyntheticRecoveryIndexes: ReadonlySet<number>,\n ): Promise<void> => {\n if (isJournalOnlyEvent(event)) return;\n let sourceEvent = event;\n const snapshot = readMessageFromSummaryEvent(event);\n if (snapshot?.metadata?.nextclaw_partial_projection === true) {\n const state = this.context.stateManager.getSnapshot();\n const original = state.streamingMessage?.id === snapshot.id ? state.streamingMessage : state.messages.find(message => message.id === snapshot.id) ?? null;\n sourceEvent = { ...event, payload: { ...(event as { payload: Record<string, unknown> }).payload,\n message: mergePartialSessionMessage(snapshot, original) } } as NcpAgentSessionReplayableEvent;\n }\n const replayEvent = createReplayEvent(sourceEvent, this.context.toolResultsByCallId);\n updateActiveTailRunIds(this.context.activeTailRunIds, replayEvent, eventIndex);\n if (supersededSyntheticRecoveryIndexes.has(eventIndex)) return;\n await replayJournalEvent(this.context, replayEvent, this.allowUnknownStreamingBootstrap);\n };\n\n finish = (): NcpMessage[] => {\n const snapshot = this.context.stateManager.getSnapshot();\n const messages = snapshot.streamingMessage\n ? insertMessageByTimeline(snapshot.messages, snapshot.streamingMessage)\n : snapshot.messages;\n return messages.map(this.context.compactionRecovery.terminalize);\n };\n}\n\nasync function createReplayContext(\n seedMessages: readonly NcpMessage[],\n activeMessageId?: string | null,\n): Promise<ReplayContext> {\n const stateManager = new DefaultNcpAgentConversationStateManager();\n if (seedMessages.length > 0) {\n stateManager.hydrate({\n sessionId: seedMessages[0]?.sessionId ?? \"\",\n messages: seedMessages\n });\n }\n const activeMessage = activeMessageId\n ? seedMessages.find((message) => message.id === activeMessageId)\n : undefined;\n if (activeMessage) {\n await stateManager.dispatch({\n occurredAt: activeMessage.timestamp,\n type: NcpEventType.MessageSent,\n payload: {\n sessionId: activeMessage.sessionId,\n message: activeMessage,\n },\n });\n }\n return new ReplayContext(stateManager, seedMessages);\n}\n\nfunction updateActiveTailRunIds(\n activeTailRunIds: Set<string>,\n event: NcpAgentSessionReplayableEvent,\n eventIndex: number,\n): void {\n if (event.type === NcpEventType.RunStarted) {\n activeTailRunIds.add(\n event.payload.runId ?? event.payload.messageId ?? `run-event-${eventIndex}`,\n );\n return;\n }\n if (\n event.type !== NcpEventType.RunFinished &&\n event.type !== NcpEventType.RunError &&\n event.type !== NcpEventType.MessageAbort\n ) {\n return;\n }\n const runId = readEventRunId(event);\n if (runId) {\n activeTailRunIds.delete(runId);\n } else {\n activeTailRunIds.clear();\n }\n}\n\nasync function replayJournalEvent(\n context: ReplayContext,\n sourceEvent: NcpEndpointEvent,\n allowUnknownStreamingBootstrap: boolean,\n): Promise<void> {\n let replayEvent = sourceEvent;\n const { activeTailRunIds, compactionRecovery, knownMessageIds, terminalMessageIds, stateManager, toolOwners, recordEvent } = context;\n const summary = readMessageFromSummaryEvent(replayEvent);\n if (summary && (summary.status === \"pending\" || summary.status === \"streaming\") && terminalMessageIds.has(summary.id)) return;\n if (replayEvent.type === NcpEventType.MessageToolCallStart && !replayEvent.payload.messageId) {\n const activeId = stateManager.getSnapshot().streamingMessage?.id;\n if (!activeId) {\n console.warn(`[ncp-agent-session-journal] ignored tool start without a message: ${replayEvent.payload.toolCallId}`);\n return;\n }\n replayEvent = { ...replayEvent, payload: { ...replayEvent.payload, messageId: activeId } };\n }\n const toolCallId = readEventToolCallId(replayEvent);\n const toolOwner = toolCallId ? toolOwners.get(toolCallId) : undefined;\n if (toolCallId && replayEvent.type !== NcpEventType.MessageToolCallStart && !toolOwner) {\n console.warn(`[ncp-agent-session-journal] ignored unowned ${replayEvent.type}: ${toolCallId}`);\n return;\n }\n if (toolOwner && terminalMessageIds.has(toolOwner) && replayEvent.type !== NcpEventType.MessageToolCallResult) return;\n const streamingMessageId = readStreamingMessageId(replayEvent);\n if (streamingMessageId && terminalMessageIds.has(streamingMessageId)) {\n return;\n }\n // Preserve legacy journals that start streaming after RunStarted without a MessageSent,\n // but never resurrect an ID after the tail has observed a run terminal.\n if (\n streamingMessageId &&\n !allowUnknownStreamingBootstrap &&\n !knownMessageIds.has(streamingMessageId) &&\n !isStreamingMessageCreationEvent(replayEvent) &&\n activeTailRunIds.size === 0\n ) {\n return;\n }\n compactionRecovery.track(replayEvent);\n const activeMessageId = stateManager.getSnapshot().streamingMessage?.id;\n await dispatchReplayEvent(context, replayEvent, streamingMessageId, allowUnknownStreamingBootstrap);\n recordEvent(replayEvent, activeMessageId);\n}\n\nasync function dispatchReplayEvent(\n context: ReplayContext,\n replayEvent: NcpEndpointEvent,\n streamingMessageId: string | null,\n allowUnknownStreamingBootstrap: boolean,\n): Promise<void> {\n const { knownMessageIds, stateManager, toolResultsByCallId } = context;\n const bootstrap = (allowUnknownStreamingBootstrap || isStreamingMessageCreationEvent(replayEvent))\n ? createReplayStreamingBootstrapEvent(replayEvent, knownMessageIds)\n : null;\n if (bootstrap) {\n knownMessageIds.add(bootstrap.messageId);\n await stateManager.dispatch(bootstrap.event);\n }\n const replayMessageId = readReplayMessageId(replayEvent);\n if (replayMessageId) {\n knownMessageIds.add(replayMessageId);\n }\n if (streamingMessageId && isStreamingMessageCreationEvent(replayEvent)) {\n knownMessageIds.add(streamingMessageId);\n }\n await stateManager.dispatch(replayEvent);\n if (\n replayEvent.type === NcpEventType.MessageToolCallResult &&\n replayEvent.payload.final !== false\n ) {\n toolResultsByCallId.set(replayEvent.payload.toolCallId, replayEvent.payload);\n }\n}\n","import {\n type AgentSessionEventRecord,\n type AgentSessionRecord,\n} from \"@nextclaw/ncp-toolkit\";\nimport {\n type NcpEndpointEvent,\n NcpEventType,\n type NcpMessage,\n type NcpSessionSummary,\n} from \"@nextclaw/ncp\";\nimport { AGENT_RUN_PEER_ID_METADATA_KEY } from \"./agent-peer-session.utils.js\";\nimport { resolveNcpAgentSessionLabel } from \"./ncp-agent-session-label.utils.js\";\n\nexport const NCP_AGENT_SESSION_JOURNAL_ENTRY_VERSION = 1;\nexport const NCP_AGENT_SESSION_JOURNAL_INDEX_FILE = \".ncp-agent-session-index.json\";\n\nexport type NcpAgentSessionJournalMetadataEntry = {\n _type: \"metadata\";\n version: typeof NCP_AGENT_SESSION_JOURNAL_ENTRY_VERSION;\n created_at: string;\n updated_at?: string;\n agent_id?: string;\n metadata: Record<string, unknown>;\n};\n\nexport const NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE = \"session.snapshot.message\";\nexport const NCP_SESSION_REQUEST_ACCEPTED_EVENT_TYPE = \"session.request.accepted\";\nexport const NCP_SESSION_REQUEST_COMPLETED_EVENT_TYPE = \"session.request.completed\";\nexport const NCP_SESSION_REQUEST_FAILED_EVENT_TYPE = \"session.request.failed\";\n\ntype NcpAgentSessionSnapshotMessageEvent = {\n type: typeof NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE;\n payload: Extract<NcpEndpointEvent, { type: NcpEventType.MessageSent }>[\"payload\"];\n};\n\nexport type NcpSessionRequestJournalEventType =\n | typeof NCP_SESSION_REQUEST_ACCEPTED_EVENT_TYPE\n | typeof NCP_SESSION_REQUEST_COMPLETED_EVENT_TYPE\n | typeof NCP_SESSION_REQUEST_FAILED_EVENT_TYPE;\n\nexport type NcpSessionRequestJournalEvent = {\n type: NcpSessionRequestJournalEventType;\n payload: {\n sessionId: string;\n request: unknown;\n };\n};\n\nexport type NcpAgentSessionJournalReplayEvent =\n | NcpEndpointEvent\n | NcpAgentSessionSnapshotMessageEvent\n | NcpSessionRequestJournalEvent;\n\nexport type NcpAgentSessionJournalEventEntry = {\n _type: \"event\";\n version: typeof NCP_AGENT_SESSION_JOURNAL_ENTRY_VERSION;\n seq: number;\n timestamp: string;\n event: NcpAgentSessionJournalReplayEvent;\n};\n\nexport type NcpAgentSessionJournalIndex = {\n version: typeof NCP_AGENT_SESSION_JOURNAL_ENTRY_VERSION;\n records: NcpSessionSummary[];\n};\n\nexport type LoadedNcpAgentJournalSession = {\n record: AgentSessionRecord;\n nextSeq: number;\n journalOffset: number;\n projectedJournalOffset: number;\n};\n\nexport function normalizeNcpSessionId(sessionId: string): string {\n return sessionId.trim();\n}\n\nexport function safeNcpSessionFilename(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n}\n\nexport function normalizeNcpAgentId(agentId: string | undefined): string | undefined {\n return agentId?.trim().toLowerCase() || undefined;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function toIsoString(value: unknown, fallback: string): string {\n const parsed = typeof value === \"string\" ? Date.parse(value) : NaN;\n return Number.isFinite(parsed) ? new Date(parsed).toISOString() : fallback;\n}\n\nexport function createNcpAgentSessionSummary(record: AgentSessionRecord): NcpSessionSummary {\n const metadata = structuredClone(record.metadata ?? {});\n const label = readOptionalText(metadata.label) ?? resolveNcpAgentSessionLabel(record.messages);\n const peerId = readNcpAgentSessionPeerId(metadata);\n if (label) {\n metadata.label = label;\n }\n const lastMessageAt = record.messages.reduceRight<string | undefined>(\n (timestamp, message) => timestamp ?? readMessageTimestamp(message),\n undefined\n );\n return {\n sessionId: record.sessionId,\n peerId: peerId ?? undefined,\n ...(normalizeNcpAgentId(record.agentId) ? { agentId: normalizeNcpAgentId(record.agentId) } : {}),\n messageCount: record.messages.length,\n ...(record.createdAt ? { createdAt: record.createdAt } : {}),\n updatedAt: record.updatedAt,\n ...(lastMessageAt ? { lastMessageAt } : {}),\n status: \"idle\",\n ...(Object.keys(metadata).length > 0 ? { metadata } : {})\n };\n}\n\nexport function readNcpAgentSessionPeerId(metadata: Record<string, unknown>): string | null {\n return readOptionalText(metadata[AGENT_RUN_PEER_ID_METADATA_KEY]);\n}\n\nexport function createNcpAgentSessionJournalMetadataEntry(\n record: AgentSessionEventRecord\n): NcpAgentSessionJournalMetadataEntry {\n return {\n _type: \"metadata\",\n version: NCP_AGENT_SESSION_JOURNAL_ENTRY_VERSION,\n created_at: record.createdAt ?? record.updatedAt,\n updated_at: record.updatedAt,\n ...(normalizeNcpAgentId(record.agentId) ? { agent_id: normalizeNcpAgentId(record.agentId) } : {}),\n metadata: structuredClone(record.metadata ?? {})\n };\n}\n\nexport function upsertNcpAgentSessionSummaryEvent(params: {\n current: NcpSessionSummary | undefined;\n sessionId: string;\n event: NcpAgentSessionJournalReplayEvent;\n updatedAt: string;\n}): NcpSessionSummary {\n const { current, event, sessionId, updatedAt } = params;\n const eventMessage = readMessageFromSummaryEvent(event);\n const messageCount = current ? current.messageCount + (eventMessage ? 1 : 0) : eventMessage ? 1 : 0;\n const lastMessageAt = readMessageTimestamp(eventMessage) ?? current?.lastMessageAt;\n return {\n sessionId,\n peerId: current?.peerId,\n ...(normalizeNcpAgentId(current?.agentId) ? { agentId: normalizeNcpAgentId(current?.agentId) } : {}),\n messageCount,\n createdAt: current?.createdAt ?? updatedAt,\n updatedAt,\n ...(lastMessageAt ? { lastMessageAt } : {}),\n status: \"idle\"\n };\n}\n\nexport { replayNcpAgentSessionEvents } from \"./ncp-agent-session-replay.utils.js\";\n\nexport function readNcpSessionSummaryActivityAt(summary: NcpSessionSummary): string {\n return summary.lastMessageAt ?? summary.createdAt ?? summary.updatedAt;\n}\n\nfunction readMessageTimestamp(message: NcpMessage | undefined): string | undefined {\n return message?.status === \"final\" ? toIsoString(message.timestamp, \"\") || undefined : undefined;\n}\n\nfunction readOptionalText(value: unknown): string | null {\n const trimmed = typeof value === \"string\" ? value.trim() : \"\";\n return trimmed || null;\n}\n\nfunction readMessageFromSummaryEvent(event: NcpAgentSessionJournalReplayEvent): NcpMessage | undefined {\n if (\n event.type === NcpEventType.MessageSent ||\n event.type === NcpEventType.MessageCompleted ||\n event.type === NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE\n ) {\n return event.payload.message;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;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