@nextclaw/kernel 0.19.7 → 0.19.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/dist/app/worker/index.d.ts +1 -1
  2. package/dist/app/worker/index.js +2 -2
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.js +210 -94
  5. package/dist/index.js.map +1 -1
  6. package/dist/{ncp-agent-session-journal-entry.utils-oYJG8jpX.js → ncp-agent-session-journal-entry.utils-BmQvCIr4.js} +2 -2
  7. package/dist/{ncp-agent-session-journal-entry.utils-oYJG8jpX.js.map → ncp-agent-session-journal-entry.utils-BmQvCIr4.js.map} +1 -1
  8. package/dist/{ncp-agent-session-journal.utils-CkymaYrF.js → ncp-agent-session-journal.utils-DPKiIDII.js} +12 -5
  9. package/dist/ncp-agent-session-journal.utils-DPKiIDII.js.map +1 -0
  10. package/dist/{ncp-agent-session-message-projection-tail.store-_7hsonM_.js → ncp-agent-session-message-projection-tail.store-Cne7-WRQ.js} +3 -3
  11. package/dist/{ncp-agent-session-message-projection-tail.store-_7hsonM_.js.map → ncp-agent-session-message-projection-tail.store-Cne7-WRQ.js.map} +1 -1
  12. package/dist/{nextclaw-harness.manager-DXaastB0.d.ts → nextclaw-harness.manager-BDFxf9mf.d.ts} +15 -4
  13. package/dist/nextclaw-harness.manager-BDFxf9mf.d.ts.map +1 -0
  14. package/dist/{nextclaw-harness.manager-Bv3YnpO5.js → nextclaw-harness.manager-CjDdaCHx.js} +283 -115
  15. package/dist/nextclaw-harness.manager-CjDdaCHx.js.map +1 -0
  16. package/dist/{session-journal-maintenance.store-BQmO1EKq.js → session-journal-maintenance.store-CizXaviA.js} +49 -14
  17. package/dist/session-journal-maintenance.store-CizXaviA.js.map +1 -0
  18. package/package.json +9 -9
  19. package/dist/ncp-agent-session-journal.utils-CkymaYrF.js.map +0 -1
  20. package/dist/nextclaw-harness.manager-Bv3YnpO5.js.map +0 -1
  21. package/dist/nextclaw-harness.manager-DXaastB0.d.ts.map +0 -1
  22. package/dist/session-journal-maintenance.store-BQmO1EKq.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { $ as resolveNcpAgentSessionLabel, D as CONTEXT_COMPACTION_PART_START, F as buildContextCompactionTimelineNcpMessage, H as readContextRecoveryState, J as buildContextBlockInputMessages, P as buildContextCompactionModelProjection, Q as ContextCompactionJournalRecoveryService, R as isContextCompactionProjectionMessage, S as readEventRunId$1, T as ContextCompactionPreflightService, V as readContextCompactionCheckpoint, W as readLatestContextCompactionCheckpoint, X as estimateToolInputTokens, Y as buildProviderTools, Z as composeAgentToolCatalog, a as NCP_SESSION_REQUEST_FAILED_EVENT_TYPE, b as isStreamingMessageCreationEvent, et as createAgentPeerSessionIdentity, h as mergePartialSessionMessage, i as NCP_SESSION_REQUEST_COMPLETED_EVENT_TYPE, m as SessionEventReplayer, nt as StructuredResultSubmitTool, q as COMPACTION_RECOVERY_NOTICE, r as NCP_SESSION_REQUEST_ACCEPTED_EVENT_TYPE, s as createNcpAgentSessionSummary, tt as STRUCTURED_RESULT_TOOL_NAME, w as readMessageFromSummaryEvent, x as readEventMessageId, y as isReplayContinuationEvent } from "./ncp-agent-session-journal.utils-CkymaYrF.js";
