@nextclaw/kernel 0.19.7 → 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;
@@ -4398,53 +4445,6 @@ var SessionActivityPreviewEventService = class {
4398
4445
  };
4399
4446
  };
4400
4447
  //#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
4448
4448
  //#region src/services/session-event-ingestion.service.ts
4449
4449
  const SESSION_METADATA_PATCH_RUN_METADATA_KIND = "session_metadata_patch";
4450
4450
  const PERSISTED_SESSION_EVENT_SOURCE = "session-event-coordinator:persisted";
@@ -4463,6 +4463,7 @@ var SessionEventIngestionService = class {
4463
4463
  activityPreview;
4464
4464
  chains = /* @__PURE__ */ new Map();
4465
4465
  failedWrites = /* @__PURE__ */ new Map();
4466
+ failedProjections = /* @__PURE__ */ new Set();
4466
4467
  pendingDeltas = /* @__PURE__ */ new Map();
4467
4468
  cleanup = null;
4468
4469
  constructor(options) {
@@ -4545,6 +4546,21 @@ var SessionEventIngestionService = class {
4545
4546
  await this.chains.get(sessionId);
4546
4547
  this.throwIfFailed(sessionId);
4547
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
+ };
4548
4564
  flush = async () => {
4549
4565
  for (const sessionId of this.pendingDeltas.keys()) this.flushPendingDelta(sessionId);
4550
4566
  await Promise.all([...this.chains.values()]);
@@ -4557,6 +4573,7 @@ var SessionEventIngestionService = class {
4557
4573
  this.pendingDeltas.clear();
4558
4574
  this.chains.clear();
4559
4575
  this.failedWrites.clear();
4576
+ this.failedProjections.clear();
4560
4577
  this.activityPreview.clear();
4561
4578
  };
4562
4579
  flushPendingDelta = (sessionId) => {
@@ -4592,7 +4609,6 @@ var SessionEventIngestionService = class {
4592
4609
  if (failure) throw failure;
4593
4610
  };
4594
4611
  handleDurableEvent = async (sessionId, event, signal) => {
4595
- const preview = this.activityPreview.projectEvent(event, (/* @__PURE__ */ new Date()).toISOString());
4596
4612
  const metadataPatch = readRuntimeSessionMetadataPatch(event);
4597
4613
  if (metadataPatch) {
4598
4614
  await this.options.updateSessionMetadata(sessionId, metadataPatch);
@@ -4603,11 +4619,33 @@ var SessionEventIngestionService = class {
4603
4619
  sessionId,
4604
4620
  signal
4605
4621
  });
4606
- if (event.type === NcpEventType.MessageSent) {
4607
- const checkpoint = readContextCompactionCheckpoint(event.payload.message);
4608
- 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);
4609
4648
  }
4610
- if (preview) await this.activityPreview.updatePreview(preview);
4611
4649
  };
4612
4650
  };
4613
4651
  //#endregion
@@ -4621,9 +4659,23 @@ var SessionEventCoordinatorService = class {
4621
4659
  getSessionRecord: options.getSessionRecord,
4622
4660
  listUnfinishedRuns: options.listUnfinishedRuns,
4623
4661
  onError: (sessionId, error, event) => {
4624
- const detail = formatSessionJournalError(error);
4625
- console.error(`[session-manager] failed to handle ncp event for ${sessionId}: ${detail}`);
4626
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);
4627
4679
  const endedAt = (/* @__PURE__ */ new Date()).toISOString();
4628
4680
  options.eventBus.emit(eventKeys.ncpEvent, {
4629
4681
  type: NcpEventType.RunError,
@@ -4651,6 +4703,33 @@ var SessionEventCoordinatorService = class {
4651
4703
  flushSession = async (sessionId) => await this.ingestion.flushSession(sessionId);
4652
4704
  flush = async () => await this.ingestion.flush();
4653
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
+ });
4654
4733
  publish = async (params) => {
4655
4734
  const { event, sessionId, source, synchronizeMessageProjection, persistFirst } = params;
4656
4735
  if (persistFirst) {
@@ -5048,11 +5127,8 @@ var SessionManager = class {
5048
5127
  if (!this.options.journalStore.readSessionMessagePart) throw new Error("This session host does not support exact history reads.");
5049
5128
  return this.options.journalStore.readSessionMessagePart(params);
5050
5129
  };
5051
- loadSessionRunSeed = async (sessionId) => {
5052
- if (!this.options.journalStore.loadSessionRunSeed) throw new Error("This session host does not support bounded run loading.");
5053
- await this.sessionEvents.flushSession(sessionId);
5054
- return this.options.journalStore.loadSessionRunSeed(sessionId);
5055
- };
5130
+ loadSessionRunSeed = (sessionId) => this.sessionEvents.loadRunSeed(sessionId);
5131
+ recoverSessionRun = (sessionId) => this.sessionEvents.recoverRun(sessionId);
5056
5132
  getSession = async (sessionId) => {
5057
5133
  const normalizedSessionId = normalizeSessionId(sessionId);
5058
5134
  if (!normalizedSessionId) return null;
@@ -7089,6 +7165,7 @@ var AgentRunRequestManager = class {
7089
7165
  const queuedRequest = sessionRun.enqueueRequest(normalizedRequest, session);
7090
7166
  const steeringRequest = request.delivery === "prefer-steer" && sessionRun.isRunning() ? this.pendingInputs.promotePreferredSteeringInput(sessionRun, queuedRequest.id, session) : null;
7091
7167
  if (steeringRequest) {
7168
+ sessionRun.acknowledgeRequest(queuedRequest.id);
7092
7169
  this.publishRunQueueUpdated(session.sessionId);
7093
7170
  return {
7094
7171
  sessionId: session.sessionId,
@@ -7102,6 +7179,7 @@ var AgentRunRequestManager = class {
7102
7179
  this.publishRunQueueUpdated(session.sessionId);
7103
7180
  if (activeRequest?.id === queuedRequest.id) await this.startQueuedRun(sessionRun, activeRequest);
7104
7181
  else if (activeRequest) this.startQueuedRun(sessionRun, activeRequest).catch(() => void 0);
7182
+ sessionRun.acknowledgeRequest(queuedRequest.id);
7105
7183
  return {
7106
7184
  sessionId: session.sessionId,
7107
7185
  userMessageId: queuedRequest.request.message.id,
@@ -7134,12 +7212,6 @@ var AgentRunRequestManager = class {
7134
7212
  startedAt: requestRunStartedAt,
7135
7213
  trigger
7136
7214
  });
7137
- const providerRequest = {
7138
- ...request,
7139
- agentId: spec.agentId,
7140
- sessionId: session.sessionId,
7141
- message
7142
- };
7143
7215
  const correlationId = request.correlationId ?? activeRequest.runId;
7144
7216
  const parentCorrelationId = typeof request.metadata?.[DIAGNOSTIC_CORRELATION_METADATA_KEY] === "string" ? request.metadata[DIAGNOSTIC_CORRELATION_METADATA_KEY] : void 0;
7145
7217
  this.diagnostics?.record({
@@ -7154,16 +7226,15 @@ var AgentRunRequestManager = class {
7154
7226
  ...request.channel ? { channel: request.channel } : {}
7155
7227
  }
7156
7228
  });
7157
- const messageSentEvent = createMessageSentEvent({
7229
+ const initialEvents = [createMessageSentEvent({
7158
7230
  sessionId: session.sessionId,
7159
7231
  message,
7160
7232
  correlationId: request.correlationId
7161
- });
7162
- const triggerEvent = createRunTriggerMetadataEvent({
7233
+ }), createRunTriggerMetadataEvent({
7163
7234
  sessionId: session.sessionId,
7164
7235
  spec,
7165
7236
  trigger
7166
- });
7237
+ })];
7167
7238
  try {
7168
7239
  releaseCapacity = await this.admissions.acquireExecution(activeRequest.signal);
7169
7240
  executionClaim = await this.claimSessionExecutionOrFail({
@@ -7172,15 +7243,19 @@ var AgentRunRequestManager = class {
7172
7243
  spec
7173
7244
  });
7174
7245
  activeRequest.signal.throwIfAborted();
7175
- await sessionRun.applyEvents([messageSentEvent, triggerEvent]);
7176
- this.publishNcpEvent(messageSentEvent);
7177
- this.publishNcpEvent(triggerEvent);
7246
+ await sessionRun.applyEvents(initialEvents);
7247
+ initialEvents.forEach(this.publishNcpEvent);
7178
7248
  const runtime = this.agentRuntimeManager.getOrCreate({
7179
7249
  agentRuntimeId: session.agentRuntimeId,
7180
7250
  session,
7181
7251
  sessionRun
7182
7252
  });
7183
- 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
+ });
7184
7259
  this.startRuntimeRun({
7185
7260
  options: {
7186
7261
  contextBlocks,
@@ -7213,13 +7288,17 @@ var AgentRunRequestManager = class {
7213
7288
  providerCode: classification.providerCode,
7214
7289
  facts: classification.facts
7215
7290
  });
7216
- await this.publishRunStartupFailure({
7217
- error,
7218
- requestRunStartedAt,
7219
- sessionRun,
7220
- spec
7221
- });
7222
- 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
+ }
7223
7302
  throw error;
7224
7303
  }
7225
7304
  };
@@ -7243,11 +7322,13 @@ var AgentRunRequestManager = class {
7243
7322
  };
7244
7323
  startRuntimeRun = (params) => {
7245
7324
  const { executionClaim, releaseCapacity, ...runtimeParams } = params;
7325
+ params.options.sessionRun.markRuntimeStarted(params.spec.runId);
7246
7326
  this.runtimeRuns.start({
7247
7327
  ...runtimeParams,
7248
7328
  onSettled: (sessionRun) => {
7249
7329
  executionClaim?.release();
7250
7330
  releaseCapacity?.();
7331
+ sessionRun.settleRun(params.spec.runId);
7251
7332
  this.startNextQueuedRun(sessionRun);
7252
7333
  }
7253
7334
  });
@@ -7636,6 +7717,7 @@ function recordProductActivityBestEffort(sink, signal) {
7636
7717
  //#region src/managers/session-pending-inputs.manager.ts
7637
7718
  /** Single owner for inputs waiting for either the next run or the next safe step. */
7638
7719
  var SessionPendingInputs = class {
7720
+ acknowledged = /* @__PURE__ */ new Set();
7639
7721
  nextRun = [];
7640
7722
  nextStep = [];
7641
7723
  claimedNextStep = /* @__PURE__ */ new Map();
@@ -7680,11 +7762,22 @@ var SessionPendingInputs = class {
7680
7762
  const index = this.nextRun.findIndex(({ id }) => id === requestId);
7681
7763
  if (index < 0) return null;
7682
7764
  const [removed] = this.nextRun.splice(index, 1);
7765
+ this.acknowledged.delete(requestId);
7683
7766
  return removed ? structuredClone(removed) : null;
7684
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
+ };
7685
7775
  shiftNextRun = () => {
7686
7776
  const request = this.nextRun.shift();
7687
- return request ? structuredClone(request) : null;
7777
+ return request ? {
7778
+ ...structuredClone(request),
7779
+ acknowledged: this.acknowledged.delete(request.id)
7780
+ } : null;
7688
7781
  };
7689
7782
  claimNextStep = (runId) => {
7690
7783
  const claimed = [];
@@ -7698,7 +7791,10 @@ var SessionPendingInputs = class {
7698
7791
  return structuredClone(claimed);
7699
7792
  };
7700
7793
  acknowledgeNextStep = (requestIds) => {
7701
- 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
+ }
7702
7798
  };
7703
7799
  restoreNextStep = (runId) => {
7704
7800
  const restored = [...this.nextStep.filter(({ intendedRunId }) => intendedRunId === runId), ...[...this.claimedNextStep.values()].filter(({ intendedRunId }) => intendedRunId === runId)].sort((left, right) => left.enqueuedAt.localeCompare(right.enqueuedAt));
@@ -7714,6 +7810,7 @@ var SessionPendingInputs = class {
7714
7810
  this.nextRun.length = 0;
7715
7811
  this.nextStep.length = 0;
7716
7812
  this.claimedNextStep.clear();
7813
+ this.acknowledged.clear();
7717
7814
  };
7718
7815
  toPendingRequest = (request, placement, intendedRunId) => structuredClone({
7719
7816
  ...request,
@@ -7743,6 +7840,9 @@ var SessionRun = class {
7743
7840
  eventChain = Promise.resolve();
7744
7841
  windowGrowthBytes = 0;
7745
7842
  persistenceFailure = null;
7843
+ execution = null;
7844
+ recovery = null;
7845
+ disposed = false;
7746
7846
  constructor(seed, stateManager = new DefaultNcpAgentConversationStateManager(), productActivitySink, persistEvent) {
7747
7847
  this.stateManager = stateManager;
7748
7848
  this.productActivitySink = productActivitySink;
@@ -7959,13 +8059,61 @@ var SessionRun = class {
7959
8059
  acknowledgeNextStepRequests = (requestIds) => {
7960
8060
  this.pendingInputs.acknowledgeNextStep(requestIds);
7961
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
+ };
7962
8099
  getActiveRunId = () => this.activeRunId;
7963
8100
  beginNextRun = () => {
7964
8101
  if (this.persistenceFailure) return null;
7965
- if (this.activeRunId) return null;
8102
+ if (this.activeRunId || this.execution) return null;
7966
8103
  const wasBusy = this.isBusy();
7967
- const queuedRequest = this.pendingInputs.shiftNextRun();
7968
- 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
+ };
7969
8117
  const controller = new AbortController();
7970
8118
  this.activeRunId = queuedRequest.runId;
7971
8119
  this.activeRunController = controller;
@@ -7991,7 +8139,7 @@ var SessionRun = class {
7991
8139
  failPersistence = (error) => {
7992
8140
  const wasBusy = this.isBusy();
7993
8141
  this.persistenceFailure ??= typeof error === "string" ? Object.assign(new Error(error), { code: SESSION_JOURNAL_WRITE_FAILED }) : error;
7994
- this.pendingInputs.clear();
8142
+ if (this.activeRunId) this.pendingInputs.restoreNextStep(this.activeRunId);
7995
8143
  this.activeRunController?.abort(this.persistenceFailure);
7996
8144
  this.activeRunController = null;
7997
8145
  this.activeRunId = null;
@@ -7999,9 +8147,10 @@ var SessionRun = class {
7999
8147
  this.emitStatusChangeIfNeeded(wasBusy);
8000
8148
  };
8001
8149
  isRunning = () => this.activeRunId !== null;
8002
- isBusy = () => this.isRunning() || this.pendingInputs.hasNextRun;
8150
+ isBusy = () => this.isRunning() || this.execution !== null || this.recovery !== null || this.pendingInputs.hasNextRun;
8003
8151
  dispose = () => {
8004
8152
  const wasBusy = this.isBusy();
8153
+ this.disposed = true;
8005
8154
  this.activeRunController?.abort({
8006
8155
  code: "abort-error",
8007
8156
  message: "Session run owner was disposed; the current run was cancelled.",
@@ -8011,6 +8160,8 @@ var SessionRun = class {
8011
8160
  this.activeRunId = null;
8012
8161
  this.activeProductActivitySource = null;
8013
8162
  this.pendingInputs.clear();
8163
+ this.execution?.resolve();
8164
+ this.execution = null;
8014
8165
  this.emitStatusChangeIfNeeded(wasBusy);
8015
8166
  this.statusListeners.clear();
8016
8167
  };
@@ -8066,8 +8217,17 @@ var SessionRunManager = class {
8066
8217
  }] : [];
8067
8218
  });
8068
8219
  getOrCreateSessionRun = async (sessionId) => {
8220
+ if (this.disposed) throw new Error("Session run manager is disposed.");
8069
8221
  const existing = this.getSessionRun(sessionId);
8070
- 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
+ }
8071
8231
  const pending = this.pendingCreations.get(sessionId);
8072
8232
  if (pending) return await pending;
8073
8233
  const creation = this.createSessionRun(sessionId).finally(() => {
@@ -8094,6 +8254,20 @@ var SessionRunManager = class {
8094
8254
  if (this.runs.has(sessionId)) throw new Error(`Session run already exists: ${sessionId}`);
8095
8255
  const messages = this.sessionManager.loadSessionRunSeed ? await this.sessionManager.loadSessionRunSeed(sessionId) : await this.sessionManager.listSessionMessages(sessionId);
8096
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) => {
8097
8271
  const checkpoint = readLatestContextCompactionCheckpoint(messages);
8098
8272
  const firstOrdinal = messages.reduce((first, message) => {
8099
8273
  const ordinal = Number((message.metadata?.nextclaw_source)?.ordinal);
@@ -8146,17 +8320,6 @@ var SessionRunManager = class {
8146
8320
  });
8147
8321
  messages.push(marker);
8148
8322
  }
8149
- const run = new SessionRun({
8150
- messages,
8151
- sessionId
8152
- }, void 0, this.productActivitySink, this.sessionManager.persistSessionEvent);
8153
- this.runs.set(sessionId, run);
8154
- run.onStatusChange((status) => {
8155
- if (status === "running") this.inactiveBytes.delete(sessionId);
8156
- else this.trimInactive(sessionId);
8157
- });
8158
- this.trimInactive(sessionId);
8159
- return run;
8160
8323
  };
8161
8324
  trimInactive = (protectedId) => {
8162
8325
  const current = this.runs.get(protectedId);
@@ -9459,6 +9622,6 @@ var NextclawHarness = class {
9459
9622
  };
9460
9623
  };
9461
9624
  //#endregion
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 };
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 };
9463
9626
 
9464
- //# sourceMappingURL=nextclaw-harness.manager-Bv3YnpO5.js.map
9627
+ //# sourceMappingURL=nextclaw-harness.manager-DIL9tOd-.js.map