chainlesschain 0.166.145 → 0.166.147

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 (53) hide show
  1. package/README.md +67 -10
  2. package/package.json +2 -2
  3. package/src/assets/linux-subreaper/linux-arm64/manifest.json +1 -1
  4. package/src/assets/linux-subreaper/linux-x64/manifest.json +1 -1
  5. package/src/command-help-index.json +2 -2
  6. package/src/commands/agent.js +20 -1
  7. package/src/commands/mcp-tasks.js +37 -4
  8. package/src/commands/mcp.js +24 -0
  9. package/src/commands/memory.js +131 -7
  10. package/src/data/changelog.json +26 -0
  11. package/src/generated/cc-agent-protocol.schema.json +175 -69
  12. package/src/harness/jsonl-session-store.js +4 -0
  13. package/src/harness/mcp-client.js +273 -48
  14. package/src/harness/prompt-compressor.js +1 -0
  15. package/src/harness/session-index.js +8 -0
  16. package/src/harness/session-list-index.js +2 -0
  17. package/src/lib/agent-session-export.js +19 -0
  18. package/src/lib/app-server/context-memory-notifications.js +11 -2
  19. package/src/lib/app-server/server.js +1 -0
  20. package/src/lib/background-launch-profile.js +38 -6
  21. package/src/lib/context-memory-kernel/local-semantic-source.js +426 -0
  22. package/src/lib/context-memory-kernel/local-semantic-worker.py +109 -0
  23. package/src/lib/context-memory-kernel/memory-service.js +35 -2
  24. package/src/lib/context-memory-kernel/provider-context.js +1 -1
  25. package/src/lib/context-memory-kernel/runtime.js +40 -0
  26. package/src/lib/evolution/evolution-artifact-ports.js +36 -1
  27. package/src/lib/evolution/evolution-ledger-file-manifest-head-store.js +19 -0
  28. package/src/lib/evolution/evolution-ledger-manifest-catalog.js +13 -0
  29. package/src/lib/evolution/evolution-ledger-manifest-head-store.js +17 -0
  30. package/src/lib/evolution/evolution-ledger-v2-manifest-backend.js +29 -2
  31. package/src/lib/formal-budget-authority.js +56 -3
  32. package/src/lib/formal-budget-contract.js +90 -5
  33. package/src/lib/mcp-client.js +1 -0
  34. package/src/lib/mcp-stateless-protocol.js +158 -0
  35. package/src/lib/mcp-task-continuation-contract.js +129 -0
  36. package/src/lib/mcp-task-continuation.js +147 -0
  37. package/src/lib/mcp-task-journal-projection.js +49 -4
  38. package/src/lib/mcp-task-runtime.js +148 -1
  39. package/src/lib/mcp-tasks.js +24 -0
  40. package/src/lib/session-host-snapshot.js +31 -0
  41. package/src/lib/session-input-lifecycle.js +147 -0
  42. package/src/lib/session-input-receipt.js +64 -0
  43. package/src/lib/session-message-provenance.js +6 -5
  44. package/src/lib/session-model-usage-recovery.js +115 -0
  45. package/src/lib/session-transcript-history.js +3 -0
  46. package/src/lib/session-transcript-structure.js +8 -1
  47. package/src/lib/storage-failure-cause-codes.js +79 -0
  48. package/src/repl/agent-repl.js +348 -23
  49. package/src/runtime/agent-core.js +29 -11
  50. package/src/runtime/headless-runner.js +1 -0
  51. package/src/runtime/headless-stream.js +40 -33
  52. package/src/runtime/mcp-config.js +5 -3
  53. package/src/runtime/policies/agent-policy.js +1 -0
@@ -1,4 +1,6 @@
1
+ import { formatSessionModelUsageRecoveryNotice } from "../lib/session-model-usage-recovery.js";
1
2
  import { createPersistedModelInputObserver } from "../lib/session-model-input-diagnostics.js";
