@nextclaw/kernel 0.19.6 → 0.19.8

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.
@@ -2091,6 +2091,53 @@ var SessionMessagePreparationStore = class SessionMessagePreparationStore {
2091
2091
  };
2092
2092
  };
2093
2093
  //#endregion
2094
+ //#region src/utils/session-journal-error.utils.ts
2095
+ const SESSION_JOURNAL_FAILURE_SOURCE = "session-event-coordinator:journal-failure";
2096
+ const SESSION_JOURNAL_WRITE_FAILED = "SESSION_JOURNAL_WRITE_FAILED";
2097
+ var SessionJournalWriteError = class extends Error {
2098
+ code = SESSION_JOURNAL_WRITE_FAILED;
2099
+ constructor(sessionId, cause) {
2100
+ const detail = cause instanceof Error ? cause.message : String(cause);
2101
+ const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
2102
+ super(`Session journal write failed for ${sessionId}; refusing further writes until recovery. The run was stopped to prevent unsaved work. Check storage access, then send again to recover this session. Pending inputs are retained while NextClaw stays open. Cause: ${code} ${detail}`, { cause });
2103
+ this.name = "SessionJournalWriteError";
2104
+ }
2105
+ };
2106
+ function isSessionJournalWriteError(error) {
2107
+ return error instanceof Error && "code" in error && error.code === "SESSION_JOURNAL_WRITE_FAILED";
2108
+ }
2109
+ /** Read only the transaction's scalar diagnostics; never copy the failed event. */
2110
+ function readSessionJournalFailureContext(error) {
2111
+ const seen = /* @__PURE__ */ new Set();
2112
+ let current = error;
2113
+ for (let depth = 0; current && typeof current === "object" && depth < 8 && !seen.has(current); depth++) {
2114
+ seen.add(current);
2115
+ const record = current;
2116
+ const context = record.sessionPersistence;
2117
+ if (context && typeof context === "object") {
2118
+ const detail = {};
2119
+ for (const key of [
2120
+ "operation",
2121
+ "stage",
2122
+ "path",
2123
+ "seq",
2124
+ "previousOffset",
2125
+ "journalOffset",
2126
+ "rollback",
2127
+ "journalCommitted",
2128
+ "metadataCommitted"
2129
+ ]) {
2130
+ const value = context[key];
2131
+ if (typeof value === "string") detail[key] = value.slice(0, 2048);
2132
+ else if (typeof value === "number" || typeof value === "boolean") detail[key] = value;
2133
+ }
2134
+ return detail;
2135
+ }
2136
+ current = record.cause;
2137
+ }
2138
+ return {};
2139
+ }
2140
+ //#endregion
2094
2141
  //#region src/features/runtime-registry/utils/agent-runtime-registry.utils.ts
2095
2142
  function normalizeIdentifier(value) {
2096
2143
  if (typeof value !== "string") return null;
@@ -4416,6 +4463,7 @@ var SessionEventIngestionService = class {
4416
4463
  activityPreview;
4417
4464
  chains = /* @__PURE__ */ new Map();
4418
4465
  failedWrites = /* @__PURE__ */ new Map();
4466
+ failedProjections = /* @__PURE__ */ new Set();
4419
4467
  pendingDeltas = /* @__PURE__ */ new Map();
4420
4468
  cleanup = null;
4421
4469
  constructor(options) {
@@ -4426,11 +4474,8 @@ var SessionEventIngestionService = class {
4426
4474
  });
4427
4475
  }
4428
4476
  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
- });
4477
+ if (envelope.source === "session-event-coordinator:persisted" || envelope.source === "session-event-coordinator:journal-failure") return;
4478
+ this.ingestEvent(event).catch(() => void 0);
4434
4479
  };
