@nextclaw/kernel 0.19.3 → 0.19.5

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 (33) hide show
  1. package/dist/app/worker/index.d.ts +2 -2
  2. package/dist/app/worker/index.js +3 -2
  3. package/dist/{automatic-update-check.utils-C6lQfErN.d.ts → automatic-update-check.utils-8_3eYuwY.d.ts} +1 -1
  4. package/dist/{automatic-update-check.utils-C6lQfErN.d.ts.map → automatic-update-check.utils-8_3eYuwY.d.ts.map} +1 -1
  5. package/dist/index.d.ts +4 -4
  6. package/dist/index.js +524 -1403
  7. package/dist/index.js.map +1 -1
  8. package/dist/ncp-agent-session-journal-entry.utils-Dh0Ck_oW.js +112 -0
  9. package/dist/ncp-agent-session-journal-entry.utils-Dh0Ck_oW.js.map +1 -0
  10. package/dist/ncp-agent-session-journal.utils-B7a_PKCq.js +1457 -0
  11. package/dist/ncp-agent-session-journal.utils-B7a_PKCq.js.map +1 -0
  12. package/dist/ncp-agent-session-message-projection-tail.store-5sjmoFxv.js +117 -0
  13. package/dist/ncp-agent-session-message-projection-tail.store-5sjmoFxv.js.map +1 -0
  14. package/dist/{nextclaw-harness.manager-GK_qgrlk.d.ts → nextclaw-harness.manager-j0JHST4g.d.ts} +348 -80
  15. package/dist/nextclaw-harness.manager-j0JHST4g.d.ts.map +1 -0
  16. package/dist/{nextclaw-harness.manager-DHzYOORP.js → nextclaw-harness.manager-mJToWeCB.js} +1871 -1657
  17. package/dist/nextclaw-harness.manager-mJToWeCB.js.map +1 -0
  18. package/dist/session-journal-delta-coalescer.utils-CI-N-Zpj.js +25 -0
  19. package/dist/session-journal-delta-coalescer.utils-CI-N-Zpj.js.map +1 -0
  20. package/dist/session-journal-maintenance.store-CImhMMBv.js +626 -0
  21. package/dist/session-journal-maintenance.store-CImhMMBv.js.map +1 -0
  22. package/dist/session-journal-stream.utils-CupSA3YS.js +207 -0
  23. package/dist/session-journal-stream.utils-CupSA3YS.js.map +1 -0
  24. package/dist/types/update-contract.types.d.ts +1 -1
  25. package/dist/types/update-contract.types.js +1 -1
  26. package/dist/{update-manifest.types-CBp2VTM1.js → update-manifest.types-DUocefbs.js} +1 -1
  27. package/dist/{update-manifest.types-CBp2VTM1.js.map → update-manifest.types-DUocefbs.js.map} +1 -1
  28. package/dist/{update-manifest.types-C_60CVvw.d.ts → update-manifest.types-Dijq24Om.d.ts} +1 -1
  29. package/dist/{update-manifest.types-C_60CVvw.d.ts.map → update-manifest.types-Dijq24Om.d.ts.map} +1 -1
  30. package/dist/utils/automatic-update-check.utils.d.ts +1 -1
  31. package/package.json +12 -9
  32. package/dist/nextclaw-harness.manager-DHzYOORP.js.map +0 -1
  33. package/dist/nextclaw-harness.manager-GK_qgrlk.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
1
- import { $ as coalesceSessionJournalDeltas, $t as DEFAULT_AGENT_RUNTIME_ENTRY_ID, A as ContextProviderRunContextService, At as NEXTCLAW_TIMELINE_KIND_METADATA_KEY, B as normalizeOptionalString, Bt as readLatestContextCompactionCheckpoint, C as ToolProviderRunContextService, Ct as ContextCompactionPreflightService, D as readProjectId, Dt as CONTEXT_COMPACTION_PROJECTION_METADATA_KEY, E as createAgentToolRunTriggerInput, Et as CONTEXT_COMPACTION_PROJECTION_KIND, F as CurrentSessionContextProvider, Ft as isContextCompactionProjectionMessage, G as syncSessionThinkingPreference, Gt as assertObservationJsonValue, H as readMetadataThinking, Ht as shouldRefreshContextWindowImmediately, I as AgentBootstrapContextProvider, It as isContextCompactionTimelineMessage, J as describeAgentRuntimeSessionTypes, Jt as evaluateObservationEventAdmission, K as appendCurrentTimeContextTail, Kt as assertObservationPredicate, L as renderAgentBootstrapContext, Lt as isContextWindowSnapshot, M as ExecutionPolicyContextProvider, Mt as buildContextCompactionTimelineNcpMessage, N as renderAgentSafetyContext, Nt as createContextCompactionMessageId, O as readProjectRoot, Ot as CONTEXT_COMPACTION_SYSTEM_PREAMBLE, P as renderSystemExecutionPolicy, Pt as createContextWindowSignature, Q as canCoalesceSessionJournalDeltas, Qt as toBoundedJson, R as truncateContextText, Rt as readContextCompactionCheckpoint, S as AgentManager, St as readEventToolCallId, T as attachSourceToolCall, Tt as CONTEXT_COMPACTION_PART_START, U as resolveEffectiveModel, Ut as composeAgentToolCatalog, V as readMetadataModel, Vt as shouldRefreshContextWindowDuringStream, W as resolveSessionChannelContext, Wt as ContextCompactionJournalRecoveryService, X as resolveAgentRuntimeEntries, Xt as parseObservationDuration, Y as normalizeAgentRuntimeSessionTypeIcon, Yt as matchesObservationPredicate, Zt as readJsonPointer, _ as createQuestionMessage, _t as SessionEventReplayer, a as dispatchAgentRuntimeSessionRequest, at as applyNcpAgentRunLifecycleEvent, b as SessionManager, bt as SessionReplaySupersessionTracker, c as Contribution, ct as NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE, d as dispatchPromptOverNcpResult, dt as isRecord$15, en as STRUCTURED_RESULT_TOOL_NAME, et as isSessionJournalDelta, f as startPromptOverNcpExecution, ft as normalizeNcpAgentId, g as USER_QUESTION_EXTENSION_TYPE, gt as upsertNcpAgentSessionSummaryEvent, h as UserQuestionManager, ht as toIsoString, i as createAgentRuntimeSessionRequestSourceNotifier, it as isSessionSettingsError, j as WorkspaceMemoryContextProvider, jt as buildContextCompactionModelProjection, k as buildRunMetadata, kt as CONTEXT_COMPACTION_TIMELINE_KIND, l as NextclawHarnessError, lt as createNcpAgentSessionJournalMetadataEntry, m as UserQuestionError, mt as safeNcpSessionFilename, n as buildSessionRequestCompletionMessage, nn as CommandRegistry, nt as SessionSettingsError, o as waitForAgentRuntimeSessionReply, ot as isNcpAgentRunLifecycleEvent, p as buildAgentRunSendPayload, pt as normalizeNcpSessionId, q as serializeModelInputTail, qt as buildObservationEventModelMessage, r as createAgentRuntimeSessionRequestDispatcher, rt as isSessionMessageCursorError, s as SessionRequestManager, st as NCP_AGENT_SESSION_JOURNAL_INDEX_FILE, t as NextclawHarness, tn as AgentRunClient, tt as SessionMessageCursorError, u as dispatchPromptOverNcp, ut as createNcpAgentSessionSummary, v as createQuestionResolutionMessage, vt as readReplayToolOwners, w as createShowContentTools, wt as CONTEXT_COMPACTION_CONTINUATION_TEXT, x as createWorkspaceByteTools, xt as readEventMessageId, y as projectUserQuestions, yt as seedReplayToolOwners, z as buildNextclawNcpRunContext, zt as readContextWindowEventSessionId } from "./nextclaw-harness.manager-DHzYOORP.js";
1
+ import { a as restoreSessionJournalBackup, c as syncSessionJournalFile, d as openSqliteDatabase, f as runSqliteTransaction, i as recoverSessionJournalTornTail, l as SessionJournalLoaderStore, n as compactSessionJournal, r as recoverSessionJournalMaintenance, s as syncSessionJournalDirectory, t as assertSessionJournalTailComplete, u as NcpAgentSessionMetadataStore } from "./session-journal-maintenance.store-CImhMMBv.js";
2
+ import { $ as SessionEventProjectionStore, A as ContextProviderRunContextService, B as normalizeOptionalString, C as ToolProviderRunContextService, D as readProjectId, E as createAgentToolRunTriggerInput, F as CurrentSessionContextProvider, G as syncSessionThinkingPreference, H as readMetadataThinking, I as AgentBootstrapContextProvider, J as describeAgentRuntimeSessionTypes, K as appendCurrentTimeContextTail, L as renderAgentBootstrapContext, M as ExecutionPolicyContextProvider, N as renderAgentSafetyContext, O as readProjectRoot, P as renderSystemExecutionPolicy, Q as SessionMessageSqlProjectionStore, R as truncateContextText, S as AgentManager, T as attachSourceToolCall, U as resolveEffectiveModel, V as readMetadataModel, W as resolveSessionChannelContext, X as resolveAgentRuntimeEntries, Y as normalizeAgentRuntimeSessionTypeIcon, Z as SessionMessagePreparationStore, _ as createQuestionMessage, _t as CommandRegistry, a as dispatchAgentRuntimeSessionRequest, at as applyNcpAgentRunLifecycleEvent, b as SessionManager, c as Contribution, ct as assertObservationPredicate, d as dispatchPromptOverNcpResult, dt as matchesObservationPredicate, et as sessionJsonChunks, f as startPromptOverNcpExecution, ft as parseObservationDuration, g as USER_QUESTION_EXTENSION_TYPE, gt as AgentRunClient, h as UserQuestionManager, ht as DEFAULT_AGENT_RUNTIME_ENTRY_ID, i as createAgentRuntimeSessionRequestSourceNotifier, it as isSessionSettingsError, j as WorkspaceMemoryContextProvider, k as buildRunMetadata, l as NextclawHarnessError, lt as buildObservationEventModelMessage, m as UserQuestionError, mt as toBoundedJson, n as buildSessionRequestCompletionMessage, nt as SessionSettingsError, o as waitForAgentRuntimeSessionReply, ot as isNcpAgentRunLifecycleEvent, p as buildAgentRunSendPayload, pt as readJsonPointer, q as serializeModelInputTail, r as createAgentRuntimeSessionRequestDispatcher, rt as isSessionMessageCursorError, s as SessionRequestManager, st as assertObservationJsonValue, t as NextclawHarness, tt as SessionMessageCursorError, u as dispatchPromptOverNcp, ut as evaluateObservationEventAdmission, v as createQuestionResolutionMessage, w as createShowContentTools, x as createWorkspaceByteTools, y as projectUserQuestions, z as buildNextclawNcpRunContext } from "./nextclaw-harness.manager-mJToWeCB.js";
3
+ import { A as CONTEXT_COMPACTION_RECOVERY_PREAMBLE, B as isContextWindowSnapshot, D as CONTEXT_COMPACTION_PART_START, E as CONTEXT_COMPACTION_CONTINUATION_TEXT, F as buildContextCompactionTimelineNcpMessage, G as shouldRefreshContextWindowDuringStream, H as readContextRecoveryState, I as createContextCompactionMessageId, K as shouldRefreshContextWindowImmediately, L as createContextWindowSignature, M as CONTEXT_COMPACTION_TIMELINE_KIND, N as NEXTCLAW_TIMELINE_KIND_METADATA_KEY, O as CONTEXT_COMPACTION_PROJECTION_KIND, P as buildContextCompactionModelProjection, Q as ContextCompactionJournalRecoveryService, R as isContextCompactionProjectionMessage, T as ContextCompactionPreflightService, U as readContextWindowEventSessionId, V as readContextCompactionCheckpoint, W as readLatestContextCompactionCheckpoint, Z as composeAgentToolCatalog, c as isRecord$13, d as safeNcpSessionFilename, f as toIsoString, j as CONTEXT_COMPACTION_SYSTEM_PREAMBLE, k as CONTEXT_COMPACTION_PROJECTION_METADATA_KEY, m as SessionEventReplayer, n as NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE, p as upsertNcpAgentSessionSummaryEvent, s as createNcpAgentSessionSummary, t as NCP_AGENT_SESSION_JOURNAL_INDEX_FILE, tt as STRUCTURED_RESULT_TOOL_NAME, u as normalizeNcpSessionId, z as isContextCompactionTimelineMessage } from "./ncp-agent-session-journal.utils-B7a_PKCq.js";
4
+ import { i as isSessionJournalDelta, n as canCoalesceSessionJournalDeltas, r as coalesceSessionJournalDeltas } from "./session-journal-delta-coalescer.utils-CI-N-Zpj.js";
2
5
  import { AUTOMATIC_UPDATE_CHECK_INTERVAL_MS, getAutomaticUpdateCheckDelay, resolveAutomaticUpdateCheckIntervalMs } from "./utils/automatic-update-check.utils.js";
3
- import { n as getUnsignedUpdateManifest, r as serializeUnsignedUpdateManifest, t as UpdateManifestReader } from "./update-manifest.types-CBp2VTM1.js";
6
+ import { n as getUnsignedUpdateManifest, r as serializeUnsignedUpdateManifest, t as UpdateManifestReader } from "./update-manifest.types-DUocefbs.js";
4
7
  import { createRequire } from "node:module";
