chainlesschain 0.166.161 → 0.166.163

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 (48) hide show
  1. package/README.md +15 -3
  2. package/package.json +1 -1
  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 +1 -1
  6. package/src/commands/agenda.js +23 -2
  7. package/src/commands/agent.js +56 -21
  8. package/src/commands/ccron.js +1 -0
  9. package/src/commands/loop.js +34 -1
  10. package/src/commands/mcp.js +13 -3
  11. package/src/commands/plugin.js +10 -31
  12. package/src/commands/skill.js +31 -6
  13. package/src/commands/tasks.js +20 -2
  14. package/src/data/changelog.json +26 -0
  15. package/src/harness/background-task-command-runner.js +23 -25
  16. package/src/harness/prompt-compressor.js +10 -1
  17. package/src/lib/__tests__/provider-stream.test.js +16 -0
  18. package/src/lib/background-agent-supervisor.js +3 -0
  19. package/src/lib/chat-core.js +10 -3
  20. package/src/lib/coding-task-guidance.js +1 -0
  21. package/src/lib/context-memory-kernel/live-compaction.js +100 -19
  22. package/src/lib/cowork-cron.js +115 -31
  23. package/src/lib/install-command-policy.js +23 -0
  24. package/src/lib/json-schema-output.js +12 -31
  25. package/src/lib/loop.js +30 -11
  26. package/src/lib/lsp/__tests__/code-intelligence.integration.test.js +17 -15
  27. package/src/lib/plan-mode.js +16 -0
  28. package/src/lib/plugin-runtime/install.js +111 -67
  29. package/src/lib/process-execution-broker/index.js +19 -9
  30. package/src/lib/provider-stream.js +7 -3
  31. package/src/lib/public-ide-capability-manifest.js +88 -0
  32. package/src/lib/public-ide-capability-validation.js +24 -0
  33. package/src/lib/read-file-loop-guard.js +9 -1
  34. package/src/lib/repl-denials.js +11 -0
  35. package/src/lib/search-command.js +13 -2
  36. package/src/lib/secret-store.js +30 -5
  37. package/src/lib/session-plan-approval.js +11 -2
  38. package/src/lib/status-line.cjs +3 -2
  39. package/src/lib/stream-retry.js +20 -0
  40. package/src/lib/task-record.js +12 -1
  41. package/src/lib/text-file-search.js +7 -2
  42. package/src/repl/agent-repl.js +195 -33
  43. package/src/runtime/agent-core.js +44 -18
  44. package/src/runtime/coding-agent-contract-shared.cjs +4 -2
  45. package/src/runtime/headless-runner.js +61 -4
  46. package/src/runtime/headless-stream.js +86 -17
  47. package/src/runtime/provider-stream-state.js +3 -1
  48. package/src/workers/background-agent-worker.js +11 -10
@@ -149,6 +149,8 @@ import {
149
149
  classifyDenial,
150
150
  recordDenial,
151
151
  formatDenials,
152
+ DESTRUCTIVE_SHELL_DENIAL_CODE,
153
+ isDestructiveShellDenial,
152
154
  } from "../lib/repl-denials.js";
153
155
  import executionBroker from "../lib/process-execution-broker/index.js";
154
156
  import { extractPluginUsageAttribution } from "../lib/plugin-usage-attribution.js";
@@ -640,6 +642,7 @@ async function withHeadlessSessionHostLease(options, deps, task) {
640
642
  let budgetRoot = null;
641
643
  let scopedOptions = options;
642
644
  let preflightAdmission;
645
+ let taskStarted = false;
643
646
  try {
644
647
  // Session authority/lease/budget setup can lazily initialize AppConfig and
645
648
  // DatabaseManager. Those legacy diagnostics use console.info (stdout), and
@@ -805,12 +808,50 @@ async function withHeadlessSessionHostLease(options, deps, task) {
805
808
  scopedOptions = { ...scopedOptions, ...budgetRoot.options };
806
809
  }
807
810
  });
811
+ taskStarted = true;
808
812
  return await task(scopedOptions, {
809
813
  ...deps,
810
814
  [HEADLESS_SESSION_RESOLUTION]: resolution,
811
815
  [HEADLESS_SESSION_HOST_LEASE]: lease,
812
816
  [HEADLESS_CANONICAL_ADMISSION]: preflightAdmission,
813
817
  });
