@nextclaw/kernel 0.19.6 → 0.19.7

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.
@@ -4398,6 +4398,53 @@ var SessionActivityPreviewEventService = class {
4398
4398
  };
4399
4399
  };
4400
4400
  //#endregion
4401
+ //#region src/utils/session-journal-error.utils.ts
4402
+ const SESSION_JOURNAL_FAILURE_SOURCE = "session-event-coordinator:journal-failure";
4403
+ const SESSION_JOURNAL_WRITE_FAILED = "SESSION_JOURNAL_WRITE_FAILED";
4404
+ var SessionJournalWriteError = class extends Error {
4405
+ code = SESSION_JOURNAL_WRITE_FAILED;
4406
+ constructor(sessionId, cause) {
4407
+ const detail = cause instanceof Error ? cause.message : String(cause);
4408
+ const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
4409
+ super(`Session journal write failed for ${sessionId}; refusing further writes until recovery. The run was stopped to prevent unsaved work. Check storage access and restart NextClaw before retrying. Cause: ${code} ${detail}`, { cause });
4410
+ this.name = "SessionJournalWriteError";
4411
+ }
4412
+ };
4413
+ function isSessionJournalWriteError(error) {
4414
+ return error instanceof Error && "code" in error && error.code === "SESSION_JOURNAL_WRITE_FAILED";
4415
+ }
4416
+ /** Keep filesystem/JSON diagnostics without logging the failed user event or provider configuration. */
4417
+ function formatSessionJournalError(error) {
4418
+ const causes = [];
4419
+ const seen = /* @__PURE__ */ new Set();
4420
+ let current = error;
4421
+ while (current !== void 0 && causes.length < 8 && !seen.has(current)) {
4422
+ seen.add(current);
4423
+ if (!current || typeof current !== "object") {
4424
+ causes.push({ message: String(current).slice(0, 2048) });
4425
+ break;
4426
+ }
4427
+ const record = current;
4428
+ const detail = {};
4429
+ for (const key of [
4430
+ "name",
4431
+ "message",
4432
+ "code",
4433
+ "errno",
4434
+ "syscall",
4435
+ "path",
4436
+ "stack"
4437
+ ]) {
4438
+ const value = record[key];
4439
+ if (typeof value === "string") detail[key] = value.slice(0, key === "stack" ? 8192 : 2048);
4440
+ else if (typeof value === "number") detail[key] = value;
4441
+ }
4442
+ causes.push(detail);
4443
+ current = record.cause;
4444
+ }
4445
+ return JSON.stringify(causes);
4446
+ }
4447
+ //#endregion
4401
4448
  //#region src/services/session-event-ingestion.service.ts
4402
4449
  const SESSION_METADATA_PATCH_RUN_METADATA_KIND = "session_metadata_patch";
4403
4450
  const PERSISTED_SESSION_EVENT_SOURCE = "session-event-coordinator:persisted";
@@ -4426,11 +4473,8 @@ var SessionEventIngestionService = class {
4426
4473
  });
4427
4474
  }
4428
4475
  handleEvent = (event, envelope) => {
4429
- if (envelope.source === "session-event-coordinator:persisted") return;
4430
- this.ingestEvent(event).catch((error) => {
4431
- const sessionId = readEventSessionId(event);
4432
- if (sessionId) this.options.onError(sessionId, error);
4433
- });
4476
+ if (envelope.source === "session-event-coordinator:persisted" || envelope.source === "session-event-coordinator:journal-failure") return;
4477
+ this.ingestEvent(event).catch(() => void 0);
4434
4478
  };