4435
4480
  start = async () => {
4436
4481
  if (this.cleanup) return;
@@ -4453,7 +4498,10 @@ var SessionEventIngestionService = class {
4453
4498
  ingestEvent = (event, signal) => {
4454
4499
  const existing = this.acceptedEvents.get(event);
4455
4500
  if (existing) return existing;
4456
- const operation = this.ingestEventOnce(event, signal);
4501
+ const operation = this.ingestEventOnce(event, signal).catch((error) => {
4502
+ const sessionId = readEventSessionId(event);
4503
+ throw sessionId ? this.recordFailure(sessionId, error, event) : error;
4504
+ });
4457
4505
  this.acceptedEvents.set(event, operation);
4458
4506
  operation.catch(() => {
4459
4507
  this.acceptedEvents.delete(event);
@@ -4481,7 +4529,7 @@ var SessionEventIngestionService = class {
4481
4529
  return;
4482
4530
  }
4483
4531
  const timer = setTimeout(() => {
4484
- this.flushPendingDelta(sessionId).catch((error) => this.options.onError(sessionId, error));
4532
+ this.flushPendingDelta(sessionId).catch(() => void 0);
4485
4533
  }, 100);
4486
4534
  timer.unref?.();
4487
4535
  this.pendingDeltas.set(sessionId, {
@@ -4498,10 +4546,25 @@ var SessionEventIngestionService = class {
4498
4546
  await this.chains.get(sessionId);
4499
4547
  this.throwIfFailed(sessionId);
4500
4548
  };
4549
+ recoverSession = async (sessionId, restore) => {
4550
+ await this.chains.get(sessionId);
4551
+ try {
4552
+ const result = await restore();
4553
+ this.failedWrites.delete(sessionId);
4554
+ return result;
4555
+ } catch (error) {
4556
+ console.error("Session storage recovery failed", {
4557
+ event: "session.persistence.recovery_failed",
4558
+ sessionId,
4559
+ ...readSessionJournalFailureContext(error)
4560
+ }, error);
4561
+ throw error;
4562
+ }
4563
+ };
4501
4564
  flush = async () => {
4502
4565
  for (const sessionId of this.pendingDeltas.keys()) this.flushPendingDelta(sessionId);
4503
4566
  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.");
4567
+ 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
4568
  };
4506
4569
  dispose = () => {
4507
4570
  this.cleanup?.();
@@ -4510,6 +4573,7 @@ var SessionEventIngestionService = class {
4510
4573
  this.pendingDeltas.clear();
4511
4574
  this.chains.clear();
4512
4575
  this.failedWrites.clear();
4576
+ this.failedProjections.clear();
4513
4577
  this.activityPreview.clear();
4514
4578
  };
4515
4579
  flushPendingDelta = (sessionId) => {
@@ -4518,24 +4582,33 @@ var SessionEventIngestionService = class {
4518
4582
  clearTimeout(pending.timer);
4519
4583
  this.pendingDeltas.delete(sessionId);
4520
4584
  const next = this.enqueue(sessionId, pending.event);
4521
- next.catch((error) => this.options.onError(sessionId, error));
4585
+ next.catch(() => void 0);
4522
4586
  return next;
4523
4587
  };
4524
4588
  enqueue = (sessionId, event, signal) => {
4525
4589
  const next = (this.chains.get(sessionId) ?? Promise.resolve()).then(() => {
4526
4590
  this.throwIfFailed(sessionId);
4527
4591
  return this.handleDurableEvent(sessionId, event, signal);
4592
+ }).catch((error) => {
4593
+ throw this.recordFailure(sessionId, error, event);
4528
4594
  });
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
- }));
4595
+ this.chains.set(sessionId, next.catch(() => void 0));
4532
4596
  return next;
4533
4597
  };
4598
+ recordFailure = (sessionId, error, event) => {
4599
+ if (error && typeof error === "object" && "journalCommitRejected" in error && error.journalCommitRejected === true && !("journalWriteFailed" in error && error.journalWriteFailed === true)) return error;
4600
+ const existing = this.failedWrites.get(sessionId);
4601
+ if (existing) return existing;
4602
+ const failure = new SessionJournalWriteError(sessionId, error);
4603
+ this.failedWrites.set(sessionId, failure);
4604
+ this.options.onError(sessionId, failure, event);
4605
+ return failure;
4606
+ };
4534
4607
  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) });
4608
+ const failure = this.failedWrites.get(sessionId);
4609
+ if (failure) throw failure;
4536
4610
  };
4537
4611
  handleDurableEvent = async (sessionId, event, signal) => {
4538
- const preview = this.activityPreview.projectEvent(event, (/* @__PURE__ */ new Date()).toISOString());
4539
4612
  const metadataPatch = readRuntimeSessionMetadataPatch(event);
4540
4613
  if (metadataPatch) {
4541
4614
  await this.options.updateSessionMetadata(sessionId, metadataPatch);
@@ -4546,11 +4619,33 @@ var SessionEventIngestionService = class {
4546
4619
  sessionId,
4547
4620
  signal
4548
4621
  });
4549
- if (event.type === NcpEventType.MessageSent) {
4550
- const checkpoint = readContextCompactionCheckpoint(event.payload.message);
4551
- if (checkpoint) await this.options.updateSessionMetadata(sessionId, { [CONTEXT_COMPACTION_METADATA_KEY]: checkpoint });
4622
+ let operation = "checkpoint-metadata";
4623
+ try {
4624
+ if (event.type === NcpEventType.MessageSent) {
4625
+ const checkpoint = readContextCompactionCheckpoint(event.payload.message);
4626
+ if (checkpoint) await this.options.updateSessionMetadata(sessionId, { [CONTEXT_COMPACTION_METADATA_KEY]: checkpoint });
4627
+ }
4628
+ this.failedProjections.delete(`${sessionId}:${operation}`);
4629
+ operation = "activity-preview";
4630
+ const preview = this.activityPreview.projectEvent(event, (/* @__PURE__ */ new Date()).toISOString());
4631
+ if (preview) {
4632
+ await this.activityPreview.updatePreview(preview);
4633
+ this.failedProjections.delete(`${sessionId}:${operation}`);
4634
+ }
4635
+ } catch (error) {
4636
+ const key = `${sessionId}:${operation}`;
4637
+ if (this.failedProjections.has(key)) return;
4638
+ this.failedProjections.add(key);
4639
+ console.warn("Session projection failed after the event was saved", {
4640
+ event: "session.persistence.projection_failed",
4641
+ operation,
4642
+ projection: operation,
4643
+ sessionId,
4644
+ eventType: event.type,
4645
+ journalCommitted: true,
4646
+ ...readSessionJournalFailureContext(error)
4647
+ }, error);
4552
4648
  }
4553
- if (preview) await this.activityPreview.updatePreview(preview);
4554
4649
  };
4555
4650
  };
4556
4651
  //#endregion
@@ -4563,9 +4658,41 @@ var SessionEventCoordinatorService = class {
4563
4658
  appendSessionEvent: options.appendSessionEvent,
4564
4659
  getSessionRecord: options.getSessionRecord,
4565
4660
  listUnfinishedRuns: options.listUnfinishedRuns,
4566
- onError: (sessionId, error) => {
4567
- const detail = error instanceof Error ? error.stack ?? error.message : String(error);
4568
- console.error(`[session-manager] failed to handle ncp event for ${sessionId}: ${detail}`);
4661
+ onError: (sessionId, error, event) => {
4662
+ const payload = event && "payload" in event ? event.payload : void 0;
4663
+ const detail = error instanceof Error ? error.message : String(error);
4664
+ console.error(`[session-manager] failed to handle ncp event for ${sessionId}: ${detail}`, {
4665
+ event: "session.persistence.failed",
4666
+ outcome: "failed",
4667
+ sessionId,
4668
+ eventType: event?.type,
4669
+ operation: event?.type === NcpEventType.RunMetadata ? "metadata.update" : "event.ingest",
4670
+ ...event ? {
4671
+ runId: readEventRunId$1(event),
4672
+ messageId: readEventMessageId(event)
4673
+ } : {},
4674
+ ...payload && "correlationId" in payload ? { correlationId: payload.correlationId } : {},
4675
+ nodeVersion: process.version,
4676
+ platform: process.platform,
4677
+ ...readSessionJournalFailureContext(error)
4678
+ }, error);
4679
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
4680
+ options.eventBus.emit(eventKeys.ncpEvent, {
4681
+ type: NcpEventType.RunError,
4682
+ occurredAt: endedAt,
4683
+ payload: {
4684
+ sessionId,
4685
+ endedAt,
4686
+ interrupted: true,
4687
+ ...payload && "messageId" in payload ? { messageId: payload.messageId } : {},
4688
+ ...payload && "runId" in payload ? { runId: payload.runId } : {},
4689
+ ...payload && "correlationId" in payload ? { correlationId: payload.correlationId } : {},
4690
+ error: error instanceof Error ? error.message : String(error)
4691
+ }
4692
+ }, {
4693
+ emittedAt: endedAt,
4694
+ source: SESSION_JOURNAL_FAILURE_SOURCE
4695
+ });
4569
4696
  },
4570
4697
  subscribe: (handler) => options.eventBus.on(eventKeys.ncpEvent, handler),
4571
4698
  updateSessionMetadata: options.updateSessionMetadata
@@ -4576,6 +4703,33 @@ var SessionEventCoordinatorService = class {
4576
4703
  flushSession = async (sessionId) => await this.ingestion.flushSession(sessionId);
4577
4704
  flush = async () => await this.ingestion.flush();
4578
4705
  persist = (event, signal) => this.ingestion.ingestEvent(event, signal);
4706
+ loadRunSeed = async (sessionId) => {
4707
+ if (!this.options.journalStore.loadSessionRunSeed) throw new Error("This session host does not support bounded run loading.");
4708
+ await this.ingestion.flushSession(sessionId);
4709
+ return this.options.journalStore.loadSessionRunSeed(sessionId);
4710
+ };
4711
+ recoverRun = (sessionId) => this.ingestion.recoverSession(sessionId, async () => {
4712
+ const store = this.options.journalStore;
4713
+ if (!store.loadSessionRunSeed || !store.getSessionSummary) throw new Error("This session host does not support bounded recovery.");
4714
+ const state = await store.prepareSessionHistory?.(sessionId, {
4715
+ retry: true,
4716
+ wait: true
4717
+ });
4718
+ if (state && state.status !== "ready") throw new Error(state.error ?? "Session history recovery is not ready.");
4719
+ if (!await store.getSessionSummary(sessionId)) throw new Error("The saved session is unavailable; its original files were retained.");
4720
+ await this.options.appendSessionEvent({
4721
+ sessionId,
4722
+ event: {
4723
+ type: NcpEventType.RunMetadata,
4724
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
4725
+ payload: {
4726
+ sessionId,
4727
+ metadata: { kind: "session_storage_recovery" }
4728
+ }
4729
+ }
4730
+ });
4731
+ return store.loadSessionRunSeed(sessionId);
4732
+ });
4579
4733
  publish = async (params) => {
4580
4734
  const { event, sessionId, source, synchronizeMessageProjection, persistFirst } = params;
4581
4735
  if (persistFirst) {
@@ -4973,11 +5127,8 @@ var SessionManager = class {
4973
5127
  if (!this.options.journalStore.readSessionMessagePart) throw new Error("This session host does not support exact history reads.");
4974
5128
  return this.options.journalStore.readSessionMessagePart(params);
4975
5129
  };
4976
- loadSessionRunSeed = async (sessionId) => {
4977
- if (!this.options.journalStore.loadSessionRunSeed) throw new Error("This session host does not support bounded run loading.");
4978
- await this.sessionEvents.flushSession(sessionId);
4979
- return this.options.journalStore.loadSessionRunSeed(sessionId);
4980
- };
5130
+ loadSessionRunSeed = (sessionId) => this.sessionEvents.loadRunSeed(sessionId);
5131
+ recoverSessionRun = (sessionId) => this.sessionEvents.recoverRun(sessionId);
4981
5132
  getSession = async (sessionId) => {
4982
5133
  const normalizedSessionId = normalizeSessionId(sessionId);
4983
5134
  if (!normalizedSessionId) return null;
@@ -6761,6 +6912,10 @@ var AgentRuntimeRunObserverService = class {
6761
6912
  start = (params) => {
6762
6913
  const { options, parentCorrelationId, requestRunStartedAt, runtime, spec } = params;
6763
6914
  const { session, sessionRun } = options;
6915
+ const stopWatchingStorage = this.options.eventBus.on(eventKeys.ncpEvent, (event, envelope) => {
6916
+ if (envelope.source !== "session-event-coordinator:journal-failure" || event.type !== NcpEventType.RunError || event.payload.sessionId !== session.sessionId) return;
6917
+ sessionRun.failPersistence(event.payload.error ?? "Session history could not be saved.");
6918
+ });
6764
6919
  let messageCompletedSeen = false;
6765
6920
  const initialMessageIds = new Set(options.initialMessages.map(({ id }) => id));
6766
6921
  let executionMetadataSeen = false;
@@ -6809,6 +6964,11 @@ var AgentRuntimeRunObserverService = class {
6809
6964
  failureReason = classification.reasonCode;
6810
6965
  failureProviderCode = classification.providerCode;
6811
6966
  failureFacts = classification.facts;
6967
+ if (isSessionJournalWriteError(error)) {
6968
+ failureReason = "session_journal_write_failed";
6969
+ sessionRun.failPersistence(error);
6970
+ return;
6971
+ }
6812
6972
  if (!executionMetadataSeen) {
6813
6973
  const metadataEvent = createUnavailableAiExecutionMetadataEvent({
6814
6974
  spec,
@@ -6826,19 +6986,24 @@ var AgentRuntimeRunObserverService = class {
6826
6986
  });
6827
6987
  await sessionRun.applyEvents([event]);
6828
6988
  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
- }));
6989
+ })), { defaultValue: void 0 }).finally(() => {
6990
+ stopWatchingStorage();
6991
+ return this.finish({
6992
+ failureFacts,
6993
+ failureOutcome,
6994
+ failureProviderCode,
6995
+ failureReason,
6996
+ onSettled: params.onSettled,
6997
+ parentCorrelationId,
6998
+ runStartedAt,
6999
+ runtimeCancelled,
7000
+ runtimeFailed,
7001
+ spec,
7002
+ options
7003
+ });
7004
+ }).catch((error) => {
7005
+ if (!isSessionJournalWriteError(error)) console.error("[agent-run-request] failed to settle runtime events", error);
7006
+ });
6842
7007
  };
6843
7008
  finish = async (input) => {
6844
7009
  const { session, sessionRun } = input.options;
@@ -6884,7 +7049,7 @@ var AgentRuntimeRunObserverService = class {
6884
7049
  publishNcpEvent = (event) => {
6885
7050
  this.options.eventBus.emit(eventKeys.ncpEvent, event, {
6886
7051
  emittedAt: (/* @__PURE__ */ new Date()).toISOString(),
6887
- source: "agent-run-request"
7052
+ source: PERSISTED_SESSION_EVENT_SOURCE
6888
7053
  });
6889
7054
  };
6890
7055
  };
@@ -7000,6 +7165,7 @@ var AgentRunRequestManager = class {
7000
7165
  const queuedRequest = sessionRun.enqueueRequest(normalizedRequest, session);
7001
7166
  const steeringRequest = request.delivery === "prefer-steer" && sessionRun.isRunning() ? this.pendingInputs.promotePreferredSteeringInput(sessionRun, queuedRequest.id, session) : null;
7002
7167
  if (steeringRequest) {
7168
+ sessionRun.acknowledgeRequest(queuedRequest.id);
7003
7169
  this.publishRunQueueUpdated(session.sessionId);
7004
7170
  return {
7005
7171
  sessionId: session.sessionId,
@@ -7013,6 +7179,7 @@ var AgentRunRequestManager = class {
7013
7179
  this.publishRunQueueUpdated(session.sessionId);
7014
7180
  if (activeRequest?.id === queuedRequest.id) await this.startQueuedRun(sessionRun, activeRequest);
7015
7181
  else if (activeRequest) this.startQueuedRun(sessionRun, activeRequest).catch(() => void 0);
7182
+ sessionRun.acknowledgeRequest(queuedRequest.id);
7016
7183
  return {
7017
7184
  sessionId: session.sessionId,
7018
7185
  userMessageId: queuedRequest.request.message.id,
@@ -7045,12 +7212,6 @@ var AgentRunRequestManager = class {
7045
7212
  startedAt: requestRunStartedAt,
7046
7213
  trigger
7047
7214
  });
7048
- const providerRequest = {
7049
- ...request,
7050
- agentId: spec.agentId,
7051
- sessionId: session.sessionId,
7052
- message
7053
- };
7054
7215
  const correlationId = request.correlationId ?? activeRequest.runId;
7055
7216
  const parentCorrelationId = typeof request.metadata?.[DIAGNOSTIC_CORRELATION_METADATA_KEY] === "string" ? request.metadata[DIAGNOSTIC_CORRELATION_METADATA_KEY] : void 0;
7056
7217
  this.diagnostics?.record({
@@ -7065,16 +7226,15 @@ var AgentRunRequestManager = class {
7065
7226
  ...request.channel ? { channel: request.channel } : {}
7066
7227
  }
7067
7228
  });
7068
- const messageSentEvent = createMessageSentEvent({
7229
+ const initialEvents = [createMessageSentEvent({
7069
7230
  sessionId: session.sessionId,
7070
7231
  message,
7071
7232
  correlationId: request.correlationId
7072
- });
7073
- const triggerEvent = createRunTriggerMetadataEvent({
7233
+ }), createRunTriggerMetadataEvent({
7074
7234
  sessionId: session.sessionId,
7075
7235
  spec,
7076
7236
  trigger
7077
- });
7237
+ })];
7078
7238
  try {
7079
7239
  releaseCapacity = await this.admissions.acquireExecution(activeRequest.signal);
7080
7240
  executionClaim = await this.claimSessionExecutionOrFail({
@@ -7083,15 +7243,19 @@ var AgentRunRequestManager = class {
7083
7243
  spec
7084
7244
  });
7085
7245
  activeRequest.signal.throwIfAborted();
7086
- await sessionRun.applyEvents([messageSentEvent, triggerEvent]);
7087
- this.publishNcpEvent(messageSentEvent);
7088
- this.publishNcpEvent(triggerEvent);
7246
+ await sessionRun.applyEvents(initialEvents);
7247
+ initialEvents.forEach(this.publishNcpEvent);
7089
7248
  const runtime = this.agentRuntimeManager.getOrCreate({
7090
7249
  agentRuntimeId: session.agentRuntimeId,
7091
7250
  session,
7092
7251
  sessionRun
7093
7252
  });
7094
- const { contextBlocks, tools } = await this.agentContextWindowManager.resolveRunSurface(providerRequest);
7253
+ const { contextBlocks, tools } = await this.agentContextWindowManager.resolveRunSurface({
7254
+ ...request,
7255
+ agentId: spec.agentId,
7256
+ sessionId: session.sessionId,
7257
+ message
7258
+ });
7095
7259
  this.startRuntimeRun({
7096
7260
  options: {
7097
7261
  contextBlocks,
@@ -7124,13 +7288,17 @@ var AgentRunRequestManager = class {
7124
7288
  providerCode: classification.providerCode,
7125
7289
  facts: classification.facts
7126
7290
  });
7127
- await this.publishRunStartupFailure({
7128
- error,
7129
- requestRunStartedAt,
7130
- sessionRun,
7131
- spec
7132
- });
7133
- this.startNextQueuedRun(sessionRun);
7291
+ try {
7292
+ await this.publishRunStartupFailure({
7293
+ error,
7294
+ requestRunStartedAt,
7295
+ sessionRun,
7296
+ spec
7297
+ });
7298
+ } finally {
7299
+ sessionRun.settleRun(activeRequest.runId);
7300
+ this.startNextQueuedRun(sessionRun);
7301
+ }
7134
7302
  throw error;
7135
7303
  }
7136
7304
  };
@@ -7154,17 +7322,23 @@ var AgentRunRequestManager = class {
7154
7322
  };
7155
7323
  startRuntimeRun = (params) => {
7156
7324
  const { executionClaim, releaseCapacity, ...runtimeParams } = params;
7325
+ params.options.sessionRun.markRuntimeStarted(params.spec.runId);
7157
7326
  this.runtimeRuns.start({
7158
7327
  ...runtimeParams,
7159
7328
  onSettled: (sessionRun) => {
7160
7329
  executionClaim?.release();
7161
7330
  releaseCapacity?.();
7331
+ sessionRun.settleRun(params.spec.runId);
7162
7332
  this.startNextQueuedRun(sessionRun);
7163
7333
  }
7164
7334
  });
7165
7335
  };
7166
7336
  publishRunStartupFailure = async (params) => {
7167
7337
  const { error, requestRunStartedAt, sessionRun, spec } = params;
7338
+ if (isSessionJournalWriteError(error)) {
7339
+ sessionRun.failPersistence(error);
7340
+ return;
7341
+ }
7168
7342
  const metadataEvent = createUnavailableAiExecutionMetadataEvent({
7169
7343
  spec,
7170
7344
  sessionId: sessionRun.sessionId
@@ -7209,7 +7383,7 @@ var AgentRunRequestManager = class {
7209
7383
  publishNcpEvent = (event) => {
7210
7384
  this.eventBus.emit(eventKeys.ncpEvent, event, {
7211
7385
  emittedAt: (/* @__PURE__ */ new Date()).toISOString(),
7212
- source: "agent-run-request"
7386
+ source: PERSISTED_SESSION_EVENT_SOURCE
7213
7387
  });
7214
7388
  };
7215
7389
  getOrCreateSessionForRequest = async (request) => {
@@ -7540,9 +7714,10 @@ function recordProductActivityBestEffort(sink, signal) {
7540
7714
  } catch {}
7541
7715
  }
7542
7716
  //#endregion
7543
- //#region src/managers/session-run.manager.ts
7717
+ //#region src/managers/session-pending-inputs.manager.ts
7544
7718
  /** Single owner for inputs waiting for either the next run or the next safe step. */
7545
7719
  var SessionPendingInputs = class {
7720
+ acknowledged = /* @__PURE__ */ new Set();
7546
7721
  nextRun = [];
7547
7722
  nextStep = [];
7548
7723
  claimedNextStep = /* @__PURE__ */ new Map();
@@ -7587,11 +7762,22 @@ var SessionPendingInputs = class {
7587
7762
  const index = this.nextRun.findIndex(({ id }) => id === requestId);
7588
7763
  if (index < 0) return null;
7589
7764
  const [removed] = this.nextRun.splice(index, 1);
7765
+ this.acknowledged.delete(requestId);
7590
7766
  return removed ? structuredClone(removed) : null;
7591
7767
  };
7768
+ acknowledgeRequest = (requestId) => {
7769
+ if (this.nextRun.some((request) => request.id === requestId) || this.nextStep.some((request) => request.id === requestId) || this.claimedNextStep.has(requestId)) this.acknowledged.add(requestId);
7770
+ };
7771
+ restoreNextRun = (request) => {
7772
+ this.acknowledged.add(request.id);
7773
+ this.nextRun.unshift(request);
7774
+ };
7592
7775
  shiftNextRun = () => {
7593
7776
  const request = this.nextRun.shift();
7594
- return request ? structuredClone(request) : null;
7777
+ return request ? {
7778
+ ...structuredClone(request),
7779
+ acknowledged: this.acknowledged.delete(request.id)
7780
+ } : null;
7595
7781
  };
7596
7782
  claimNextStep = (runId) => {
7597
7783
  const claimed = [];
@@ -7605,7 +7791,10 @@ var SessionPendingInputs = class {
7605
7791
  return structuredClone(claimed);
7606
7792
  };
7607
7793
  acknowledgeNextStep = (requestIds) => {
7608
- for (const requestId of requestIds) this.claimedNextStep.delete(requestId);
7794
+ for (const requestId of requestIds) {
7795
+ this.claimedNextStep.delete(requestId);
7796
+ this.acknowledged.delete(requestId);
7797
+ }
7609
7798
  };
7610
7799
  restoreNextStep = (runId) => {
7611
7800
  const restored = [...this.nextStep.filter(({ intendedRunId }) => intendedRunId === runId), ...[...this.claimedNextStep.values()].filter(({ intendedRunId }) => intendedRunId === runId)].sort((left, right) => left.enqueuedAt.localeCompare(right.enqueuedAt));
@@ -7621,6 +7810,7 @@ var SessionPendingInputs = class {
7621
7810
  this.nextRun.length = 0;
7622
7811
  this.nextStep.length = 0;
7623
7812
  this.claimedNextStep.clear();
7813
+ this.acknowledged.clear();
7624
7814
  };
7625
7815
  toPendingRequest = (request, placement, intendedRunId) => structuredClone({
7626
7816
  ...request,
@@ -7628,6 +7818,8 @@ var SessionPendingInputs = class {
7628
7818
  intendedRunId
7629
7819
  });
7630
7820
  };
7821
+ //#endregion
7822
+ //#region src/managers/session-run.manager.ts
7631
7823
  function isConversationStateEvent(event) {
7632
7824
  return event.type !== NcpEventType.ContextWindowUpdated;
7633
7825
  }
@@ -7647,10 +7839,14 @@ var SessionRun = class {
7647
7839
  activeProductActivitySource = null;
7648
7840
  eventChain = Promise.resolve();
7649
7841
  windowGrowthBytes = 0;
7650
- constructor(seed, stateManager = new DefaultNcpAgentConversationStateManager(), productActivitySink, persistCompaction) {
7842
+ persistenceFailure = null;
7843
+ execution = null;
7844
+ recovery = null;
7845
+ disposed = false;
7846
+ constructor(seed, stateManager = new DefaultNcpAgentConversationStateManager(), productActivitySink, persistEvent) {
7651
7847
  this.stateManager = stateManager;
7652
7848
  this.productActivitySink = productActivitySink;
7653
- this.persistCompaction = persistCompaction;
7849
+ this.persistEvent = persistEvent;
7654
7850
  this.sessionId = seed.sessionId;
7655
7851
  this.stateManager.hydrate({
7656
7852
  sessionId: seed.sessionId,
@@ -7669,9 +7865,12 @@ var SessionRun = class {
7669
7865
  return operation;
7670
7866
  };
7671
7867
  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);
7868
+ if (this.persistenceFailure) throw this.persistenceFailure;
7869
+ try {
7870
+ for (const event of events) await this.persistEvent?.(event, signal);
7871
+ } catch (error) {
7872
+ if (isSessionJournalWriteError(error)) this.failPersistence(error);
7873
+ throw error;
7675
7874
  }
7676
7875
  this.applyRunEvents(events);
7677
7876
  let archived = false;
@@ -7827,6 +8026,7 @@ var SessionRun = class {
7827
8026
  };
7828
8027
  };
7829
8028
  enqueueRequest = (request, session) => {
8029
+ if (this.persistenceFailure) throw this.persistenceFailure;
7830
8030
  const wasBusy = this.isBusy();
7831
8031
  const queuedRequest = {
7832
8032
  id: `queued-input-${crypto.randomUUID()}`,
@@ -7859,12 +8059,61 @@ var SessionRun = class {
7859
8059
  acknowledgeNextStepRequests = (requestIds) => {
7860
8060
  this.pendingInputs.acknowledgeNextStep(requestIds);
7861
8061
  };
8062
+ acknowledgeRequest = (requestId) => {
8063
+ if (this.execution?.request.id === requestId) this.execution.acknowledged = true;
8064
+ else this.pendingInputs.acknowledgeRequest(requestId);
8065
+ };
8066
+ markRuntimeStarted = (runId) => {
8067
+ if (this.execution?.request.runId === runId) this.execution.runtimeStarted = true;
8068
+ };
8069
+ settleRun = (runId) => {
8070
+ const execution = this.execution;
8071
+ if (!execution || execution.request.runId !== runId) return;
8072
+ const wasBusy = this.isBusy();
8073
+ if (this.persistenceFailure && execution.acknowledged && !execution.runtimeStarted) this.pendingInputs.restoreNextRun(execution.request);
8074
+ this.execution = null;
8075
+ execution.resolve();
8076
+ this.emitStatusChangeIfNeeded(wasBusy);
8077
+ };
8078
+ recoverPersistence = (load) => {
8079
+ if (!this.persistenceFailure) return Promise.resolve();
8080
+ if (this.recovery) return this.recovery;
8081
+ this.recovery = (async () => {
8082
+ await this.execution?.settled;
8083
+ await this.eventChain;
8084
+ if (this.disposed) throw new Error("Session run was disposed during storage recovery.");
8085
+ const messages = await load();
8086
+ if (this.disposed) throw new Error("Session run was disposed during storage recovery.");
8087
+ this.stateManager.hydrate({
8088
+ sessionId: this.sessionId,
8089
+ messages
8090
+ });
8091
+ this.windowGrowthBytes = 0;
8092
+ for (const fragment of sessionJsonFragments(messages)) this.windowGrowthBytes += Buffer.byteLength(fragment);
8093
+ this.persistenceFailure = null;
8094
+ })().finally(() => {
8095
+ this.recovery = null;
8096
+ });
8097
+ return this.recovery;
8098
+ };
7862
8099
  getActiveRunId = () => this.activeRunId;
7863
8100
  beginNextRun = () => {
7864
- if (this.activeRunId) return null;
8101
+ if (this.persistenceFailure) return null;
8102
+ if (this.activeRunId || this.execution) return null;
7865
8103
  const wasBusy = this.isBusy();
7866
- const queuedRequest = this.pendingInputs.shiftNextRun();
7867
- if (!queuedRequest) return null;
8104
+ const next = this.pendingInputs.shiftNextRun();
8105
+ if (!next) return null;
8106
+ const { acknowledged, ...queuedRequest } = next;
8107
+ let resolve;
8108
+ this.execution = {
8109
+ request: queuedRequest,
8110
+ acknowledged,
8111
+ runtimeStarted: false,
8112
+ settled: new Promise((done) => {
8113
+ resolve = done;
8114
+ }),
8115
+ resolve
8116
+ };
7868
8117
  const controller = new AbortController();
7869
8118
  this.activeRunId = queuedRequest.runId;
7870
8119
  this.activeRunController = controller;
@@ -7886,10 +8135,22 @@ var SessionRun = class {
7886
8135
  this.activeRunController.abort(reason);
7887
8136
  return true;
7888
8137
  };
8138
+ /** A storage fault terminates control state without inventing a durable history event. */
8139
+ failPersistence = (error) => {
8140
+ const wasBusy = this.isBusy();
8141
+ this.persistenceFailure ??= typeof error === "string" ? Object.assign(new Error(error), { code: SESSION_JOURNAL_WRITE_FAILED }) : error;
8142
+ if (this.activeRunId) this.pendingInputs.restoreNextStep(this.activeRunId);
8143
+ this.activeRunController?.abort(this.persistenceFailure);
8144
+ this.activeRunController = null;
8145
+ this.activeRunId = null;
8146
+ this.activeProductActivitySource = null;
8147
+ this.emitStatusChangeIfNeeded(wasBusy);
8148
+ };
7889
8149
  isRunning = () => this.activeRunId !== null;
7890
- isBusy = () => this.isRunning() || this.pendingInputs.hasNextRun;
8150
+ isBusy = () => this.isRunning() || this.execution !== null || this.recovery !== null || this.pendingInputs.hasNextRun;
7891
8151
  dispose = () => {
7892
8152
  const wasBusy = this.isBusy();
8153
+ this.disposed = true;
7893
8154
  this.activeRunController?.abort({
7894
8155
  code: "abort-error",
7895
8156
  message: "Session run owner was disposed; the current run was cancelled.",
@@ -7899,6 +8160,8 @@ var SessionRun = class {
7899
8160
  this.activeRunId = null;
7900
8161
  this.activeProductActivitySource = null;
7901
8162
  this.pendingInputs.clear();
8163
+ this.execution?.resolve();
8164
+ this.execution = null;
7902
8165
  this.emitStatusChangeIfNeeded(wasBusy);
7903
8166
  this.statusListeners.clear();
7904
8167
  };
@@ -7954,8 +8217,17 @@ var SessionRunManager = class {
7954
8217
  }] : [];
7955
8218
  });
7956
8219
  getOrCreateSessionRun = async (sessionId) => {
8220
+ if (this.disposed) throw new Error("Session run manager is disposed.");
7957
8221
  const existing = this.getSessionRun(sessionId);
7958
- if (existing) return existing;
8222
+ if (existing) {
8223
+ await existing.recoverPersistence(async () => {
8224
+ if (!this.sessionManager.recoverSessionRun) throw new Error("This session host cannot recover storage without restarting.");
8225
+ const messages = await this.sessionManager.recoverSessionRun(sessionId);
8226
+ await this.prepareRunMessages(sessionId, messages);
8227
+ return messages;
8228
+ });
8229
+ return existing;
8230
+ }
7959
8231
  const pending = this.pendingCreations.get(sessionId);
7960
8232
  if (pending) return await pending;
7961
8233
  const creation = this.createSessionRun(sessionId).finally(() => {
@@ -7982,6 +8254,20 @@ var SessionRunManager = class {
7982
8254
  if (this.runs.has(sessionId)) throw new Error(`Session run already exists: ${sessionId}`);
7983
8255
  const messages = this.sessionManager.loadSessionRunSeed ? await this.sessionManager.loadSessionRunSeed(sessionId) : await this.sessionManager.listSessionMessages(sessionId);
7984
8256
  if (this.disposed) throw new Error("Session run manager is disposed.");
8257
+ await this.prepareRunMessages(sessionId, messages);
8258
+ const run = new SessionRun({
8259
+ messages,
8260
+ sessionId
8261
+ }, void 0, this.productActivitySink, this.sessionManager.persistSessionEvent);
8262
+ this.runs.set(sessionId, run);
8263
+ run.onStatusChange((status) => {
8264
+ if (status === "running") this.inactiveBytes.delete(sessionId);
8265
+ else this.trimInactive(sessionId);
8266
+ });
8267
+ this.trimInactive(sessionId);
8268
+ return run;
8269
+ };
8270
+ prepareRunMessages = async (sessionId, messages) => {
7985
8271
  const checkpoint = readLatestContextCompactionCheckpoint(messages);
7986
8272
  const firstOrdinal = messages.reduce((first, message) => {
7987
8273
  const ordinal = Number((message.metadata?.nextclaw_source)?.ordinal);
@@ -8034,17 +8320,6 @@ var SessionRunManager = class {
8034
8320
  });
8035
8321
  messages.push(marker);
8036
8322
  }
8037
- const run = new SessionRun({
8038
- messages,
8039
- sessionId
8040
- }, void 0, this.productActivitySink, this.sessionManager.persistSessionEvent);
8041
- this.runs.set(sessionId, run);
8042
- run.onStatusChange((status) => {
8043
- if (status === "running") this.inactiveBytes.delete(sessionId);
8044
- else this.trimInactive(sessionId);
8045
- });
8046
- this.trimInactive(sessionId);
8047
- return run;
8048
8323
  };
8049
8324
  trimInactive = (protectedId) => {
8050
8325
  const current = this.runs.get(protectedId);
@@ -9347,6 +9622,6 @@ var NextclawHarness = class {
9347
9622
  };
9348
9623
  };
9349
9624
  //#endregion
9350
- 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 };
9625
+ export { SessionMessageSqlProjectionStore 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, SessionMessagePreparationStore 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, readSessionJournalFailureContext as Z, createQuestionMessage as _, AgentRunClient as _t, dispatchAgentRuntimeSessionRequest as a, isSessionSettingsError as at, SessionManager as b, Contribution$1 as c, assertObservationJsonValue as ct, dispatchPromptOverNcpResult as d, evaluateObservationEventAdmission as dt, SessionEventProjectionStore as et, startPromptOverNcpExecution as f, matchesObservationPredicate as ft, USER_QUESTION_EXTENSION_TYPE as g, DEFAULT_AGENT_RUNTIME_ENTRY_ID as gt, UserQuestionManager as h, toBoundedJson as ht, createAgentRuntimeSessionRequestSourceNotifier as i, isSessionMessageCursorError as it, WorkspaceMemoryContextProvider as j, buildRunMetadata as k, NextclawHarnessError as l, assertObservationPredicate as lt, UserQuestionError as m, readJsonPointer as mt, buildSessionRequestCompletionMessage as n, SessionMessageCursorError as nt, waitForAgentRuntimeSessionReply as o, applyNcpAgentRunLifecycleEvent as ot, buildAgentRunSendPayload as p, parseObservationDuration as pt, serializeModelInputTail as q, createAgentRuntimeSessionRequestDispatcher as r, SessionSettingsError as rt, SessionRequestManager as s, isNcpAgentRunLifecycleEvent as st, NextclawHarness as t, sessionJsonChunks as tt, dispatchPromptOverNcp as u, buildObservationEventModelMessage as ut, createQuestionResolutionMessage as v, CommandRegistry as vt, createShowContentTools as w, createWorkspaceByteTools as x, projectUserQuestions as y, buildNextclawNcpRunContext as z };
9351
9626
 
9352
- //# sourceMappingURL=nextclaw-harness.manager-ajpoljL-.js.map
9627
+ //# sourceMappingURL=nextclaw-harness.manager-DIL9tOd-.js.map