3
+ import { summarizeMcpPayload } from "../lib/mcp-call-ledger.js";
2
4
  /**
3
5
  * Agentic REPL - Claude Code / Codex style
4
6
  *
@@ -108,6 +110,10 @@ import {
108
110
  persistSideEffectLedger,
109
111
  } from "../lib/side-effect-ledger-store.js";
110
112
  import { operationIdempotencyKey } from "../lib/idempotency.js";
113
+ import {
114
+ appendSessionInputAcceptance,
115
+ appendSessionInputSettlement,
116
+ } from "../lib/session-input-receipt.js";
111
117
  import { collectToolResourceIdentifiers } from "../lib/permission-side-effect-center.js";
112
118
  import {
113
119
  preserveDurableSystemMessageProvenance,
@@ -2070,7 +2076,7 @@ function collapseValidatedPlainReplTailInPlace(messages) {
2070
2076
  return true;
2071
2077
  }
2072
2078
 
2073
- function normalizeReplReplayMessages(rebuiltMessages) {
2079
+ function normalizeReplReplayMessages(rebuiltMessages, referenceDigests = []) {
2074
2080
  // Validate the immutable raw snapshot before any normalization. In
2075
2081
  // particular, never let a same-role merge hide malformed tool authority.
2076
2082
  validateRawReplReplayMessages(rebuiltMessages);
@@ -2087,9 +2093,25 @@ function normalizeReplReplayMessages(rebuiltMessages) {
2087
2093
  );
2088
2094
  let phase = "expect-initial-conversation-message";
2089
2095
  let pendingToolCallIds = null;
2096
+ let previousConversation = null;
2097
+ const references = new Set(referenceDigests);
2090
2098
 
2091
2099
  for (let index = 0; index < conversationMessages.length; index += 1) {
2092
2100
  const message = conversationMessages[index];
2101
+ // External references are neither model answers nor tool exchanges. Only
2102
+ // exact commitments from this same verified transcript may be transparent
2103
+ // to alternation; a peer-chosen name or prefix cannot grant this exception.
2104
+ if (
2105
+ message.role === "assistant" &&
2106
+ message.name === "mcp_task_result" &&
2107
+ references.has(summarizeMcpPayload(message).sha256)
2108
+ )
2109
+ continue;
2110
+ const samePlainRun =
2111
+ previousConversation?.role === message.role &&
2112
+ isPlainReplMergeMessage(previousConversation) &&
2113
+ isPlainReplMergeMessage(message);
2114
+ previousConversation = message;
2093
2115
  const hasToolCalls = Object.prototype.hasOwnProperty.call(
2094
2116
  message,
2095
2117
  "tool_calls",
@@ -2113,7 +2135,8 @@ function normalizeReplReplayMessages(rebuiltMessages) {
2113
2135
  if (message.role === "user") {
2114
2136
  if (
2115
2137
  phase !== "expect-user" &&
2116
- phase !== "expect-initial-conversation-message"
2138
+ phase !== "expect-initial-conversation-message" &&
2139
+ !samePlainRun
2117
2140
  ) {
2118
2141
  throw invalidReplRecovery(
2119
2142
  `REPL session user message[${index}] breaks role alternation`,
@@ -2127,7 +2150,8 @@ function normalizeReplReplayMessages(rebuiltMessages) {
2127
2150
  if (
2128
2151
  phase !== "expect-assistant" &&
2129
2152
  phase !== "expect-assistant-after-tools" &&
2130
- phase !== "expect-initial-conversation-message"
2153
+ phase !== "expect-initial-conversation-message" &&
2154
+ !samePlainRun
2131
2155
  ) {
2132
2156
  throw invalidReplRecovery(
2133
2157
  `REPL session assistant message[${index}] breaks role alternation`,
@@ -2263,7 +2287,27 @@ export function prepareReplJsonlResumeCandidate(sessionId, dependencies = {}) {
2263
2287
  const rebuiltMessages = snapshotReplMessages(
2264
2288
  projectCanonicalResumeMessages(rawRebuiltMessages),
2265
2289
  );
2266
- const normalizedReplay = normalizeReplReplayMessages(rebuiltMessages);
2290
+ const referenceDigests = snapshotReplMessageValue(
2291
+ dataDescriptorValue(
2292
+ stateDescriptors,
2293
+ "mcpTaskReferenceDigests",
2294
+ "REPL session host resume state",
2295
+ { required: false, fallback: [] },
2296
+ ),
2297
+ "MCP task reference commitments",
2298
+ );
2299
+ if (
2300
+ !Array.isArray(referenceDigests) ||
2301
+ !referenceDigests.every(
2302
+ (value) =>
2303
+ typeof value === "string" && /^sha256:[a-f0-9]{64}$/u.test(value),
2304
+ )
2305
+ )
2306
+ throw invalidReplRecovery("Invalid MCP task reference commitments");
2307
+ const normalizedReplay = normalizeReplReplayMessages(
2308
+ rebuiltMessages,
2309
+ referenceDigests,
2310
+ );
2267
2311
  const mcp = createReplMcpRecoveryCandidate(
2268
2312
  sessionId,
2269
2313
  dataDescriptorValue(
@@ -2300,10 +2344,20 @@ export function prepareReplJsonlResumeCandidate(sessionId, dependencies = {}) {
2300
2344
  "REPL session budget declaration",
2301
2345
  ),
2302
2346
  );
2347
+ const modelUsageRecovery = snapshotReplMessageValue(
2348
+ dataDescriptorValue(
2349
+ stateDescriptors,
2350
+ "modelUsageRecovery",
2351
+ "REPL local usage recovery",
2352
+ { required: false },
2353
+ ) ?? null,
2354
+ "REPL local usage recovery",
2355
+ );
2303
2356
  return brandedFrozenCandidate(REPL_JSONL_RESUME_CANDIDATES, {
2304
2357
  ok: true,
2305
2358
  sessionId,
2306
2359
  sessionBudgetRoot,
2360
+ modelUsageRecovery,
2307
2361
  rebuiltMessages,
2308
2362
  replayMessages: normalizedReplay.replayMessages,
2309
2363
  canonicalSystemMessages: normalizedReplay.canonicalSystemMessages,
@@ -3285,6 +3339,10 @@ async function startAgentReplInWorkspaceOwned(
3285
3339
  let _processingLine = false;
3286
3340
  let _lineSettled = null;
3287
3341
  const _activeBtwCalls = new Set();
3342
+ const _mcpTaskTrackers = new Map();
3343
+ const _mcpTaskAutoWakeQueue = [];
3344
+ let _mcpTaskAutoWakeRunning = false;
3345
+ const _mcpTaskAutoWakeSentinel = Symbol("mcp-task-auto-wake");
3288
3346
  const _pendingLines = [];
3289
3347
  const _runtimeLedgerTerminalLatch = createReplRuntimeLedgerTerminalLatch({
3290
3348
  onTrip: (terminalError) => {
@@ -4388,6 +4446,7 @@ async function startAgentReplInWorkspaceOwned(
4388
4446
  // the first prompt turn of a persistable (JSONL) session. This is Critical
4389
4447
  // recovery state: a failure blocks subsequent model/tool turns.
4390
4448
  let _turnBindingProducer = null;
4449
+ let _sessionInputAccepted = null;
4391
4450
  let _turnBindingCriticalError = null;
4392
4451
  // Apply --output-style or the settings.json `outputStyle` default at startup.
4393
4452
  try {
@@ -4910,6 +4969,11 @@ async function startAgentReplInWorkspaceOwned(
4910
4969
  error.code = "CC_REPL_SESSION_RESUME_NOT_PREPARED";
4911
4970
  throw error;
4912
4971
  }
4972
+ const usageRecoveryNotice = formatSessionModelUsageRecoveryNotice(
4973
+ sessionId,
4974
+ prepared.modelUsageRecovery,
4975
+ );
4976
+ if (usageRecoveryNotice) logger.warn(usageRecoveryNotice);
4913
4977
  messages.push(...prepared.canonicalSystemMessages);
4914
4978
  if (_startupReplSideEffects.noticeMessage) {
4915
4979
  messages.push(_startupReplSideEffects.noticeMessage);
@@ -5230,6 +5294,7 @@ async function startAgentReplInWorkspaceOwned(
5230
5294
  "/ide",
5231
5295
  "/init",
5232
5296
  "/mcp",
5297
+ "/mcp-watch",
5233
5298
  "/memory",
5234
5299
  "/microcompact",
5235
5300
  "/model",
@@ -5864,7 +5929,83 @@ async function startAgentReplInWorkspaceOwned(
5864
5929
  // continuation backslash keeps the prompt open; `_mlBuffer` accumulates the
5865
5930
  // pieces and the whole block submits when a line does not continue.
5866
5931
  const _mlBuffer = [];
5932
+ const kickMcpTaskAutoWake = () => {
5933
+ if (
5934
+ _processingLine ||
5935
+ _mcpTaskAutoWakeRunning ||
5936
+ _replClosing ||
5937
+ _mlBuffer.length > 0 ||
5938
+ (_replRl?.line || "").length > 0 ||
5939
+ _mcpTaskAutoWakeQueue.length === 0
5940
+ ) {
5941
+ return;
5942
+ }
5943
+ _mcpTaskAutoWakeRunning = true;
5944
+ _processingLine = true;
5945
+ let settleLine;
5946
+ _lineSettled = new Promise((resolve) => {
5947
+ settleLine = resolve;
5948
+ });
5949
+ void (async () => {
5950
+ try {
5951
+ await handleLine(_mcpTaskAutoWakeSentinel);
5952
+ if (!(await _waitForReplOutput())) return;
5953
+ while (
5954
+ _pendingLines.length &&
5955
+ !_replClosing &&
5956
+ !_runtimeLedgerTerminalLatch.isTripped()
5957
+ ) {
5958
+ const next = _pendingLines.shift();
5959
+ await handleLine(next);
5960
+ if (!(await _waitForReplOutput())) return;
5961
+ }
5962
+ } finally {
5963
+ _processingLine = false;
5964
+ settleLine();
5965
+ _lineSettled = null;
5966
+ _mcpTaskAutoWakeRunning = false;
5967
+ kickMcpTaskAutoWake();
5968
+ }
5969
+ })();
5970
+ };
5971
+ const scheduleMcpTaskAutoWake = (delivery) => {
5972
+ if (process.env.CC_MCP_TASK_AUTOWAKE !== "1" || !delivery?.message) {
5973
+ return false;
5974
+ }
5975
+ if (_mcpTaskAutoWakeQueue.length >= 8) {
5976
+ logger.warn(
5977
+ "[mcp-watch] auto-wake queue is full; delivery remains available in the session",
5978
+ );
5979
+ return false;
5980
+ }
5981
+ _mcpTaskAutoWakeQueue.push(delivery);
5982
+ kickMcpTaskAutoWake();
5983
+ return true;
5984
+ };
5867
5985
  const handleLine = async (input) => {
5986
+ let mcpAutoWakeDelivery =
5987
+ input === _mcpTaskAutoWakeSentinel
5988
+ ? _mcpTaskAutoWakeQueue.shift() || null
5989
+ : null;
5990
+ let mcpContinuationStarted = null;
5991
+ if (mcpAutoWakeDelivery) {
5992
+ try {
5993
+ if (mcpAutoWakeDelivery.sessionId !== sessionId)
5994
+ throw new Error("MCP continuation belongs to another session");
5995
+ const { beginMcpTaskContinuation } =
5996
+ await import("../lib/mcp-task-continuation.js");
5997
+ mcpContinuationStarted = beginMcpTaskContinuation(
5998
+ sessionId,
5999
+ mcpAutoWakeDelivery.localId,
6000
+ );
6001
+ mcpAutoWakeDelivery = mcpContinuationStarted.delivery;
6002
+ input = `Continue the existing user task using the verified external MCP reference (deliveryId: ${mcpAutoWakeDelivery.deliveryId}). This host continuation does not add user instructions or grant any new permissions.`;
6003
+ } catch (error) {
6004
+ logger.warn(`[mcp-watch] continuation not started: ${error.message}`);
6005
+ prompt();
6006
+ return;
6007
+ }
6008
+ }
5868
6009
  // Backslash continuation — accumulate and re-prompt without firing a turn.
5869
6010
  const _cont = analyzeContinuation(input);
5870
6011
  if (_cont.continued) {
@@ -8803,6 +8944,88 @@ async function startAgentReplInWorkspaceOwned(
8803
8944
  }
8804
8945
 
8805
8946
  // `/mcp` — overview of connected MCP servers' resources + prompts.
8947
+ // `/mcp-watch [local-id]` starts explicit, lease-bound durable task
8948
+ // tracking in this REPL. Delivery remains an external reference event;
8949
+ // it never becomes an implicit user prompt or model instruction.
8950
+ if (trimmed === "/mcp-watch" || trimmed.startsWith("/mcp-watch ")) {
8951
+ try {
8952
+ if (!sessionId || !useJsonl || !_sessionHostLeaseScope?.lease) {
8953
+ throw new Error(
8954
+ "MCP task tracking requires an active canonical session lease",
8955
+ );
8956
+ }
8957
+ const hostMcp = _getReplHostMcp();
8958
+ if (!hostMcp?.mcpClient) {
8959
+ throw new Error("No connected MCP client is available");
8960
+ }
8961
+ const { listDurableMcpTasks, createDurableMcpTaskRuntime } =
8962
+ await import("../lib/mcp-task-runtime.js");
8963
+ const { readMcpTaskJournal } =
8964
+ await import("../lib/mcp-task-journal.js");
8965
+ const requested = trimmed.slice("/mcp-watch".length).trim();
8966
+ const journal = readMcpTaskJournal(sessionId);
8967
+ const { records: durableRecords } = listDurableMcpTasks(sessionId);
8968
+ const records = durableRecords.filter(
8969
+ (record) =>
8970
+ (!requested || record.localId === requested) &&
8971
+ !_mcpTaskTrackers.has(record.localId) &&
8972
+ !journal.continuations.some(
8973
+ (item) => item.localId === record.localId,
8974
+ ) &&
8975
+ (!record.delivered || process.env.CC_MCP_TASK_AUTOWAKE === "1"),
8976
+ );
8977
+ if (
8978
+ requested &&
8979
+ !records.some((record) => record.localId === requested)
8980
+ ) {
8981
+ throw new Error("No pending durable MCP task matches that local id");
8982
+ }
8983
+ for (const record of records) {
8984
+ const runtime = createDurableMcpTaskRuntime({
8985
+ client: hostMcp.mcpClient,
8986
+ sessionId,
8987
+ lease: _sessionHostLeaseScope.lease,
8988
+ });
8989
+ const tracker = runtime.startTracking(record.localId, {
8990
+ deliver: true,
8991
+ onUpdate: (update) => {
8992
+ logger.verbose(
8993
+ `[mcp-watch] ${record.localId}: ${
8994
+ update.remoteStatus || update.phase
8995
+ }`,
8996
+ );
8997
+ },
8998
+ onDelivery: (receipt, delivery) => {
8999
+ const scheduled = scheduleMcpTaskAutoWake(delivery);
9000
+ logger.log(
9001
+ chalk.green(
9002
+ `✓ MCP task ${receipt.localId} delivered as external reference; ${scheduled ? "continuation queued." : "submit a prompt to continue."}`,
9003
+ ),
9004
+ );
9005
+ },
9006
+ });
9007
+ _mcpTaskTrackers.set(record.localId, tracker);
9008
+ void tracker.promise
9009
+ .catch((error) => {
9010
+ if (error?.code !== "CC_MCP_TASK_TRACKING_STOPPED") {
9011
+ logger.warn(
9012
+ `[mcp-watch] ${record.localId} stopped: ${error.message}`,
9013
+ );
9014
+ }
9015
+ })
9016
+ .finally(() => _mcpTaskTrackers.delete(record.localId));
9017
+ }
9018
+ logger.log(
9019
+ records.length
9020
+ ? `MCP task tracking started for ${records.length} task(s).`
9021
+ : "No pending durable MCP tasks require tracking.",
9022
+ );
9023
+ } catch (error) {
9024
+ logger.error(chalk.red(`/mcp-watch failed: ${error.message}`));
9025
+ }
9026
+ prompt();
9027
+ return;
9028
+ }
8806
9029
  if (trimmed === "/mcp" || trimmed.startsWith("/mcp ")) {
8807
9030
  const mcpClient = _getReplHostMcp()?.mcpClient;
8808
9031
  logger.log(renderMcpSurface(mcpClient));
@@ -9301,10 +9524,12 @@ async function startAgentReplInWorkspaceOwned(
9301
9524
  // Fire UserPromptSubmit hook with rewrite/abort support.
9302
9525
  // Hooks may emit {"rewrittenPrompt": "..."} or {"abort": true, "reason": "..."}
9303
9526
  // via stdout JSON. Failures fall through to the original prompt.
9304
- const promptDirective = await fireUserPromptSubmit(_hookDb, promptText, {
9305
- sessionId,
9306
- messageCount: messages.length,
9307
- });
9527
+ const promptDirective = mcpContinuationStarted
9528
+ ? { prompt: promptText }
9529
+ : await fireUserPromptSubmit(_hookDb, promptText, {
9530
+ sessionId,
9531
+ messageCount: messages.length,
9532
+ });
9308
9533
  if (promptDirective.abort) {
9309
9534
  logger.info(
9310
9535
  chalk.yellow(
@@ -9351,7 +9576,7 @@ async function startAgentReplInWorkspaceOwned(
9351
9576
 
9352
9577
  // settings.json UserPromptSubmit hooks (decision-capable; the DB hook above
9353
9578
  // is observe-only). block → abort the turn; context → inject before the turn.
9354
- if (_settingsHooks) {
9579
+ if (_settingsHooks && !mcpContinuationStarted) {
9355
9580
  try {
9356
9581
  const { runUserPromptSubmitHooks } =
9357
9582
  await import("../lib/settings-hook-events.js");
@@ -9534,7 +9759,9 @@ async function startAgentReplInWorkspaceOwned(
9534
9759
  // Explicit clipboard attachment chips are consumed only when a real model
9535
9760
  // turn is about to start. They compose with auto-detected path images and
9536
9761
  // enter the same provider-neutral multimodal message/vision override.
9537
- const clipboardImageChips = _promptInteractions.takeClipboardImageChips();
9762
+ const clipboardImageChips = mcpContinuationStarted
9763
+ ? []
9764
+ : _promptInteractions.takeClipboardImageChips();
9538
9765
  const clipboardMerge = mergeClipboardImageChips(
9539
9766
  _userMessageContent,
9540
9767
  clipboardImageChips,
@@ -9563,8 +9790,22 @@ async function startAgentReplInWorkspaceOwned(
9563
9790
 
9564
9791
  // Add user message (keep the object ref so /note-next can be injected for
9565
9792
  // this turn's model call and then stripped before persistence).
9566
- const _userMsg = { role: "user", content: _userMessageContent };
9567
- messages.push(_userMsg);
9793
+ if (mcpAutoWakeDelivery?.message) {
9794
+ const reference = mcpAutoWakeDelivery.message;
9795
+ if (
9796
+ !messages.some(
9797
+ (item) =>
9798
+ item.role === reference.role &&
9799
+ item.name === reference.name &&
9800
+ item.content === reference.content,
9801
+ )
9802
+ )
9803
+ messages.push({ ...reference });
9804
+ }
9805
+ const _userMsg = mcpContinuationStarted
9806
+ ? null
9807
+ : { role: "user", content: _userMessageContent };
9808
+ if (_userMsg) messages.push(_userMsg);
9568
9809
 
9569
9810
  // P1 turn→checkpoint binding: anchor this turn in the explicit table at
9570
9811
  // `conversationOffset = messages.length` measured just AFTER the user
@@ -9606,7 +9847,7 @@ async function startAgentReplInWorkspaceOwned(
9606
9847
  try {
9607
9848
  const { CLISlotFiller } = await import("../lib/slot-filler.js");
9608
9849
  const intent = CLISlotFiller.detectIntent(promptText);
9609
- if (intent) {
9850
+ if (intent && !mcpContinuationStarted) {
9610
9851
  const defs = CLISlotFiller.getSlotDefinitions(intent.type);
9611
9852
  const missing = defs.required.filter((s) => !intent.entities[s]);
9612
9853
  if (missing.length > 0) {
@@ -9648,7 +9889,7 @@ async function startAgentReplInWorkspaceOwned(
9648
9889
  // get a 401). Runnable-first: keep the configured (working) model instead.
9649
9890
  let activeModel = model;
9650
9891
  const taskDetection = detectTaskType(promptText);
9651
- if (taskDetection.confidence > 0.3) {
9892
+ if (taskDetection.confidence > 0.3 && !mcpContinuationStarted) {
9652
9893
  const recommended = selectModelForTask(provider, taskDetection.taskType);
9653
9894
  const switchTo = runnableTaskModel({
9654
9895
  provider,
@@ -9691,6 +9932,28 @@ async function startAgentReplInWorkspaceOwned(
9691
9932
  }
9692
9933
 
9693
9934
  try {
9935
+ // Durable REPL input admission is a hard boundary: persist the exact
9936
+ // effective prompt before any provider dispatch. The acceptance event is
9937
+ // intentionally excluded from replay history; only a later settled event
9938
+ // publishes the user/assistant pair. Legacy and non-JSONL sessions keep
9939
+ // their existing best-effort behavior.
9940
+ _sessionInputAccepted = null;
9941
+ if (sessionId && useJsonl && !mcpContinuationStarted) {
9942
+ try {
9943
+ _sessionInputAccepted = appendSessionInputAcceptance(sessionId, {
9944
+ inputId: `repl-${randomUUID()}`,
9945
+ turnId: `${sessionId}:turn-${_turnCount + 1}`,
9946
+ prompt: effectivePrompt,
9947
+ });
9948
+ } catch (error) {
9949
+ const persistenceError = markRuntimeLedgerPersistenceError(error);
9950
+ logger.error(
9951
+ `[recovery] refusing provider dispatch because input acceptance was not persisted: ${persistenceError.message}`,
9952
+ );
9953
+ prompt();
9954
+ return;
9955
+ }
9956
+ }
9694
9957
  process.stdout.write("\n");
9695
9958
  const iterationBudget = new IterationBudget({ owner: sessionId });
9696
9959
  // Bind a cross-session goal (cc goal) into this run, if one resolves.
@@ -9710,6 +9973,13 @@ async function startAgentReplInWorkspaceOwned(
9710
9973
  } catch (_e) {
9711
9974
  /* goal binding is best-effort — fall back to defaultPrepareCall */