1
+ import { $ as resolveNcpAgentSessionLabel, D as CONTEXT_COMPACTION_PART_START, F as buildContextCompactionTimelineNcpMessage, H as readContextRecoveryState, J as buildContextBlockInputMessages, P as buildContextCompactionModelProjection, Q as ContextCompactionJournalRecoveryService, R as isContextCompactionProjectionMessage, S as readEventRunId$1, T as ContextCompactionPreflightService, V as readContextCompactionCheckpoint, W as readLatestContextCompactionCheckpoint, X as estimateToolInputTokens, Y as buildProviderTools, Z as composeAgentToolCatalog, a as NCP_SESSION_REQUEST_FAILED_EVENT_TYPE, b as isStreamingMessageCreationEvent, et as createAgentPeerSessionIdentity, h as mergePartialSessionMessage, i as NCP_SESSION_REQUEST_COMPLETED_EVENT_TYPE, m as SessionEventReplayer, nt as StructuredResultSubmitTool, q as COMPACTION_RECOVERY_NOTICE, r as NCP_SESSION_REQUEST_ACCEPTED_EVENT_TYPE, s as createNcpAgentSessionSummary, tt as STRUCTURED_RESULT_TOOL_NAME, w as readMessageFromSummaryEvent, x as readEventMessageId, y as isReplayContinuationEvent } from "./ncp-agent-session-journal.utils-DPKiIDII.js";
2
2
  import { i as isSessionJournalDelta, n as canCoalesceSessionJournalDeltas, r as coalesceSessionJournalDeltas } from "./session-journal-delta-coalescer.utils-CI-N-Zpj.js";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { CHAT_CONTINUATION_TARGET_MESSAGE_METADATA_KEY, CHAT_SESSION_MATERIALIZATION_METADATA_KEY, Contribution, DIAGNOSTIC_CORRELATION_METADATA_KEY, EventBus, Ingress, classifyDiagnosticError, createPanelAppResourceUri, createSessionResourceUri, eventKeys, ingressKeys, isRuntimeDefaultModelValue, isSilentReplyNcpMessage, readUiContentParams } from "@nextclaw/shared";
@@ -833,10 +833,27 @@ function preview(value, remaining, depth = 0) {
833
833
  function buildSessionValuePreview(value) {
834
834
  return preview(value, { chars: 8192 });
835
835
  }
836
+ function previewMessagePart(part, budget) {
837
+ const value = preview(part, budget);
838
+ if (part.type !== "tool-invocation") return value;
839
+ const fields = value && typeof value === "object" ? value : {};
840
+ const contentItems = Array.isArray(fields.resultContentItems) ? fields.resultContentItems.filter((item) => item !== null && typeof item === "object" && (item.type === "input_text" && typeof item.text === "string" || item.type === "input_image" && typeof item.imageUrl === "string" && !item.imageUrl.includes("[archived; read source]"))) : void 0;
841
+ return {
842
+ type: "tool-invocation",
843
+ toolName: part.toolName,
844
+ toolCallId: part.toolCallId,
845
+ state: part.state,
846
+ payloadDeferred: true,
847
+ ...part.args !== void 0 ? { args: part.args && typeof part.args === "object" && typeof fields.args !== "object" ? {} : fields.args ?? {} } : {},
848
+ ...part.result !== void 0 ? { result: fields.result !== void 0 ? fields.result : "[archived; read source]" } : {},
849
+ ...contentItems ? { resultContentItems: contentItems } : {},
850
+ ...part.execution ? { execution: part.execution } : {}
851
+ };
852
+ }
836
853
  /** Descriptors are persisted at ingestion, not made after reading a full stored message. */
837
854
  function buildSessionMessageDescriptor(message, revision) {
838
855
  const budget = { chars: 2048 };
839
- const parts = message.parts.slice(0, 16).map((part) => preview(part, budget));
856
+ const parts = message.parts.slice(0, 16).map((part) => previewMessagePart(part, budget));
840
857
  const descriptor = {
841
858
  id: message.id,
842
859
  sessionId: message.sessionId,
@@ -2091,6 +2108,53 @@ var SessionMessagePreparationStore = class SessionMessagePreparationStore {
2091
2108
  };
2092
2109
  };
2093
2110
  //#endregion
2111
+ //#region src/utils/session-journal-error.utils.ts
2112
+ const SESSION_JOURNAL_FAILURE_SOURCE = "session-event-coordinator:journal-failure";
2113
+ const SESSION_JOURNAL_WRITE_FAILED = "SESSION_JOURNAL_WRITE_FAILED";
2114
+ var SessionJournalWriteError = class extends Error {
2115
+ code = SESSION_JOURNAL_WRITE_FAILED;
2116
+ constructor(sessionId, cause) {
2117
+ const detail = cause instanceof Error ? cause.message : String(cause);
2118
+ const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
2119
+ 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 });
2120
+ this.name = "SessionJournalWriteError";
2121
+ }
2122
+ };
2123
+ function isSessionJournalWriteError(error) {
2124
+ return error instanceof Error && "code" in error && error.code === "SESSION_JOURNAL_WRITE_FAILED";
2125
+ }
2126
+ /** Read only the transaction's scalar diagnostics; never copy the failed event. */
2127
+ function readSessionJournalFailureContext(error) {
2128
+ const seen = /* @__PURE__ */ new Set();
2129
+ let current = error;
2130
+ for (let depth = 0; current && typeof current === "object" && depth < 8 && !seen.has(current); depth++) {
2131
+ seen.add(current);
2132
+ const record = current;
2133
+ const context = record.sessionPersistence;
2134
+ if (context && typeof context === "object") {
2135
+ const detail = {};
2136
+ for (const key of [
2137
+ "operation",
2138
+ "stage",
2139
+ "path",
2140
+ "seq",
2141
+ "previousOffset",
2142
+ "journalOffset",
2143
+ "rollback",
2144
+ "journalCommitted",
2145
+ "metadataCommitted"
2146
+ ]) {
2147
+ const value = context[key];
2148
+ if (typeof value === "string") detail[key] = value.slice(0, 2048);
2149
+ else if (typeof value === "number" || typeof value === "boolean") detail[key] = value;
2150
+ }
2151
+ return detail;
2152
+ }
2153
+ current = record.cause;
2154
+ }
2155
+ return {};
2156
+ }
2157
+ //#endregion
2094
2158
  //#region src/features/runtime-registry/utils/agent-runtime-registry.utils.ts
2095
2159
  function normalizeIdentifier(value) {
2096
2160
  if (typeof value !== "string") return null;
@@ -4398,53 +4462,6 @@ var SessionActivityPreviewEventService = class {
4398
4462
  };
4399
4463
  };
4400
4464
  //#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
4465
  //#region src/services/session-event-ingestion.service.ts
4449
4466
  const SESSION_METADATA_PATCH_RUN_METADATA_KIND = "session_metadata_patch";
4450
4467
  const PERSISTED_SESSION_EVENT_SOURCE = "session-event-coordinator:persisted";
@@ -4463,6 +4480,7 @@ var SessionEventIngestionService = class {
4463
4480
  activityPreview;
4464
4481
  chains = /* @__PURE__ */ new Map();
4465
4482
  failedWrites = /* @__PURE__ */ new Map();
4483
+ failedProjections = /* @__PURE__ */ new Set();
4466
4484
  pendingDeltas = /* @__PURE__ */ new Map();
4467
4485
  cleanup = null;
4468
4486
  constructor(options) {
@@ -4545,6 +4563,21 @@ var SessionEventIngestionService = class {
4545
4563
  await this.chains.get(sessionId);
4546
4564
  this.throwIfFailed(sessionId);
4547
4565
  };
4566
+ recoverSession = async (sessionId, restore) => {
4567
+ await this.chains.get(sessionId);
4568
+ try {
4569
+ const result = await restore();
4570
+ this.failedWrites.delete(sessionId);
4571
+ return result;
4572
+ } catch (error) {
4573
+ console.error("Session storage recovery failed", {
4574
+ event: "session.persistence.recovery_failed",
4575
+ sessionId,
4576
+ ...readSessionJournalFailureContext(error)
4577
+ }, error);
4578
+ throw error;
4579
+ }
4580
+ };
4548
4581
  flush = async () => {
4549
4582
  for (const sessionId of this.pendingDeltas.keys()) this.flushPendingDelta(sessionId);
4550
4583
  await Promise.all([...this.chains.values()]);
@@ -4557,6 +4590,7 @@ var SessionEventIngestionService = class {
4557
4590
  this.pendingDeltas.clear();
4558
4591
  this.chains.clear();
4559
4592
  this.failedWrites.clear();
4593
+ this.failedProjections.clear();
4560
4594
  this.activityPreview.clear();
4561
4595
  };
4562
4596
  flushPendingDelta = (sessionId) => {
@@ -4592,7 +4626,6 @@ var SessionEventIngestionService = class {
4592
4626
  if (failure) throw failure;
4593
4627
  };
4594
4628
  handleDurableEvent = async (sessionId, event, signal) => {
4595
- const preview = this.activityPreview.projectEvent(event, (/* @__PURE__ */ new Date()).toISOString());
4596
4629
  const metadataPatch = readRuntimeSessionMetadataPatch(event);
4597
4630
  if (metadataPatch) {
4598
4631
  await this.options.updateSessionMetadata(sessionId, metadataPatch);
@@ -4603,11 +4636,33 @@ var SessionEventIngestionService = class {
4603
4636
  sessionId,
4604
4637
  signal
4605
4638
  });
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 });
4639
+ let operation = "checkpoint-metadata";
4640
+ try {
4641
+ if (event.type === NcpEventType.MessageSent) {
4642
+ const checkpoint = readContextCompactionCheckpoint(event.payload.message);
4643
+ if (checkpoint) await this.options.updateSessionMetadata(sessionId, { [CONTEXT_COMPACTION_METADATA_KEY]: checkpoint });
4644
+ }
4645
+ this.failedProjections.delete(`${sessionId}:${operation}`);
4646
+ operation = "activity-preview";
4647
+ const preview = this.activityPreview.projectEvent(event, (/* @__PURE__ */ new Date()).toISOString());
4648
+ if (preview) {
4649
+ await this.activityPreview.updatePreview(preview);
4650
+ this.failedProjections.delete(`${sessionId}:${operation}`);
4651
+ }
4652
+ } catch (error) {
4653
+ const key = `${sessionId}:${operation}`;
4654
+ if (this.failedProjections.has(key)) return;
4655
+ this.failedProjections.add(key);
4656
+ console.warn("Session projection failed after the event was saved", {
4657
+ event: "session.persistence.projection_failed",
4658
+ operation,
4659
+ projection: operation,
4660
+ sessionId,
4661
+ eventType: event.type,
4662
+ journalCommitted: true,
4663
+ ...readSessionJournalFailureContext(error)
4664
+ }, error);
4609
4665
  }
4610
- if (preview) await this.activityPreview.updatePreview(preview);
4611
4666
  };
4612
4667
  };
4613
4668
  //#endregion
@@ -4621,9 +4676,23 @@ var SessionEventCoordinatorService = class {
4621
4676
  getSessionRecord: options.getSessionRecord,
4622
4677
  listUnfinishedRuns: options.listUnfinishedRuns,
4623
4678
  onError: (sessionId, error, event) => {
4624
- const detail = formatSessionJournalError(error);
4625
- console.error(`[session-manager] failed to handle ncp event for ${sessionId}: ${detail}`);
4626
4679
  const payload = event && "payload" in event ? event.payload : void 0;
4680
+ const detail = error instanceof Error ? error.message : String(error);
4681
+ console.error(`[session-manager] failed to handle ncp event for ${sessionId}: ${detail}`, {
4682
+ event: "session.persistence.failed",
4683
+ outcome: "failed",
4684
+ sessionId,
4685
+ eventType: event?.type,
4686
+ operation: event?.type === NcpEventType.RunMetadata ? "metadata.update" : "event.ingest",
4687
+ ...event ? {
4688
+ runId: readEventRunId$1(event),
4689
+ messageId: readEventMessageId(event)
4690
+ } : {},
4691
+ ...payload && "correlationId" in payload ? { correlationId: payload.correlationId } : {},
4692
+ nodeVersion: process.version,
4693
+ platform: process.platform,
4694
+ ...readSessionJournalFailureContext(error)
4695
+ }, error);
4627
4696
  const endedAt = (/* @__PURE__ */ new Date()).toISOString();
4628
4697
  options.eventBus.emit(eventKeys.ncpEvent, {
4629
4698
  type: NcpEventType.RunError,
@@ -4651,6 +4720,33 @@ var SessionEventCoordinatorService = class {
4651
4720
  flushSession = async (sessionId) => await this.ingestion.flushSession(sessionId);
4652
4721
  flush = async () => await this.ingestion.flush();
4653
4722
  persist = (event, signal) => this.ingestion.ingestEvent(event, signal);
4723
+ loadRunSeed = async (sessionId) => {
4724
+ if (!this.options.journalStore.loadSessionRunSeed) throw new Error("This session host does not support bounded run loading.");
4725
+ await this.ingestion.flushSession(sessionId);
4726
+ return this.options.journalStore.loadSessionRunSeed(sessionId);
4727
+ };
4728
+ recoverRun = (sessionId) => this.ingestion.recoverSession(sessionId, async () => {
4729
+ const store = this.options.journalStore;
4730
+ if (!store.loadSessionRunSeed || !store.getSessionSummary) throw new Error("This session host does not support bounded recovery.");
4731
+ const state = await store.prepareSessionHistory?.(sessionId, {
4732
+ retry: true,
4733
+ wait: true
4734
+ });
4735
+ if (state && state.status !== "ready") throw new Error(state.error ?? "Session history recovery is not ready.");
4736
+ if (!await store.getSessionSummary(sessionId)) throw new Error("The saved session is unavailable; its original files were retained.");
4737
+ await this.options.appendSessionEvent({
4738
+ sessionId,
4739
+ event: {
4740
+ type: NcpEventType.RunMetadata,
4741
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
4742
+ payload: {
4743
+ sessionId,
4744
+ metadata: { kind: "session_storage_recovery" }
4745
+ }
4746
+ }
4747
+ });
4748
+ return store.loadSessionRunSeed(sessionId);
4749
+ });
4654
4750
  publish = async (params) => {
4655
4751
  const { event, sessionId, source, synchronizeMessageProjection, persistFirst } = params;
4656
4752
  if (persistFirst) {
@@ -5048,11 +5144,8 @@ var SessionManager = class {
5048
5144
  if (!this.options.journalStore.readSessionMessagePart) throw new Error("This session host does not support exact history reads.");
5049
5145
  return this.options.journalStore.readSessionMessagePart(params);
5050
5146
  };
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
- };
5147
+ loadSessionRunSeed = (sessionId) => this.sessionEvents.loadRunSeed(sessionId);
5148
+ recoverSessionRun = (sessionId) => this.sessionEvents.recoverRun(sessionId);
5056
5149
  getSession = async (sessionId) => {
5057
5150
  const normalizedSessionId = normalizeSessionId(sessionId);
5058
5151
  if (!normalizedSessionId) return null;
@@ -5190,7 +5283,6 @@ var SessionManager = class {
5190
5283
  //#endregion
5191
5284
  //#region src/utils/user-question.utils.ts
5192
5285
  const USER_QUESTION_EXTENSION_TYPE = "nextclaw.user-question";
5193
- const CONTEXT_RECOVERY_CHANNEL_CONFIRMATION_PREFIX = "确认续做:";
5194
5286
  function createQuestionMessage(sessionId, prompts) {
5195
5287
  if (prompts.length < 1 || prompts.length > 3) throw new Error("Provide one to three questions.");
5196
5288
  const questions = prompts.map((prompt) => ({
@@ -5317,17 +5409,6 @@ var UserQuestionManager = class {
5317
5409
  throw new UserQuestionError("INVALID_ANSWER", error instanceof Error ? error.message : "Invalid question");
5318
5410
  }
5319
5411
  const { message } = created;
5320
- const recovery = this.runs.getSessionRun(sessionId)?.getContextRecoveryState();
5321
- if (recovery?.required) {
5322
- message.metadata = {
5323
- ...message.metadata,
5324
- nextclaw_context_recovery_checkpoint: recovery.checkpointId
5325
- };
5326
- message.parts.push({
5327
- type: "text",
5328
- text: `此前部分上下文尚未核实。请确认本次继续任务的具体条件;旧操作的结果仍须核实,不能直接重做。通过聊天回复时,请使用“${CONTEXT_RECOVERY_CHANNEL_CONFIRMATION_PREFIX}”开头,并写明任务范围和条件。`
5329
- });
5330
- }
5331
5412
  const event = {
5332
5413
  type: NcpEventType.MessageSent,
5333
5414
  occurredAt: message.timestamp,
@@ -7089,6 +7170,7 @@ var AgentRunRequestManager = class {
7089
7170
  const queuedRequest = sessionRun.enqueueRequest(normalizedRequest, session);
7090
7171
  const steeringRequest = request.delivery === "prefer-steer" && sessionRun.isRunning() ? this.pendingInputs.promotePreferredSteeringInput(sessionRun, queuedRequest.id, session) : null;
7091
7172
  if (steeringRequest) {
7173
+ sessionRun.acknowledgeRequest(queuedRequest.id);
7092
7174
  this.publishRunQueueUpdated(session.sessionId);
7093
7175
  return {
7094
7176
  sessionId: session.sessionId,
@@ -7102,6 +7184,7 @@ var AgentRunRequestManager = class {
7102
7184
  this.publishRunQueueUpdated(session.sessionId);
7103
7185
  if (activeRequest?.id === queuedRequest.id) await this.startQueuedRun(sessionRun, activeRequest);
7104
7186
  else if (activeRequest) this.startQueuedRun(sessionRun, activeRequest).catch(() => void 0);
7187
+ sessionRun.acknowledgeRequest(queuedRequest.id);
7105
7188
  return {
7106
7189
  sessionId: session.sessionId,
7107
7190
  userMessageId: queuedRequest.request.message.id,
@@ -7134,12 +7217,6 @@ var AgentRunRequestManager = class {
7134
7217
  startedAt: requestRunStartedAt,
7135
7218
  trigger
7136
7219
  });
7137
- const providerRequest = {
7138
- ...request,
7139
- agentId: spec.agentId,
7140
- sessionId: session.sessionId,
7141
- message
7142
- };
7143
7220
  const correlationId = request.correlationId ?? activeRequest.runId;
7144
7221
  const parentCorrelationId = typeof request.metadata?.[DIAGNOSTIC_CORRELATION_METADATA_KEY] === "string" ? request.metadata[DIAGNOSTIC_CORRELATION_METADATA_KEY] : void 0;
7145
7222
  this.diagnostics?.record({
@@ -7154,16 +7231,15 @@ var AgentRunRequestManager = class {
7154
7231
  ...request.channel ? { channel: request.channel } : {}
7155
7232
  }
7156
7233
  });
7157
- const messageSentEvent = createMessageSentEvent({
7234
+ const initialEvents = [createMessageSentEvent({
7158
7235
  sessionId: session.sessionId,
7159
7236
  message,
7160
7237
  correlationId: request.correlationId
7161
- });
7162
- const triggerEvent = createRunTriggerMetadataEvent({
7238
+ }), createRunTriggerMetadataEvent({
7163
7239
  sessionId: session.sessionId,
7164
7240
  spec,
7165
7241
  trigger
7166
- });
7242
+ })];
7167
7243
  try {
7168
7244
  releaseCapacity = await this.admissions.acquireExecution(activeRequest.signal);
7169
7245
  executionClaim = await this.claimSessionExecutionOrFail({
@@ -7172,15 +7248,19 @@ var AgentRunRequestManager = class {
7172
7248
  spec
7173
7249
  });
7174
7250
  activeRequest.signal.throwIfAborted();
7175
- await sessionRun.applyEvents([messageSentEvent, triggerEvent]);
7176
- this.publishNcpEvent(messageSentEvent);
7177
- this.publishNcpEvent(triggerEvent);
7251
+ await sessionRun.applyEvents(initialEvents);
7252
+ initialEvents.forEach(this.publishNcpEvent);
7178
7253
  const runtime = this.agentRuntimeManager.getOrCreate({
7179
7254
  agentRuntimeId: session.agentRuntimeId,
7180
7255
  session,
7181
7256
  sessionRun
7182
7257
  });
7183
- const { contextBlocks, tools } = await this.agentContextWindowManager.resolveRunSurface(providerRequest);
7258
+ const { contextBlocks, tools } = await this.agentContextWindowManager.resolveRunSurface({
7259
+ ...request,
7260
+ agentId: spec.agentId,
7261
+ sessionId: session.sessionId,
7262
+ message
7263
+ });
7184
7264
  this.startRuntimeRun({
7185
7265
  options: {
7186
7266
  contextBlocks,
@@ -7213,13 +7293,17 @@ var AgentRunRequestManager = class {
7213
7293
  providerCode: classification.providerCode,
7214
7294
  facts: classification.facts
7215
7295
  });
7216
- await this.publishRunStartupFailure({
7217
- error,
7218
- requestRunStartedAt,
7219
- sessionRun,
7220
- spec
7221
- });
7222
- this.startNextQueuedRun(sessionRun);
7296
+ try {
7297
+ await this.publishRunStartupFailure({
7298
+ error,
7299
+ requestRunStartedAt,
7300
+ sessionRun,
7301
+ spec
7302
+ });
7303
+ } finally {
7304
+ sessionRun.settleRun(activeRequest.runId);
7305
+ this.startNextQueuedRun(sessionRun);
7306
+ }
7223
7307
  throw error;
7224
7308
  }
7225
7309
  };
@@ -7243,11 +7327,13 @@ var AgentRunRequestManager = class {
7243
7327
  };
7244
7328
  startRuntimeRun = (params) => {
7245
7329
  const { executionClaim, releaseCapacity, ...runtimeParams } = params;
7330
+ params.options.sessionRun.markRuntimeStarted(params.spec.runId);
7246
7331
  this.runtimeRuns.start({
7247
7332
  ...runtimeParams,
7248
7333
  onSettled: (sessionRun) => {
7249
7334
  executionClaim?.release();
7250
7335
  releaseCapacity?.();
7336
+ sessionRun.settleRun(params.spec.runId);
7251
7337
  this.startNextQueuedRun(sessionRun);
7252
7338
  }
7253
7339
  });
@@ -7636,6 +7722,7 @@ function recordProductActivityBestEffort(sink, signal) {
7636
7722
  //#region src/managers/session-pending-inputs.manager.ts
7637
7723
  /** Single owner for inputs waiting for either the next run or the next safe step. */
7638
7724
  var SessionPendingInputs = class {
7725
+ acknowledged = /* @__PURE__ */ new Set();
7639
7726
  nextRun = [];
7640
7727
  nextStep = [];
7641
7728
  claimedNextStep = /* @__PURE__ */ new Map();
@@ -7680,11 +7767,22 @@ var SessionPendingInputs = class {
7680
7767
  const index = this.nextRun.findIndex(({ id }) => id === requestId);
7681
7768
  if (index < 0) return null;
7682
7769
  const [removed] = this.nextRun.splice(index, 1);
7770
+ this.acknowledged.delete(requestId);
7683
7771
  return removed ? structuredClone(removed) : null;
7684
7772
  };
7773
+ acknowledgeRequest = (requestId) => {
7774
+ if (this.nextRun.some((request) => request.id === requestId) || this.nextStep.some((request) => request.id === requestId) || this.claimedNextStep.has(requestId)) this.acknowledged.add(requestId);
7775
+ };
7776
+ restoreNextRun = (request) => {
7777
+ this.acknowledged.add(request.id);
7778
+ this.nextRun.unshift(request);
7779
+ };
7685
7780
  shiftNextRun = () => {
7686
7781
  const request = this.nextRun.shift();
7687
- return request ? structuredClone(request) : null;
7782
+ return request ? {
7783
+ ...structuredClone(request),
7784
+ acknowledged: this.acknowledged.delete(request.id)
7785
+ } : null;
7688
7786
  };
7689
7787
  claimNextStep = (runId) => {
7690
7788
  const claimed = [];
@@ -7698,7 +7796,10 @@ var SessionPendingInputs = class {
7698
7796
  return structuredClone(claimed);
7699
7797
  };
7700
7798
  acknowledgeNextStep = (requestIds) => {
7701
- for (const requestId of requestIds) this.claimedNextStep.delete(requestId);
7799
+ for (const requestId of requestIds) {
7800
+ this.claimedNextStep.delete(requestId);
7801
+ this.acknowledged.delete(requestId);
7802
+ }
7702
7803
  };
7703
7804
  restoreNextStep = (runId) => {
7704
7805
  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 +7815,7 @@ var SessionPendingInputs = class {
7714
7815
  this.nextRun.length = 0;
7715
7816
  this.nextStep.length = 0;
7716
7817
  this.claimedNextStep.clear();
7818
+ this.acknowledged.clear();
7717
7819
  };
7718
7820
  toPendingRequest = (request, placement, intendedRunId) => structuredClone({
7719
7821
  ...request,
@@ -7743,6 +7845,9 @@ var SessionRun = class {
7743
7845
  eventChain = Promise.resolve();
7744
7846
  windowGrowthBytes = 0;
7745
7847
  persistenceFailure = null;
7848
+ execution = null;
7849
+ recovery = null;
7850
+ disposed = false;
7746
7851
  constructor(seed, stateManager = new DefaultNcpAgentConversationStateManager(), productActivitySink, persistEvent) {
7747
7852
  this.stateManager = stateManager;
7748
7853
  this.productActivitySink = productActivitySink;
@@ -7959,13 +8064,61 @@ var SessionRun = class {
7959
8064
  acknowledgeNextStepRequests = (requestIds) => {
7960
8065
  this.pendingInputs.acknowledgeNextStep(requestIds);
7961
8066
  };
8067
+ acknowledgeRequest = (requestId) => {
8068
+ if (this.execution?.request.id === requestId) this.execution.acknowledged = true;
8069
+ else this.pendingInputs.acknowledgeRequest(requestId);
8070
+ };
8071
+ markRuntimeStarted = (runId) => {
8072
+ if (this.execution?.request.runId === runId) this.execution.runtimeStarted = true;
8073
+ };
8074
+ settleRun = (runId) => {
8075
+ const execution = this.execution;
8076
+ if (!execution || execution.request.runId !== runId) return;
8077
+ const wasBusy = this.isBusy();
8078
+ if (this.persistenceFailure && execution.acknowledged && !execution.runtimeStarted) this.pendingInputs.restoreNextRun(execution.request);
8079
+ this.execution = null;
8080
+ execution.resolve();
8081
+ this.emitStatusChangeIfNeeded(wasBusy);
8082
+ };
8083
+ recoverPersistence = (load) => {
8084
+ if (!this.persistenceFailure) return Promise.resolve();
8085
+ if (this.recovery) return this.recovery;
8086
+ this.recovery = (async () => {
8087
+ await this.execution?.settled;
8088
+ await this.eventChain;
8089
+ if (this.disposed) throw new Error("Session run was disposed during storage recovery.");
8090
+ const messages = await load();
8091
+ if (this.disposed) throw new Error("Session run was disposed during storage recovery.");
8092
+ this.stateManager.hydrate({
8093
+ sessionId: this.sessionId,
8094
+ messages
8095
+ });
8096
+ this.windowGrowthBytes = 0;
8097
+ for (const fragment of sessionJsonFragments(messages)) this.windowGrowthBytes += Buffer.byteLength(fragment);
8098
+ this.persistenceFailure = null;
8099
+ })().finally(() => {
8100
+ this.recovery = null;
8101
+ });
8102
+ return this.recovery;
8103
+ };
7962
8104
  getActiveRunId = () => this.activeRunId;
7963
8105
  beginNextRun = () => {
7964
8106
  if (this.persistenceFailure) return null;
7965
- if (this.activeRunId) return null;
8107
+ if (this.activeRunId || this.execution) return null;
7966
8108
  const wasBusy = this.isBusy();
7967
- const queuedRequest = this.pendingInputs.shiftNextRun();
7968
- if (!queuedRequest) return null;
8109
+ const next = this.pendingInputs.shiftNextRun();
8110
+ if (!next) return null;
8111
+ const { acknowledged, ...queuedRequest } = next;
8112
+ let resolve;
8113
+ this.execution = {
8114
+ request: queuedRequest,
8115
+ acknowledged,
8116
+ runtimeStarted: false,
8117
+ settled: new Promise((done) => {
8118
+ resolve = done;
8119
+ }),
8120
+ resolve
8121
+ };
7969
8122
  const controller = new AbortController();
7970
8123
  this.activeRunId = queuedRequest.runId;
7971
8124
  this.activeRunController = controller;
@@ -7991,7 +8144,7 @@ var SessionRun = class {
7991
8144
  failPersistence = (error) => {
7992
8145
  const wasBusy = this.isBusy();
7993
8146
  this.persistenceFailure ??= typeof error === "string" ? Object.assign(new Error(error), { code: SESSION_JOURNAL_WRITE_FAILED }) : error;
7994
- this.pendingInputs.clear();
8147
+ if (this.activeRunId) this.pendingInputs.restoreNextStep(this.activeRunId);
7995
8148
  this.activeRunController?.abort(this.persistenceFailure);
7996
8149
  this.activeRunController = null;
7997
8150
  this.activeRunId = null;
@@ -7999,9 +8152,10 @@ var SessionRun = class {
7999
8152
  this.emitStatusChangeIfNeeded(wasBusy);
8000
8153
  };
8001
8154
  isRunning = () => this.activeRunId !== null;
8002
- isBusy = () => this.isRunning() || this.pendingInputs.hasNextRun;
8155
+ isBusy = () => this.isRunning() || this.execution !== null || this.recovery !== null || this.pendingInputs.hasNextRun;
8003
8156
  dispose = () => {
8004
8157
  const wasBusy = this.isBusy();
8158
+ this.disposed = true;
8005
8159
  this.activeRunController?.abort({
8006
8160
  code: "abort-error",
8007
8161
  message: "Session run owner was disposed; the current run was cancelled.",
@@ -8011,6 +8165,8 @@ var SessionRun = class {
8011
8165
  this.activeRunId = null;
8012
8166
  this.activeProductActivitySource = null;
8013
8167
  this.pendingInputs.clear();
8168
+ this.execution?.resolve();
8169
+ this.execution = null;
8014
8170
  this.emitStatusChangeIfNeeded(wasBusy);
8015
8171
  this.statusListeners.clear();
8016
8172
  };
@@ -8066,8 +8222,17 @@ var SessionRunManager = class {
8066
8222
  }] : [];
8067
8223
  });
8068
8224
  getOrCreateSessionRun = async (sessionId) => {
8225
+ if (this.disposed) throw new Error("Session run manager is disposed.");
8069
8226
  const existing = this.getSessionRun(sessionId);
8070
- if (existing) return existing;
8227
+ if (existing) {
8228
+ await existing.recoverPersistence(async () => {
8229
+ if (!this.sessionManager.recoverSessionRun) throw new Error("This session host cannot recover storage without restarting.");
8230
+ const messages = await this.sessionManager.recoverSessionRun(sessionId);
8231
+ await this.prepareRunMessages(sessionId, messages);
8232
+ return messages;
8233
+ });
8234
+ return existing;
8235
+ }
8071
8236
  const pending = this.pendingCreations.get(sessionId);
8072
8237
  if (pending) return await pending;
8073
8238
  const creation = this.createSessionRun(sessionId).finally(() => {
@@ -8094,6 +8259,20 @@ var SessionRunManager = class {
8094
8259
  if (this.runs.has(sessionId)) throw new Error(`Session run already exists: ${sessionId}`);
8095
8260
  const messages = this.sessionManager.loadSessionRunSeed ? await this.sessionManager.loadSessionRunSeed(sessionId) : await this.sessionManager.listSessionMessages(sessionId);
8096
8261
  if (this.disposed) throw new Error("Session run manager is disposed.");
8262
+ await this.prepareRunMessages(sessionId, messages);
8263
+ const run = new SessionRun({
8264
+ messages,
8265
+ sessionId
8266
+ }, void 0, this.productActivitySink, this.sessionManager.persistSessionEvent);
8267
+ this.runs.set(sessionId, run);
8268
+ run.onStatusChange((status) => {
8269
+ if (status === "running") this.inactiveBytes.delete(sessionId);
8270
+ else this.trimInactive(sessionId);
8271
+ });
8272
+ this.trimInactive(sessionId);
8273
+ return run;
8274
+ };
8275
+ prepareRunMessages = async (sessionId, messages) => {
8097
8276
  const checkpoint = readLatestContextCompactionCheckpoint(messages);
8098
8277
  const firstOrdinal = messages.reduce((first, message) => {
8099
8278
  const ordinal = Number((message.metadata?.nextclaw_source)?.ordinal);
@@ -8146,17 +8325,6 @@ var SessionRunManager = class {
8146
8325
  });
8147
8326
  messages.push(marker);
8148
8327
  }
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
8328
  };
8161
8329
  trimInactive = (protectedId) => {
8162
8330
  const current = this.runs.get(protectedId);
@@ -9459,6 +9627,6 @@ var NextclawHarness = class {
9459
9627
  };
9460
9628
  };
9461
9629
  //#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 };
9630
+ 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
9631
 
9464
- //# sourceMappingURL=nextclaw-harness.manager-Bv3YnpO5.js.map
9632
+ //# sourceMappingURL=nextclaw-harness.manager-CjDdaCHx.js.map