4435
4479
  start = async () => {
4436
4480
  if (this.cleanup) return;
@@ -4453,7 +4497,10 @@ var SessionEventIngestionService = class {
4453
4497
  ingestEvent = (event, signal) => {
4454
4498
  const existing = this.acceptedEvents.get(event);
4455
4499
  if (existing) return existing;
4456
- const operation = this.ingestEventOnce(event, signal);
4500
+ const operation = this.ingestEventOnce(event, signal).catch((error) => {
4501
+ const sessionId = readEventSessionId(event);
4502
+ throw sessionId ? this.recordFailure(sessionId, error, event) : error;
4503
+ });
4457
4504
  this.acceptedEvents.set(event, operation);
4458
4505
  operation.catch(() => {
4459
4506
  this.acceptedEvents.delete(event);
@@ -4481,7 +4528,7 @@ var SessionEventIngestionService = class {
4481
4528
  return;
4482
4529
  }
4483
4530
  const timer = setTimeout(() => {
4484
- this.flushPendingDelta(sessionId).catch((error) => this.options.onError(sessionId, error));
4531
+ this.flushPendingDelta(sessionId).catch(() => void 0);
4485
4532
  }, 100);
4486
4533
  timer.unref?.();
4487
4534
  this.pendingDeltas.set(sessionId, {
@@ -4501,7 +4548,7 @@ var SessionEventIngestionService = class {
4501
4548
  flush = async () => {
4502
4549
  for (const sessionId of this.pendingDeltas.keys()) this.flushPendingDelta(sessionId);
4503
4550
  await Promise.all([...this.chains.values()]);
4504
- if (this.failedWrites.size > 0) throw new Error("Cannot prepare a restart after a session journal write failed.");
4551
+ if (this.failedWrites.size > 0) throw new Error("Cannot prepare a restart after a session journal write failed.", { cause: this.failedWrites.values().next().value });
4505
4552
  };
4506
4553
  dispose = () => {
4507
4554
  this.cleanup?.();
@@ -4518,21 +4565,31 @@ var SessionEventIngestionService = class {
4518
4565
  clearTimeout(pending.timer);
4519
4566
  this.pendingDeltas.delete(sessionId);
4520
4567
  const next = this.enqueue(sessionId, pending.event);
4521
- next.catch((error) => this.options.onError(sessionId, error));
4568
+ next.catch(() => void 0);
4522
4569
  return next;
4523
4570
  };
4524
4571
  enqueue = (sessionId, event, signal) => {
4525
4572
  const next = (this.chains.get(sessionId) ?? Promise.resolve()).then(() => {
4526
4573
  this.throwIfFailed(sessionId);
4527
4574
  return this.handleDurableEvent(sessionId, event, signal);
4575
+ }).catch((error) => {
4576
+ throw this.recordFailure(sessionId, error, event);
4528
4577
  });
4529
- this.chains.set(sessionId, next.catch((error) => {
4530
- if (!(error && typeof error === "object" && "journalCommitRejected" in error && error.journalCommitRejected === true)) this.failedWrites.set(sessionId, error);
4531
- }));
4578
+ this.chains.set(sessionId, next.catch(() => void 0));
4532
4579
  return next;
4533
4580
  };
4581
+ recordFailure = (sessionId, error, event) => {
4582
+ if (error && typeof error === "object" && "journalCommitRejected" in error && error.journalCommitRejected === true && !("journalWriteFailed" in error && error.journalWriteFailed === true)) return error;
4583
+ const existing = this.failedWrites.get(sessionId);
4584
+ if (existing) return existing;
4585
+ const failure = new SessionJournalWriteError(sessionId, error);
4586
+ this.failedWrites.set(sessionId, failure);
4587
+ this.options.onError(sessionId, failure, event);
4588
+ return failure;
4589
+ };
4534
4590
  throwIfFailed = (sessionId) => {
4535
- if (this.failedWrites.has(sessionId)) throw new Error(`Session journal write failed for ${sessionId}; refusing further writes until recovery.`, { cause: this.failedWrites.get(sessionId) });
4591
+ const failure = this.failedWrites.get(sessionId);
4592
+ if (failure) throw failure;
4536
4593
  };
4537
4594
  handleDurableEvent = async (sessionId, event, signal) => {
4538
4595
  const preview = this.activityPreview.projectEvent(event, (/* @__PURE__ */ new Date()).toISOString());
@@ -4563,9 +4620,27 @@ var SessionEventCoordinatorService = class {
4563
4620
  appendSessionEvent: options.appendSessionEvent,
4564
4621
  getSessionRecord: options.getSessionRecord,
4565
4622
  listUnfinishedRuns: options.listUnfinishedRuns,
4566
- onError: (sessionId, error) => {
4567
- const detail = error instanceof Error ? error.stack ?? error.message : String(error);
4623
+ onError: (sessionId, error, event) => {
4624
+ const detail = formatSessionJournalError(error);
4568
4625
  console.error(`[session-manager] failed to handle ncp event for ${sessionId}: ${detail}`);
4626
+ const payload = event && "payload" in event ? event.payload : void 0;
4627
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
4628
+ options.eventBus.emit(eventKeys.ncpEvent, {
4629
+ type: NcpEventType.RunError,
4630
+ occurredAt: endedAt,
4631
+ payload: {
4632
+ sessionId,
4633
+ endedAt,
4634
+ interrupted: true,
4635
+ ...payload && "messageId" in payload ? { messageId: payload.messageId } : {},
4636
+ ...payload && "runId" in payload ? { runId: payload.runId } : {},
4637
+ ...payload && "correlationId" in payload ? { correlationId: payload.correlationId } : {},
4638
+ error: error instanceof Error ? error.message : String(error)
4639
+ }
4640
+ }, {
4641
+ emittedAt: endedAt,
4642
+ source: SESSION_JOURNAL_FAILURE_SOURCE
4643
+ });
4569
4644
  },
4570
4645
  subscribe: (handler) => options.eventBus.on(eventKeys.ncpEvent, handler),
4571
4646
  updateSessionMetadata: options.updateSessionMetadata
@@ -6761,6 +6836,10 @@ var AgentRuntimeRunObserverService = class {
6761
6836
  start = (params) => {
6762
6837
  const { options, parentCorrelationId, requestRunStartedAt, runtime, spec } = params;
6763
6838
  const { session, sessionRun } = options;
6839
+ const stopWatchingStorage = this.options.eventBus.on(eventKeys.ncpEvent, (event, envelope) => {
6840
+ if (envelope.source !== "session-event-coordinator:journal-failure" || event.type !== NcpEventType.RunError || event.payload.sessionId !== session.sessionId) return;
6841
+ sessionRun.failPersistence(event.payload.error ?? "Session history could not be saved.");
6842
+ });
6764
6843
  let messageCompletedSeen = false;
6765
6844
  const initialMessageIds = new Set(options.initialMessages.map(({ id }) => id));
6766
6845
  let executionMetadataSeen = false;
@@ -6809,6 +6888,11 @@ var AgentRuntimeRunObserverService = class {
6809
6888
  failureReason = classification.reasonCode;
6810
6889
  failureProviderCode = classification.providerCode;
6811
6890
  failureFacts = classification.facts;
6891
+ if (isSessionJournalWriteError(error)) {
6892
+ failureReason = "session_journal_write_failed";
6893
+ sessionRun.failPersistence(error);
6894
+ return;
6895
+ }
6812
6896
  if (!executionMetadataSeen) {
6813
6897
  const metadataEvent = createUnavailableAiExecutionMetadataEvent({
6814
6898
  spec,
@@ -6826,19 +6910,24 @@ var AgentRuntimeRunObserverService = class {
6826
6910
  });
6827
6911
  await sessionRun.applyEvents([event]);
6828
6912
  this.publishNcpEvent(event);
6829
- })), { defaultValue: void 0 }).finally(() => this.finish({
6830
- failureFacts,
6831
- failureOutcome,
6832
- failureProviderCode,
6833
- failureReason,
6834
- onSettled: params.onSettled,
6835
- parentCorrelationId,
6836
- runStartedAt,
6837
- runtimeCancelled,
6838
- runtimeFailed,
6839
- spec,
6840
- options
6841
- }));
6913
+ })), { defaultValue: void 0 }).finally(() => {
6914
+ stopWatchingStorage();
6915
+ return this.finish({
6916
+ failureFacts,
6917
+ failureOutcome,
6918
+ failureProviderCode,
6919
+ failureReason,
6920
+ onSettled: params.onSettled,
6921
+ parentCorrelationId,
6922
+ runStartedAt,
6923
+ runtimeCancelled,
6924
+ runtimeFailed,
6925
+ spec,
6926
+ options
6927
+ });
6928
+ }).catch((error) => {
6929
+ if (!isSessionJournalWriteError(error)) console.error("[agent-run-request] failed to settle runtime events", error);
6930
+ });
6842
6931
  };
6843
6932
  finish = async (input) => {
6844
6933
  const { session, sessionRun } = input.options;
@@ -6884,7 +6973,7 @@ var AgentRuntimeRunObserverService = class {
6884
6973
  publishNcpEvent = (event) => {
6885
6974
  this.options.eventBus.emit(eventKeys.ncpEvent, event, {
6886
6975
  emittedAt: (/* @__PURE__ */ new Date()).toISOString(),
6887
- source: "agent-run-request"
6976
+ source: PERSISTED_SESSION_EVENT_SOURCE
6888
6977
  });
6889
6978
  };
6890
6979
  };
@@ -7165,6 +7254,10 @@ var AgentRunRequestManager = class {
7165
7254
  };
7166
7255
  publishRunStartupFailure = async (params) => {
7167
7256
  const { error, requestRunStartedAt, sessionRun, spec } = params;
7257
+ if (isSessionJournalWriteError(error)) {
7258
+ sessionRun.failPersistence(error);
7259
+ return;
7260
+ }
7168
7261
  const metadataEvent = createUnavailableAiExecutionMetadataEvent({
7169
7262
  spec,
7170
7263
  sessionId: sessionRun.sessionId
@@ -7209,7 +7302,7 @@ var AgentRunRequestManager = class {
7209
7302
  publishNcpEvent = (event) => {
7210
7303
  this.eventBus.emit(eventKeys.ncpEvent, event, {
7211
7304
  emittedAt: (/* @__PURE__ */ new Date()).toISOString(),
7212
- source: "agent-run-request"
7305
+ source: PERSISTED_SESSION_EVENT_SOURCE
7213
7306
  });
7214
7307
  };
7215
7308
  getOrCreateSessionForRequest = async (request) => {
@@ -7540,7 +7633,7 @@ function recordProductActivityBestEffort(sink, signal) {
7540
7633
  } catch {}
7541
7634
  }
7542
7635
  //#endregion
7543
- //#region src/managers/session-run.manager.ts
7636
+ //#region src/managers/session-pending-inputs.manager.ts
7544
7637
  /** Single owner for inputs waiting for either the next run or the next safe step. */
7545
7638
  var SessionPendingInputs = class {
7546
7639
  nextRun = [];
@@ -7628,6 +7721,8 @@ var SessionPendingInputs = class {
7628
7721
  intendedRunId
7629
7722
  });
7630
7723
  };
7724
+ //#endregion
7725
+ //#region src/managers/session-run.manager.ts
7631
7726
  function isConversationStateEvent(event) {
7632
7727
  return event.type !== NcpEventType.ContextWindowUpdated;
7633
7728
  }
@@ -7647,10 +7742,11 @@ var SessionRun = class {
7647
7742
  activeProductActivitySource = null;
7648
7743
  eventChain = Promise.resolve();
7649
7744
  windowGrowthBytes = 0;
7650
- constructor(seed, stateManager = new DefaultNcpAgentConversationStateManager(), productActivitySink, persistCompaction) {
7745
+ persistenceFailure = null;
7746
+ constructor(seed, stateManager = new DefaultNcpAgentConversationStateManager(), productActivitySink, persistEvent) {
7651
7747
  this.stateManager = stateManager;
7652
7748
  this.productActivitySink = productActivitySink;
7653
- this.persistCompaction = persistCompaction;
7749
+ this.persistEvent = persistEvent;
7654
7750
  this.sessionId = seed.sessionId;
7655
7751
  this.stateManager.hydrate({
7656
7752
  sessionId: seed.sessionId,
@@ -7669,9 +7765,12 @@ var SessionRun = class {
7669
7765
  return operation;
7670
7766
  };
7671
7767
  applyEventsNow = async (events, signal) => {
7672
- for (const event of events) if (event.type === NcpEventType.MessageSent && event.payload.message.metadata?.nextclaw_timeline_kind === "context_compaction") {
7673
- const status = event.payload.message.metadata.checkpoint?.status;
7674
- if (status === "compressed" || status === "failed" || status === "cancelled") await this.persistCompaction?.(event, signal);
7768
+ if (this.persistenceFailure) throw this.persistenceFailure;
7769
+ try {
7770
+ for (const event of events) await this.persistEvent?.(event, signal);
7771
+ } catch (error) {
7772
+ if (isSessionJournalWriteError(error)) this.failPersistence(error);
7773
+ throw error;
7675
7774
  }
7676
7775
  this.applyRunEvents(events);
7677
7776
  let archived = false;
@@ -7827,6 +7926,7 @@ var SessionRun = class {
7827
7926
  };
7828
7927
  };
7829
7928
  enqueueRequest = (request, session) => {
7929
+ if (this.persistenceFailure) throw this.persistenceFailure;
7830
7930
  const wasBusy = this.isBusy();
7831
7931
  const queuedRequest = {
7832
7932
  id: `queued-input-${crypto.randomUUID()}`,
@@ -7861,6 +7961,7 @@ var SessionRun = class {
7861
7961
  };
7862
7962
  getActiveRunId = () => this.activeRunId;
7863
7963
  beginNextRun = () => {
7964
+ if (this.persistenceFailure) return null;
7864
7965
  if (this.activeRunId) return null;
7865
7966
  const wasBusy = this.isBusy();
7866
7967
  const queuedRequest = this.pendingInputs.shiftNextRun();
@@ -7886,6 +7987,17 @@ var SessionRun = class {
7886
7987
  this.activeRunController.abort(reason);
7887
7988
  return true;
7888
7989
  };
7990
+ /** A storage fault terminates control state without inventing a durable history event. */
7991
+ failPersistence = (error) => {
7992
+ const wasBusy = this.isBusy();
7993
+ this.persistenceFailure ??= typeof error === "string" ? Object.assign(new Error(error), { code: SESSION_JOURNAL_WRITE_FAILED }) : error;
7994
+ this.pendingInputs.clear();
7995
+ this.activeRunController?.abort(this.persistenceFailure);
7996
+ this.activeRunController = null;
7997
+ this.activeRunId = null;
7998
+ this.activeProductActivitySource = null;
7999
+ this.emitStatusChangeIfNeeded(wasBusy);
8000
+ };
7889
8001
  isRunning = () => this.activeRunId !== null;
7890
8002
  isBusy = () => this.isRunning() || this.pendingInputs.hasNextRun;
7891
8003
  dispose = () => {
@@ -9349,4 +9461,4 @@ var NextclawHarness = class {
9349
9461
  //#endregion
9350
9462
  export { SessionEventProjectionStore as $, ContextProviderRunContextService as A, normalizeOptionalString$2 as B, ToolProviderRunContextService as C, readProjectId as D, createAgentToolRunTriggerInput as E, CurrentSessionContextProvider as F, syncSessionThinkingPreference as G, readMetadataThinking as H, AgentBootstrapContextProvider as I, describeAgentRuntimeSessionTypes as J, appendCurrentTimeContextTail as K, renderAgentBootstrapContext as L, ExecutionPolicyContextProvider as M, renderAgentSafetyContext as N, readProjectRoot as O, renderSystemExecutionPolicy as P, SessionMessageSqlProjectionStore as Q, truncateContextText as R, AgentManager as S, attachSourceToolCall as T, resolveEffectiveModel as U, readMetadataModel as V, resolveSessionChannelContext as W, resolveAgentRuntimeEntries as X, normalizeAgentRuntimeSessionTypeIcon as Y, SessionMessagePreparationStore as Z, createQuestionMessage as _, CommandRegistry as _t, dispatchAgentRuntimeSessionRequest as a, applyNcpAgentRunLifecycleEvent as at, SessionManager as b, Contribution$1 as c, assertObservationPredicate as ct, dispatchPromptOverNcpResult as d, matchesObservationPredicate as dt, sessionJsonChunks as et, startPromptOverNcpExecution as f, parseObservationDuration as ft, USER_QUESTION_EXTENSION_TYPE as g, AgentRunClient as gt, UserQuestionManager as h, DEFAULT_AGENT_RUNTIME_ENTRY_ID as ht, createAgentRuntimeSessionRequestSourceNotifier as i, isSessionSettingsError as it, WorkspaceMemoryContextProvider as j, buildRunMetadata as k, NextclawHarnessError as l, buildObservationEventModelMessage as lt, UserQuestionError as m, toBoundedJson as mt, buildSessionRequestCompletionMessage as n, SessionSettingsError as nt, waitForAgentRuntimeSessionReply as o, isNcpAgentRunLifecycleEvent as ot, buildAgentRunSendPayload as p, readJsonPointer as pt, serializeModelInputTail as q, createAgentRuntimeSessionRequestDispatcher as r, isSessionMessageCursorError as rt, SessionRequestManager as s, assertObservationJsonValue as st, NextclawHarness as t, SessionMessageCursorError as tt, dispatchPromptOverNcp as u, evaluateObservationEventAdmission as ut, createQuestionResolutionMessage as v, createShowContentTools as w, createWorkspaceByteTools as x, projectUserQuestions as y, buildNextclawNcpRunContext as z };
9351
9463
 
9352
- //# sourceMappingURL=nextclaw-harness.manager-ajpoljL-.js.map
9464
+ //# sourceMappingURL=nextclaw-harness.manager-Bv3YnpO5.js.map