5
8
  import { createHash, createHmac, randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
6
9
  import { CHAT_CONVERSATION_EXCERPT_TOKEN_KIND, CHAT_INLINE_TOKENS_METADATA_KEY, CHAT_INLINE_TOKENS_SCHEMA_VERSION, CHAT_PROJECT_TOKEN_KIND, CHAT_SYSTEM_OBJECT_TOKEN_KIND, CHAT_UI_RESOURCE_TOKEN_KIND, CHAT_WORKSPACE_DIRECTORY_TOKEN_KIND, CHAT_WORKSPACE_EXCERPT_TOKEN_KIND, CHAT_WORKSPACE_FILE_TOKEN_KIND, Contribution as Contribution$1, EventBus, EventBus as EventBus$1, Ingress, Ingress as Ingress$1, PANEL_APP_INLINE_HOST_CONTRACT, PANEL_APP_SCROLL_RESTORATION_CONTRACT, SYSTEM_OBJECT_REFERENCE_DEFAULT_LIMIT, SYSTEM_OBJECT_REFERENCE_MAX_LIMIT, SYSTEM_OBJECT_TYPE_CRON_JOB, SYSTEM_OBJECT_TYPE_INBOX_DELIVERY, UI_CONTENT_PARAMS_HOST_CONTRACT, classifyDiagnosticError, createPanelAppResourceUri, createSessionResourceUri, createSystemObjectReferenceUri, createTypedKey, eventKeys, eventKeys as eventKeys$1, ingressKeys, ingressKeys as ingressKeys$1, isRuntimeDefaultModelValue, normalizeRuntimeModelSelectionMode, parseSystemObjectReferenceUri, readChatUiResourceReference, readInlineContentHeight, readSystemObjectResolvedReference } from "@nextclaw/shared";
@@ -8,14 +11,13 @@ import { LocalAssetStore, buildAssetContentPath, isTextLikeAsset } from "@nextcl
8
11
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
9
12
  import { accessSync, appendFileSync, chmodSync, constants, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
10
13
  import { APP_NAME, AgentRouteResolver, ConfigSchema, CronService, CronTool, DEFAULT_PANELS_DIR, DEFAULT_PROJECT_SKILLS_DIR_NAME, DEFAULT_SERVICE_APPS_DIR, DEFAULT_SESSION_SEARCH_LIMIT, DEFAULT_WORKSPACE_REPOSITORY_IDENTITY_RESOLVER, DIAGNOSTIC_CORRELATION_METADATA_KEY as DIAGNOSTIC_CORRELATION_METADATA_KEY$1, DiagnosticRuntime, EditFileTool, ExecTool, ExtensionChannelAdapter, GatewayTool, LLMProvider, ListDirTool, LiteLLMProvider, LocalExecutionClaimService, MAX_SESSION_SEARCH_LIMIT, MemoryGetTool, MemorySearchTool, MessageBus, MessageTool, ProviderModelDiscoveryService, ProviderRegistry, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV as RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV$1, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV as RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV$1, RUNTIME_INSTANCE_DISTRIBUTION_ENV, RUNTIME_INSTANCE_DISTRIBUTION_ENV as RUNTIME_INSTANCE_DISTRIBUTION_ENV$1, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV as RUNTIME_INSTANCE_INSTALLATION_KIND_ENV$1, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV as RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV$1, ReadFileTool, SILENT_REPLY_TOKEN, SessionProjectContextResolver, SessionSearchService, SkillsLoader, ViewImageTool, WebFetchTool, WebSearchTool, WriteFileTool, buildConfigSchema, buildLocalizedTextMap, buildReloadPlan, createAgentProfile, createAssistantStreamDeltaControlMessage, createAssistantStreamResetControlMessage, createRuntimeChildEnv, createTypingStopControlMessage, diffConfigPaths, ensureDir, evaluateSilentReply, expandHome, getConfigPath, getDataDir, getDataPath, getLogsPath, getSessionsPath, getWorkspacePath, getWorkspacePathFromConfig, isNextclawControlMessage, loadConfig, mergeExtensionConfigView, modelSupportsVision, normalizeInlineSecretRefs, normalizeModelThinkingCapability, normalizeProviderModelConfig, normalizeToolParams, parseSkillFrontmatter, parseSkillFrontmatter as parseSkillFrontmatter$1, parseThinkingLevel, readParentSessionId, redactConfigObject, removeAgentProfile, resolveConfigSecrets, resolveImplicitAgentHomePath, resolveNextclawSelfManageGuidePaths, resolveProviderRuntime, resolveRuntimeCommandLaunch, resolveSecretRef, resolveSessionProjectContext, safeFilename, sanitizeOutboundAssistantContent, saveConfig, stripSkillFrontmatter, stripSkillFrontmatter as stripSkillFrontmatter$1, toExtensionConfigView, updateAgentProfile } from "@nextclaw/core";
11
- import { access, appendFile, chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
14
+ import { access, chmod, copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
12
15
  import { AppGrantService, AppHomeService, AppInstallationService, AppInstanceInventoryService, AppInstanceStorageService, AppManifestService, AppPlatformTargetService, AppRegistryService, AppServiceLaunchService, FileLockService, isAppComponentManifestBundle } from "@nextclaw/app-runtime";
13
16
  import { execFileSync, spawn } from "node:child_process";
14
17
  import { fileURLToPath } from "node:url";
15
18
  import { NcpEventType, OBSERVATION_EVENT_EXTENSION_TYPE, sanitizeAssistantReplyTags } from "@nextclaw/ncp";
16
19
  import { McpRegistryService, McpServerLifecycleManager, normalizeMcpServerName } from "@nextclaw/mcp";
17
20
  import { createInterface } from "node:readline";
18
- import { isDeepStrictEqual } from "node:util";
19
21
  import { BUILTIN_PROVIDER_PLUGINS } from "@nextclaw/runtime";
20
22
  import { HttpRuntimeConfigResolver, HttpRuntimeNcpAgentRuntime } from "@nextclaw/nextclaw-ncp-runtime-http-client";
21
23
  import { StdioRuntimeConfigResolver, StdioRuntimeNcpAgentRuntime, probeStdioRuntime } from "@nextclaw/nextclaw-ncp-runtime-stdio-client";
@@ -1399,7 +1401,7 @@ function parseServiceAppManifest(raw, options = {}) {
1399
1401
  } catch (error) {
1400
1402
  throw new Error(`service-app.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
1401
1403
  }
1402
- if (!isRecord$14(parsed)) throw new Error("service-app.json must contain an object.");
1404
+ if (!isRecord$12(parsed)) throw new Error("service-app.json must contain an object.");
1403
1405
  const id = readRequiredString$8(parsed, "id");
1404
1406
  if (!SERVICE_APP_ID_PATTERN$1.test(id)) throw new Error("service app id must be kebab-case.");
1405
1407
  const protocol = readOptionalString$8(parsed, "protocol") ?? "mcp";
@@ -1428,12 +1430,12 @@ function parseServiceAppManifest(raw, options = {}) {
1428
1430
  }
1429
1431
  function readServiceAppProvides(value) {
1430
1432
  if (value === void 0) return void 0;
1431
- if (!isRecord$14(value)) throw new Error("service app provides must be an object.");
1433
+ if (!isRecord$12(value)) throw new Error("service app provides must be an object.");
1432
1434
  if (value.capabilities === void 0) return void 0;
1433
1435
  if (!Array.isArray(value.capabilities)) throw new Error("service app provides.capabilities must be an array.");
1434
1436
  const seen = /* @__PURE__ */ new Set();
1435
1437
  const capabilities = value.capabilities.map((entry, index) => {
1436
- if (!isRecord$14(entry)) throw new Error(`service app provides.capabilities[${index}] must be an object.`);
1438
+ if (!isRecord$12(entry)) throw new Error(`service app provides.capabilities[${index}] must be an object.`);
1437
1439
  const id = readRequirementIdentifier(entry, "id", `provides.capabilities[${index}].id`);
1438
1440
  const version = readOptionalString$8(entry, "version");
1439
1441
  if (!version) throw new Error(`service app provides.capabilities[${index}].version is required.`);
@@ -1461,7 +1463,7 @@ function readCapabilityResourceTypes(value, index) {
1461
1463
  }
1462
1464
  function readServiceAppRequirements(value, protocol) {
1463
1465
  if (value === void 0) return void 0;
1464
- if (!isRecord$14(value)) throw new Error("service app requires must be an object.");
1466
+ if (!isRecord$12(value)) throw new Error("service app requires must be an object.");
1465
1467
  const capabilities = readCapabilityRequirements(value.capabilities, protocol);
1466
1468
  const resources = readResourceRequirements(value.resources);
1467
1469
  const modelSlots = readModelCapabilitySlots(value.modelSlots);
@@ -1485,7 +1487,7 @@ function readCapabilitySlots(value, name, hasModelLimits) {
1485
1487
  const seen = /* @__PURE__ */ new Set();
1486
1488
  return value.map((entry, index) => {
1487
1489
  const field = `requires.${name}[${index}]`;
1488
- if (!isRecord$14(entry)) throw new Error(`service app ${field} must be an object.`);
1490
+ if (!isRecord$12(entry)) throw new Error(`service app ${field} must be an object.`);
1489
1491
  const allowed = hasModelLimits ? [
1490
1492
  "id",
1491
1493
  "title",
@@ -1527,7 +1529,7 @@ function readCapabilityRequirements(value, protocol) {
1527
1529
  if (!Array.isArray(value)) throw new Error("service app requires.capabilities must be an array.");
1528
1530
  const seen = /* @__PURE__ */ new Set();
1529
1531
  return value.map((entry, index) => {
1530
- if (!isRecord$14(entry)) throw new Error(`service app requires.capabilities[${index}] must be an object.`);
1532
+ if (!isRecord$12(entry)) throw new Error(`service app requires.capabilities[${index}] must be an object.`);
1531
1533
  const id = readRequirementIdentifier(entry, "id", `requires.capabilities[${index}].id`);
1532
1534
  const version = readOptionalString$8(entry, "version");
1533
1535
  const key = `${id}@${version ?? "*"}`;
@@ -1550,7 +1552,7 @@ function readCapabilityRequirements(value, protocol) {
1550
1552
  }
1551
1553
  function readWitContract(value, fieldName, role) {
1552
1554
  if (value === void 0) return void 0;
1553
- if (!isRecord$14(value)) throw new Error(`service app ${fieldName} must be an object.`);
1555
+ if (!isRecord$12(value)) throw new Error(`service app ${fieldName} must be an object.`);
1554
1556
  const packageName = readOptionalString$8(value, "package");
1555
1557
  if (!packageName || !WIT_PACKAGE_PATTERN.test(packageName)) throw new Error(`service app ${fieldName}.package must be a WIT package identifier.`);
1556
1558
  const interfaceName = readRequirementIdentifier(value, "interface", `${fieldName}.interface`);
@@ -1577,7 +1579,7 @@ function readResourceRequirements(value) {
1577
1579
  if (!Array.isArray(value)) throw new Error("service app requires.resources must be an array.");
1578
1580
  const seen = /* @__PURE__ */ new Set();
1579
1581
  return value.map((entry, index) => {
1580
- if (!isRecord$14(entry)) throw new Error(`service app requires.resources[${index}] must be an object.`);
1582
+ if (!isRecord$12(entry)) throw new Error(`service app requires.resources[${index}] must be an object.`);
1581
1583
  const binding = readRequirementIdentifier(entry, "binding", `requires.resources[${index}].binding`);
1582
1584
  if (seen.has(binding)) throw new Error(`service app requires.resources contains duplicate binding ${binding}.`);
1583
1585
  seen.add(binding);
@@ -1598,7 +1600,7 @@ function readRequirementIdentifier(record, key, fieldName) {
1598
1600
  }
1599
1601
  function readExternalRemediation(value, fieldPrefix) {
1600
1602
  if (value === void 0) return void 0;
1601
- if (!isRecord$14(value) || value.kind !== "agent-setup") throw new Error(`service app ${fieldPrefix}.remediation.kind must be agent-setup.`);
1603
+ if (!isRecord$12(value) || value.kind !== "agent-setup") throw new Error(`service app ${fieldPrefix}.remediation.kind must be agent-setup.`);
1602
1604
  const summary = readOptionalString$8(value, "summary");
1603
1605
  if (!summary) throw new Error(`service app ${fieldPrefix}.remediation.summary is required.`);
1604
1606
  return {
@@ -1609,7 +1611,7 @@ function readExternalRemediation(value, fieldPrefix) {
1609
1611
  }
1610
1612
  function readServiceAppLifecycle(value) {
1611
1613
  if (value === void 0) return { mode: "action" };
1612
- if (!isRecord$14(value)) throw new Error("service app lifecycle must be an object.");
1614
+ if (!isRecord$12(value)) throw new Error("service app lifecycle must be an object.");
1613
1615
  const mode = readOptionalString$8(value, "mode") ?? "action";
1614
1616
  if (mode === "action") return { mode };
1615
1617
  if (mode === "provider") return { mode };
@@ -1637,7 +1639,7 @@ function readServiceAppId(record, key, fieldName) {
1637
1639
  }
1638
1640
  function readPortableComponentEntry(record) {
1639
1641
  const component = record.component;
1640
- if (!isRecord$14(component)) throw new Error("service app component is required for wasi-component.");
1642
+ if (!isRecord$12(component)) throw new Error("service app component is required for wasi-component.");
1641
1643
  const entry = readRequiredString$8(component, "entry").replace(/\\/g, "/");
1642
1644
  if (path.isAbsolute(entry) || entry.includes("\0") || entry.split("/").includes("..")) throw new Error("service app component.entry must be a package-relative path.");
1643
1645
  if (!entry.endsWith(".wasm")) throw new Error("service app component.entry must reference a .wasm file.");
@@ -1645,16 +1647,16 @@ function readPortableComponentEntry(record) {
1645
1647
  }
1646
1648
  function readManifestActions(value) {
1647
1649
  if (value === void 0) throw new Error("service app actions are required.");
1648
- if (!isRecord$14(value)) throw new Error("service app actions must be an object.");
1650
+ if (!isRecord$12(value)) throw new Error("service app actions must be an object.");
1649
1651
  if (Object.keys(value).length === 0) throw new Error("service app actions cannot be empty.");
1650
1652
  const actions = {};
1651
1653
  for (const [name, action] of Object.entries(value)) {
1652
1654
  if (!name.trim()) throw new Error("service app action name cannot be empty.");
1653
- if (!isRecord$14(action)) throw new Error(`service app action ${name} must be an object.`);
1655
+ if (!isRecord$12(action)) throw new Error(`service app action ${name} must be an object.`);
1654
1656
  const risk = readOptionalString$8(action, "risk");
1655
1657
  if (risk !== void 0 && !SERVICE_ACTION_RISKS.has(risk)) throw new Error(`service app action ${name} has invalid risk.`);
1656
1658
  const inputSchema = action.inputSchema;
1657
- if (inputSchema !== void 0 && !isRecord$14(inputSchema)) throw new Error(`service app action ${name} inputSchema must be an object.`);
1659
+ if (inputSchema !== void 0 && !isRecord$12(inputSchema)) throw new Error(`service app action ${name} inputSchema must be an object.`);
1658
1660
  const timeoutMs = readOptionalNumber$1(action, "timeoutMs");
1659
1661
  if (timeoutMs !== void 0 && (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 3e5)) throw new Error(`service app action ${name} timeoutMs must be an integer between 100 and 300000.`);
1660
1662
  actions[name] = {
@@ -1689,7 +1691,7 @@ function readOptionalNumber$1(record, key) {
1689
1691
  if (typeof record[key] !== "number") throw new Error(`service app ${key} must be number.`);
1690
1692
  return record[key];
1691
1693
  }
1692
- function isRecord$14(value) {
1694
+ function isRecord$12(value) {
1693
1695
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1694
1696
  }
1695
1697
  //#endregion
@@ -4015,13 +4017,13 @@ function stableStringify(value) {
4015
4017
  }
4016
4018
  function sortValue(value) {
4017
4019
  if (Array.isArray(value)) return value.map(sortValue);
4018
- if (!isRecord$13(value)) return value;
4020
+ if (!isRecord$11(value)) return value;
4019
4021
  return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortValue(value[key])]));
4020
4022
  }
4021
4023
  function normalizeJsonValue(value) {
4022
4024
  if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return value;
4023
4025
  if (Array.isArray(value)) return value.map(normalizeJsonValue);
4024
- if (isRecord$13(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeJsonValue(item)]));
4026
+ if (isRecord$11(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeJsonValue(item)]));
4025
4027
  throw new Error("Capability grant target must be JSON-compatible.");
4026
4028
  }
4027
4029
  function requireString$1(value, field) {
@@ -4029,7 +4031,7 @@ function requireString$1(value, field) {
4029
4031
  if (!normalized) throw new Error(`Capability grant ${field} is required.`);
4030
4032
  return normalized;
4031
4033
  }
4032
- function isRecord$13(value) {
4034
+ function isRecord$11(value) {
4033
4035
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4034
4036
  }
4035
4037
  //#endregion
@@ -4513,10 +4515,10 @@ function toGrantRecord(grants) {
4513
4515
  }));
4514
4516
  }
4515
4517
  function normalizeStoreData(value) {
4516
- if (!isRecord$12(value) || value.version !== 1 || !isRecord$12(value.grants)) throw new Error("Capability grant store is invalid.");
4518
+ if (!isRecord$10(value) || value.version !== 1 || !isRecord$10(value.grants)) throw new Error("Capability grant store is invalid.");
4517
4519
  const grants = [];
4518
4520
  for (const grant of Object.values(value.grants)) {
4519
- if (!isRecord$12(grant) || !isRecord$12(grant.subject) || !isRecord$12(grant.resource) || !Array.isArray(grant.access) || !grant.access.every((item) => typeof item === "string") || typeof grant.declarationFingerprint !== "string" || typeof grant.grantedAt !== "string") throw new Error("Capability grant store contains an invalid grant.");
4521
+ if (!isRecord$10(grant) || !isRecord$10(grant.subject) || !isRecord$10(grant.resource) || !Array.isArray(grant.access) || !grant.access.every((item) => typeof item === "string") || typeof grant.declarationFingerprint !== "string" || typeof grant.grantedAt !== "string") throw new Error("Capability grant store contains an invalid grant.");
4520
4522
  const request = normalizeCapabilityGrantRequest({
4521
4523
  subject: {
4522
4524
  type: String(grant.subject.type ?? ""),
@@ -4540,11 +4542,11 @@ function normalizeStoreData(value) {
4540
4542
  grants: toGrantRecord(grants)
4541
4543
  };
4542
4544
  }
4543
- function isRecord$12(value) {
4545
+ function isRecord$10(value) {
4544
4546
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4545
4547
  }
4546
4548
  function isMissingFileError$2(error) {
4547
- return isRecord$12(error) && error.code === "ENOENT";
4549
+ return isRecord$10(error) && error.code === "ENOENT";
4548
4550
  }
4549
4551
  //#endregion
4550
4552
  //#region src/features/capability-grants/managers/capability-grant.manager.ts
@@ -6473,7 +6475,7 @@ function parsePanelAppFolderManifest(raw) {
6473
6475
  } catch (error) {
6474
6476
  throw new Error(`panel-app.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
6475
6477
  }
6476
- if (!isRecord$11(parsed)) throw new Error("panel-app.json must contain an object.");
6478
+ if (!isRecord$9(parsed)) throw new Error("panel-app.json must contain an object.");
6477
6479
  const id = readOptionalString$7(parsed, "id");
6478
6480
  if (id && !PANEL_APP_ID_PATTERN.test(id)) throw new Error("panel app id must be kebab-case.");
6479
6481
  return {
@@ -6560,7 +6562,7 @@ function readStringArray(value, key) {
6560
6562
  if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw new Error(`panel app ${key} must be a string array.`);
6561
6563
  return [...new Set(value.map((entry) => entry.trim()).filter(Boolean))];
6562
6564
  }
6563
- function isRecord$11(value) {
6565
+ function isRecord$9(value) {
6564
6566
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6565
6567
  }
6566
6568
  function normalizeTextValue(value) {
@@ -7109,7 +7111,7 @@ const PANEL_APP_AGENT_MAX_CONTEXT_CHARS = 8e4;
7109
7111
  function normalizePanelAppGenerateObjectInput(input) {
7110
7112
  const peerId = input.peerId.trim();
7111
7113
  const prompt = input.prompt.trim();
7112
- if (!peerId || !prompt || !isRecord$10(input.schema)) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "invalid generateObject request");
7114
+ if (!peerId || !prompt || !isRecord$8(input.schema)) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "invalid generateObject request");
7113
7115
  if (prompt.length > PANEL_APP_AGENT_MAX_PROMPT_CHARS) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "generateObject prompt is too large");
7114
7116
  if (stringifyJsonValue(input.context ?? null).length > PANEL_APP_AGENT_MAX_CONTEXT_CHARS) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "generateObject context is too large");
7115
7117
  return {
@@ -7250,7 +7252,7 @@ function readStructuredResultEvent(event, resultToolCallId) {
7250
7252
  };
7251
7253
  }
7252
7254
  function assertToolResultContent(content) {
7253
- if (!isRecord$10(content) || content.ok !== false || !isRecord$10(content.error)) return;
7255
+ if (!isRecord$8(content) || content.ok !== false || !isRecord$8(content.error)) return;
7254
7256
  if (content.error.code === "invalid_tool_arguments") throw new PanelAppError("AGENT_OBJECT_RESULT_SCHEMA_INVALID", "agent object result did not match the schema");
7255
7257
  throw new PanelAppError("AGENT_OBJECT_REQUEST_FAILED", typeof content.error.message === "string" ? content.error.message : "agent object request failed");
7256
7258
  }
@@ -7266,7 +7268,7 @@ function stringifyJsonValue(value) {
7266
7268
  throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "value is not JSON serializable");
7267
7269
  }
7268
7270
  }
7269
- function isRecord$10(value) {
7271
+ function isRecord$8(value) {
7270
7272
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7271
7273
  }
7272
7274
  //#endregion
@@ -11684,7 +11686,7 @@ var ServiceAppAiCapabilityService = class {
11684
11686
  const payload = requireHostCallObject(call.request.input);
11685
11687
  if (call.request.capability === "model-complete") {
11686
11688
  const messages = payload.messages;
11687
- if (!Array.isArray(messages) || !messages.every(isRecord$9)) throw new ServiceAppError("SERVICE_APP_RUNTIME_FAILED", "AI model messages must be an array of objects.");
11689
+ if (!Array.isArray(messages) || !messages.every(isRecord$7)) throw new ServiceAppError("SERVICE_APP_RUNTIME_FAILED", "AI model messages must be an array of objects.");
11688
11690
  return await this.modelComplete({
11689
11691
  app: call.app,
11690
11692
  manifest: call.manifest,
@@ -11696,7 +11698,7 @@ var ServiceAppAiCapabilityService = class {
11696
11698
  }
11697
11699
  if (call.request.capability === "agent-start") {
11698
11700
  const input = payload.input;
11699
- if (!isRecord$9(input)) throw new ServiceAppError("SERVICE_APP_RUNTIME_FAILED", "AI Agent input must be an object.");
11701
+ if (!isRecord$7(input)) throw new ServiceAppError("SERVICE_APP_RUNTIME_FAILED", "AI Agent input must be an object.");
11700
11702
  const execution = await this.agentStart({
11701
11703
  app: call.app,
11702
11704
  manifest: call.manifest,
@@ -11821,11 +11823,11 @@ var ServiceAppAiCapabilityService = class {
11821
11823
  };
11822
11824
  };
11823
11825
  };
11824
- function isRecord$9(value) {
11826
+ function isRecord$7(value) {
11825
11827
  return typeof value === "object" && value !== null && !Array.isArray(value);
11826
11828
  }
11827
11829
  function requireHostCallObject(value) {
11828
- if (!isRecord$9(value)) throw new ServiceAppError("SERVICE_APP_RUNTIME_FAILED", "Portable host call input must be an object.");
11830
+ if (!isRecord$7(value)) throw new ServiceAppError("SERVICE_APP_RUNTIME_FAILED", "Portable host call input must be an object.");
11829
11831
  return value;
11830
11832
  }
11831
11833
  function requireHostCallString(value, key) {
@@ -14256,160 +14258,6 @@ var PortableRuntimeAcceptanceManager = class {
14256
14258
  });
14257
14259
  };
14258
14260
  //#endregion
14259
- //#region src/stores/sqlite-database.store.ts
14260
- const require = createRequire(import.meta.url);
14261
- const portableDatabases = /* @__PURE__ */ new Map();
14262
- async function openSqliteDatabase(databasePath) {
14263
- try {
14264
- return new (require("node:sqlite")).DatabaseSync(databasePath);
14265
- } catch (error) {
14266
- if (!isMissingNodeSqlite(error)) throw error;
14267
- return await openPortableDatabase(databasePath);
14268
- }
14269
- }
14270
- function runSqliteTransaction(database, operation, mode = "DEFERRED") {
14271
- database.exec(`BEGIN ${mode}`);
14272
- try {
14273
- const result = operation();
14274
- database.exec("COMMIT");
14275
- return result;
14276
- } catch (error) {
14277
- database.exec("ROLLBACK");
14278
- throw error;
14279
- }
14280
- }
14281
- function isMissingNodeSqlite(error) {
14282
- const code = typeof error === "object" && error !== null ? error.code : void 0;
14283
- return code === "ERR_UNKNOWN_BUILTIN_MODULE" || code === "MODULE_NOT_FOUND";
14284
- }
14285
- async function openPortableDatabase(databasePath) {
14286
- const existing = portableDatabases.get(databasePath);
14287
- if (existing) return (await existing).acquire();
14288
- const opening = createPortableDatabase(databasePath).catch((error) => {
14289
- portableDatabases.delete(databasePath);
14290
- throw error;
14291
- });
14292
- portableDatabases.set(databasePath, opening);
14293
- return (await opening).acquire();
14294
- }
14295
- async function createPortableDatabase(databasePath) {
14296
- const initialize = (await import("sql.js")).default;
14297
- const sqlite = await initialize({ locateFile: resolveSqlJsAsset });
14298
- return new PortableSqliteDatabase(databasePath, existsSync(databasePath) ? new sqlite.Database(readFileSync(databasePath)) : new sqlite.Database());
14299
- }
14300
- function resolveSqlJsAsset(file) {
14301
- try {
14302
- return require.resolve(`sql.js/dist/${file}`);
14303
- } catch (error) {
14304
- const bundledAssetPath = fileURLToPath(new URL(file, import.meta.url));
14305
- if (file === "sql-wasm.wasm" && existsSync(bundledAssetPath)) return bundledAssetPath;
14306
- throw error;
14307
- }
14308
- }
14309
- var PortableSqliteDatabase = class {
14310
- inTransaction = false;
14311
- dirty = false;
14312
- leaseCount = 0;
14313
- constructor(databasePath, database) {
14314
- this.databasePath = databasePath;
14315
- this.database = database;
14316
- }
14317
- acquire = () => {
14318
- this.leaseCount += 1;
14319
- return new PortableSqliteLease(this);
14320
- };
14321
- exec = (sql) => {
14322
- const command = sql.trim().toUpperCase();
14323
- this.database.run(sql);
14324
- if (command.startsWith("BEGIN")) {
14325
- this.inTransaction = true;
14326
- return;
14327
- }
14328
- if (command.startsWith("ROLLBACK")) {
14329
- this.inTransaction = false;
14330
- this.dirty = false;
14331
- return;
14332
- }
14333
- if (command.startsWith("COMMIT")) {
14334
- this.inTransaction = false;
14335
- this.persistIfDirty();
14336
- return;
14337
- }
14338
- if (!command.startsWith("PRAGMA")) this.markDirty();
14339
- };
14340
- prepare = (sql) => new PortableSqliteStatement(this, sql);
14341
- release = () => {
14342
- this.leaseCount -= 1;
14343
- if (this.leaseCount > 0) return;
14344
- this.persistIfDirty();
14345
- this.database.close();
14346
- portableDatabases.delete(this.databasePath);
14347
- };
14348
- run = (sql, params) => {
14349
- this.database.run(sql, normalizeParams(params));
14350
- this.markDirty();
14351
- };
14352
- readRows = (sql, params) => {
14353
- const statement = this.database.prepare(sql);
14354
- try {
14355
- bindStatement(statement, params);
14356
- const rows = [];
14357
- while (statement.step()) rows.push(statement.getAsObject());
14358
- return rows;
14359
- } finally {
14360
- statement.free();
14361
- }
14362
- };
14363
- markDirty = () => {
14364
- this.dirty = true;
14365
- if (!this.inTransaction) this.persistIfDirty();
14366
- };
14367
- persistIfDirty = () => {
14368
- if (!this.dirty) return;
14369
- const temporaryPath = `${this.databasePath}.tmp`;
14370
- writeFileSync(temporaryPath, this.database.export());
14371
- renameSync(temporaryPath, this.databasePath);
14372
- this.dirty = false;
14373
- };
14374
- };
14375
- var PortableSqliteLease = class {
14376
- closed = false;
14377
- constructor(owner) {
14378
- this.owner = owner;
14379
- }
14380
- close = () => {
14381
- if (this.closed) return;
14382
- this.closed = true;
14383
- this.owner.release();
14384
- };
14385
- exec = (sql) => this.owner.exec(sql);
14386
- prepare = (sql) => this.owner.prepare(sql);
14387
- };
14388
- var PortableSqliteStatement = class {
14389
- constructor(database, sql) {
14390
- this.database = database;
14391
- this.sql = sql;
14392
- }
14393
- all = (...params) => this.database.readRows(this.sql, params);
14394
- get = (...params) => this.all(...params)[0];
14395
- run = (...params) => {
14396
- this.database.run(this.sql, params);
14397
- return {};
14398
- };
14399
- };
14400
- function bindStatement(statement, params) {
14401
- const normalized = normalizeParams(params);
14402
- if (Array.isArray(normalized) && normalized.length === 0) return;
14403
- statement.bind(normalized);
14404
- }
14405
- function normalizeParams(params) {
14406
- if (params.length !== 1 || !isRecord$8(params[0])) return params;
14407
- return Object.fromEntries(Object.entries(params[0]).map(([key, value]) => [`@${key}`, value]));
14408
- }
14409
- function isRecord$8(value) {
14410
- return typeof value === "object" && value !== null && !Array.isArray(value);
14411
- }
14412
- //#endregion
14413
14261
  //#region src/features/projects/stores/project.store.ts
14414
14262
  const PROJECT_STORE_VERSION = 3;
14415
14263
  const LEGACY_PROJECTS_MIGRATION_ID = "projects-json-to-sqlite-v1";
@@ -15763,9 +15611,10 @@ async function loadNcpAgentSessionSummary(params) {
15763
15611
  const projectionMeta = await params.projectionStore.readMeta(params.sessionId);
15764
15612
  if (projectionMeta && projectionMeta.projectedJournalOffset <= journalStat.size) {
15765
15613
  const metadata = await params.metadataStore.read(params.sessionId, {
15766
- createdAt: params.updatedAt,
15614
+ ...projectionMeta.legacyMetadata?.agentId ? { agentId: projectionMeta.legacyMetadata.agentId } : {},
15615
+ createdAt: projectionMeta.legacyMetadata?.createdAt ?? params.updatedAt,
15767
15616
  updatedAt: params.updatedAt,
15768
- metadata: {}
15617
+ metadata: projectionMeta.legacyMetadata?.metadata ?? {}
15769
15618
  });
15770
15619
  const page = await params.projectionStore.listPage({
15771
15620
  sessionId: params.sessionId,
@@ -15780,6 +15629,7 @@ async function loadNcpAgentSessionSummary(params) {
15780
15629
  metadata: metadata.metadata,
15781
15630
  messages: page?.messages ?? []
15782
15631
  }),
15632
+ metadata: Object.keys(metadata.metadata ?? {}).length ? metadata.metadata : void 0,
15783
15633
  messageCount: page?.total ?? projectionMeta.total
15784
15634
  };
15785
15635
  }
@@ -15791,6 +15641,33 @@ async function loadNcpAgentSessionSummary(params) {
15791
15641
  });
15792
15642
  }
15793
15643
  async function loadNcpAgentSessionSummaryWithoutReplay(params) {
15644
+ const journalStat = await stat(params.journalPath);
15645
+ if (journalStat.size > 256 * 1024) {
15646
+ const handle = await open(params.journalPath, "r");
15647
+ const prefix = Buffer.alloc(64 * 1024);
15648
+ let header = {};
15649
+ try {
15650
+ const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0);
15651
+ const newline = prefix.subarray(0, bytesRead).indexOf(10);
15652
+ if (newline >= 0) {
15653
+ const parsed = parseJournalLine(prefix.subarray(0, newline).toString("utf8"));
15654
+ if (parsed?._type === "metadata") header = parsed;
15655
+ }
15656
+ } finally {
15657
+ await handle.close();
15658
+ }
15659
+ const metadata = await params.metadataStore.read(params.sessionId, {
15660
+ createdAt: toIsoString(header.created_at, journalStat.birthtime.toISOString()),
15661
+ updatedAt: params.updatedAt,
15662
+ ...typeof header.agent_id === "string" ? { agentId: header.agent_id } : {},
15663
+ metadata: isRecord$13(header.metadata) ? header.metadata : {}
15664
+ });
15665
+ return createNcpAgentSessionSummary({
15666
+ sessionId: params.sessionId,
15667
+ ...metadata,
15668
+ messages: []
15669
+ });
15670
+ }
15794
15671
  const stream = createReadStream(params.journalPath, { encoding: "utf-8" });
15795
15672
  const lines = createInterface({
15796
15673
  input: stream,
@@ -15837,18 +15714,18 @@ function applyJournalSummaryLine(state, line) {
15837
15714
  if (parsed._type === "metadata") {
15838
15715
  state.createdAt = toIsoString(parsed.created_at, state.createdAt);
15839
15716
  state.agentId = typeof parsed.agent_id === "string" ? parsed.agent_id : state.agentId;
15840
- if (isRecord$15(parsed.metadata)) state.metadata = structuredClone(parsed.metadata);
15717
+ if (isRecord$13(parsed.metadata)) state.metadata = structuredClone(parsed.metadata);
15841
15718
  return;
15842
15719
  }
15843
- if (parsed._type !== "event" || !isRecord$15(parsed.event)) return;
15720
+ if (parsed._type !== "event" || !isRecord$13(parsed.event)) return;
15844
15721
  const event = parsed.event;
15845
- const payload = isRecord$15(event.payload) ? event.payload : null;
15846
- const message = payload && isRecord$15(payload.message) ? payload.message : null;
15722
+ const payload = isRecord$13(event.payload) ? event.payload : null;
15723
+ const message = payload && isRecord$13(payload.message) ? payload.message : null;
15847
15724
  const messageId = typeof message?.id === "string" ? message.id : typeof payload?.messageId === "string" ? payload.messageId : null;
15848
15725
  if (!isMessageStartEvent(event.type) || !messageId || state.messageIds.has(messageId)) return;
15849
15726
  state.messageIds.add(messageId);
15850
15727
  state.messageCount += 1;
15851
- if (isRecord$15(message?.metadata) && message.metadata.nextclaw_timeline_kind === "context_compaction") state.requiresReplay = true;
15728
+ if (isRecord$13(message?.metadata) && message.metadata.nextclaw_timeline_kind === "context_compaction") state.requiresReplay = true;
15852
15729
  if (!isFinalMessageEvent(event.type)) return;
15853
15730
  const timestamp = toIsoString(message?.timestamp, "");
15854
15731
  if (timestamp && (!state.lastMessageAt || timestamp > state.lastMessageAt)) state.lastMessageAt = timestamp;
@@ -15857,7 +15734,7 @@ function parseJournalLine(line) {
15857
15734
  if (!line.trim()) return null;
15858
15735
  try {
15859
15736
  const parsed = JSON.parse(line);
15860
- return isRecord$15(parsed) ? parsed : null;
15737
+ return isRecord$13(parsed) ? parsed : null;
15861
15738
  } catch {
15862
15739
  return null;
15863
15740
  }
@@ -15963,7 +15840,7 @@ function readRunLifecycleEvent(line) {
15963
15840
  } catch {
15964
15841
  return null;
15965
15842
  }
15966
- if (!isRecord$15(parsed) || parsed._type !== "event" || !isRecord$15(parsed.event)) return null;
15843
+ if (!isRecord$13(parsed) || parsed._type !== "event" || !isRecord$13(parsed.event)) return null;
15967
15844
  const event = parsed.event;
15968
15845
  return event.type === NcpEventType.RunStarted || event.type === NcpEventType.RunFinished || event.type === NcpEventType.RunError || event.type === NcpEventType.MessageAbort ? event : null;
15969
15846
  }
@@ -15973,716 +15850,243 @@ function resolveUnfinishedRun(sessionId, startedEvent, reverseTerminalEvents) {
15973
15850
  return activeRun;
15974
15851
  }
15975
15852
  //#endregion
15976
- //#region src/utils/ncp-agent-session-journal-entry.utils.ts
15977
- function isNcpAgentSessionMessageProjectionBoundaryEvent(event) {
15978
- return event.type === NcpEventType.MessageSent || event.type === NcpEventType.MessageCompleted || event.type === NcpEventType.MessageAbort || event.type === NcpEventType.RunFinished || event.type === NcpEventType.RunError || event.type === "session.snapshot.message";
15979
- }
15980
- function serializeNcpAgentSessionJournalEntry(entry) {
15981
- const serialized = JSON.stringify(entry);
15982
- if (!serialized) throw new Error("ncp agent session journal entry serialization produced empty output");
15983
- if (!isRecord$15(JSON.parse(serialized))) throw new Error("ncp agent session journal entry serialization produced a non-object entry");
15984
- return serialized;
15985
- }
15986
- function attachNcpAgentSessionJournalTimestamp(event, timestamp) {
15987
- if (!("payload" in event) || !isRecord$15(event.payload)) return event;
15988
- return {
15989
- ...event,
15990
- payload: {
15991
- ...event.payload,
15992
- timestamp
15993
- }
15994
- };
15995
- }
15996
- var NcpAgentSessionJournalParser = class {
15997
- metadata = {};
15998
- agentId;
15999
- createdAt = (/* @__PURE__ */ new Date()).toISOString();
16000
- updatedAt = this.createdAt;
16001
- nextSeq = 1;
16002
- projectedJournalOffset = 0;
16003
- events = [];
16004
- constructor(collectEvents = true) {
16005
- this.collectEvents = collectEvents;
16006
- }
16007
- append = (line, index, lineEndOffset) => {
16008
- if (!line.trim()) return null;
16009
- const parsed = this.parseLine(line, index);
16010
- if (!parsed) return null;
16011
- if (parsed._type === "metadata") {
16012
- this.applyMetadata(parsed);
16013
- return null;
16014
- }
16015
- if (parsed._type === "event" && isRecord$15(parsed.event)) return this.applyEvent(parsed, lineEndOffset);
16016
- return null;
16017
- };
16018
- finish = () => ({
16019
- metadata: this.metadata,
16020
- ...this.agentId ? { agentId: this.agentId } : {},
16021
- createdAt: this.createdAt,
16022
- updatedAt: this.updatedAt,
16023
- nextSeq: this.nextSeq,
16024
- projectedJournalOffset: this.projectedJournalOffset,
16025
- events: this.events
16026
- });
16027
- parseLine = (line, index) => {
16028
- try {
16029
- const parsed = JSON.parse(line);
16030
- return isRecord$15(parsed) ? parsed : null;
16031
- } catch (error) {
16032
- console.warn(`[ncp-agent-session-journal] skipped corrupted journal line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`);
16033
- return null;
16034
- }
16035
- };
16036
- applyMetadata = (entry) => {
16037
- this.metadata = isRecord$15(entry.metadata) ? structuredClone(entry.metadata) : {};
16038
- this.agentId = normalizeNcpAgentId(typeof entry.agent_id === "string" ? entry.agent_id : void 0);
16039
- this.createdAt = toIsoString(entry.created_at, this.createdAt);
16040
- this.updatedAt = toIsoString(entry.updated_at, this.updatedAt);
16041
- };
16042
- applyEvent = (entry, lineEndOffset) => {
16043
- const seq = Number(entry.seq);
16044
- this.nextSeq = Math.max(this.nextSeq, Number.isFinite(seq) ? Math.trunc(seq) + 1 : this.nextSeq);
16045
- const eventTimestamp = toIsoString(entry.timestamp, this.updatedAt);
16046
- this.updatedAt = eventTimestamp;
16047
- const replayEvent = attachNcpAgentSessionJournalTimestamp(structuredClone(entry.event), eventTimestamp);
16048
- if (this.collectEvents) this.events.push(replayEvent);
16049
- if (isNcpAgentSessionMessageProjectionBoundaryEvent(replayEvent)) this.projectedJournalOffset = lineEndOffset;
16050
- return replayEvent;
16051
- };
16052
- };
16053
- async function scanSessionJournal(params) {
16054
- const { endOffset, onEvent, path } = params;
16055
- const startOffset = Math.max(0, params.startOffset ?? 0);
16056
- const parser = new NcpAgentSessionJournalParser(false);
16057
- if (endOffset <= startOffset) return parser.finish();
16058
- const file = await open(path, "r");
16059
- const stream = file.createReadStream({
16060
- start: startOffset,
16061
- end: endOffset - 1,
16062
- encoding: "utf-8",
16063
- autoClose: false
16064
- });
16065
- const lines = createInterface({
16066
- input: stream,
16067
- crlfDelay: Infinity
16068
- });
16069
- let lineIndex = 0;
16070
- let byteOffset = startOffset;
16071
- try {
16072
- for await (const line of lines) {
16073
- const lineEndOffset = Math.min(endOffset, byteOffset + Buffer.byteLength(line, "utf-8") + 1);
16074
- const event = parser.append(line, lineIndex, lineEndOffset);
16075
- if (event) await onEvent?.(event, lineIndex);
16076
- byteOffset = lineEndOffset;
16077
- lineIndex += 1;
16078
- }
16079
- return parser.finish();
16080
- } finally {
16081
- lines.close();
16082
- stream.destroy();
16083
- await file.close();
16084
- }
16085
- }
16086
- //#endregion
16087
- //#region src/stores/ncp-agent-session-metadata.store.ts
16088
- var NcpAgentSessionMetadataStore = class {
15853
+ //#region src/stores/ncp-agent-session-message-projection-persistence.store.ts
15854
+ const projectionPath = (directory, id) => join(directory, ".message-projections", safeNcpSessionFilename(id));
15855
+ const journalPath = (directory, id) => join(directory, `${safeNcpSessionFilename(id)}.jsonl`);
15856
+ /** Local file/SQLite adapter; shared projection semantics live in SessionMessageSqlProjectionStore. */
15857
+ var NcpAgentSessionMessageProjectionPersistenceStore = class extends SessionMessageSqlProjectionStore {
16089
15858
  constructor(journalDir) {
16090
- this.journalDir = journalDir;
16091
- }
16092
- write = async (record) => {
16093
- await mkdir(this.journalDir, { recursive: true });
16094
- const targetPath = this.metadataPath(record.sessionId);
16095
- const tempPath = `${targetPath}.${process.pid}.${randomUUID()}.tmp`;
16096
- try {
16097
- await writeFile(tempPath, `${JSON.stringify(createNcpAgentSessionJournalMetadataEntry(record))}\n`, "utf-8");
16098
- await rename(tempPath, targetPath);
16099
- } catch (error) {
16100
- await rm(tempPath, { force: true });
16101
- throw error;
16102
- }
16103
- };
16104
- read = async (sessionId, activitySnapshot) => {
16105
- try {
16106
- const parsed = JSON.parse(await readFile(this.metadataPath(sessionId), "utf-8"));
16107
- if (!isRecord$15(parsed) || parsed._type !== "metadata" || !isRecord$15(parsed.metadata)) throw new Error(`invalid ncp agent session metadata sidecar: ${sessionId}`);
16108
- const createdAt = toIsoString(parsed.created_at, activitySnapshot.createdAt);
16109
- const sidecarUpdatedAt = toIsoString(parsed.updated_at, activitySnapshot.updatedAt);
16110
- const updatedAt = Date.parse(sidecarUpdatedAt) > Date.parse(activitySnapshot.updatedAt) ? sidecarUpdatedAt : activitySnapshot.updatedAt;
16111
- const agentId = normalizeNcpAgentId(typeof parsed.agent_id === "string" ? parsed.agent_id : void 0);
16112
- return {
16113
- metadata: structuredClone(parsed.metadata),
16114
- ...agentId ? { agentId } : {},
16115
- createdAt,
16116
- updatedAt
16117
- };
16118
- } catch (error) {
16119
- if ((error && typeof error === "object" && "code" in error ? error.code : void 0) === "ENOENT") return activitySnapshot;
16120
- throw error;
16121
- }
16122
- };
16123
- delete = async (sessionId) => {
16124
- await rm(this.metadataPath(sessionId), { force: true });
16125
- };
16126
- metadataPath = (sessionId) => {
16127
- return join(this.journalDir, `${safeNcpSessionFilename(sessionId.replace(/:/g, "_"))}.metadata.json`);
16128
- };
16129
- };
16130
- //#endregion
16131
- //#region src/utils/ncp-agent-session-message-projection.utils.ts
16132
- const OFFSET_FIELD_WIDTH = 20;
16133
- OFFSET_FIELD_WIDTH * 2 + 2;
16134
- function serializeNcpAgentSessionMessage(message) {
16135
- return Buffer.from(`${JSON.stringify(message)}\n`, "utf-8");
16136
- }
16137
- function serializeNcpAgentSessionMessageLocation(location) {
16138
- const offset = String(location.offset).padStart(OFFSET_FIELD_WIDTH, "0");
16139
- const length = String(location.length).padStart(OFFSET_FIELD_WIDTH, "0");
16140
- if (offset.length !== OFFSET_FIELD_WIDTH || length.length !== OFFSET_FIELD_WIDTH) throw new Error("Session message projection exceeded its supported file size.");
16141
- return `${offset}:${length}\n`;
16142
- }
16143
- function parseNcpAgentSessionMessageLocation(value) {
16144
- const match = /^(\d{20}):(\d{20})\n$/.exec(value);
16145
- const offset = Number(match?.[1]);
16146
- const length = Number(match?.[2]);
16147
- if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 1) throw new Error("Session message projection contains an invalid offset record.");
16148
- return {
16149
- offset,
16150
- length
16151
- };
16152
- }
16153
- function encodeNcpAgentSessionMessageCursor(ordinal) {
16154
- return Buffer.from(`v1:${ordinal}`, "utf-8").toString("base64url");
16155
- }
16156
- function decodeNcpAgentSessionMessageCursor(cursor, maximumBoundary) {
16157
- let decoded = "";
16158
- try {
16159
- decoded = Buffer.from(cursor, "base64url").toString("utf-8");
16160
- } catch {
16161
- throw new SessionMessageCursorError();
16162
- }
16163
- const match = /^v1:([1-9]\d*)$/.exec(decoded);
16164
- const ordinal = Number(match?.[1]);
16165
- if (!Number.isSafeInteger(ordinal) || ordinal < 1 || ordinal > maximumBoundary) throw new SessionMessageCursorError();
16166
- return ordinal;
16167
- }
16168
- function deduplicateNcpAgentSessionTailMessages(messages) {
16169
- const byId = /* @__PURE__ */ new Map();
16170
- for (const message of messages) {
16171
- byId.delete(message.id);
16172
- byId.set(message.id, structuredClone(message));
16173
- }
16174
- return [...byId.values()];
16175
- }
16176
- function isNcpAgentSessionMessageProjectionMeta(value, sessionId) {
16177
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
16178
- const meta = value;
16179
- return meta.version === 8 && meta.sessionId === sessionId && Number.isSafeInteger(meta.total) && Number.isSafeInteger(meta.projectedJournalOffset) && Number.isSafeInteger(meta.dataBytes) && (meta.activeMessageId === null || typeof meta.activeMessageId === "string") && Array.isArray(meta.pendingCompactionMessageIds) && meta.pendingCompactionMessageIds.every((id) => typeof id === "string") && (meta.contextWindow === null || isRecord$7(meta.contextWindow));
16180
- }
16181
- function readActiveAssistantMessageId(messages) {
16182
- for (let index = messages.length - 1; index >= 0; index -= 1) {
16183
- const message = messages[index];
16184
- if (message?.role === "assistant" && (message.status === "pending" || message.status === "streaming")) return message.id;
16185
- }
16186
- return null;
16187
- }
16188
- function readPendingCompactionMessageIds(messages) {
16189
- const pending = /* @__PURE__ */ new Set();
16190
- for (const message of messages) if (readCompactionStatus(message) === "compressing") pending.add(message.id);
16191
- return [...pending];
16192
- }
16193
- function mergePendingCompactionMessageIds(current, messages) {
16194
- const pending = new Set(current);
16195
- for (const message of messages) {
16196
- const status = readCompactionStatus(message);
16197
- if (status === "compressing") pending.add(message.id);
16198
- else if (status) pending.delete(message.id);
16199
- }
16200
- return pending;
16201
- }
16202
- function isRecord$7(value) {
16203
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
16204
- }
16205
- function readCompactionStatus(message) {
16206
- const checkpoint = message.metadata?.checkpoint;
16207
- if (message.metadata?.nextclaw_timeline_kind !== "context_compaction" || !isRecord$7(checkpoint)) return null;
16208
- return typeof checkpoint.status === "string" ? checkpoint.status : null;
16209
- }
16210
- //#endregion
16211
- //#region src/stores/ncp-agent-session-message-projection-tail.store.ts
16212
- const TOOL_CALL_START_EVENT_NEEDLE = `"type":"${NcpEventType.MessageToolCallStart}"`;
16213
- async function readNcpAgentSessionProjectionTail(journalPath, meta, readMessage) {
16214
- const file = await open(journalPath, "r");
16215
- try {
16216
- const { size } = await file.stat();
16217
- const offset = meta.projectedJournalOffset;
16218
- if (offset < 0 || offset >= size) return [];
16219
- const seedIds = new Set(meta.pendingCompactionMessageIds);
16220
- if (meta.activeMessageId) seedIds.add(meta.activeMessageId);
16221
- const toolOwners = seedReplayToolOwners((await Promise.all([...seedIds].map(readMessage))).filter((message) => Boolean(message)));
16222
- const missingToolCallIds = /* @__PURE__ */ new Set();
16223
- const supersessionTracker = new SessionReplaySupersessionTracker();
16224
- await scanSessionJournal({
16225
- path: journalPath,
16226
- startOffset: offset,
16227
- endOffset: size,
16228
- onEvent: (event, eventIndex) => {
16229
- supersessionTracker.observe(event, eventIndex);
16230
- const toolCallId = readEventToolCallId(event);
16231
- if (toolCallId && !readEventMessageId(event) && !toolOwners.has(toolCallId)) missingToolCallIds.add(toolCallId);
16232
- for (const [callId, messageId] of readReplayToolOwners(event)) toolOwners.set(callId, messageId);
16233
- if (event.type === NcpEventType.RunFinished || event.type === NcpEventType.RunError || event.type === NcpEventType.RunMetadata || event.type === NcpEventType.MessageAbort) {
16234
- const messageId = readEventMessageId(event);
16235
- if (messageId) seedIds.add(messageId);
16236
- }
16237
- }
16238
- });
16239
- let seeds = (await Promise.all([...seedIds].map(readMessage))).filter((message) => Boolean(message));
16240
- if (missingToolCallIds.size > 0) {
16241
- const historicalOwners = await readHistoricalToolOwners(file, offset, missingToolCallIds);
16242
- const ownerMessageIds = new Set(historicalOwners.values());
16243
- const ownerSeeds = (await Promise.all([...ownerMessageIds].map(readMessage))).filter((message) => Boolean(message));
16244
- seeds = deduplicateMessages([...seeds, ...ownerSeeds]);
16245
- const unresolvedToolCallIds = [...missingToolCallIds].filter((toolCallId) => {
16246
- const ownerMessageId = historicalOwners.get(toolCallId);
16247
- return !ownerMessageId || !seeds.some((message) => message.id === ownerMessageId);
16248
- });
16249
- if (unresolvedToolCallIds.length > 0) console.warn("[ncp-agent-session-journal] unresolved historical tool owners", {
16250
- sessionId: meta.sessionId,
16251
- toolCallIds: unresolvedToolCallIds,
16252
- fallback: "ignore-unowned-tail-events"
16253
- });
16254
- }
16255
- const replayer = await SessionEventReplayer.create(seeds, meta.activeMessageId, false);
16256
- const supersededSyntheticRecoveryIndexes = supersessionTracker.finish();
16257
- await scanSessionJournal({
16258
- path: journalPath,
16259
- startOffset: offset,
16260
- endOffset: size,
16261
- onEvent: async (event, eventIndex) => {
16262
- await replayer.append(event, eventIndex, supersededSyntheticRecoveryIndexes);
15859
+ super({
15860
+ database: async (sessionId, create) => {
15861
+ const path = projectionPath(journalDir, sessionId);
15862
+ if (create) await mkdir(path, { recursive: true });
15863
+ else if (!await stat(join(path, "messages.sqlite")).catch(() => null)) return null;
15864
+ const database = await openSqliteDatabase(join(path, "messages.sqlite"), { incremental: true });
15865
+ database.exec("PRAGMA busy_timeout=50; PRAGMA cache_size=-2048; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");
15866
+ return database;
15867
+ },
15868
+ journalBytes: async (id) => (await stat(journalPath(journalDir, id)).catch(() => null))?.size ?? null,
15869
+ journalIdentity: async (id) => {
15870
+ const value = await stat(journalPath(journalDir, id)).catch(() => null);
15871
+ return value ? `${value.dev}:${value.ino}:${value.birthtimeMs}` : null;
15872
+ },
15873
+ delete: (id) => rm(projectionPath(journalDir, id), {
15874
+ recursive: true,
15875
+ force: true
15876
+ }),
15877
+ transaction: async () => {
15878
+ throw new Error("Local journal preparation uses the native file transaction adapter.");
16263
15879
  }
16264
15880
  });
16265
- return replayer.finish();
16266
- } finally {
16267
- await file.close();
16268
- }
16269
- }
16270
- async function readHistoricalToolOwners(file, endOffset, targetToolCallIds) {
16271
- const owners = /* @__PURE__ */ new Map();
16272
- if (endOffset <= 0 || targetToolCallIds.size === 0) return owners;
16273
- const stream = file.createReadStream({
16274
- start: 0,
16275
- end: endOffset - 1,
16276
- encoding: "utf-8",
16277
- autoClose: false
16278
- });
16279
- const lines = createInterface({
16280
- input: stream,
16281
- crlfDelay: Infinity
16282
- });
16283
- try {
16284
- for await (const line of lines) {
16285
- if (!line.includes(TOOL_CALL_START_EVENT_NEEDLE)) continue;
16286
- const owner = readToolCallOwner(line);
16287
- if (!owner || !targetToolCallIds.has(owner.toolCallId)) continue;
16288
- owners.set(owner.toolCallId, owner.messageId);
16289
- if (owners.size === targetToolCallIds.size) break;
16290
- }
16291
- return owners;
16292
- } finally {
16293
- lines.close();
16294
- stream.destroy();
16295
- }
16296
- }
16297
- function readToolCallOwner(line) {
16298
- let parsed;
16299
- try {
16300
- parsed = JSON.parse(line);
16301
- } catch {
16302
- return null;
16303
- }
16304
- if (!isRecord$15(parsed) || !isRecord$15(parsed.event) || parsed.event.type !== NcpEventType.MessageToolCallStart) return null;
16305
- const payload = isRecord$15(parsed.event.payload) ? parsed.event.payload : null;
16306
- const toolCallId = typeof payload?.toolCallId === "string" ? payload.toolCallId.trim() : "";
16307
- const messageId = typeof payload?.messageId === "string" ? payload.messageId.trim() : "";
16308
- return toolCallId && messageId ? {
16309
- toolCallId,
16310
- messageId
16311
- } : null;
16312
- }
16313
- function deduplicateMessages(messages) {
16314
- return [...new Map(messages.map((message) => [message.id, message])).values()];
16315
- }
16316
- //#endregion
16317
- //#region src/stores/ncp-agent-session-message-projection-persistence.store.ts
16318
- const PROJECTION_ROOT_DIRECTORY = ".message-projections";
16319
- const RETRYABLE_META_RENAME_CODES = new Set([
16320
- "EPERM",
16321
- "EACCES",
16322
- "EBUSY"
16323
- ]);
16324
- const META_RENAME_RETRY_DELAYS_MS = [
16325
- 50,
16326
- 100,
16327
- 200,
16328
- 400
16329
- ];
16330
- var NcpAgentSessionMessageProjectionPersistenceStore = class {
16331
- messageOrdinals = /* @__PURE__ */ new Map();
16332
- constructor(journalDir) {
16333
15881
  this.journalDir = journalDir;
16334
15882
  }
16335
- readMeta = async (sessionId) => {
16336
- try {
16337
- const parsed = JSON.parse(await readFile(this.metaPath(sessionId), "utf-8"));
16338
- if (!isNcpAgentSessionMessageProjectionMeta(parsed, sessionId)) return null;
16339
- const meta = parsed;
16340
- const [dataStat, offsetsStat] = await Promise.all([stat(this.dataPath(sessionId)), stat(this.offsetsPath(sessionId))]);
16341
- if (dataStat.size !== meta.dataBytes || offsetsStat.size !== meta.total * 42 || meta.total < 0 || meta.projectedJournalOffset < 0 || meta.dataBytes < 0) return null;
16342
- return structuredClone(meta);
16343
- } catch {
16344
- return null;
15883
+ prepare = async (sessionId, signal, onProgress) => {
15884
+ const { stat } = await import("node:fs/promises");
15885
+ const { scanBoundedSessionJournal } = await import("./session-journal-stream.utils-CupSA3YS.js");
15886
+ const { recoverSessionJournalTornTail } = await import("./session-journal-maintenance.store-CImhMMBv.js").then((n) => n.o);
15887
+ await recoverSessionJournalTornTail(this.journalPath(sessionId), signal);
15888
+ const journalBytes = (await stat(this.journalPath(sessionId))).size;
15889
+ const journalIdentity = await this.journalIdentity(sessionId);
15890
+ const database = await this.database(sessionId, true);
15891
+ let meta = this.meta(database, sessionId, true);
15892
+ if (!meta || meta.projectedJournalOffset > journalBytes || meta.journalIdentity !== journalIdentity) {
15893
+ database.exec("DELETE FROM messages; DELETE FROM tool_owners; DELETE FROM part_fields; DELETE FROM part_chunks; DELETE FROM part_previews; DELETE FROM settled_tools; DELETE FROM session_questions; DELETE FROM session_interruptions; DELETE FROM interruption_fields; DELETE FROM interruption_chunks;");
15894
+ meta = {
15895
+ version: 12,
15896
+ sessionId,
15897
+ total: 0,
15898
+ dataBytes: 0,
15899
+ projectedJournalOffset: 0,
15900
+ nextSeq: 1,
15901
+ contextWindow: null,
15902
+ activeMessageId: null,
15903
+ pendingCompactionMessageIds: [],
15904
+ journalIdentity
15905
+ };
16345
15906
  }
16346
- };
16347
- rebuild = async (params) => {
16348
- const { contextWindow, messages: sourceMessages, projectedJournalOffset, sessionId } = params;
16349
- const messages = deduplicateNcpAgentSessionTailMessages(sourceMessages);
16350
- const projectionPath = this.projectionPath(sessionId);
16351
- const projectionRoot = dirname(projectionPath);
16352
- await mkdir(projectionRoot, { recursive: true });
16353
- const temporaryPath = await mkdtemp(join(projectionRoot, ".rebuild-"));
15907
+ const projector = new SessionEventProjectionStore(database, meta);
15908
+ projector.parts.omitSmallDeltaStaging = true;
15909
+ let pendingDelta = null;
15910
+ const flushDelta = async () => {
15911
+ if (!pendingDelta) return;
15912
+ await projector.apply(pendingDelta.event, false, signal, true, pendingDelta.timestamp);
15913
+ meta.projectedJournalOffset = pendingDelta.boundary;
15914
+ meta.nextSeq = Math.max(meta.nextSeq ?? 1, pendingDelta.nextSeq);
15915
+ pendingDelta = null;
15916
+ };
15917
+ let transaction = false;
15918
+ let lastCommit = performance.now();
15919
+ const commitIfDue = async () => {
15920
+ if (performance.now() - lastCommit < 50) return;
15921
+ await flushDelta();
15922
+ this.writeMeta(database, meta);
15923
+ database.exec("COMMIT");
15924
+ transaction = false;
15925
+ signal?.throwIfAborted();
15926
+ await new Promise((resolve) => setImmediate(resolve));
15927
+ database.exec("BEGIN IMMEDIATE");
15928
+ transaction = true;
15929
+ lastCommit = performance.now();
15930
+ };
16354
15931
  try {
16355
- const dataFile = await open(join(temporaryPath, "messages.jsonl"), "w");
16356
- let dataBytes = 0;
16357
- try {
16358
- const offsetsFile = await open(join(temporaryPath, "offsets.idx"), "w");
16359
- try {
16360
- for (const message of messages) {
16361
- const serialized = serializeNcpAgentSessionMessage(message);
16362
- await dataFile.write(serialized, 0, serialized.length, dataBytes);
16363
- await offsetsFile.write(serializeNcpAgentSessionMessageLocation({
16364
- offset: dataBytes,
16365
- length: serialized.length
16366
- }));
16367
- dataBytes += serialized.length;
15932
+ meta.preparation = {
15933
+ status: "preparing",
15934
+ journalBytes
15935
+ };
15936
+ this.writeMeta(database, meta);
15937
+ database.exec("BEGIN IMMEDIATE");
15938
+ transaction = true;
15939
+ projector.parts.clearStaging();
15940
+ await scanBoundedSessionJournal({
15941
+ path: this.journalPath(sessionId),
15942
+ startOffset: meta.projectedJournalOffset,
15943
+ endOffset: journalBytes,
15944
+ signal,
15945
+ onToken: (token, path) => projector.parts.captureToken(token, path),
15946
+ onProgress: (bytes) => onProgress?.(Math.min(bytes, journalBytes), journalBytes),
15947
+ onEntry: async (entry, boundary, _index, truncated) => {
15948
+ this.assertSupportedEntry(entry);
15949
+ if (entry._type === "metadata") meta.legacyMetadata = {
15950
+ metadata: entry.metadata && typeof entry.metadata === "object" && !Array.isArray(entry.metadata) ? entry.metadata : {},
15951
+ ...typeof entry.agent_id === "string" ? { agentId: entry.agent_id } : {},
15952
+ createdAt: typeof entry.created_at === "string" ? entry.created_at : (/* @__PURE__ */ new Date(0)).toISOString(),
15953
+ updatedAt: typeof entry.updated_at === "string" ? entry.updated_at : (/* @__PURE__ */ new Date(0)).toISOString()
15954
+ };
15955
+ const event = entry.event;
15956
+ const endpoint = event;
15957
+ if (!truncated && endpoint && isSessionJournalDelta(endpoint) && Buffer.byteLength(endpoint.payload.delta) <= 2048) {
15958
+ if (pendingDelta && (!canCoalesceSessionJournalDeltas(pendingDelta.event, endpoint) || Buffer.byteLength(pendingDelta.event.payload.delta) + Buffer.byteLength(endpoint.payload.delta) > 16 * 1024)) await flushDelta();
15959
+ pendingDelta = {
15960
+ event: pendingDelta ? coalesceSessionJournalDeltas(pendingDelta.event, endpoint) : endpoint,
15961
+ boundary,
15962
+ nextSeq: Math.max(pendingDelta?.nextSeq ?? 1, Number(entry.seq ?? 0) + 1),
15963
+ timestamp: pendingDelta?.timestamp ?? (typeof entry.timestamp === "string" ? entry.timestamp : void 0)
15964
+ };
15965
+ projector.parts.clearStaging();
15966
+ onProgress?.(boundary, journalBytes);
15967
+ await commitIfDue();
15968
+ return;
15969
+ }
15970
+ await flushDelta();
15971
+ if (entry._type === "event" && event?.type) {
15972
+ await projector.apply(event, true, signal, false, typeof entry.timestamp === "string" ? entry.timestamp : void 0);
15973
+ meta.nextSeq = Math.max(meta.nextSeq ?? 1, Number(entry.seq ?? 0) + 1);
16368
15974
  }
16369
- await Promise.all([dataFile.sync(), offsetsFile.sync()]);
16370
- } finally {
16371
- await offsetsFile.close();
15975
+ await projector.parts.clearStagingBounded(signal);
15976
+ meta.projectedJournalOffset = boundary;
15977
+ onProgress?.(boundary, journalBytes);
15978
+ await commitIfDue();
16372
15979
  }
16373
- } finally {
16374
- await dataFile.close();
16375
- }
16376
- const meta = {
16377
- version: 8,
16378
- sessionId,
16379
- total: messages.length,
16380
- projectedJournalOffset,
16381
- dataBytes,
16382
- contextWindow: contextWindow ? structuredClone(contextWindow) : null,
16383
- activeMessageId: readActiveAssistantMessageId(messages),
16384
- pendingCompactionMessageIds: readPendingCompactionMessageIds(messages)
16385
- };
16386
- await writeFile(join(temporaryPath, "meta.json"), `${JSON.stringify(meta)}\n`, "utf-8");
16387
- await rm(projectionPath, {
16388
- recursive: true,
16389
- force: true
16390
15980
  });
16391
- await rename(temporaryPath, projectionPath);
16392
- this.messageOrdinals.set(sessionId, new Map(messages.map((message, index) => [message.id, index + 1])));
15981
+ await flushDelta();
15982
+ signal?.throwIfAborted();
15983
+ meta.preparation = {
15984
+ status: "ready",
15985
+ journalBytes
15986
+ };
15987
+ meta.projectedJournalOffset = journalBytes;
15988
+ this.writeMeta(database, meta);
15989
+ database.exec("COMMIT");
15990
+ transaction = false;
16393
15991
  } catch (error) {
16394
- await rm(temporaryPath, {
16395
- recursive: true,
16396
- force: true
16397
- });
15992
+ if (transaction) database.exec("ROLLBACK");
16398
15993
  throw error;
16399
- }
16400
- };
16401
- synchronize = async (params) => {
16402
- const { messages: sourceMessages, projectedJournalOffset, sessionId } = params;
16403
- const meta = await this.readMeta(sessionId);
16404
- if (!meta) return false;
16405
- const messages = deduplicateNcpAgentSessionTailMessages(sourceMessages);
16406
- const pendingCompactionMessageIds = mergePendingCompactionMessageIds(meta.pendingCompactionMessageIds, messages);
16407
- const messageOrdinals = await this.readMessageOrdinals(sessionId, meta);
16408
- const dataFile = await open(this.dataPath(sessionId), "r+");
16409
- const offsetsFile = await open(this.offsetsPath(sessionId), "r+");
16410
- try {
16411
- for (const message of messages) {
16412
- const serialized = serializeNcpAgentSessionMessage(message);
16413
- const location = {
16414
- offset: meta.dataBytes,
16415
- length: serialized.length
16416
- };
16417
- const serializedLocation = Buffer.from(serializeNcpAgentSessionMessageLocation(location), "utf-8");
16418
- await dataFile.write(serialized, 0, serialized.length, meta.dataBytes);
16419
- meta.dataBytes += serialized.length;
16420
- const ordinal = messageOrdinals.get(message.id);
16421
- if (ordinal) {
16422
- await offsetsFile.write(serializedLocation, 0, 42, (ordinal - 1) * 42);
16423
- continue;
16424
- }
16425
- await offsetsFile.write(serializedLocation, 0, 42, meta.total * 42);
16426
- meta.total += 1;
16427
- messageOrdinals.set(message.id, meta.total);
16428
- }
16429
- await Promise.all([dataFile.sync(), offsetsFile.sync()]);
16430
15994
  } finally {
16431
- await Promise.all([dataFile.close(), offsetsFile.close()]);
15995
+ database.close();
16432
15996
  }
16433
- meta.projectedJournalOffset = projectedJournalOffset;
16434
- meta.activeMessageId = readActiveAssistantMessageId(messages);
16435
- meta.pendingCompactionMessageIds = [...pendingCompactionMessageIds];
16436
- await this.writeMeta(meta);
16437
- return true;
16438
15997
  };
16439
- synchronizeJournalTail = async (params) => {
16440
- const { journalOffset, sessionId } = params;
16441
- const meta = await this.readMeta(sessionId);
16442
- if (!meta) return false;
16443
- const messages = await this.readJournalTailMessages(sessionId, meta);
16444
- return await this.synchronize({
16445
- sessionId,
16446
- messages,
16447
- projectedJournalOffset: journalOffset
16448
- });
16449
- };
16450
- updateContextWindow = async (sessionId, contextWindow) => {
16451
- const meta = await this.readMeta(sessionId);
16452
- if (!meta) return;
16453
- meta.contextWindow = contextWindow ? structuredClone(contextWindow) : null;
16454
- await this.writeMeta(meta);
16455
- };
16456
- listPage = async (params) => {
16457
- const { cursor, limit, sessionId } = params;
16458
- let meta = await this.readMeta(sessionId);
16459
- const journalStat = await stat(this.journalPath(sessionId));
16460
- if (meta && meta.projectedJournalOffset > journalStat.size) meta = null;
16461
- if (!meta) return null;
16462
- return await this.readPage({
16463
- sessionId,
16464
- limit,
16465
- cursor,
16466
- tailMessages: await this.readJournalTailMessages(sessionId, meta)
16467
- });
16468
- };
16469
- readAll = async (sessionId) => {
16470
- let meta = await this.readMeta(sessionId);
16471
- const journalStat = await stat(this.journalPath(sessionId));
16472
- if (meta && meta.projectedJournalOffset > journalStat.size) meta = null;
16473
- if (!meta) return null;
16474
- const tailMessages = await this.readJournalTailMessages(sessionId, meta);
16475
- const stableMessages = meta.total > 0 ? await this.readMessages(sessionId, 1, meta.total) : [];
16476
- const byId = new Map(stableMessages.map((message) => [message.id, message]));
16477
- for (const message of tailMessages) byId.set(message.id, message);
16478
- return {
16479
- messages: [...byId.values()],
16480
- meta
16481
- };
16482
- };
16483
- readPage = async (params) => {
16484
- const { cursor, limit: requestedLimit, sessionId, tailMessages } = params;
16485
- const meta = await this.readMeta(sessionId);
16486
- if (!meta) return null;
16487
- const uniqueTailMessages = deduplicateNcpAgentSessionTailMessages(tailMessages ?? []);
16488
- const tailById = new Map(uniqueTailMessages.map((message) => [message.id, message]));
16489
- const messageOrdinals = uniqueTailMessages.length > 0 ? await this.readMessageOrdinals(sessionId, meta) : null;
16490
- const additionalTailMessages = messageOrdinals ? uniqueTailMessages.filter((message) => !messageOrdinals.has(message.id)) : [];
16491
- const limit = Number.isFinite(requestedLimit) ? Math.min(200, Math.max(1, Math.trunc(requestedLimit))) : 40;
16492
- const boundary = cursor ? decodeNcpAgentSessionMessageCursor(cursor, meta.total + 1) : meta.total + 1;
16493
- const includeTail = !cursor;
16494
- const stableLimit = includeTail ? Math.max(0, limit - additionalTailMessages.length) : limit;
16495
- const endOrdinal = Math.min(meta.total, boundary - 1);
16496
- const startOrdinal = stableLimit > 0 ? Math.max(1, endOrdinal - stableLimit + 1) : endOrdinal + 1;
16497
- const stableMessages = startOrdinal <= endOrdinal ? await this.readMessages(sessionId, startOrdinal, endOrdinal) : [];
16498
- const messages = stableMessages.map((message) => tailById.get(message.id) ?? message);
16499
- const messageDetailCursors = Object.fromEntries(stableMessages.map((message, index) => [message.id, encodeNcpAgentSessionMessageCursor(startOrdinal + index + 1)]));
16500
- if (includeTail) messages.push(...additionalTailMessages);
16501
- const cursorOrdinal = stableMessages.length > 0 ? startOrdinal : meta.total + 1;
16502
- return {
16503
- messages,
16504
- messageDetailCursors,
16505
- total: meta.total + additionalTailMessages.length,
16506
- pageInfo: {
16507
- startCursor: messages.length > 0 ? encodeNcpAgentSessionMessageCursor(cursorOrdinal) : null,
16508
- hasPreviousPage: cursorOrdinal > 1
16509
- },
16510
- contextWindow: meta.contextWindow ? structuredClone(meta.contextWindow) : null
16511
- };
16512
- };
16513
- readJournalTailMessages = async (sessionId, meta) => readNcpAgentSessionProjectionTail(this.journalPath(sessionId), meta, (messageId) => this.readMessageById(sessionId, meta, messageId));
16514
- delete = async (sessionId) => {
16515
- this.messageOrdinals.delete(sessionId);
16516
- await rm(this.projectionPath(sessionId), {
16517
- recursive: true,
16518
- force: true
16519
- });
16520
- };
16521
- readMessageOrdinals = async (sessionId, meta) => {
16522
- const cached = this.messageOrdinals.get(sessionId);
16523
- if (cached) return cached;
16524
- const ordinals = /* @__PURE__ */ new Map();
16525
- for (let ordinal = 1; ordinal <= meta.total; ordinal += 1) {
16526
- const message = (await this.readMessages(sessionId, ordinal, ordinal))[0];
16527
- if (message) ordinals.set(message.id, ordinal);
16528
- }
16529
- this.messageOrdinals.set(sessionId, ordinals);
16530
- return ordinals;
16531
- };
16532
- readMessages = async (sessionId, startOrdinal, endOrdinal) => {
16533
- const count = endOrdinal - startOrdinal + 1;
16534
- const indexBuffer = Buffer.alloc(count * 42);
16535
- const offsetsFile = await open(this.offsetsPath(sessionId), "r");
16536
- const dataFile = await open(this.dataPath(sessionId), "r");
16537
- try {
16538
- if ((await offsetsFile.read(indexBuffer, 0, indexBuffer.length, (startOrdinal - 1) * 42)).bytesRead !== indexBuffer.length) throw new Error("Session message projection ended before the requested page.");
16539
- const messages = [];
16540
- for (let index = 0; index < count; index += 1) {
16541
- const recordStart = index * 42;
16542
- const location = parseNcpAgentSessionMessageLocation(indexBuffer.subarray(recordStart, recordStart + 42).toString("utf-8"));
16543
- const messageBuffer = Buffer.alloc(location.length);
16544
- if ((await dataFile.read(messageBuffer, 0, location.length, location.offset)).bytesRead !== location.length) throw new Error("Session message projection contains a truncated message.");
16545
- messages.push(JSON.parse(messageBuffer.toString("utf-8")));
15998
+ readJournalTailMessages = async (sessionId, meta) => {
15999
+ const { readNcpAgentSessionProjectionTail } = await import("./ncp-agent-session-message-projection-tail.store-5sjmoFxv.js");
16000
+ return readNcpAgentSessionProjectionTail(this.journalPath(sessionId), meta, async (messageId) => {
16001
+ const database = await this.database(sessionId);
16002
+ if (!database) return null;
16003
+ try {
16004
+ const row = database.prepare("SELECT ordinal,id,descriptor,revision,bytes FROM messages WHERE id=?").get(messageId);
16005
+ return row ? this.assemble(database, row) : null;
16006
+ } finally {
16007
+ database.close();
16546
16008
  }
16547
- return messages;
16548
- } finally {
16549
- await Promise.all([offsetsFile.close(), dataFile.close()]);
16550
- }
16551
- };
16552
- readMessageById = async (sessionId, meta, messageId) => {
16553
- const ordinal = (await this.readMessageOrdinals(sessionId, meta)).get(messageId);
16554
- if (!ordinal) return null;
16555
- return (await this.readMessages(sessionId, ordinal, ordinal))[0] ?? null;
16556
- };
16557
- writeMeta = async (meta) => {
16558
- const path = this.metaPath(meta.sessionId);
16559
- const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
16560
- await writeFile(temporaryPath, `${JSON.stringify(meta)}\n`, "utf-8");
16561
- let attempts = 0;
16562
- try {
16563
- for (;;) {
16564
- attempts += 1;
16565
- try {
16566
- await this.renameMeta(temporaryPath, path);
16567
- return;
16568
- } catch (error) {
16569
- if (this.shouldStopMetaRenameRetry(error, attempts)) throw this.withMetaRenameAttempts(error, attempts);
16570
- await this.waitForMetaRenameRetry(META_RENAME_RETRY_DELAYS_MS[attempts - 1]);
16571
- }
16009
+ }, async (callId) => {
16010
+ const database = await this.database(sessionId);
16011
+ if (!database) return null;
16012
+ try {
16013
+ return database.prepare("SELECT message_id FROM tool_owners WHERE call_id=?").get(callId)?.message_id ?? null;
16014
+ } finally {
16015
+ database.close();
16572
16016
  }
16573
- } finally {
16574
- await rm(temporaryPath, { force: true }).catch(() => void 0);
16575
- }
16576
- };
16577
- renameMeta = async (from, to) => {
16578
- await rename(from, to);
16579
- };
16580
- waitForMetaRenameRetry = async (delayMs) => {
16581
- await new Promise((resolve) => setTimeout(resolve, delayMs));
16582
- };
16583
- shouldStopMetaRenameRetry = (error, attempts) => !this.isRetryableMetaRenameError(error) || attempts > META_RENAME_RETRY_DELAYS_MS.length;
16584
- withMetaRenameAttempts = (error, attempts) => {
16585
- if (error instanceof Error) error.projectionRenameAttempts = attempts;
16586
- return error;
16017
+ });
16587
16018
  };
16588
- isRetryableMetaRenameError = (error) => error instanceof Error && RETRYABLE_META_RENAME_CODES.has(error.code ?? "");
16589
- projectionPath = (sessionId) => join(this.journalDir, PROJECTION_ROOT_DIRECTORY, safeNcpSessionFilename(sessionId));
16590
- journalPath = (sessionId) => join(this.journalDir, `${safeNcpSessionFilename(sessionId)}.jsonl`);
16591
- metaPath = (sessionId) => join(this.projectionPath(sessionId), "meta.json");
16592
- dataPath = (sessionId) => join(this.projectionPath(sessionId), "messages.jsonl");
16593
- offsetsPath = (sessionId) => join(this.projectionPath(sessionId), "offsets.idx");
16019
+ journalPath = (sessionId) => journalPath(this.journalDir, sessionId);
16594
16020
  };
16595
16021
  //#endregion
16596
16022
  //#region src/stores/ncp-agent-session-message-projection.store.ts
16597
16023
  var NcpAgentSessionMessageProjectionStore = class {
16598
16024
  operationChains = /* @__PURE__ */ new Map();
16599
- degradedSessionIds = /* @__PURE__ */ new Set();
16600
16025
  persistence;
16601
- constructor(journalDir, source) {
16602
- this.source = source;
16026
+ preparation;
16027
+ constructor(journalDir) {
16603
16028
  this.persistence = new NcpAgentSessionMessageProjectionPersistenceStore(journalDir);
16029
+ this.preparation = new SessionMessagePreparationStore(async (sessionId, signal, progress) => {
16030
+ await this.enqueue(sessionId, async () => {
16031
+ const meta = await this.persistence.readMeta(sessionId, true).catch(() => null);
16032
+ const identity = await this.persistence.journalIdentity(sessionId);
16033
+ const bytes = await this.persistence.journalBytes(sessionId);
16034
+ if (!meta || meta.journalIdentity !== identity || meta.projectedJournalOffset > (bytes ?? 0)) await this.persistence.delete(sessionId);
16035
+ await this.persistence.prepare(sessionId, signal, progress);
16036
+ });
16037
+ });
16604
16038
  }
16605
- readMeta = async (sessionId) => await this.enqueue(sessionId, async () => this.degradedSessionIds.has(sessionId) ? null : await this.persistence.readMeta(sessionId));
16606
- readAllSnapshot = async (sessionId) => {
16607
- if (this.degradedSessionIds.has(sessionId)) return null;
16039
+ readMeta = (sessionId) => this.persistence.readMeta(sessionId);
16040
+ readPart = (sessionId, messageId, part, cursor) => this.enqueue(sessionId, () => this.persistence.readPart(sessionId, messageId, part, cursor));
16041
+ readRunWindow = (sessionId) => this.enqueue(sessionId, () => this.persistence.readRunWindow(sessionId));
16042
+ readQuestionMessages = (sessionId, questionId) => this.enqueue(sessionId, () => this.persistence.readQuestionMessages(sessionId, questionId));
16043
+ findIngressMessage = (sessionId, key) => this.enqueue(sessionId, () => this.persistence.findIngressMessage(sessionId, key));
16044
+ captureSource = (sessionId, messageIds) => this.enqueue(sessionId, () => this.persistence.captureSource(sessionId, messageIds));
16045
+ validateSource = (sessionId, source) => this.enqueue(sessionId, () => this.persistence.validateSource(sessionId, source));
16046
+ prepare = async (sessionId, options = {}) => {
16047
+ const active = this.preparation.get(sessionId);
16048
+ if (active && ["queued", "preparing"].includes(active.status)) {
16049
+ if (options.wait) await this.preparation.wait(sessionId);
16050
+ return this.preparation.get(sessionId);
16051
+ }
16052
+ const bytes = await this.persistence.journalBytes(sessionId);
16053
+ if (bytes === null) return null;
16054
+ let healthy = false;
16608
16055
  try {
16609
- return await this.persistence.readAll(sessionId);
16056
+ const meta = await this.persistence.readMeta(sessionId);
16057
+ healthy = Boolean(meta && meta.projectedJournalOffset === bytes && meta.journalIdentity === await this.persistence.journalIdentity(sessionId));
16610
16058
  } catch (error) {
16611
- if (!(error instanceof Error)) throw error;
16612
- this.degrade(sessionId, "readAllSnapshot", error);
16613
- return null;
16059
+ if (!(error instanceof Error) || !("code" in error)) throw error;
16614
16060
  }
16061
+ if (healthy) return {
16062
+ status: "ready",
16063
+ processedBytes: bytes,
16064
+ totalBytes: bytes
16065
+ };
16066
+ const state = this.preparation.start(sessionId, bytes, options.retry || active?.status === "ready");
16067
+ if (options.wait) {
16068
+ await this.preparation.wait(sessionId);
16069
+ return this.preparation.get(sessionId);
16070
+ }
16071
+ return state;
16615
16072
  };
16616
- rebuild = async (params) => {
16617
- await this.mutate(params.sessionId, "rebuild", async () => {
16618
- await this.persistence.rebuild(params);
16619
- this.recover(params.sessionId, "rebuild");
16620
- });
16621
- };
16622
- synchronize = async (params) => await this.mutate(params.sessionId, "synchronize", async () => {
16623
- if (await this.rebuildIfDegraded(params.sessionId, "synchronize")) return true;
16624
- return await this.persistence.synchronize(params);
16625
- }, false);
16073
+ cancelPreparation = (sessionId) => this.preparation.cancel(sessionId);
16074
+ rebuild = (params) => this.enqueue(params.sessionId, () => this.persistence.rebuild(params));
16075
+ synchronize = (params) => this.enqueue(params.sessionId, () => this.persistence.synchronize(params));
16626
16076
  synchronizeSource = async (sessionId) => {
16627
- const loaded = await this.source?.loadSession(sessionId);
16628
- if (!loaded) return false;
16629
- if (!await this.synchronize({
16630
- sessionId,
16631
- messages: loaded.record.messages,
16632
- projectedJournalOffset: loaded.journalOffset
16633
- })) await this.rebuild({
16634
- sessionId,
16635
- messages: loaded.record.messages,
16636
- projectedJournalOffset: loaded.journalOffset
16637
- });
16638
- return true;
16639
- };
16640
- synchronizeJournalTail = async (params) => await this.mutate(params.sessionId, "synchronizeJournalTail", async () => {
16641
- if (await this.rebuildIfDegraded(params.sessionId, "synchronizeJournalTail")) return true;
16642
- return await this.persistence.synchronizeJournalTail(params);
16643
- }, false);
16644
- updateContextWindow = async (sessionId, contextWindow) => {
16645
- await this.mutate(sessionId, "updateContextWindow", async () => {
16646
- if (!this.degradedSessionIds.has(sessionId)) await this.persistence.updateContextWindow(sessionId, contextWindow);
16647
- });
16648
- };
16649
- listPage = async (params) => await this.enqueue(params.sessionId, async () => {
16650
- if (this.degradedSessionIds.has(params.sessionId)) return await this.readJournalPage(params);
16651
- try {
16652
- const page = await this.persistence.listPage(params);
16653
- if (page) return page;
16654
- const loaded = await this.source?.loadSession(params.sessionId);
16655
- if (!loaded) return null;
16656
- await this.persistence.rebuild({
16657
- sessionId: params.sessionId,
16658
- messages: loaded.record.messages,
16659
- projectedJournalOffset: loaded.journalOffset
16660
- });
16661
- return await this.persistence.listPage(params);
16662
- } catch (error) {
16663
- if (!this.isProjectionStorageError(error)) throw error;
16664
- this.degrade(params.sessionId, "listPage", error);
16665
- return await this.readJournalPage(params);
16666
- }
16667
- });
16668
- readPage = async (params) => await this.enqueue(params.sessionId, async () => this.degradedSessionIds.has(params.sessionId) ? await this.readJournalPage(params) : await this.persistence.readPage(params));
16077
+ return (await this.prepare(sessionId, {
16078
+ retry: true,
16079
+ wait: true
16080
+ }))?.status === "ready";
16081
+ };
16082
+ synchronizeJournalTail = async (params) => this.synchronizeSource(params.sessionId);
16083
+ appendEvent = (sessionId, event, offset, nextSeq, previousOffset, timestamp) => this.enqueue(sessionId, () => this.persistence.appendEvent(sessionId, event, offset, nextSeq, previousOffset, timestamp));
16084
+ updateContextWindow = (sessionId, contextWindow) => this.enqueue(sessionId, () => this.persistence.updateContextWindow(sessionId, contextWindow));
16085
+ listPage = (params) => this.enqueue(params.sessionId, () => this.persistence.listPage(params));
16086
+ readPage = (params) => this.enqueue(params.sessionId, () => this.persistence.readPage(params));
16669
16087
  delete = async (sessionId) => {
16670
- await this.mutate(sessionId, "delete", async () => {
16671
- await this.persistence.delete(sessionId);
16672
- this.degradedSessionIds.delete(sessionId);
16673
- });
16674
- };
16675
- rebuildIfDegraded = async (sessionId, operation) => {
16676
- if (!this.degradedSessionIds.has(sessionId)) return false;
16677
- const loaded = await this.source?.loadSession(sessionId);
16678
- if (!loaded) return false;
16679
- await this.persistence.rebuild({
16680
- sessionId,
16681
- messages: loaded.record.messages,
16682
- projectedJournalOffset: loaded.journalOffset
16683
- });
16684
- this.recover(sessionId, operation);
16685
- return true;
16088
+ this.preparation.cancel(sessionId);
16089
+ await this.enqueue(sessionId, () => this.persistence.delete(sessionId));
16686
16090
  };
16687
16091
  enqueue = async (sessionId, operation) => {
16688
16092
  const next = (this.operationChains.get(sessionId) ?? Promise.resolve()).then(operation);
@@ -16691,175 +16095,7 @@ var NcpAgentSessionMessageProjectionStore = class {
16691
16095
  settled.finally(() => {
16692
16096
  if (this.operationChains.get(sessionId) === settled) this.operationChains.delete(sessionId);
16693
16097
  });
16694
- return await next;
16695
- };
16696
- mutate = async (sessionId, operation, mutation, fallback) => await this.enqueue(sessionId, async () => {
16697
- try {
16698
- return await mutation();
16699
- } catch (error) {
16700
- if (!this.isProjectionStorageError(error)) throw error;
16701
- this.degrade(sessionId, operation, error);
16702
- return fallback;
16703
- }
16704
- });
16705
- isProjectionStorageError = (error) => error instanceof Error && typeof error.code === "string";
16706
- degrade = (sessionId, operation, error) => {
16707
- if (this.degradedSessionIds.has(sessionId)) return;
16708
- this.degradedSessionIds.add(sessionId);
16709
- console.warn("Session message projection degraded", {
16710
- sessionId,
16711
- operation,
16712
- code: error.code,
16713
- renameAttempts: error.projectionRenameAttempts ?? 1,
16714
- fallback: "journal-replay"
16715
- });
16716
- };
16717
- recover = (sessionId, operation) => {
16718
- if (!this.degradedSessionIds.delete(sessionId)) return;
16719
- console.info("Session message projection recovered", {
16720
- sessionId,
16721
- operation
16722
- });
16723
- };
16724
- readJournalPage = async (params) => {
16725
- const { cursor, limit: requestedLimit, sessionId } = params;
16726
- const loaded = await this.source?.loadSession(sessionId);
16727
- if (!loaded) return null;
16728
- const messages = loaded.record.messages.map((message) => structuredClone(message));
16729
- const limit = Number.isFinite(requestedLimit) ? Math.min(200, Math.max(1, Math.trunc(requestedLimit))) : 40;
16730
- const boundary = cursor ? decodeNcpAgentSessionMessageCursor(cursor, messages.length + 1) : messages.length + 1;
16731
- const endOrdinal = Math.min(messages.length, boundary - 1);
16732
- const startOrdinal = Math.max(1, endOrdinal - limit + 1);
16733
- const pageMessages = startOrdinal <= endOrdinal ? messages.slice(startOrdinal - 1, endOrdinal) : [];
16734
- return {
16735
- messages: pageMessages,
16736
- messageDetailCursors: Object.fromEntries(pageMessages.map((message, index) => [message.id, encodeNcpAgentSessionMessageCursor(startOrdinal + index)])),
16737
- total: messages.length,
16738
- pageInfo: {
16739
- startCursor: pageMessages.length ? encodeNcpAgentSessionMessageCursor(startOrdinal) : null,
16740
- hasPreviousPage: startOrdinal > 1
16741
- },
16742
- contextWindow: null
16743
- };
16744
- };
16745
- };
16746
- //#endregion
16747
- //#region src/stores/session-journal-loader.store.ts
16748
- var SessionJournalLoaderStore = class {
16749
- constructor(metadataStore, messageProjectionStore) {
16750
- this.metadataStore = metadataStore;
16751
- this.messageProjectionStore = messageProjectionStore;
16752
- }
16753
- load = async (sessionId, path) => {
16754
- let journalStat;
16755
- try {
16756
- journalStat = await stat(path);
16757
- } catch {
16758
- return null;
16759
- }
16760
- const projected = await this.messageProjectionStore.readAllSnapshot(sessionId);
16761
- if (projected) {
16762
- const journalTail = await this.readLastJournalState(path, journalStat.size);
16763
- const { agentId, createdAt, updatedAt, metadata } = await this.metadataStore.read(sessionId, {
16764
- metadata: {},
16765
- createdAt: journalStat.birthtime.toISOString(),
16766
- updatedAt: journalTail.updatedAt ?? journalStat.mtime.toISOString()
16767
- });
16768
- return {
16769
- record: {
16770
- sessionId,
16771
- ...agentId ? { agentId } : {},
16772
- messages: projected.messages,
16773
- createdAt,
16774
- updatedAt,
16775
- metadata
16776
- },
16777
- nextSeq: journalTail.nextSeq,
16778
- journalOffset: journalStat.size,
16779
- projectedJournalOffset: projected.meta.projectedJournalOffset
16780
- };
16781
- }
16782
- return await this.loadFromJournalStream(sessionId, path, journalStat.size);
16783
- };
16784
- loadFromJournalStream = async (sessionId, path, journalOffset) => {
16785
- const supersessionTracker = new SessionReplaySupersessionTracker();
16786
- const parsedJournal = await scanSessionJournal({
16787
- path,
16788
- endOffset: journalOffset,
16789
- onEvent: (event, eventIndex) => supersessionTracker.observe(event, eventIndex)
16790
- });
16791
- const { agentId, createdAt, updatedAt, metadata } = await this.metadataStore.read(sessionId, parsedJournal);
16792
- const replayer = await SessionEventReplayer.create();
16793
- const supersededSyntheticRecoveryIndexes = supersessionTracker.finish();
16794
- await scanSessionJournal({
16795
- path,
16796
- endOffset: journalOffset,
16797
- onEvent: async (event, eventIndex) => {
16798
- await replayer.append(event, eventIndex, supersededSyntheticRecoveryIndexes);
16799
- }
16800
- });
16801
- return {
16802
- record: {
16803
- sessionId,
16804
- ...agentId ? { agentId } : {},
16805
- messages: replayer.finish(),
16806
- createdAt,
16807
- updatedAt,
16808
- metadata
16809
- },
16810
- nextSeq: parsedJournal.nextSeq,
16811
- journalOffset,
16812
- projectedJournalOffset: parsedJournal.projectedJournalOffset
16813
- };
16814
- };
16815
- readLastJournalState = async (path, size) => {
16816
- if (size <= 0) return {
16817
- nextSeq: 1,
16818
- updatedAt: null
16819
- };
16820
- const file = await open(path, "r");
16821
- const chunkBytes = 64 * 1024;
16822
- let position = size;
16823
- let suffix = Buffer.alloc(0);
16824
- try {
16825
- while (position > 0) {
16826
- const start = Math.max(0, position - chunkBytes);
16827
- const chunk = Buffer.alloc(position - start);
16828
- const { bytesRead } = await file.read(chunk, 0, chunk.length, start);
16829
- const data = Buffer.concat([chunk.subarray(0, bytesRead), suffix]);
16830
- let lineEnd = data.length;
16831
- for (;;) {
16832
- const newline = data.lastIndexOf(10, lineEnd - 1);
16833
- if (newline < 0) break;
16834
- const state = this.readStateFromJournalLine(data.subarray(newline + 1, lineEnd));
16835
- if (state) return state;
16836
- lineEnd = newline;
16837
- }
16838
- suffix = data.subarray(0, lineEnd);
16839
- position = start;
16840
- }
16841
- return this.readStateFromJournalLine(suffix) ?? {
16842
- nextSeq: 1,
16843
- updatedAt: null
16844
- };
16845
- } finally {
16846
- await file.close();
16847
- }
16848
- };
16849
- readStateFromJournalLine = (line) => {
16850
- if (line.length === 0) return null;
16851
- try {
16852
- const entry = JSON.parse(line.toString("utf-8"));
16853
- const seq = Number(entry._type === "event" ? entry.seq : NaN);
16854
- if (!Number.isFinite(seq)) return null;
16855
- const updatedAt = typeof entry.timestamp === "string" && Number.isFinite(Date.parse(entry.timestamp)) ? new Date(entry.timestamp).toISOString() : null;
16856
- return {
16857
- nextSeq: Math.trunc(seq) + 1,
16858
- updatedAt
16859
- };
16860
- } catch {
16861
- return null;
16862
- }
16098
+ return next;
16863
16099
  };
16864
16100
  };
16865
16101
  //#endregion
@@ -17158,7 +16394,7 @@ var NcpAgentSessionSummaryIndexStore = class {
17158
16394
  event,
17159
16395
  updatedAt
17160
16396
  }),
17161
- messageCount: readEventMessage(event) ? 1 : 0
16397
+ messageCount: params.projectedMessageCount ?? (readEventMessage(event) ? 1 : 0)
17162
16398
  });
17163
16399
  this.db().prepare(`INSERT INTO sessions (
17164
16400
  session_id, peer_id, agent_id, created_at, updated_at,
@@ -17178,7 +16414,7 @@ var NcpAgentSessionSummaryIndexStore = class {
17178
16414
  WHEN excluded.last_message_at > sessions.last_message_at THEN excluded.last_message_at
17179
16415
  ELSE sessions.last_message_at
17180
16416
  END,
17181
- message_count = sessions.message_count + excluded.message_count,
16417
+ message_count = ${params.projectedMessageCount === void 0 ? "sessions.message_count + excluded.message_count" : "excluded.message_count"},
17182
16418
  status = excluded.status
17183
16419
  WHERE sessions.deleted_at IS NULL`).run(upsertParams);
17184
16420
  this.lastSummaryWriteAt.set(sessionId, now);
@@ -17369,282 +16605,8 @@ var NcpAgentSessionSummaryReadStore = class {
17369
16605
  };
17370
16606
  };
17371
16607
  //#endregion
17372
- //#region src/stores/session-journal-maintenance.store.ts
17373
- const CATALOG_FILE = ".ncp-agent-session-catalog.sqlite";
17374
- function paths(journalDir, sessionId) {
17375
- const basename = safeNcpSessionFilename(sessionId.replace(/:/g, "_"));
17376
- const source = join(journalDir, `${basename}.jsonl`);
17377
- return {
17378
- source,
17379
- backup: `${source}.backup`,
17380
- pending: `${source}.pending`,
17381
- marker: `${source}.maintenance`,
17382
- markerDraft: `${source}.maintenance.tmp`,
17383
- projection: join(journalDir, ".message-projections", basename)
17384
- };
17385
- }
17386
- async function syncDirectory(path) {
17387
- const handle = await open(path, "r");
17388
- try {
17389
- await handle.sync();
17390
- } finally {
17391
- await handle.close();
17392
- }
17393
- }
17394
- async function syncFile(path) {
17395
- const handle = await open(path, "r");
17396
- try {
17397
- await handle.sync();
17398
- } finally {
17399
- await handle.close();
17400
- }
17401
- }
17402
- async function hashFile(path) {
17403
- const hash = createHash("sha256");
17404
- for await (const chunk of createReadStream(path)) hash.update(chunk);
17405
- return hash.digest("hex");
17406
- }
17407
- async function assertSourceUnchanged(source, expected) {
17408
- const current = await stat(source);
17409
- if (current.size !== expected.size || current.mtimeMs !== expected.mtimeMs || current.ino !== expected.ino) throw new Error("Journal changed during compaction; refusing activation.");
17410
- }
17411
- /** Refuse to append after a partial write: another JSONL entry would hide the torn tail. */
17412
- async function assertSessionJournalTailComplete(source) {
17413
- let handle;
17414
- try {
17415
- handle = await open(source, "r");
17416
- } catch (error) {
17417
- if (error.code === "ENOENT") return;
17418
- throw error;
17419
- }
17420
- try {
17421
- const size = (await handle.stat()).size;
17422
- if (size === 0) return;
17423
- const suffix = Buffer.alloc(1);
17424
- await handle.read(suffix, 0, 1, size - 1);
17425
- if (suffix[0] !== 10) throw new Error("Journal has an incomplete tail line; refusing further writes.");
17426
- } finally {
17427
- await handle.close();
17428
- }
17429
- }
17430
- async function invalidateDerivedState(journalDir, sessionId, projection) {
17431
- await rm(projection, {
17432
- recursive: true,
17433
- force: true
17434
- });
17435
- const catalogPath = join(journalDir, CATALOG_FILE);
17436
- try {
17437
- await stat(catalogPath);
17438
- } catch (error) {
17439
- if (error.code === "ENOENT") return;
17440
- throw error;
17441
- }
17442
- const database = await openSqliteDatabase(catalogPath);
17443
- try {
17444
- database.exec("PRAGMA busy_timeout = 10000; PRAGMA synchronous = FULL; PRAGMA foreign_keys = ON;");
17445
- runSqliteTransaction(database, () => {
17446
- database.prepare("DELETE FROM run_recovery WHERE session_id = ?").run(sessionId);
17447
- database.prepare("DELETE FROM sessions WHERE session_id = ? AND deleted_at IS NULL").run(sessionId);
17448
- }, "IMMEDIATE");
17449
- } finally {
17450
- database.close();
17451
- }
17452
- await syncDirectory(journalDir);
17453
- }
17454
- /** Runs before the catalog opens. An interrupted switch always rolls back to the untouched backup. */
17455
- async function recoverSessionJournalMaintenance(journalDir) {
17456
- let names;
17457
- try {
17458
- names = await readdir(journalDir);
17459
- } catch (error) {
17460
- if (error.code === "ENOENT") return;
17461
- throw error;
17462
- }
17463
- for (const name of names.filter((item) => item.endsWith(".jsonl.maintenance"))) {
17464
- const sessionId = normalizeNcpSessionId(JSON.parse(await readFile(join(journalDir, name), "utf8")).sessionId ?? "");
17465
- if (!sessionId || `${safeNcpSessionFilename(sessionId.replace(/:/g, "_"))}.jsonl.maintenance` !== name) throw new Error(`Invalid journal maintenance marker: ${name}`);
17466
- const source = join(journalDir, name.slice(0, -12));
17467
- const backup = `${source}.backup`;
17468
- const restore = `${source}.restore`;
17469
- await copyFile(backup, restore);
17470
- await syncFile(restore);
17471
- await rename(restore, source);
17472
- await invalidateDerivedState(journalDir, sessionId, join(journalDir, ".message-projections", name.slice(0, -18)));
17473
- await rm(`${source}.pending`, { force: true });
17474
- await rm(join(journalDir, name));
17475
- await syncDirectory(journalDir);
17476
- }
17477
- }
17478
- async function validateColdReplay(journalDir, sessionId, source, candidate) {
17479
- const loader = new SessionJournalLoaderStore(new NcpAgentSessionMetadataStore(journalDir), { readAllSnapshot: async () => null });
17480
- const original = await loader.load(sessionId, source);
17481
- const compacted = await loader.load(sessionId, candidate);
17482
- if (!original || !compacted || !isDeepStrictEqual(original.record.messages, compacted.record.messages)) throw new Error("Session journal compaction changed cold-replayed messages.");
17483
- }
17484
- async function writeCoalescedJournal(source, pending) {
17485
- const output = await open(pending, "wx");
17486
- let inputLines = 0;
17487
- let outputLines = 0;
17488
- let nextSeq = 1;
17489
- let pendingEntry = null;
17490
- const flush = async () => {
17491
- if (!pendingEntry) return;
17492
- if (pendingEntry._type === "event") pendingEntry.seq = nextSeq++;
17493
- await output.writeFile(`${JSON.stringify(pendingEntry)}\n`);
17494
- outputLines++;
17495
- pendingEntry = null;
17496
- };
17497
- try {
17498
- const lines = createInterface({
17499
- input: createReadStream(source),
17500
- crlfDelay: Infinity
17501
- });
17502
- for await (const line of lines) {
17503
- if (!line) throw new Error("Journal contains a blank line; compaction requires a valid complete source.");
17504
- inputLines++;
17505
- const entry = JSON.parse(line);
17506
- if (!entry || typeof entry !== "object" || !["event", "metadata"].includes(entry._type)) throw new Error(`Invalid journal entry at line ${inputLines}.`);
17507
- if (entry.version !== void 0 && entry.version !== 1) throw new Error(`Unsupported journal entry version at line ${inputLines}.`);
17508
- if (entry._type === "event") {
17509
- if (!Number.isSafeInteger(entry.seq) || entry.seq < 1 || !entry.event?.type || !("payload" in entry.event)) throw new Error(`Invalid journal sequence or event at line ${inputLines}.`);
17510
- }
17511
- if (pendingEntry?._type === "event" && entry._type === "event" && pendingEntry.event && entry.event && canCoalesceSessionJournalDeltas(pendingEntry.event, entry.event) && isSessionJournalDelta(pendingEntry.event) && isSessionJournalDelta(entry.event)) {
17512
- const merged = coalesceSessionJournalDeltas(pendingEntry.event, entry.event);
17513
- if (Buffer.byteLength(merged.payload.delta, "utf8") <= 16384) {
17514
- pendingEntry.event = merged;
17515
- continue;
17516
- }
17517
- }
17518
- await flush();
17519
- pendingEntry = entry;
17520
- }
17521
- await flush();
17522
- await output.sync();
17523
- } finally {
17524
- await output.close();
17525
- }
17526
- return {
17527
- inputLines,
17528
- outputLines
17529
- };
17530
- }
17531
- async function writeMaintenanceMarker(journalDir, target, sessionId) {
17532
- const marker = await open(target.markerDraft, "wx");
17533
- try {
17534
- await marker.writeFile(`${JSON.stringify({ sessionId })}\n`);
17535
- await marker.sync();
17536
- } finally {
17537
- await marker.close();
17538
- }
17539
- await rename(target.markerDraft, target.marker);
17540
- await syncDirectory(journalDir);
17541
- }
17542
- async function activateCompactedJournal(journalDir, sessionId, target, sourceStat) {
17543
- let renamed = false;
17544
- try {
17545
- await copyFile(target.source, target.backup, constants.COPYFILE_EXCL);
17546
- await syncFile(target.backup);
17547
- await assertSourceUnchanged(target.source, sourceStat);
17548
- await writeMaintenanceMarker(journalDir, target, sessionId);
17549
- await assertSourceUnchanged(target.source, sourceStat);
17550
- await rename(target.pending, target.source);
17551
- renamed = true;
17552
- await syncDirectory(journalDir);
17553
- await invalidateDerivedState(journalDir, sessionId, target.projection);
17554
- await rm(target.marker);
17555
- await syncDirectory(journalDir);
17556
- } catch (error) {
17557
- if (renamed) await recoverSessionJournalMaintenance(journalDir);
17558
- else {
17559
- await rm(target.markerDraft, { force: true });
17560
- await rm(target.marker, { force: true });
17561
- await rm(target.backup, { force: true });
17562
- }
17563
- throw error;
17564
- }
17565
- }
17566
- /** Restores the original v1 journal after a successful offline compaction. All writers must be stopped. */
17567
- async function restoreSessionJournalBackup(input) {
17568
- const sessionId = normalizeNcpSessionId(input.sessionId);
17569
- if (!sessionId || input.writersStopped !== true) throw new Error("Stop all writers and explicitly acknowledge it before restoring a journal backup.");
17570
- const target = paths(input.journalDir, sessionId);
17571
- await stat(target.backup);
17572
- for (const candidate of [
17573
- target.pending,
17574
- target.marker,
17575
- target.markerDraft
17576
- ]) try {
17577
- await stat(candidate);
17578
- throw new Error(`Unresolved journal maintenance file: ${candidate}`);
17579
- } catch (error) {
17580
- if (error.code !== "ENOENT") throw error;
17581
- }
17582
- const sourceStat = await stat(target.source);
17583
- let recoveryStarted = false;
17584
- try {
17585
- await writeCoalescedJournal(target.backup, target.pending);
17586
- const expected = await stat(target.pending);
17587
- if (sourceStat.size !== expected.size || await hashFile(target.source) !== await hashFile(target.pending)) throw new Error("Journal changed since compaction; refusing restore to protect later events.");
17588
- await assertSourceUnchanged(target.source, sourceStat);
17589
- await writeMaintenanceMarker(input.journalDir, target, sessionId);
17590
- await assertSourceUnchanged(target.source, sourceStat);
17591
- recoveryStarted = true;
17592
- await recoverSessionJournalMaintenance(input.journalDir);
17593
- } catch (error) {
17594
- await rm(target.markerDraft, { force: true });
17595
- if (!recoveryStarted) await rm(target.marker, { force: true });
17596
- throw error;
17597
- } finally {
17598
- await rm(target.pending, { force: true });
17599
- }
17600
- return {
17601
- sessionId,
17602
- restored: true
17603
- };
17604
- }
17605
- /** Explicit offline operation. The caller must stop every writer for this HOME before apply. */
17606
- async function compactSessionJournal(input) {
17607
- const sessionId = normalizeNcpSessionId(input.sessionId);
17608
- if (!sessionId) throw new Error("A session ID is required.");
17609
- if (input.apply && input.writersStopped !== true) throw new Error("Stop all writers and explicitly acknowledge it before applying compaction.");
17610
- const target = paths(input.journalDir, sessionId);
17611
- for (const candidate of [
17612
- target.backup,
17613
- target.pending,
17614
- target.marker,
17615
- target.markerDraft
17616
- ]) try {
17617
- await stat(candidate);
17618
- throw new Error(`Unresolved journal maintenance file: ${candidate}`);
17619
- } catch (error) {
17620
- if (error.code !== "ENOENT") throw error;
17621
- }
17622
- const before = await stat(target.source);
17623
- await assertSessionJournalTailComplete(target.source);
17624
- try {
17625
- const { inputLines, outputLines } = await writeCoalescedJournal(target.source, target.pending);
17626
- await validateColdReplay(input.journalDir, sessionId, target.source, target.pending);
17627
- await assertSourceUnchanged(target.source, before);
17628
- const outputBytes = (await stat(target.pending)).size;
17629
- const result = {
17630
- sessionId,
17631
- applied: input.apply,
17632
- inputBytes: before.size,
17633
- outputBytes,
17634
- inputLines,
17635
- outputLines
17636
- };
17637
- if (!input.apply) return result;
17638
- await activateCompactedJournal(input.journalDir, sessionId, target, before);
17639
- return result;
17640
- } finally {
17641
- await rm(target.pending, { force: true });
17642
- }
17643
- }
17644
- //#endregion
17645
16608
  //#region src/stores/ncp-agent-session-journal.store.ts
17646
16609
  var NcpAgentSessionJournalStore = class {
17647
- sessions = /* @__PURE__ */ new Map();
17648
16610
  nextSeqBySession = /* @__PURE__ */ new Map();
17649
16611
  writeChains = /* @__PURE__ */ new Map();
17650
16612
  metadataStore;
@@ -17656,12 +16618,8 @@ var NcpAgentSessionJournalStore = class {
17656
16618
  constructor(journalDir) {
17657
16619
  this.journalDir = journalDir;
17658
16620
  this.metadataStore = new NcpAgentSessionMetadataStore(journalDir);
17659
- this.messageProjectionStore = new NcpAgentSessionMessageProjectionStore(journalDir, { loadSession: async (sessionId) => {
17660
- const loaded = this.sessions.get(sessionId) ?? await this.loadSession(sessionId);
17661
- if (loaded) this.sessions.set(sessionId, loaded);
17662
- return loaded;
17663
- } });
17664
- this.journalLoaderStore = new SessionJournalLoaderStore(this.metadataStore, this.messageProjectionStore);
16621
+ this.messageProjectionStore = new NcpAgentSessionMessageProjectionStore(journalDir);
16622
+ this.journalLoaderStore = new SessionJournalLoaderStore(this.metadataStore);
17665
16623
  this.summaryIndexStore = new NcpAgentSessionSummaryIndexStore(journalDir, async (sessionId) => this.loadSession(sessionId), async (sessionId) => {
17666
16624
  try {
17667
16625
  const journalStat = await stat(this.sessionPath(sessionId));
@@ -17692,23 +16650,19 @@ var NcpAgentSessionJournalStore = class {
17692
16650
  appendSessionEvent = async (params) => {
17693
16651
  const sessionId = normalizeNcpSessionId(params.sessionId);
17694
16652
  if (!sessionId) return;
17695
- const next = (this.writeChains.get(sessionId) ?? Promise.resolve()).then(() => this.appendSessionEventNow({
16653
+ return this.enqueueWrite(sessionId, () => this.appendSessionEventNow({
17696
16654
  ...params,
17697
16655
  sessionId
17698
16656
  }));
17699
- this.writeChains.set(sessionId, next.catch(() => void 0));
17700
- await next;
17701
16657
  };
17702
16658
  synchronizeSessionMessageProjection = (sessionId) => this.messageProjectionStore.synchronizeSource(normalizeNcpSessionId(sessionId));
17703
16659
  getSession = async (sessionId) => {
17704
16660
  const normalizedSessionId = normalizeNcpSessionId(sessionId);
17705
16661
  if (!normalizedSessionId) return null;
17706
- const cached = this.sessions.get(normalizedSessionId);
17707
- if (cached) return structuredClone(cached.record);
16662
+ await this.writeChains.get(normalizedSessionId);
17708
16663
  const loaded = await this.loadSession(normalizedSessionId);
17709
16664
  if (!loaded) return null;
17710
- this.sessions.set(normalizedSessionId, loaded);
17711
- return structuredClone(loaded.record);
16665
+ return loaded.record;
17712
16666
  };
17713
16667
  listSessionSummaries = async (options) => {
17714
16668
  return await this.summaryReadStore.list(options?.limit);
@@ -17717,13 +16671,57 @@ var NcpAgentSessionJournalStore = class {
17717
16671
  getSessionSummary = async (sessionId) => {
17718
16672
  const normalizedSessionId = normalizeNcpSessionId(sessionId);
17719
16673
  if (!normalizedSessionId) return null;
17720
- return await this.summaryReadStore.get(normalizedSessionId);
16674
+ const summary = await this.summaryReadStore.get(normalizedSessionId);
16675
+ const meta = await this.messageProjectionStore.readMeta(normalizedSessionId);
16676
+ if (!summary || !meta) return summary;
16677
+ const header = meta.legacyMetadata;
16678
+ if (!header) return {
16679
+ ...summary,
16680
+ messageCount: meta.total
16681
+ };
16682
+ const current = await this.metadataStore.read(normalizedSessionId, header);
16683
+ return {
16684
+ ...summary,
16685
+ ...current,
16686
+ messageCount: meta.total
16687
+ };
17721
16688
  };
17722
16689
  listUnfinishedRuns = () => this.unfinishedRunStore.list();
17723
16690
  listSessionMessages = async (sessionId) => {
17724
16691
  const session = await this.getSession(sessionId);
17725
16692
  return session ? session.messages.map((message) => structuredClone(message)) : [];
17726
16693
  };
16694
+ readSessionMessagePart = async (params) => this.messageProjectionStore.readPart(normalizeNcpSessionId(params.sessionId), params.messageId, params.part, params.cursor);
16695
+ loadSessionRunSeed = async (sessionId) => {
16696
+ await this.messageProjectionStore.prepare(normalizeNcpSessionId(sessionId), { wait: true });
16697
+ const window = await this.messageProjectionStore.readRunWindow(normalizeNcpSessionId(sessionId));
16698
+ if (!window) throw new Error("Session history index is preparing; retry when preparation completes.");
16699
+ return window.messages;
16700
+ };
16701
+ prepareSessionHistory = async (sessionId, options) => {
16702
+ const id = normalizeNcpSessionId(sessionId);
16703
+ const write = this.writeChains.get(id);
16704
+ if (write && !options?.wait) return {
16705
+ status: "queued",
16706
+ processedBytes: 0,
16707
+ totalBytes: 0
16708
+ };
16709
+ if (write) await write;
16710
+ const state = await this.messageProjectionStore.prepare(id, options);
16711
+ if (state?.status === "ready") {
16712
+ const previous = await this.summaryIndexStore.get(id);
16713
+ const meta = await this.messageProjectionStore.readMeta(id);
16714
+ if (previous && meta && previous.messageCount !== meta.total) await this.summaryIndexStore.upsert({
16715
+ ...previous,
16716
+ messageCount: meta.total
16717
+ });
16718
+ }
16719
+ return state;
16720
+ };
16721
+ cancelSessionHistoryPreparation = (sessionId) => this.messageProjectionStore.cancelPreparation(normalizeNcpSessionId(sessionId));
16722
+ listSessionQuestionMessages = (sessionId, questionId) => this.messageProjectionStore.readQuestionMessages(normalizeNcpSessionId(sessionId), questionId);
16723
+ findSessionMessageByIngressKey = (sessionId, key) => this.messageProjectionStore.findIngressMessage(normalizeNcpSessionId(sessionId), key);
16724
+ captureCompactionSource = (sessionId, messageIds) => this.messageProjectionStore.captureSource(normalizeNcpSessionId(sessionId), messageIds);
17727
16725
  listSessionMessagePage = async (params) => {
17728
16726
  const sessionId = normalizeNcpSessionId(params.sessionId);
17729
16727
  if (!sessionId) return null;
@@ -17747,22 +16745,18 @@ var NcpAgentSessionJournalStore = class {
17747
16745
  setSessionMetadata = async (params) => {
17748
16746
  const sessionId = normalizeNcpSessionId(params.sessionId);
17749
16747
  if (!sessionId) return false;
17750
- const next = (this.writeChains.get(sessionId) ?? Promise.resolve()).then(() => this.setSessionMetadataNow({
16748
+ return this.enqueueWrite(sessionId, () => this.setSessionMetadataNow({
17751
16749
  ...params,
17752
16750
  sessionId
17753
16751
  }));
17754
- this.writeChains.set(sessionId, next.then(() => void 0, () => void 0));
17755
- return await next;
17756
16752
  };
17757
16753
  updateSessionMetadata = async (params) => {
17758
16754
  const sessionId = normalizeNcpSessionId(params.sessionId);
17759
16755
  if (!sessionId) return false;
17760
- const next = (this.writeChains.get(sessionId) ?? Promise.resolve()).then(() => this.updateSessionMetadataNow({
16756
+ return this.enqueueWrite(sessionId, () => this.updateSessionMetadataNow({
17761
16757
  ...params,
17762
16758
  sessionId
17763
16759
  }));
17764
- this.writeChains.set(sessionId, next.then(() => void 0, () => void 0));
17765
- return await next;
17766
16760
  };
17767
16761
  setSessionMetadataNow = async (params) => {
17768
16762
  const { metadata, sessionId } = params;
@@ -17772,12 +16766,11 @@ var NcpAgentSessionJournalStore = class {
17772
16766
  } catch {
17773
16767
  return false;
17774
16768
  }
17775
- const cached = this.sessions.get(sessionId);
17776
16769
  const summary = await this.summaryReadStore.get(sessionId);
17777
16770
  const activity = await this.metadataStore.read(sessionId, {
17778
16771
  metadata: {},
17779
- createdAt: cached?.record.createdAt ?? summary?.createdAt ?? journalStat.birthtime.toISOString(),
17780
- updatedAt: cached?.record.updatedAt ?? summary?.updatedAt ?? journalStat.mtime.toISOString()
16772
+ createdAt: summary?.createdAt ?? journalStat.birthtime.toISOString(),
16773
+ updatedAt: summary?.updatedAt ?? journalStat.mtime.toISOString()
17781
16774
  });
17782
16775
  const nextRecord = {
17783
16776
  sessionId,
@@ -17788,16 +16781,6 @@ var NcpAgentSessionJournalStore = class {
17788
16781
  metadata: structuredClone(metadata)
17789
16782
  };
17790
16783
  await this.metadataStore.write(nextRecord);
17791
- if (cached) {
17792
- const record = {
17793
- ...cached.record,
17794
- metadata: structuredClone(metadata)
17795
- };
17796
- this.sessions.set(sessionId, {
17797
- ...cached,
17798
- record
17799
- });
17800
- }
17801
16784
  await this.summaryIndexStore.upsert(summary ? {
17802
16785
  ...summary,
17803
16786
  metadata: structuredClone(metadata)
@@ -17812,12 +16795,11 @@ var NcpAgentSessionJournalStore = class {
17812
16795
  } catch {
17813
16796
  return false;
17814
16797
  }
17815
- const cached = this.sessions.get(sessionId);
17816
16798
  const summary = await this.summaryReadStore.get(sessionId);
17817
16799
  const activity = await this.metadataStore.read(sessionId, {
17818
16800
  metadata: {},
17819
- createdAt: cached?.record.createdAt ?? summary?.createdAt ?? journalStat.birthtime.toISOString(),
17820
- updatedAt: cached?.record.updatedAt ?? summary?.updatedAt ?? journalStat.mtime.toISOString()
16801
+ createdAt: summary?.createdAt ?? journalStat.birthtime.toISOString(),
16802
+ updatedAt: summary?.updatedAt ?? journalStat.mtime.toISOString()
17821
16803
  });
17822
16804
  if (expectedMetadata && Object.entries(expectedMetadata).some(([key, value]) => activity.metadata?.[key] !== value)) return false;
17823
16805
  return await this.setSessionMetadataNow({
@@ -17828,55 +16810,121 @@ var NcpAgentSessionJournalStore = class {
17828
16810
  }
17829
16811
  });
17830
16812
  };
17831
- importSessionSnapshot = async (record) => {
16813
+ importSessionSnapshot = (record) => this.enqueueWrite(normalizeNcpSessionId(record.sessionId), () => this.importSessionSnapshotNow(record));
16814
+ importSessionSnapshotNow = async (record) => {
17832
16815
  const sessionId = normalizeNcpSessionId(record.sessionId);
17833
16816
  if (!sessionId) return;
17834
16817
  await this.ensureJournalDir();
17835
- const nextRecord = structuredClone({
16818
+ const nextRecord = {
17836
16819
  ...record,
17837
- sessionId
17838
- });
17839
- await this.metadataStore.write(nextRecord);
17840
- const entries = nextRecord.messages.map((message, index) => ({
17841
- _type: "event",
17842
- version: 1,
17843
- seq: index + 1,
17844
- timestamp: message.timestamp ?? nextRecord.updatedAt,
17845
- event: {
17846
- type: NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE,
17847
- payload: {
16820
+ sessionId,
16821
+ metadata: structuredClone(record.metadata ?? {})
16822
+ };
16823
+ const path = this.sessionPath(sessionId);
16824
+ const staged = `${path}.import-${randomUUID()}.tmp`;
16825
+ const backup = `${path}.import-backup`;
16826
+ const marker = `${path}.import-maintenance`;
16827
+ if (await stat(marker).catch(() => null)) throw new Error("An interrupted session import requires startup recovery before another import.");
16828
+ const previousStat = await stat(path).catch(() => null);
16829
+ const previousSummary = await this.summaryReadStore.get(sessionId);
16830
+ const previousMetadata = await this.metadataStore.read(sessionId, {
16831
+ metadata: previousSummary?.metadata ?? {},
16832
+ createdAt: previousSummary?.createdAt ?? (/* @__PURE__ */ new Date(0)).toISOString(),
16833
+ updatedAt: previousSummary?.updatedAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
16834
+ });
16835
+ let activated = false;
16836
+ const output = await open(staged, "wx");
16837
+ try {
16838
+ for (const [index, message] of nextRecord.messages.entries()) {
16839
+ const entry = {
16840
+ _type: "event",
16841
+ version: 1,
16842
+ seq: index + 1,
16843
+ timestamp: message.timestamp ?? nextRecord.updatedAt,
16844
+ event: {
16845
+ type: NCP_AGENT_SESSION_SNAPSHOT_MESSAGE_EVENT_TYPE,
16846
+ payload: {
16847
+ sessionId,
16848
+ message
16849
+ }
16850
+ }
16851
+ };
16852
+ for (const chunk of sessionJsonChunks(entry)) await output.writeFile(chunk);
16853
+ await output.writeFile("\n");
16854
+ }
16855
+ await output.sync();
16856
+ await output.close();
16857
+ await rm(backup, { force: true });
16858
+ if (previousStat) await link(path, backup);
16859
+ const intent = await open(marker, "wx");
16860
+ try {
16861
+ await intent.writeFile(JSON.stringify({
17848
16862
  sessionId,
17849
- message: structuredClone(message)
16863
+ snapshot: {
16864
+ hadSource: Boolean(previousStat),
16865
+ metadata: previousMetadata
16866
+ }
16867
+ }));
16868
+ await intent.sync();
16869
+ } finally {
16870
+ await intent.close();
16871
+ }
16872
+ await syncSessionJournalDirectory(this.journalDir);
16873
+ await rename(staged, path);
16874
+ activated = true;
16875
+ const nextSeq = nextRecord.messages.length + 1;
16876
+ const journalStat = await stat(path);
16877
+ this.nextSeqBySession.set(sessionId, nextSeq);
16878
+ await this.messageProjectionStore.rebuild({
16879
+ sessionId,
16880
+ messages: nextRecord.messages,
16881
+ projectedJournalOffset: journalStat.size,
16882
+ nextSeq
16883
+ });
16884
+ await this.metadataStore.write(nextRecord);
16885
+ await this.summaryIndexStore.upsert(createNcpAgentSessionSummary(nextRecord));
16886
+ await syncSessionJournalDirectory(this.journalDir);
16887
+ await rm(marker);
16888
+ await syncSessionJournalDirectory(this.journalDir);
16889
+ await rm(backup, { force: true });
16890
+ } catch (error) {
16891
+ await output.close().catch(() => void 0);
16892
+ if (activated) {
16893
+ if (previousStat) {
16894
+ await copyFile(backup, staged);
16895
+ await syncSessionJournalFile(staged);
16896
+ await rename(staged, path);
16897
+ } else await rm(path, { force: true });
16898
+ await this.messageProjectionStore.delete(sessionId);
16899
+ if (previousStat) {
16900
+ await this.metadataStore.write({
16901
+ sessionId,
16902
+ ...previousMetadata
16903
+ });
16904
+ if (previousSummary) await this.summaryIndexStore.upsert(previousSummary);
16905
+ } else {
16906
+ await this.metadataStore.delete(sessionId);
16907
+ await this.summaryIndexStore.remove(sessionId);
17850
16908
  }
17851
16909
  }
17852
- }));
17853
- await writeFile(this.sessionPath(sessionId), entries.length > 0 ? `${entries.map(serializeNcpAgentSessionJournalEntry).join("\n")}\n` : "", "utf-8");
17854
- const nextSeq = nextRecord.messages.length + 1;
17855
- const journalStat = await stat(this.sessionPath(sessionId));
17856
- this.sessions.set(sessionId, {
17857
- record: nextRecord,
17858
- nextSeq,
17859
- journalOffset: journalStat.size,
17860
- projectedJournalOffset: journalStat.size
17861
- });
17862
- this.nextSeqBySession.set(sessionId, nextSeq);
17863
- await this.messageProjectionStore.rebuild({
17864
- sessionId,
17865
- messages: nextRecord.messages,
17866
- projectedJournalOffset: journalStat.size
17867
- });
17868
- await this.summaryIndexStore.upsert(createNcpAgentSessionSummary(nextRecord));
16910
+ this.nextSeqBySession.delete(sessionId);
16911
+ await rm(marker, { force: true });
16912
+ await syncSessionJournalDirectory(this.journalDir);
16913
+ throw error;
16914
+ } finally {
16915
+ await rm(staged, { force: true });
16916
+ }
17869
16917
  };
17870
16918
  deleteSession = async (sessionId) => {
17871
16919
  const normalizedSessionId = normalizeNcpSessionId(sessionId);
17872
16920
  if (!normalizedSessionId) return null;
17873
16921
  const existing = await this.getSession(normalizedSessionId);
17874
- this.sessions.delete(normalizedSessionId);
17875
16922
  this.nextSeqBySession.delete(normalizedSessionId);
17876
16923
  try {
17877
16924
  await unlink(this.sessionPath(normalizedSessionId));
17878
16925
  } catch {}
17879
16926
  await this.metadataStore.delete(normalizedSessionId);
16927
+ await rm(`${this.sessionPath(normalizedSessionId)}.import-backup`, { force: true });
17880
16928
  await this.messageProjectionStore.delete(normalizedSessionId);
17881
16929
  await this.summaryIndexStore.remove(normalizedSessionId);
17882
16930
  return existing;
@@ -17890,31 +16938,56 @@ var NcpAgentSessionJournalStore = class {
17890
16938
  const { event, sessionId } = params;
17891
16939
  const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
17892
16940
  await this.ensureJournalDir();
17893
- const existing = this.sessions.get(sessionId) ?? (this.nextSeqBySession.has(sessionId) ? null : await this.loadSession(sessionId));
17894
- const nextSeq = this.nextSeqBySession.get(sessionId) ?? existing?.nextSeq ?? 1;
17895
16941
  const path = this.sessionPath(sessionId);
16942
+ if (!this.nextSeqBySession.has(sessionId)) {
16943
+ const journalBytes = (await stat(path).catch(() => null))?.size ?? 0;
16944
+ let meta = await this.messageProjectionStore.readMeta(sessionId);
16945
+ if (!meta && journalBytes === 0) {
16946
+ await this.messageProjectionStore.rebuild({
16947
+ sessionId,
16948
+ messages: [],
16949
+ projectedJournalOffset: 0,
16950
+ nextSeq: 1
16951
+ });
16952
+ meta = await this.messageProjectionStore.readMeta(sessionId);
16953
+ } else if (!meta || meta.projectedJournalOffset !== journalBytes) {
16954
+ await this.messageProjectionStore.prepare(sessionId, { wait: true });
16955
+ meta = await this.messageProjectionStore.readMeta(sessionId);
16956
+ }
16957
+ this.nextSeqBySession.set(sessionId, meta?.nextSeq ?? 1);
16958
+ }
16959
+ const nextSeq = this.nextSeqBySession.get(sessionId);
16960
+ if (event.type === NcpEventType.MessageSent && event.payload.message.metadata?.nextclaw_timeline_kind === "context_compaction") {
16961
+ const checkpoint = event.payload.message.metadata.checkpoint;
16962
+ if (checkpoint.status === "compressed" && checkpoint.source && !await this.messageProjectionStore.validateSource(sessionId, checkpoint.source)) throw Object.assign(/* @__PURE__ */ new Error("Compaction source changed before durable installation."), {
16963
+ code: "CONTEXT_COMPACTION_STALE",
16964
+ journalCommitRejected: true
16965
+ });
16966
+ }
17896
16967
  const entry = {
17897
16968
  _type: "event",
17898
16969
  version: 1,
17899
16970
  seq: nextSeq,
17900
16971
  timestamp: updatedAt,
17901
- event: structuredClone(event)
16972
+ event
17902
16973
  };
17903
- await this.appendJournalEntry(path, entry);
16974
+ const written = await this.appendJournalEntry(path, entry, params.signal);
17904
16975
  this.nextSeqBySession.set(sessionId, nextSeq + 1);
17905
- this.sessions.delete(sessionId);
17906
- let journalOffset = null;
17907
- if (isNcpAgentSessionMessageProjectionBoundaryEvent(event)) {
17908
- journalOffset = (await stat(path)).size;
17909
- await this.messageProjectionStore.synchronizeJournalTail({
16976
+ const journalOffset = written.offset;
16977
+ try {
16978
+ await this.messageProjectionStore.appendEvent(sessionId, event, journalOffset, nextSeq + 1, written.previousOffset, updatedAt);
16979
+ } catch (error) {
16980
+ console.warn("Session message index requires repair after a durable append", {
17910
16981
  sessionId,
17911
- journalOffset
16982
+ error: error instanceof Error ? error.message : String(error)
17912
16983
  });
17913
16984
  }
16985
+ const projection = await this.messageProjectionStore.readMeta(sessionId);
17914
16986
  await this.summaryIndexStore.upsertForEvent({
17915
16987
  sessionId,
17916
16988
  event,
17917
- updatedAt
16989
+ updatedAt,
16990
+ projectedMessageCount: projection?.total
17918
16991
  });
17919
16992
  if (isNcpAgentRunLifecycleEvent(event)) await this.summaryIndexStore.recordRunRecoveryEvent({
17920
16993
  sessionId,
@@ -17927,13 +17000,61 @@ var NcpAgentSessionJournalStore = class {
17927
17000
  if (loaded) this.nextSeqBySession.set(sessionId, loaded.nextSeq);
17928
17001
  return loaded;
17929
17002
  };
17930
- appendJournalEntry = async (path, entry) => {
17003
+ appendJournalEntry = async (path, entry, signal) => {
17004
+ if (signal?.aborted) throw Object.assign(signal.reason instanceof Error ? signal.reason : new DOMException("Cancelled", "AbortError"), { journalCommitRejected: true });
17931
17005
  await assertSessionJournalTailComplete(path);
17932
- await appendFile(path, `${serializeNcpAgentSessionJournalEntry(entry)}\n`, "utf-8");
17006
+ const file = await open(path, "a");
17007
+ const previousOffset = (await file.stat()).size;
17008
+ let completed = false;
17009
+ try {
17010
+ let offset = previousOffset;
17011
+ const write = async (text) => {
17012
+ const buffer = Buffer.from(text);
17013
+ let position = 0;
17014
+ while (position < buffer.length) {
17015
+ const result = await file.write(buffer, position, buffer.length - position, null);
17016
+ if (!result.bytesWritten) throw new Error("Session journal append made no progress.");
17017
+ position += result.bytesWritten;
17018
+ offset += result.bytesWritten;
17019
+ }
17020
+ };
17021
+ for (const chunk of sessionJsonChunks(entry)) await write(chunk);
17022
+ await write("\n");
17023
+ if (signal?.aborted) {
17024
+ await file.truncate(previousOffset);
17025
+ await file.sync();
17026
+ throw Object.assign(signal.reason instanceof Error ? signal.reason : new DOMException("Cancelled", "AbortError"), { journalCommitRejected: true });
17027
+ }
17028
+ const event = entry.event;
17029
+ if (event.type === NcpEventType.MessageSent && event.payload.message.metadata?.nextclaw_timeline_kind === "context_compaction" && event.payload.message.metadata.checkpoint?.status === "compressed") await file.sync();
17030
+ completed = true;
17031
+ return {
17032
+ previousOffset,
17033
+ offset
17034
+ };
17035
+ } catch (error) {
17036
+ if (!completed) {
17037
+ await file.truncate(previousOffset);
17038
+ await file.sync();
17039
+ if (error instanceof Error) Object.assign(error, { journalCommitRejected: true });
17040
+ }
17041
+ throw error;
17042
+ } finally {
17043
+ await file.close();
17044
+ }
17933
17045
  };
17934
17046
  ensureJournalDir = async () => {
17935
17047
  await mkdir(this.journalDir, { recursive: true });
17936
17048
  };
17049
+ enqueueWrite = (sessionId, operation) => {
17050
+ const next = (this.writeChains.get(sessionId) ?? Promise.resolve()).then(operation);
17051
+ const settled = next.then(() => void 0, () => void 0);
17052
+ this.writeChains.set(sessionId, settled);
17053
+ settled.finally(() => {
17054
+ if (this.writeChains.get(sessionId) === settled) this.writeChains.delete(sessionId);
17055
+ });
17056
+ return next;
17057
+ };
17937
17058
  sessionPath = (sessionId) => {
17938
17059
  return join(this.journalDir, `${safeNcpSessionFilename(sessionId.replace(/:/g, "_"))}.jsonl`);
17939
17060
  };
@@ -23769,6 +22890,6 @@ function resolveLegacyEventType(message) {
23769
22890
  return `message.${role || "other"}`;
23770
22891
  }
23771
22892
  //#endregion
23772
- export { AUTOMATIC_UPDATE_CHECK_INTERVAL_MS, AccessManager, AgentManager, AgentRunClient, AppDataError, AppDataManager, AppPackageError, AppPackageManager, AutomationManager, BuiltinNarpRuntimeProviderService, CONTEXT_COMPACTION_CONTINUATION_TEXT, CONTEXT_COMPACTION_PART_START, CONTEXT_COMPACTION_PROJECTION_KIND, CONTEXT_COMPACTION_PROJECTION_METADATA_KEY, CONTEXT_COMPACTION_SYSTEM_PREAMBLE, CONTEXT_COMPACTION_TIMELINE_KIND, CapabilityGrantLegacyMigrationService, CapabilityGrantManager, CapabilityGrantStore, ChannelManager, CommandRegistry, ConfigManager, ContextCompactionJournalRecoveryService, ContextCompactionPreflightService, Contribution, DEFAULT_AGENT_RUNTIME_ENTRY_ID, DEFAULT_SERVICE_ACTION_RISK, DESKTOP_HOST_ACCESS, DESKTOP_HOST_PROTOCOL_VERSION, DesktopHostCapabilityManager, DesktopNodeReplService, DesktopSessionStateService, EventBus, ExtensionManager, FeatureControlsService, GatewayInboundProcessor, InboxDeliveryError, InboxDeliveryManager, Ingress, LlmProviderManager, LlmUsageManager, LlmUsageStore, LocalAgentProfileStore, LocalConfigStore, LocalProduct, LocalWorkspaceStore, MAX_INBOX_DELIVERY_CONTENT_LENGTH, McpManager, McpServiceAppRuntimeService, NARP_HTTP_RUNTIME_KIND, NARP_STDIO_RUNTIME_KIND, NEXTCLAW_TIMELINE_KIND_METADATA_KEY, NcpAgentSessionJournalStore, NextclawHarness, NextclawHarnessError, NextclawKernel, NodePlatform, ObservationManager, PANEL_APP_AGENT_CAPABILITIES, PORTABLE_RUNTIME_ACCEPTANCE_CONTRACT, PORTABLE_RUNTIME_ACCEPTANCE_CONTRACT_FINGERPRINT, PORTABLE_RUNTIME_ACCEPTANCE_LOCALES, PORTABLE_RUNTIME_ACCEPTANCE_PLATFORMS, PORTABLE_RUNTIME_ACCEPTANCE_PRESENTATION, PORTABLE_RUNTIME_ACCEPTANCE_REFERENCE_APP_ID, PROJECT_TEMPLATE_IDS, PROJECT_WORK_ATTENTION_VALUES, PROJECT_WORK_STATE_CATEGORIES, PROVIDER_MODEL_CATALOG_REFRESH_INTERVAL_MS, PanelAppAssetTokenService, PanelAppError, PanelAppManager, PlannedRestartRecoveryManager, PortableRuntimeAcceptanceIdentityService, PortableRuntimeAcceptanceManager, PreferenceError, PreferenceManager, ProjectError, ProjectManager, ProjectMaterialService, ProjectWorkError, ProjectWorkManager, ProviderManagerNcpLLMApi, ProviderModelCatalogManager, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV, RUNTIME_INSTANCE_DISTRIBUTION_ENV, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV, SERVICE_APP_MANIFEST_FILE_NAME, ServiceAppAiCapabilityService, ServiceAppError, ServiceAppJobJournalService, ServiceAppManager, ServiceAppResidentEventInboxService, ServiceAppRuntimeService, SessionContextCompactionError, SessionContextCompactionManager, SessionEventReplayer, SessionManager, SessionMessageCursorError, SessionRequestManager, SessionSettingsError, SkillManager, SystemObjectReferenceError, SystemObjectReferenceManager, USER_QUESTION_EXTENSION_TYPE, UnavailableDesktopHost, UpdateManifestReader, UserQuestionError, UserQuestionManager, VerificationRecordService, appendCurrentTimeContextTail, applyNcpAgentRunLifecycleEvent, assertObservationJsonValue, assertObservationPredicate, assertSessionJournalTailComplete, buildAgentRunSendPayload, buildContextCompactionModelProjection, buildContextCompactionTimelineNcpMessage, buildLlmUsageSummary, buildLocalizedTextMap, buildNextclawNcpRunContext, buildObservationEventModelMessage, buildServiceActionId, buildSessionRequestCompletionMessage, capabilityGrantCovers, compactSessionJournal, composeAgentToolCatalog, createAgentRuntimeSessionRequestDispatcher, createAgentRuntimeSessionRequestSourceNotifier, createAssetTools, createCapabilityDeclarationFingerprint, createContextCompactionMessageId, createContextWindowSignature, createCronJobSystemObjectProvider, createDesktopHostError, createInboxDeliverySystemObjectProvider, createLlmUsageRecord, createNcpAgentSessionSummary, createPanelAppAgentGrantRequest, createPanelAppClientGrantRequest, createQuestionMessage, createQuestionResolutionMessage, createServiceActionGrantRequest, createServiceAppAgentSlotGrantRequest, createServiceAppModelSlotGrantRequest, createShowContentTools, createTypedKey, createWorkspaceByteTools, describeAgentRuntimeSessionTypes, dispatchAgentRuntimeSessionRequest, dispatchChannelReplyRoute, dispatchPromptOverNcp, dispatchPromptOverNcpResult, evaluateObservationEventAdmission, evaluatePortableRuntimeAcceptance, evaluatePortableRuntimeAcceptanceArtifact, eventKeys, getAutomaticUpdateCheckDelay, getCapabilityGrantKey, getServiceActionName, getServiceAppManifestPath, getUiContentParamsBootstrapScript, getUnsignedUpdateManifest, hasLlmUsageTelemetry, ingressKeys, injectUiContentParamsBootstrap, isAppDataError, isAppPackageError, isContextCompactionProjectionMessage, isContextCompactionTimelineMessage, isContextWindowSnapshot, isInboxDeliveryError, isPanelAppAgentCapability, isPanelAppError, isPreferenceError, isProjectError, isProjectWorkError, isReplyCapableChannel, isServiceAppError, isSessionContextCompactionError, isSessionMessageCursorError, isSessionSettingsError, isSystemObjectReferenceError, listExtensionChannelIds, listServiceAppManifestActions, matchesCapabilityGrantFilter, matchesObservationPredicate, mergeServiceAppRuntimeActions, normalizeAgentRuntimeSessionTypeIcon, normalizeCapabilityGrantRequest, normalizeLlmUsageModel, normalizeOptionalString, normalizePortableRuntimeEnvironment, parseObservationDuration, parsePortableRuntimeAcceptanceEvidenceArtifact, parseServiceAppManifest, parseSkillFrontmatter, presentPortableRuntimeAcceptanceDefinition, projectUserQuestions, readContextCompactionCheckpoint, readContextWindowEventSessionId, readJsonPointer, readLatestContextCompactionCheckpoint, readLearningLoopRuntimeConfig, readMetadataModel, readMetadataThinking, readServiceActionTargetId, readServiceAppManifest, readServiceAppSlotTarget, recoverSessionJournalMaintenance, renderAgentBootstrapContext, renderAgentSafetyContext, renderSystemExecutionPolicy, resolveAgentRuntimeEntries, resolveAutomaticUpdateCheckIntervalMs, resolveChannelReplyRoute, resolveEffectiveModel, resolveLegacyEventType, resolvePortableRuntimeAcceptanceLocale, resolveRuntimeInstanceSnapshot, resolveSessionChannelContext, restoreSessionJournalBackup, runGatewayInboundLoop, sanitizeLlmUsage, serializeModelInputTail, serializeUnsignedUpdateManifest, shouldRefreshContextWindowDuringStream, shouldRefreshContextWindowImmediately, startPromptOverNcpExecution, stripSkillFrontmatter, syncSessionThinkingPreference, toBoundedJson, toNcpMessages, truncateContextText, waitForAgentRuntimeSessionReply };
22893
+ export { AUTOMATIC_UPDATE_CHECK_INTERVAL_MS, AccessManager, AgentManager, AgentRunClient, AppDataError, AppDataManager, AppPackageError, AppPackageManager, AutomationManager, BuiltinNarpRuntimeProviderService, CONTEXT_COMPACTION_CONTINUATION_TEXT, CONTEXT_COMPACTION_PART_START, CONTEXT_COMPACTION_PROJECTION_KIND, CONTEXT_COMPACTION_PROJECTION_METADATA_KEY, CONTEXT_COMPACTION_RECOVERY_PREAMBLE, CONTEXT_COMPACTION_SYSTEM_PREAMBLE, CONTEXT_COMPACTION_TIMELINE_KIND, CapabilityGrantLegacyMigrationService, CapabilityGrantManager, CapabilityGrantStore, ChannelManager, CommandRegistry, ConfigManager, ContextCompactionJournalRecoveryService, ContextCompactionPreflightService, Contribution, DEFAULT_AGENT_RUNTIME_ENTRY_ID, DEFAULT_SERVICE_ACTION_RISK, DESKTOP_HOST_ACCESS, DESKTOP_HOST_PROTOCOL_VERSION, DesktopHostCapabilityManager, DesktopNodeReplService, DesktopSessionStateService, EventBus, ExtensionManager, FeatureControlsService, GatewayInboundProcessor, InboxDeliveryError, InboxDeliveryManager, Ingress, LlmProviderManager, LlmUsageManager, LlmUsageStore, LocalAgentProfileStore, LocalConfigStore, LocalProduct, LocalWorkspaceStore, MAX_INBOX_DELIVERY_CONTENT_LENGTH, McpManager, McpServiceAppRuntimeService, NARP_HTTP_RUNTIME_KIND, NARP_STDIO_RUNTIME_KIND, NEXTCLAW_TIMELINE_KIND_METADATA_KEY, NcpAgentSessionJournalStore, NextclawHarness, NextclawHarnessError, NextclawKernel, NodePlatform, ObservationManager, PANEL_APP_AGENT_CAPABILITIES, PORTABLE_RUNTIME_ACCEPTANCE_CONTRACT, PORTABLE_RUNTIME_ACCEPTANCE_CONTRACT_FINGERPRINT, PORTABLE_RUNTIME_ACCEPTANCE_LOCALES, PORTABLE_RUNTIME_ACCEPTANCE_PLATFORMS, PORTABLE_RUNTIME_ACCEPTANCE_PRESENTATION, PORTABLE_RUNTIME_ACCEPTANCE_REFERENCE_APP_ID, PROJECT_TEMPLATE_IDS, PROJECT_WORK_ATTENTION_VALUES, PROJECT_WORK_STATE_CATEGORIES, PROVIDER_MODEL_CATALOG_REFRESH_INTERVAL_MS, PanelAppAssetTokenService, PanelAppError, PanelAppManager, PlannedRestartRecoveryManager, PortableRuntimeAcceptanceIdentityService, PortableRuntimeAcceptanceManager, PreferenceError, PreferenceManager, ProjectError, ProjectManager, ProjectMaterialService, ProjectWorkError, ProjectWorkManager, ProviderManagerNcpLLMApi, ProviderModelCatalogManager, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV, RUNTIME_INSTANCE_DISTRIBUTION_ENV, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV, SERVICE_APP_MANIFEST_FILE_NAME, ServiceAppAiCapabilityService, ServiceAppError, ServiceAppJobJournalService, ServiceAppManager, ServiceAppResidentEventInboxService, ServiceAppRuntimeService, SessionContextCompactionError, SessionContextCompactionManager, SessionEventReplayer, SessionManager, SessionMessageCursorError, SessionMessagePreparationStore, SessionMessageSqlProjectionStore, SessionRequestManager, SessionSettingsError, SkillManager, SystemObjectReferenceError, SystemObjectReferenceManager, USER_QUESTION_EXTENSION_TYPE, UnavailableDesktopHost, UpdateManifestReader, UserQuestionError, UserQuestionManager, VerificationRecordService, appendCurrentTimeContextTail, applyNcpAgentRunLifecycleEvent, assertObservationJsonValue, assertObservationPredicate, assertSessionJournalTailComplete, buildAgentRunSendPayload, buildContextCompactionModelProjection, buildContextCompactionTimelineNcpMessage, buildLlmUsageSummary, buildLocalizedTextMap, buildNextclawNcpRunContext, buildObservationEventModelMessage, buildServiceActionId, buildSessionRequestCompletionMessage, capabilityGrantCovers, compactSessionJournal, composeAgentToolCatalog, createAgentRuntimeSessionRequestDispatcher, createAgentRuntimeSessionRequestSourceNotifier, createAssetTools, createCapabilityDeclarationFingerprint, createContextCompactionMessageId, createContextWindowSignature, createCronJobSystemObjectProvider, createDesktopHostError, createInboxDeliverySystemObjectProvider, createLlmUsageRecord, createNcpAgentSessionSummary, createPanelAppAgentGrantRequest, createPanelAppClientGrantRequest, createQuestionMessage, createQuestionResolutionMessage, createServiceActionGrantRequest, createServiceAppAgentSlotGrantRequest, createServiceAppModelSlotGrantRequest, createShowContentTools, createTypedKey, createWorkspaceByteTools, describeAgentRuntimeSessionTypes, dispatchAgentRuntimeSessionRequest, dispatchChannelReplyRoute, dispatchPromptOverNcp, dispatchPromptOverNcpResult, evaluateObservationEventAdmission, evaluatePortableRuntimeAcceptance, evaluatePortableRuntimeAcceptanceArtifact, eventKeys, getAutomaticUpdateCheckDelay, getCapabilityGrantKey, getServiceActionName, getServiceAppManifestPath, getUiContentParamsBootstrapScript, getUnsignedUpdateManifest, hasLlmUsageTelemetry, ingressKeys, injectUiContentParamsBootstrap, isAppDataError, isAppPackageError, isContextCompactionProjectionMessage, isContextCompactionTimelineMessage, isContextWindowSnapshot, isInboxDeliveryError, isPanelAppAgentCapability, isPanelAppError, isPreferenceError, isProjectError, isProjectWorkError, isReplyCapableChannel, isServiceAppError, isSessionContextCompactionError, isSessionMessageCursorError, isSessionSettingsError, isSystemObjectReferenceError, listExtensionChannelIds, listServiceAppManifestActions, matchesCapabilityGrantFilter, matchesObservationPredicate, mergeServiceAppRuntimeActions, normalizeAgentRuntimeSessionTypeIcon, normalizeCapabilityGrantRequest, normalizeLlmUsageModel, normalizeOptionalString, normalizePortableRuntimeEnvironment, parseObservationDuration, parsePortableRuntimeAcceptanceEvidenceArtifact, parseServiceAppManifest, parseSkillFrontmatter, presentPortableRuntimeAcceptanceDefinition, projectUserQuestions, readContextCompactionCheckpoint, readContextRecoveryState, readContextWindowEventSessionId, readJsonPointer, readLatestContextCompactionCheckpoint, readLearningLoopRuntimeConfig, readMetadataModel, readMetadataThinking, readServiceActionTargetId, readServiceAppManifest, readServiceAppSlotTarget, recoverSessionJournalMaintenance, recoverSessionJournalTornTail, renderAgentBootstrapContext, renderAgentSafetyContext, renderSystemExecutionPolicy, resolveAgentRuntimeEntries, resolveAutomaticUpdateCheckIntervalMs, resolveChannelReplyRoute, resolveEffectiveModel, resolveLegacyEventType, resolvePortableRuntimeAcceptanceLocale, resolveRuntimeInstanceSnapshot, resolveSessionChannelContext, restoreSessionJournalBackup, runGatewayInboundLoop, sanitizeLlmUsage, serializeModelInputTail, serializeUnsignedUpdateManifest, sessionJsonChunks, shouldRefreshContextWindowDuringStream, shouldRefreshContextWindowImmediately, startPromptOverNcpExecution, stripSkillFrontmatter, syncSessionThinkingPreference, toBoundedJson, toNcpMessages, truncateContextText, waitForAgentRuntimeSessionReply };
23773
22894
 
23774
22895
  //# sourceMappingURL=index.js.map