9712
9975
  }
9976
+ if (mcpContinuationStarted) {
9977
+ const { composePrepareCall } = await import("../lib/goal-context.js");
9978
+ prepareCall = composePrepareCall([
9979
+ prepareCall,
9980
+ () => ({ systemSuffix: input }),
9981
+ ]);
9982
+ }
9713
9983
  _turnAbort = new AbortController();
9714
9984
  if (_advisorRuntime) {
9715
9985
  _advisorRuntime.beginTurn(
@@ -9770,7 +10040,7 @@ async function startAgentReplInWorkspaceOwned(
9770
10040
  // persisted (saveMessages/JSONL) or carried into later turns. Consumed on
9771
10041
  // send (cleared now) so a thrown turn doesn't re-inject next time; the
9772
10042
  // submit-start backstop restores if agentLoop throws before we get back.
9773
- if (pendingBtw.length > 0) {
10043
+ if (pendingBtw.length > 0 && !mcpContinuationStarted) {
9774
10044
  const block = buildAsideBlock(pendingBtw);
9775
10045
  if (block) {
9776
10046
  _btwRestore = { msg: _userMsg, content: _userMsg.content };
@@ -9863,6 +10133,7 @@ async function startAgentReplInWorkspaceOwned(
9863
10133
  model: _visionLlm ? _visionLlm.model : activeModel,
9864
10134
  thinking: turnThinking,
9865
10135
  thinkingBudget,
10136
+ maxOutputTokens: options.maxOutputTokens,
9866
10137
  baseUrl: _visionLlm ? _visionLlm.baseUrl : baseUrl,
9867
10138
  apiKey: _visionLlm ? _visionLlm.apiKey : apiKey,
9868
10139
  serviceTier: options.serviceTier,
@@ -10125,24 +10396,66 @@ async function startAgentReplInWorkspaceOwned(
10125
10396
  if (sessionId) {
10126
10397
  try {
10127
10398
  if (useJsonl) {
10128
- // Append incremental events (user + assistant)
10129
- appendUserMessage(sessionId, effectivePrompt);
10130
- _replCompactPersistence.record({
10131
- role: "user",
10132
- content: effectivePrompt,
10133
- });
10134
- if (effectiveResponse) {
10399
+ // A settled lifecycle event is the only replayable representation
10400
+ // of this REPL turn. The accepted prompt remains private pending
10401
+ // evidence until this append succeeds.
10402
+ if (mcpContinuationStarted) {
10403
+ const { settleMcpTaskContinuation } =
10404
+ await import("../lib/mcp-task-continuation.js");
10405
+ settleMcpTaskContinuation(
10406
+ sessionId,
10407
+ mcpContinuationStarted,
10408
+ effectiveResponse || "",
10409
+ );
10410
+ _replCompactPersistence.record({
10411
+ role: "assistant",
10412
+ content: effectiveResponse || "",
10413
+ });
10414
+ } else if (_sessionInputAccepted) {
10415
+ appendSessionInputSettlement(
10416
+ sessionId,
10417
+ _sessionInputAccepted,
10418
+ effectiveResponse || "",
10419
+ );
10420
+ } else {
10421
+ // This branch is retained for older injected hosts that do not
10422
+ // use the durable input lifecycle.
10423
+ appendUserMessage(sessionId, effectivePrompt);
10424
+ }
10425
+ if (!mcpContinuationStarted)
10426
+ _replCompactPersistence.record({
10427
+ role: "user",
10428
+ content: effectivePrompt,
10429
+ });
10430
+ if (
10431
+ effectiveResponse &&
10432
+ !_sessionInputAccepted &&
10433
+ !mcpContinuationStarted
10434
+ ) {
10135
10435
  appendAssistantMessage(sessionId, effectiveResponse);
10136
10436
  _replCompactPersistence.record({
10137
10437
  role: "assistant",
10138
10438
  content: effectiveResponse,
10139
10439
  });
10140
10440
  }
10441
+ if (_sessionInputAccepted) {
10442
+ _replCompactPersistence.record({
10443
+ role: "assistant",
10444
+ content: effectiveResponse || "",
10445
+ });
10446
+ }
10141
10447
  } else if (db) {
10142
10448
  saveMessages(db, sessionId, messages);
10143
10449
  }
10144
10450
  } catch (_e) {
10145
- // Non-critical
10451
+ if (useJsonl && (_sessionInputAccepted || mcpContinuationStarted)) {
10452
+ const terminalError = _runtimeLedgerTerminalLatch.trip(
10453
+ markRuntimeLedgerPersistenceError(_e),
10454
+ );
10455
+ if (terminalError) _reportRuntimeLedgerTerminal();
10456
+ throw _e;
10457
+ }
10458
+ // Legacy persistence remains best-effort.
10146
10459
  }
10147
10460
  }
10148
10461
  // Persist the explicit turn-binding table for this settled turn,
@@ -10371,14 +10684,24 @@ async function startAgentReplInWorkspaceOwned(
10371
10684
  _processingLine = false;
10372
10685
  settleLine();
10373
10686
  _lineSettled = null;
10687
+ kickMcpTaskAutoWake();
10374
10688
  }
10375
10689
  });
10376
10690
 
10691
+ // Opt-in restart recovery: with auto-wake enabled, scan the canonical
10692
+ // journal after the line listener is live and resume pending task trackers.
10693
+ if (process.env.CC_MCP_TASK_AUTOWAKE === "1") {
10694
+ setImmediate(() => {
10695
+ if (!_replClosing) rl.emit("line", "/mcp-watch");
10696
+ });
10697
+ }
10698
+
10377
10699
  rl.on("close", async () => {
10378
10700
  if (_replCleanupStarted) return;
10379
10701
  _replCleanupStarted = true;
10380
10702
  _replClosing = true;
10381
10703
  _pendingLines.length = 0;
10704
+ _mcpTaskAutoWakeQueue.length = 0;
10382
10705
  // Do not certify a Run while its model/tool or auxiliary usage settlement
10383
10706
  // is still in flight. EOF during a main turn cancels and leaves it incomplete.
10384
10707
  if (_turnAbort !== null) {
@@ -10391,6 +10714,8 @@ async function startAgentReplInWorkspaceOwned(
10391
10714
  if (_evolutionSession !== null) _replOutputFailure ||= error;
10392
10715
  _turnAbort.abort(error);
10393
10716
  }
10717
+ for (const tracker of _mcpTaskTrackers.values()) tracker.stop();
10718
+ _mcpTaskTrackers.clear();
10394
10719
  _promptInteractions.dispose();
10395
10720
  // Autonomous goals outlive the input line that submitted them. Cancel
10396
10721
  // their next-step execution and wait for any current call to settle too.
@@ -12308,6 +12308,24 @@ async function chatWithToolsAdmitted(rawMessages, options, captureAdmission) {
12308
12308
  } = { ...options, ...connection };
12309
12309
  captureAdmission(null, provider);
12310
12310
 
12311
+ // Validate the combined Anthropic output/thinking intent before admission
12312
+ // work or onProviderCallStart. Reuse these exact values in both transports.
12313
+ let anthropicOutputBudget = null;
12314
+ let anthropicThinkingParams = null;
12315
+ if (provider === "anthropic") {
12316
+ const effectiveModel = model || "claude-sonnet-4-6";
12317
+ anthropicOutputBudget = resolveAgentOutputBudget({
12318
+ provider,
12319
+ model: effectiveModel,
12320
+ maxOutputTokens: options.maxOutputTokens,
12321
+ });
12322
+ anthropicThinkingParams = _anthropicThinkingParams(
12323
+ effectiveModel,
12324
+ options,
12325
+ anthropicOutputBudget.requestMaxOutputTokens,
12326
+ );
12327
+ }
12328
+
12311
12329
  const providerRequestId = _normalizeProviderRequestId(
12312
12330
  options.providerRequestId,
12313
12331
  );
@@ -12539,11 +12557,6 @@ async function chatWithToolsAdmitted(rawMessages, options, captureAdmission) {
12539
12557
  // Fallback to the CURRENT Sonnet, not a retired snapshot:
12540
12558
  // claude-sonnet-4-20250514 was retired 2026-06-15 and would 404 here.
12541
12559
  const effModel = model || "claude-sonnet-4-6";
12542
- const anthropicOutputBudget = resolveAgentOutputBudget({
12543
- provider: "anthropic",
12544
- model: effModel,
12545
- maxOutputTokens: options.maxOutputTokens,
12546
- });
12547
12560
  const otherIndexes = messages.flatMap((message, index) =>
12548
12561
  message.role !== "system" ? [index] : [],
12549
12562
  );
@@ -12571,12 +12584,7 @@ async function chatWithToolsAdmitted(rawMessages, options, captureAdmission) {
12571
12584
  // Sampling parameters are never sent. RUNTIME-UNVERIFIED: no Anthropic key
12572
12585
  // here to E2E the
12573
12586
  // thinking-block signature replay (see cli_claude_code_parity_landed memory).
12574
- const thinkingParams = _anthropicThinkingParams(
12575
- effModel,
12576
- options,
12577
- body.max_tokens,
12578
- );
12579
- if (thinkingParams) Object.assign(body, thinkingParams);
12587
+ if (anthropicThinkingParams) Object.assign(body, anthropicThinkingParams);
12580
12588
  if (systemMsgs.length > 0) {
12581
12589
  const systemText = systemMsgs.map((m) => m.content).join("\n");
12582
12590
  // Array-form system with a cache breakpoint when caching is on; plain
@@ -13934,6 +13942,16 @@ export function _anthropicThinkingParams(
13934
13942
  return params;
13935
13943
  }
13936
13944
  if (legacy) {
13945
+ // Neither transport enables the interleaved-thinking beta exception.
13946
+ // Preserve both explicit intents: do not raise the cap or disable thinking.
13947
+ if (maxTokens <= 1024) {
13948
+ throw Object.assign(
13949
+ new RangeError(
13950
+ "Anthropic manual thinking requires maxOutputTokens greater than 1024; choose a larger output cap or explicitly disable thinking.",
13951
+ ),
13952
+ { code: "CC_ANTHROPIC_THINKING_OUTPUT_CAP_INVALID" },
13953
+ );
13954
+ }
13937
13955
  let budget = Number(options.thinkingBudget) || 8000;
13938
13956
  // budget_tokens must be strictly < max_tokens (min 1024) on legacy models
13939
13957
  if (budget >= maxTokens) budget = Math.max(1024, Math.floor(maxTokens / 2));
@@ -2952,6 +2952,7 @@ async function runAgentHeadlessInWorkspace(
2952
2952
  // is the legacy-model budget_tokens override; ignored when thinking is off.
2953
2953
  thinking: options.thinking || null,
2954
2954
  thinkingBudget: options.thinkingBudget || null,
2955
+ maxOutputTokens: options.maxOutputTokens,
2955
2956
  baseUrl,
2956
2957
  apiKey,
2957
2958
  cwd,