818
+ } catch (error) {
819
+ if (taskStarted) throw error;
820
+ const sessionId =
821
+ resolution?.resumeId || resolution?.sessionId || options.sessionId;
822
+ const persistence = projectSessionPersistenceFailure(
823
+ createSessionPersistenceFailure(error, {
824
+ sessionId,
825
+ operation: "session-start",
826
+ }),
827
+ { phase: "before-model" },
828
+ );
829
+ if (!persistence) throw error;
830
+ try {
831
+ deps.onPersistenceFailure?.(persistence);
832
+ } catch {
833
+ // Observability cannot change persistence semantics.
834
+ }
835
+ const result = `${persistence.code}: canonical session admission was refused (${persistence.fs_code}; ${persistence.commit_state})`;
836
+ if (outputFormat !== "text") {
837
+ deps.writeOut(
838
+ JSON.stringify(
839
+ buildResultEnvelope({
840
+ subtype: "error_persistence",
841
+ isError: true,
842
+ result,
843
+ sessionId,
844
+ toolCalls: [],
845
+ usage: {},
846
+ numTurns: 0,
847
+ durationMs: 0,
848
+ persistence,
849
+ }),
850
+ ) + "\n",
851
+ );
852
+ }
853
+ deps.writeErr(`${result}\n`);
854
+ return { exitCode: 1, result, isError: true, persistence };
814
855
  } finally {
815
856
  // Cleanup can touch the same lazy stores. Keep late diagnostics out of a
816
857
  // completed JSON/NDJSON payload while preserving release-on-close failure.
@@ -1591,7 +1632,13 @@ async function runAgentHeadlessInWorkspace(
1591
1632
  try {
1592
1633
  const { openSessionPlan } =
1593
1634
  await import("../lib/session-plan-approval.js");
1594
- const plan = openSessionPlan(sessionId, options.permissionMode);
1635
+ const plan = openSessionPlan(sessionId, options.permissionMode, {
1636
+ // A resumed worker replays the original launch profile. A verified
1637
+ // session approval takes precedence over that historical default.
1638
+ permissionModeIsFallback:
1639
+ Boolean(process.env.CC_BACKGROUND_AGENT_ID) &&
1640
+ process.env.CC_BACKGROUND_RESTORE_PLAN_PERMISSION === "1",
1641
+ });
1595
1642
  planManager = plan.manager;
1596
1643
  options = { ...options, permissionMode: plan.permissionMode };
1597
1644
  } catch {
@@ -3279,6 +3326,7 @@ async function runAgentHeadlessInWorkspace(
3279
3326
  };
3280
3327
  let finalText = "";
3281
3328
  let endReason = "complete";
3329
+ let destructiveShellDenied = false;
3282
3330
  let stopForCost = false;
3283
3331
  let stopForCompactionUsageUnknown = false;
3284
3332
 
@@ -3892,6 +3940,7 @@ async function runAgentHeadlessInWorkspace(
3892
3940
  }
3893
3941
  case "tool-result": {
3894
3942
  const err = event.error || event.result?.error || null;
3943
+ if (isDestructiveShellDenial(event)) destructiveShellDenied = true;
3895
3944
  // A denied request has no invocation to settle. Explicit provider
3896
3945
  // IDs must never fall back to a different pending invocation.
3897
3946
  const settledCall =
@@ -4670,10 +4719,15 @@ async function runAgentHeadlessInWorkspace(
4670
4719
  endReason === "budget-exhausted" || endReason === "max_turns";
4671
4720
  const costStopped = endReason === "cost-budget-exhausted";
4672
4721
  const goalExhausted = endReason === "goal-exhausted";
4722
+ // A final answer can follow a hard shell refusal. Keep the refusal in the
4723
+ // process result so automation cannot treat the destructive request as done.
4724
+ const deniedDestructiveRequest =
4725
+ endReason === "complete" && destructiveShellDenied;
4673
4726
  let isError =
4674
4727
  exhausted ||
4675
4728
  costStopped ||
4676
4729
  goalExhausted ||
4730
+ deniedDestructiveRequest ||
4677
4731
  endReason === "no-response" ||
4678
4732
  endReason === "deferred-mutation-unresolved";
4679
4733
  let subtype = exhausted
@@ -4847,6 +4901,9 @@ async function runAgentHeadlessInWorkspace(
4847
4901
  }
4848
4902
  }
4849
4903
 
4904
+ const resultCode =
4905
+ sessionPersistenceCode ||
4906
+ (deniedDestructiveRequest ? DESTRUCTIVE_SHELL_DENIAL_CODE : null);
4850
4907
  if (isStream) {
4851
4908
  emitStream({
4852
4909
  type: "result",
@@ -4862,7 +4919,7 @@ async function runAgentHeadlessInWorkspace(
4862
4919
  ? { compaction_degradations: compactionDegradations }
4863
4920
  : {}),
4864
4921
  ...(persistenceFailure ? { persistence: persistenceFailure } : {}),
4865
- ...(sessionPersistenceCode ? { code: sessionPersistenceCode } : {}),
4922
+ ...(resultCode ? { code: resultCode } : {}),
4866
4923
  });
4867
4924
  } else if (isJson) {
4868
4925
  writeOut(
@@ -4881,7 +4938,7 @@ async function runAgentHeadlessInWorkspace(
4881
4938
  compactionDegradations,
4882
4939
  persistence: persistenceFailure,
4883
4940
  }),
4884
- ...(sessionPersistenceCode ? { code: sessionPersistenceCode } : {}),
4941
+ ...(resultCode ? { code: resultCode } : {}),
4885
4942
  }) + "\n",
4886
4943
  );
4887
4944
  } else {
@@ -4929,7 +4986,7 @@ async function runAgentHeadlessInWorkspace(
4929
4986
  result: finalText,
4930
4987
  isError,
4931
4988
  ...(persistenceFailure ? { persistence: persistenceFailure } : {}),
4932
- ...(sessionPersistenceCode ? { code: sessionPersistenceCode } : {}),
4989
+ ...(resultCode ? { code: resultCode } : {}),
4933
4990
  };
4934
4991
  }
4935
4992
 
@@ -130,6 +130,12 @@ import {
130
130
  } from "../lib/capability-negotiation.js";
131
131
  import { IterationBudget } from "../lib/iteration-budget.js";
132
132
  import { CostBudget } from "../lib/cost-budget.js";
133
+ import {
134
+ classifyDenial,
135
+ DESTRUCTIVE_SHELL_DENIAL_CODE,
136
+ isDestructiveShellDenial,
137
+ recordDenial,
138
+ } from "../lib/repl-denials.js";
133
139
  import {
134
140
  resolvePermissionMode,
135
141
  normalizePermissionMode,
@@ -965,6 +971,7 @@ async function runTurn(
965
971
  cache_creation_input_tokens: 0,
966
972
  };
967
973
  const toolCalls = [];
974
+ const destructiveDenials = [];
968
975
  let finalText = "";
969
976
  let endReason = "complete";
970
977
  let stopForCost = false;
@@ -1074,6 +1081,12 @@ async function runTurn(
1074
1081
  }
1075
1082
  case "tool-result": {
1076
1083
  const err = event.error || event.result?.error || null;
1084
+ if (isDestructiveShellDenial(event)) {
1085
+ recordDenial(destructiveDenials, {
1086
+ ...classifyDenial(event),
1087
+ at: now(),
1088
+ });
1089
+ }
1077
1090
  // No invocation started for a preflight denial. For actual results,
1078
1091
  // retain the adjacency fallback only for legacy events without IDs.
1079
1092
  const lastCall =
@@ -1290,7 +1303,14 @@ async function runTurn(
1290
1303
  ) {
1291
1304
  sideEffects.persist();
1292
1305
  }
1293
- return { finalText, endReason, usage, toolCalls, compactionUsageUnknown };
1306
+ return {
1307
+ finalText,
1308
+ endReason,
1309
+ usage,
1310
+ toolCalls,
1311
+ compactionUsageUnknown,
1312
+ destructiveDenials,
1313
+ };
1294
1314
  }
1295
1315
 
1296
1316
  function compactionUsageUnknownDiagnostic(event) {
@@ -2664,6 +2684,7 @@ async function runAgentHeadlessStreamInWorkspace(
2664
2684
  // resolution is echoed as `approval_resolved` so UIs can settle their cards.
2665
2685
  const interactive = options.interactiveApprovals === true;
2666
2686
  const pendingApprovals = new Map();
2687
+ let currentAbort = null;
2667
2688
  let approvalSeq = 0;
2668
2689
  const approvalTimeoutMs =
2669
2690
  Number(process.env.CC_APPROVAL_TIMEOUT_MS) > 0
@@ -2678,11 +2699,18 @@ async function runAgentHeadlessStreamInWorkspace(
2678
2699
  ) => {
2679
2700
  const p = pendingApprovals.get(id);
2680
2701
  if (!p) return;
2681
- const approve = [
2682
- "acceptOnce",
2683
- "acceptForTurn",
2684
- "acceptForSession",
2685
- ].includes(decision?.kind);
2702
+ let approve = ["acceptOnce", "acceptForTurn", "acceptForSession"].includes(
2703
+ decision?.kind,
2704
+ );
2705
+ if (
2706
+ approve &&
2707
+ p.turn &&
2708
+ (p.turn !== currentAbort || p.turn.signal.aborted)
2709
+ ) {
2710
+ approve = false;
2711
+ decision = { kind: "decline", reason: "Approval turn ended" };
2712
+ via = "turn-ended";
2713
+ }
2686
2714
  // Approval binding (authority §"权限来源与跨 Agent 授权边界"): an *approve*
2687
2715
  // verdict that carries a binding which does NOT match the one the request
2688
2716
  // advertised is stale / mis-routed / argument-tampered — reject it (deny,
@@ -2746,7 +2774,8 @@ async function runAgentHeadlessStreamInWorkspace(
2746
2774
  });
2747
2775
  p.resolve(!invalidReason && approve);
2748
2776
  };
2749
- const interactiveConfirm = (ctx = {}) => {
2777
+ const interactiveConfirm = (ctx = {}, turn = currentAbort) => {
2778
+ if (turn && (turn !== currentAbort || turn.signal.aborted)) return false;
2750
2779
  const requiredPermission = approvalPermissionForContext(ctx, { cwd });
2751
2780
  if (approvalGrantLedger.allows(requiredPermission)) return true;
2752
2781
  return new Promise((resolve) => {
@@ -2776,6 +2805,7 @@ async function runAgentHeadlessStreamInWorkspace(
2776
2805
  timer,
2777
2806
  binding,
2778
2807
  requiredPermission,
2808
+ turn,
2779
2809
  });
2780
2810
  emit({
2781
2811
  type: "approval_request",
@@ -4055,10 +4085,6 @@ async function runAgentHeadlessStreamInWorkspace(
4055
4085
  classifyAllShell,
4056
4086
  enabledToolNames,
4057
4087
  disabledTools,
4058
- // --interactive-approvals: settings/hook `ask` (and, with an IDE bridge,
4059
- // edit reviews via openDiff) route to the structured approval round-trip
4060
- // instead of failing closed. Absent in CI/pipes → unchanged fail-closed.
4061
- permissionConfirm: interactive ? interactiveConfirm : undefined,
4062
4088
  // ask_user_question round-trip (opt-in via CC_INTERACTIVE_QUESTIONS): give
4063
4089
  // the tool handler an askUser that emits question_request + blocks on stdin.
4064
4090
  // Absent → agent-core returns user_not_reachable (graceful proceed).
@@ -4317,7 +4343,6 @@ async function runAgentHeadlessStreamInWorkspace(
4317
4343
  const queue = [];
4318
4344
  let wakeQueue = null;
4319
4345
  let inputDone = false;
4320
- let currentAbort = null;
4321
4346
  let inputBacklogFailure = false;
4322
4347
  let slashRequestSeq = 0;
4323
4348
  const inputLines = readJsonLines(input);
@@ -4382,7 +4407,19 @@ async function runAgentHeadlessStreamInWorkspace(
4382
4407
  settlePermissionDecisionGate(true);
4383
4408
  }
4384
4409
  if (parsed.interrupt) {
4385
- currentAbort?.abort();
4410
+ const interruptedTurn = currentAbort;
4411
+ interruptedTurn?.abort();
4412
+ if (interruptedTurn) {
4413
+ for (const [id, pending] of pendingApprovals) {
4414
+ if (pending.turn === interruptedTurn) {
4415
+ settleApproval(
4416
+ id,
4417
+ { kind: "decline", reason: "Approval turn interrupted" },
4418
+ "turn-interrupted",
4419
+ );
4420
+ }
4421
+ }
4422
+ }
4386
4423
  continue;
4387
4424
  }
4388
4425
  if (parsed.approval) {
@@ -5805,10 +5842,11 @@ async function runAgentHeadlessStreamInWorkspace(
5805
5842
  // Per-turn abort scope: an {"type":"interrupt"} from the pump above
5806
5843
  // aborts THIS turn (LLM fetch included — the signal reaches chatWithTools)
5807
5844
  // while the conversation/process stays alive for the next message.
5808
- currentAbort = new AbortController();
5845
+ const turn = new AbortController();
5846
+ currentAbort = turn;
5809
5847
  const turnSignal = options.signal
5810
- ? AbortSignal.any([options.signal, currentAbort.signal])
5811
- : currentAbort.signal;
5848
+ ? AbortSignal.any([options.signal, turn.signal])
5849
+ : turn.signal;
5812
5850
 
5813
5851
  // Capture the resumed pairs once, then normalize those same pairs only in
5814
5852
  // every provider request. The live authority array retains separate turns.
@@ -5823,6 +5861,9 @@ async function runAgentHeadlessStreamInWorkspace(
5823
5861
  messages,
5824
5862
  {
5825
5863
  ...loopOptionsBase,
5864
+ permissionConfirm: interactive
5865
+ ? (context) => interactiveConfirm(context, turn)
5866
+ : undefined,
5826
5867
  // Custom-command frontmatter scopes THIS turn (parity with `cc command
5827
5868
  // run` / headless -p): a matched /name applies its model: and
5828
5869
  // allowed-tools:. Lowest-priority override — an explicit per-turn
@@ -6060,6 +6101,28 @@ async function runAgentHeadlessStreamInWorkspace(
6060
6101
  break;
6061
6102
  }
6062
6103
 
6104
+ if (outcome.destructiveDenials.length > 0) {
6105
+ emit({
6106
+ type: "denials_summary",
6107
+ count: outcome.destructiveDenials.length,
6108
+ denials: outcome.destructiveDenials,
6109
+ session_id: sessionId,
6110
+ turn: turns,
6111
+ });
6112
+ try {
6113
+ const { appendRecentDenials } =
6114
+ await import("../lib/permission-denial-store.js");
6115
+ appendRecentDenials(outcome.destructiveDenials, {
6116
+ sessionId,
6117
+ permissionMode: options.permissionMode || "default",
6118
+ cwd,
6119
+ source: "headless",
6120
+ });
6121
+ } catch {
6122
+ // The review store is best-effort; the refusal still reaches the client.
6123
+ }
6124
+ }
6125
+
6063
6126
  if (outcome.endReason === "user-input-pending") {
6064
6127
  if (!settleToolRoundsForHost("after-model")) break;
6065
6128
  emit({
@@ -6156,9 +6219,12 @@ async function runAgentHeadlessStreamInWorkspace(
6156
6219
  outcome.endReason === "budget-exhausted" ||
6157
6220
  outcome.endReason === "max_turns";
6158
6221
  const costStopped = outcome.endReason === "cost-budget-exhausted";
6222
+ const deniedDestructiveRequest =
6223
+ outcome.endReason === "complete" && outcome.destructiveDenials.length > 0;
6159
6224
  const isError =
6160
6225
  exhausted ||
6161
6226
  costStopped ||
6227
+ deniedDestructiveRequest ||
6162
6228
  outcome.endReason === "no-response" ||
6163
6229
  outcome.endReason === "deferred-mutation-unresolved" ||
6164
6230
  Boolean(persistenceFailure);
@@ -6200,13 +6266,16 @@ async function runAgentHeadlessStreamInWorkspace(
6200
6266
  usage: outcome.usage,
6201
6267
  ...(transcriptRefs ? { transcript_refs: transcriptRefs } : {}),
6202
6268
  ...(persistenceFailure ? { persistence: persistenceFailure } : {}),
6269
+ ...(deniedDestructiveRequest && !persistenceFailure
6270
+ ? { code: DESTRUCTIVE_SHELL_DENIAL_CODE }
6271
+ : {}),
6203
6272
  });
6204
6273
 
6205
6274
  // --json-schema (P2): emit this turn's structured verdict right after its
6206
6275
  // result — schema_digest + valid + value/errors from the turn's final text.
6207
6276
  // Never falls back to free text; an unparseable/invalid reply reports
6208
6277
  // valid:false with coded/pointered errors. Parity with single-prompt output.
6209
- if (_jsonSchema) {
6278
+ if (_jsonSchema && !deniedDestructiveRequest) {
6210
6279
  const parsed = _jso.extractJsonPayload(String(outcome.finalText ?? ""));
6211
6280
  emit({
6212
6281
  ..._jso.buildStructuredResult(
@@ -8,6 +8,7 @@ import {
8
8
  projectUsagePricingContext,
9
9
  projectEnvelopePricingContext,
10
10
  } from "../lib/usage-pricing-context.js";
11
+ import { createChatCompletionsStreamError } from "../lib/stream-retry.js";
11
12
 
12
13
  export function _isNonNegativeSafeInteger(value) {
13
14
  return Number.isSafeInteger(value) && value >= 0;
@@ -321,7 +322,8 @@ export function _openaiReduceLine(state, raw, onToken) {
321
322
  state.terminationInvalid = true;
322
323
  return state;
323
324
  }
324
- if (state.streamDone || obj.error) state.terminationInvalid = true;
325
+ if (obj?.error) throw createChatCompletionsStreamError();
326
+ if (state.streamDone) state.terminationInvalid = true;
325
327
  if (!Array.isArray(obj.choices) || obj.choices.length > 1) {
326
328
  state.terminationInvalid = true;
327
329
  }
@@ -130,11 +130,11 @@ export function assertBackgroundAgentWorkerAcceptsPrompt(
130
130
  function ownsBackgroundAgentWorkerRecord(current, workerPid, workerGeneration) {
131
131
  return Boolean(
132
132
  current &&
133
- (!current.workerGeneration ||
134
- current.workerGeneration === workerGeneration) &&
135
- (Number(current.workerClaimedPid) === workerPid ||
136
- (current.workerClaimedPid == null &&
137
- Number(current.workerPid ?? current.pid) === workerPid)),
133
+ (!current.workerGeneration ||
134
+ current.workerGeneration === workerGeneration) &&
135
+ (Number(current.workerClaimedPid) === workerPid ||
136
+ (current.workerClaimedPid == null &&
137
+ Number(current.workerPid ?? current.pid) === workerPid)),
138
138
  );
139
139
  }
140
140
 
@@ -148,11 +148,10 @@ export function createBackgroundAgentWorkerFinalStateUpdater({
148
148
  now = Date.now,
149
149
  }) {
150
150
  return (current) => {
151
- if (!current || !ownsBackgroundAgentWorkerRecord(
152
- current,
153
- workerPid,
154
- workerGeneration,
155
- )) {
151
+ if (
152
+ !current ||
153
+ !ownsBackgroundAgentWorkerRecord(current, workerPid, workerGeneration)
154
+ ) {
156
155
  return null;
157
156
  }
158
157
  if (current.status !== "running") {
@@ -1123,6 +1122,8 @@ function startTurn(argv, promptText) {
1123
1122
  env: {
1124
1123
  ...process.env,
1125
1124
  CC_BACKGROUND_AGENT_ID: job.id,
1125
+ CC_BACKGROUND_RESTORE_PLAN_PERMISSION:
1126
+ job.restorePlanPermission === true ? "1" : "",
1126
1127
  CC_BACKGROUND_TURN_IPC_NONCE: turnIpcToken,
1127
1128
  [BACKGROUND_TURN_BOOTSTRAP_ENV.nonce]: turnBootstrapNonce,
1128
1129
  [BACKGROUND_TURN_BOOTSTRAP_ENV.workerGeneration]: