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
@@ -31,12 +31,17 @@ import fs from "fs";
31
31
  import os from "os";
32
32
  import path from "path";
33
33
  import { createHash, randomUUID } from "node:crypto";
34
+ import { isDeepStrictEqual } from "node:util";
34
35
  import { isPromise, isProxy } from "node:util/types";
35
36
  import { logger } from "../lib/logger.js";
36
37
  import { captureSkillRuntimeDependencies } from "../lib/evolution/skill-runtime-revalidation.js";
37
38
  import { captureAmbientExecutionLocation } from "../lib/execution-location-runtime.js";
38
39
  import { issueMcpStdioExecutionAuthority } from "../lib/mcp-stdio-execution-authority.js";
39
- import { getPlanModeManager, PlanState } from "../lib/plan-mode.js";
40
+ import { PlanModeManager, PlanState } from "../lib/plan-mode.js";
41
+ import {
42
+ openSessionPlan,
43
+ recordSessionPlanApproval,
44
+ } from "../lib/session-plan-approval.js";
40
45
  import { createVimState, feedNormalKey } from "../lib/repl-vim.js";
41
46
  import {
42
47
  analyzeContinuation,
@@ -839,9 +844,15 @@ export async function agentLoop(messages, options) {
839
844
  chalk.gray(` ⎌ checkpoint ${event.id} (before ${event.tool})\n`),
840
845
  );
841
846
  } else if (event.type === "tool-executing") {
847
+ const id = runtimeToolCallId(event.tool_use_id);
848
+ const planItem = options.planManager?.startPlanItemForTool(event.tool, {
849
+ toolUseId: id,
850
+ });
851
+ if (planItem?.error) throw new Error(planItem.error);
842
852
  const exec = {
843
- id: runtimeToolCallId(event.tool_use_id),
853
+ id,
844
854
  providerId: event.tool_use_id || null,
855
+ planItemId: planItem?.id,
845
856
  tool: event.tool,
846
857
  args: event.args,
847
858
  startedAt: options.now ? options.now() : Date.now(),
@@ -925,6 +936,14 @@ export async function agentLoop(messages, options) {
925
936
  options.sideEffects.persist();
926
937
  _currentSideEffectOpId = null;
927
938
  }
939
+ if (exec?.planItemId) {
940
+ const failed = Boolean(event.error || event.result?.error);
941
+ const settlement = options.planManager.settlePlanItem(exec.planItemId, {
942
+ success: !failed,
943
+ error: failed ? "Tool execution failed" : null,
944
+ });
945
+ if (settlement?.error) throw new Error(settlement.error);
946
+ }
928
947
  const durationMs =
929
948
  event.result?.toolTelemetryRecord?.durationMs ??
930
949
  (exec?.tool === event.tool
@@ -3229,6 +3248,7 @@ async function startAgentReplInWorkspaceOwned(
3229
3248
  let _replCleanupStarted = false;
3230
3249
  let _turnAbort = null;
3231
3250
  let _replOutputFailure = null;
3251
+ let _planApprovalFailure = null;
3232
3252
  const _requestReplOutputClose = (error) => {
3233
3253
  if (error && !_replOutputFailure) _replOutputFailure = error;
3234
3254
  if (error) {
@@ -3401,8 +3421,17 @@ async function startAgentReplInWorkspaceOwned(
3401
3421
  callModel,
3402
3422
  source: "model",
3403
3423
  });
3404
- const _runReplDirectTool = async (tool, args, { signal = null } = {}) => {
3424
+ const _runReplDirectTool = async (
3425
+ tool,
3426
+ args,
3427
+ { signal = null, approvedPlanExecution = false } = {},
3428
+ ) => {
3405
3429
  _runtimeLedgerTerminalLatch.assertOpen();
3430
+ if (planManager.executionLock && !approvedPlanExecution) {
3431
+ throw new Error(
3432
+ "Use the approved plan to run tools while its execution lock is active",
3433
+ );
3434
+ }
3406
3435
  try {
3407
3436
  const durableSessionId = resolveReplMeteredSessionId(useJsonl, sessionId);
3408
3437
  return await runReplDirectToolWithLedger({
@@ -3413,6 +3442,11 @@ async function startAgentReplInWorkspaceOwned(
3413
3442
  executeTool(name, toolArgs, {
3414
3443
  sessionId: durableSessionId,
3415
3444
  sessionBudget: _sessionBudget,
3445
+ planManager,
3446
+ approvalGate: _approvalGate,
3447
+ permissionRules: _permissionRules,
3448
+ permissionConfirm: _permissionConfirm,
3449
+ interactiveApproval: true,
3416
3450
  signal: combineReplSignals(signal, options.signal),
3417
3451
  }),
3418
3452
  now: options.now || Date.now,
@@ -3588,6 +3622,37 @@ async function startAgentReplInWorkspaceOwned(
3588
3622
  let db = null;
3589
3623
  let contextEngine = null;
3590
3624
  let sessionId = _startupJsonlResume?.sessionId || null;
3625
+ let planManager = new PlanModeManager();
3626
+ let planPermissionMode;
3627
+ const _recordPlanApproval = () => {
3628
+ if (planManager.memoryOnly) return true;
3629
+ try {
3630
+ recordSessionPlanApproval(planManager);
3631
+ return true;
3632
+ } catch (error) {
3633
+ _planApprovalFailure = error;
3634
+ logger.error("The plan approval receipt could not be persisted.");
3635
+ _replRl.close();
3636
+ return false;
3637
+ }
3638
+ };
3639
+ if (sessionId) {
3640
+ const plan = openSessionPlan(sessionId);
3641
+ if (
3642
+ plan.permissionMode &&
3643
+ options.permissionMode !== undefined &&
3644
+ !isDeepStrictEqual(
3645
+ parsePermissionModeArg(options.permissionMode),
3646
+ parsePermissionModeArg(plan.permissionMode),
3647
+ )
3648
+ ) {
3649
+ throw new Error(
3650
+ "Requested permission mode conflicts with the approved plan",
3651
+ );
3652
+ }
3653
+ planManager = plan.manager;
3654
+ planPermissionMode = plan.permissionMode;
3655
+ }
3591
3656
  const _replCompactPersistence = createReplCompactPersistence(
3592
3657
  _startupJsonlResume?.ok ? _startupJsonlResume.rebuiltMessages : [],
3593
3658
  );
@@ -3757,6 +3822,7 @@ async function startAgentReplInWorkspaceOwned(
3757
3822
  // MEDIUM/HIGH-risk commands against the session's policy tier
3758
3823
  // (strict / trusted / autopilot).
3759
3824
  let _renderStatus = null;
3825
+ let _managedSettings = null;
3760
3826
  try {
3761
3827
  const { getApprovalGate } =
3762
3828
  await import("../lib/session-core-singletons.js");
@@ -3908,6 +3974,7 @@ async function startAgentReplInWorkspaceOwned(
3908
3974
  await import("../lib/permission-authority.js");
3909
3975
  const permissionAuthorityOptions = { cwd: process.cwd() };
3910
3976
  const loaded = loadPermissionAuthority(permissionAuthorityOptions);
3977
+ _managedSettings = loaded.managed;
3911
3978
  _permissionRulesProvider = createPermissionRulesProvider(
3912
3979
  permissionAuthorityOptions,
3913
3980
  );
@@ -4151,6 +4218,9 @@ async function startAgentReplInWorkspaceOwned(
4151
4218
  }
4152
4219
  }
4153
4220
  }
4221
+ if (useJsonl && sessionId && planManager.memoryOnly) {
4222
+ planManager = new PlanModeManager({ sessionId });
4223
+ }
4154
4224
 
4155
4225
  // Phase H — register this session with session-core SessionManager so
4156
4226
  // `cc session lifecycle / park / unpark / end` can see and control it.
@@ -4882,7 +4952,16 @@ async function startAgentReplInWorkspaceOwned(
4882
4952
  }
4883
4953
 
4884
4954
  // Apply bundle approval policy to this session (after both gate and sessionId are ready)
4885
- if (_bundleResolved?.approvalPolicy?.default && _approvalGate && sessionId) {
4955
+ const { assertManagedPermissionMode } =
4956
+ await import("../lib/settings-loader.cjs");
4957
+ if (planPermissionMode)
4958
+ assertManagedPermissionMode(planPermissionMode, _managedSettings);
4959
+ if (
4960
+ !planManager.executionLock &&
4961
+ _bundleResolved?.approvalPolicy?.default &&
4962
+ _approvalGate &&
4963
+ sessionId
4964
+ ) {
4886
4965
  try {
4887
4966
  await _approvalGate.setSessionPolicy(
4888
4967
  sessionId,
@@ -4904,9 +4983,11 @@ async function startAgentReplInWorkspaceOwned(
4904
4983
  // trusted tier + the autoMode.decisions classifier. An explicit flag wins
4905
4984
  // over the bundle's approvalPolicy default. Unknown values are ignored here
4906
4985
  // (headless validates them; interactively we just keep the default tier).
4907
- if (options.permissionMode && _approvalGate && sessionId) {
4908
- const parsed = parsePermissionModeArg(options.permissionMode);
4909
- if (parsed && typeof _approvalGate.setSessionPolicy === "function") {
4986
+ if ((planPermissionMode || options.permissionMode) && sessionId) {
4987
+ const parsed = parsePermissionModeArg(
4988
+ planPermissionMode || options.permissionMode,
4989
+ );
4990
+ if (parsed && typeof _approvalGate?.setSessionPolicy === "function") {
4910
4991
  try {
4911
4992
  await _approvalGate.setSessionPolicy(sessionId, parsed.tier);
4912
4993
  await _approvalGate.awaitPersistence?.();
@@ -4914,9 +4995,17 @@ async function startAgentReplInWorkspaceOwned(
4914
4995
  parsed.auto ? "auto" : parsed.dontAsk ? "dontAsk" : parsed.tier,
4915
4996
  );
4916
4997
  } catch (error) {
4998
+ if (planManager.executionLock) throw error;
4917
4999
  logger.warn(`Approval policy was not persisted: ${error.message}`);
4918
5000
  }
5001
+ } else if (planManager.executionLock) {
5002
+ throw new Error("Cannot apply the approved plan's permission mode");
4919
5003
  }
5004
+ } else if (_approvalGate && sessionId) {
5005
+ const tier = parsePermissionTier(
5006
+ _approvalGate.getSessionPolicy?.(sessionId),
5007
+ );
5008
+ if (tier) setSessionTier(tier);
4920
5009
  }
4921
5010
 
4922
5011
  // Phase G #5 — inject top-K memory recall into system prompt for new sessions
@@ -5252,7 +5341,6 @@ async function startAgentReplInWorkspaceOwned(
5252
5341
  ? chalk.cyan("[N] ")
5253
5342
  : chalk.dim("[I] ")
5254
5343
  : "";
5255
- const planManager = getPlanModeManager();
5256
5344
  if (planManager.isActive()) {
5257
5345
  const state = planManager.state;
5258
5346
  if (state === PlanState.APPROVED || state === PlanState.EXECUTING) {
@@ -5633,6 +5721,7 @@ async function startAgentReplInWorkspaceOwned(
5633
5721
  if (isShiftTab) {
5634
5722
  _consumeReadlineKeypress(key);
5635
5723
  if (
5724
+ !planManager.executionLock &&
5636
5725
  _approvalGate &&
5637
5726
  sessionId &&
5638
5727
  typeof _approvalGate.setSessionPolicy === "function"
@@ -7865,6 +7954,12 @@ async function startAgentReplInWorkspaceOwned(
7865
7954
  initialCandidate.sessionId,
7866
7955
  );
7867
7956
  if (!prepared.ok) throw prepared.error;
7957
+ const targetPlan = openSessionPlan(prepared.sessionId);
7958
+ if (targetPlan.permissionMode)
7959
+ assertManagedPermissionMode(
7960
+ targetPlan.permissionMode,
7961
+ _managedSettings,
7962
+ );
7868
7963
  const preparedSideEffects = _prepareReplSideEffects(
7869
7964
  prepared.sessionId,
7870
7965
  { recover: true },
@@ -7892,6 +7987,24 @@ async function startAgentReplInWorkspaceOwned(
7892
7987
  prepared.conversationMessages.at(-1)?.role === "user",
7893
7988
  logMessage: `Resumed JSONL session ${prepared.sessionId} (${prepared.rebuiltMessages.length} messages)`,
7894
7989
  });
7990
+ const targetMode = parsePermissionModeArg(
7991
+ targetPlan.permissionMode ||
7992
+ (reuseCurrentLease
7993
+ ? _sessionTier
7994
+ : _approvalGate?.getSessionPolicy?.(prepared.sessionId)) ||
7995
+ "strict",
7996
+ );
7997
+ if (typeof _approvalGate?.setSessionPolicy === "function") {
7998
+ await _approvalGate.setSessionPolicy(
7999
+ prepared.sessionId,
8000
+ targetMode.tier,
8001
+ );
8002
+ await _approvalGate.awaitPersistence?.();
8003
+ } else if (targetPlan.manager.executionLock) {
8004
+ throw new Error(
8005
+ "Cannot apply the approved plan's permission mode",
8006
+ );
8007
+ }
7895
8008
  const committed = commitPreparedReplJsonlResume(
7896
8009
  prepared,
7897
8010
  () => _applyPreparedResumeState(preparedState),
@@ -7906,6 +8019,14 @@ async function startAgentReplInWorkspaceOwned(
7906
8019
  }
7907
8020
  const previousLease = _replaceSessionHostLease(targetLease);
7908
8021
  adoptedTargetLease = true;
8022
+ planManager = targetPlan.manager;
8023
+ setSessionTier(
8024
+ targetMode.auto
8025
+ ? "auto"
8026
+ : targetMode.dontAsk
8027
+ ? "dontAsk"
8028
+ : targetMode.tier,
8029
+ );
7909
8030
  _replSideEffects = preparedSideEffects.sideEffects;
7910
8031
  if (preparedSideEffects.warning) {
7911
8032
  logger.warn(preparedSideEffects.warning);
@@ -8697,7 +8818,6 @@ async function startAgentReplInWorkspaceOwned(
8697
8818
 
8698
8819
  // Plan mode commands
8699
8820
  if (trimmed.startsWith("/plan")) {
8700
- const planManager = getPlanModeManager();
8701
8821
  const subCmd = trimmed.slice(5).trim();
8702
8822
 
8703
8823
  if (!subCmd || subCmd === "enter") {
@@ -8706,7 +8826,12 @@ async function startAgentReplInWorkspaceOwned(
8706
8826
  "Already in plan mode. Use /plan show, /plan approve, or /plan reject.",
8707
8827
  );
8708
8828
  } else {
8709
- planManager.enterPlanMode({ title: "Agent Plan" });
8829
+ const result = planManager.enterPlanMode({ title: "Agent Plan" });
8830
+ if (result.error) {
8831
+ logger.error(result.error);
8832
+ prompt();
8833
+ return;
8834
+ }
8710
8835
  logger.success(
8711
8836
  "Entered plan mode. Write tools are blocked until you approve the plan.",
8712
8837
  );
@@ -8772,24 +8897,36 @@ async function startAgentReplInWorkspaceOwned(
8772
8897
  logger.warn(`Advisor plan review skipped: ${error.message}`);
8773
8898
  }
8774
8899
  }
8775
- planManager.approvePlan();
8900
+ const approved = planManager.approvePlan({
8901
+ permissionMode: permissionModeForTier(_sessionTier),
8902
+ });
8903
+ if (approved.error) {
8904
+ logger.error(approved.error);
8905
+ prompt();
8906
+ return;
8907
+ }
8908
+ if (!_recordPlanApproval()) return;
8776
8909
  logger.success(
8777
8910
  `Plan approved! ${planManager.currentPlan.items.length} items ready for execution.`,
8778
8911
  );
8779
- logger.info(
8780
- "Write/execute tools are now unlocked. The AI can proceed.",
8781
- );
8912
+ logger.info("The AI can execute the approved plan items.");
8782
8913
  messages.push({
8783
8914
  role: "system",
8784
- content: `[PLAN APPROVED] The user has approved your plan with ${planManager.currentPlan.items.length} items. You can now use all tools including write_file, edit_file, run_shell, and run_skill. Execute the plan items in order.`,
8915
+ content:
8916
+ "[PLAN APPROVED] Execute the approved plan items in order. Request a plan revision before using a write or execution tool outside the approval.",
8785
8917
  });
8786
8918
  }
8787
8919
  } else if (subCmd === "reject" || subCmd === "no") {
8788
8920
  if (!planManager.isActive()) {
8789
8921
  logger.info("No plan to reject.");
8790
8922
  } else {
8791
- planManager.rejectPlan("User rejected");
8792
- logger.info("Plan rejected. Exited plan mode.");
8923
+ const wasApproved = Boolean(planManager.executionLock);
8924
+ const result = planManager.rejectPlan("User rejected");
8925
+ if (result.error) logger.error(result.error);
8926
+ else {
8927
+ if (wasApproved && !_recordPlanApproval()) return;
8928
+ logger.info("Plan rejected. Exited plan mode.");
8929
+ }
8793
8930
  }
8794
8931
  } else if (subCmd === "risk") {
8795
8932
  if (!planManager.isActive() || !planManager.currentPlan) {
@@ -8818,17 +8955,25 @@ async function startAgentReplInWorkspaceOwned(
8818
8955
  } else {
8819
8956
  logger.info("Executing plan items in DAG order...");
8820
8957
  try {
8821
- const { results, success } = await planManager.executePlan(
8822
- async (item) => {
8823
- if (item.tool && item.params) {
8824
- process.stdout.write(
8825
- chalk.gray(` [${item.tool}] ${item.title}\n`),
8826
- );
8827
- return await _runReplDirectTool(item.tool, item.params);
8828
- }
8829
- return { skipped: true };
8830
- },
8831
- );
8958
+ const execution = await planManager.executePlan(async (item) => {
8959
+ if (item.tool && item.params) {
8960
+ process.stdout.write(
8961
+ chalk.gray(` [${item.tool}] ${item.title}\n`),
8962
+ );
8963
+ const result = await _runReplDirectTool(
8964
+ item.tool,
8965
+ item.params,
8966
+ {
8967
+ approvedPlanExecution: true,
8968
+ },
8969
+ );
8970
+ if (result?.error) throw new Error(result.error);
8971
+ return result;
8972
+ }
8973
+ return { skipped: true };
8974
+ });
8975
+ if (execution.error) throw new Error(execution.error);
8976
+ const { results, success } = execution;
8832
8977
  for (const r of results) {
8833
8978
  const icon = r.success ? chalk.green("✓") : chalk.red("✗");
8834
8979
  logger.log(
@@ -8838,15 +8983,22 @@ async function startAgentReplInWorkspaceOwned(
8838
8983
  logger.info(
8839
8984
  `Plan execution ${success ? "completed" : "finished with errors"}.`,
8840
8985
  );
8841
- planManager.exitPlanMode({ savePlan: true });
8986
+ const exited = planManager.exitPlanMode({ savePlan: true });
8987
+ if (exited.error) throw new Error(exited.error);
8988
+ if (!_recordPlanApproval()) return;
8842
8989
  } catch (err) {
8843
8990
  logger.error(`Plan execution failed: ${err.message}`);
8844
8991
  }
8845
8992
  }
8846
8993
  } else if (subCmd === "exit") {
8847
8994
  if (planManager.isActive()) {
8848
- planManager.exitPlanMode({ savePlan: true });
8849
- logger.info("Exited plan mode.");
8995
+ const wasApproved = Boolean(planManager.executionLock);
8996
+ const result = planManager.exitPlanMode({ savePlan: true });
8997
+ if (result.error) logger.error(result.error);
8998
+ else {
8999
+ if (wasApproved && !_recordPlanApproval()) return;
9000
+ logger.info("Exited plan mode.");
9001
+ }
8850
9002
  } else {
8851
9003
  logger.info("Not in plan mode.");
8852
9004
  }
@@ -9249,6 +9401,10 @@ async function startAgentReplInWorkspaceOwned(
9249
9401
  "Usage: /permissions [strict|trusted|autopilot|auto|dontask] " +
9250
9402
  "(aliases: default · manual · accept-edits · bypass). No arg = show rules.",
9251
9403
  );
9404
+ } else if (planManager.executionLock) {
9405
+ logger.info(
9406
+ "The approved plan locks the current permission mode. Use /plan exit to release it.",
9407
+ );
9252
9408
  } else if (
9253
9409
  !_approvalGate ||
9254
9410
  !sessionId ||
@@ -10180,6 +10336,7 @@ async function startAgentReplInWorkspaceOwned(
10180
10336
  ? (event) => appendEvent(sessionId, "model_decision", event)
10181
10337
  : undefined,
10182
10338
  permissionMode: _sessionTier,
10339
+ planManager,
10183
10340
  // Seed the subagent-contract CEILING with the interactive session's
10184
10341
  // CURRENT approval tier (mapped back to a permission mode) so a spawned
10185
10342
  // sub-agent inherits/tightens from it (tighten-only), mirroring the
@@ -10968,7 +11125,10 @@ async function startAgentReplInWorkspaceOwned(
10968
11125
  if (_evolutionSession !== null) {
10969
11126
  try {
10970
11127
  await _evolutionSession.close(
10971
- _replOutputFailure || _runtimeLedgerTerminalLatch.error() || null,
11128
+ _replOutputFailure ||
11129
+ _planApprovalFailure ||
11130
+ _runtimeLedgerTerminalLatch.error() ||
11131
+ null,
10972
11132
  );
10973
11133
  } catch (error) {
10974
11134
  _replOutputFailure ||= error;
@@ -10978,7 +11138,9 @@ async function startAgentReplInWorkspaceOwned(
10978
11138
  ? _replOutputFailure.code === "EPIPE"
10979
11139
  ? 0
10980
11140
  : 1
10981
- : 0;
11141
+ : _planApprovalFailure
11142
+ ? 1
11143
+ : 0;
10982
11144
  outputScope.restore();
10983
11145
  process.exit(outputExitCode);
10984
11146
  });
@@ -220,6 +220,8 @@ import {
220
220
  import { buildSearchCommand } from "../lib/search-command.js";
221
221
  import { discoverCommands } from "../lib/slash-commands.js";
222
222
  import {
223
+ CHAT_COMPLETIONS_STREAM_FAILED,
224
+ cancelProviderStreamReader,
223
225
  isRetryableStreamError,
224
226
  STREAM_RETRY_BASE_MS,
225
227
  resolveStreamRetryMax,
@@ -1266,7 +1268,7 @@ ${CODING_TASK_QUALITY_GUIDANCE}
1266
1268
  - The git tool accepts ONE Git argument list, without pipes, redirects, &&, semicolons or echo. Use log -n 5 instead of piping to head; inspect the returned exitCode for predicates such as merge-base --is-ancestor (1 means false). Discover remote names with remote -v; do not assume origin exists.
1267
1269
  - On Windows, run_shell defaults to cmd unless configured otherwise. Set shell: "powershell" for PowerShell syntax or shell: "pwsh" for PowerShell 7. Parse saved JSON after stripping an initial UTF-8 BOM; a BOM parse error is not a JavaScript syntax defect.
1268
1270
  - When asked about files or code, use search_files to locate relevant sections, then read_file with offset/limit. Follow nextRead for large files. Reuse unchanged content already in context instead of repeatedly reading the same page; re-read when the file changes or the earlier content is no longer available.
1269
- - For long text files, use search_files with path and pattern to find matching lines/columns and nearby text; read the returned nextRead location instead of paging from the top.
1271
+ - To find specific text in a long file, use search_files with path and a nonempty pattern, then read the returned nextRead location. To inspect a file without a search term, use read_file with offset and limit.
1270
1272
  - For online discovery without a known URL, use web_search with keywords. Return relevant source links and snippets; use web_fetch only when the source needs closer reading. For a known URL, fetch it directly. Download large pages once, then use snapshotId to search or read local chunks. Never invent URLs or claim a blocked search returned no results.
1271
1273
  - Large task documents include a sampled outline with line numbers. Use it to locate relevant unfinished work and inspect those sections instead of scanning the entire document unless the task requires full coverage. File coverage and excerpts survive compaction; reading to EOF is not completing the user's task.
1272
1274
  - For task counts or completion status, search the named document for the latest status/summary table first, then read that section. Distinguish historical entries from current status and repository work from external acceptance. Once the relevant entries are verified, answer; do not read every implementation detail just to count tasks.
@@ -2061,6 +2063,16 @@ export function preflightToolExecutionAuthority(name, args, context = {}) {
2061
2063
  policy: { decision: "blocked", via: "effective-tool-set" },
2062
2064
  };
2063
2065
  }
2066
+ if (
2067
+ !(name === "git" && isReadOnlyGitCommand(args?.command)) &&
2068
+ context.planManager?.allowsApprovedToolArgs?.(name, args) === false
2069
+ ) {
2070
+ return {
2071
+ error: `[Plan Execution Lock] Tool "${name}" with these arguments does not match the next approved plan item. Request a plan revision before making this change.`,
2072
+ code: "CC_PLAN_TOOL_ARGS_NOT_APPROVED",
2073
+ policy: { decision: "blocked", via: "plan-execution-lock" },
2074
+ };
2075
+ }
2064
2076
  return guardExactFileMutationScope(name, args, context, cwd);
2065
2077
  }
2066
2078
 
@@ -2987,6 +2999,7 @@ export async function executeTool(name, args, context = {}) {
2987
2999
  const authorityDenial = preflightToolExecutionAuthority(name, args, {
2988
3000
  ...context,
2989
3001
  cwd,
3002
+ planManager,
2990
3003
  });
2991
3004
  if (authorityDenial) return authorityDenial;
2992
3005
  let admittedEffectiveToolSetDigest = null;
@@ -6281,14 +6294,30 @@ async function executeToolInner(
6281
6294
  const refusal = ephemeralWorktreeConsumerRefusal("Background shell");
6282
6295
  if (refusal) return attachDescriptor(refusal);
6283
6296
  }
6297
+ const shellPolicyOpts = Object.freeze({
6298
+ ...(shellPolicyOverrides
6299
+ ? { overrideRuleIds: Object.freeze([...shellPolicyOverrides]) }
6300
+ : {}),
6301
+ ...(classifyAllShell ? { classifyAllShell: true } : {}),
6302
+ });
6303
+ let shellPolicy = evaluateShellCommandPolicy(
6304
+ args.command,
6305
+ shellPolicyOpts,
6306
+ );
6284
6307
  if (unattendedActionPolicy?.unattended === true) {
6285
6308
  const unattendedVerdict = evaluateUnattendedShellAction(args.command, {
6286
6309
  ...unattendedActionPolicy,
6287
6310
  attended: false,
6288
6311
  });
6289
6312
  if (!unattendedVerdict.allow) {
6313
+ const deleteDenied =
6314
+ shellPolicy.allowed === false &&
6315
+ shellPolicy.ruleId === "dangerous-delete";
6290
6316
  return attachDescriptor({
6291
- error: `[Unattended Action] ${unattendedVerdict.reason}; shell command was not run.`,
6317
+ error: deleteDenied
6318
+ ? `[Shell Policy] ${shellPolicy.reason} Use a non-destructive approach.`
6319
+ : `[Unattended Action] ${unattendedVerdict.reason}; shell command was not run.`,
6320
+ ...(deleteDenied ? { shellCommandPolicy: shellPolicy } : {}),
6292
6321
  unattendedAction: {
6293
6322
  actionClass: unattendedVerdict.actionClass || null,
6294
6323
  ...unattendedVerdict,
@@ -6298,12 +6327,6 @@ async function executeToolInner(
6298
6327
  }
6299
6328
  }
6300
6329
 
6301
- const shellPolicyOpts = Object.freeze({
6302
- ...(shellPolicyOverrides
6303
- ? { overrideRuleIds: Object.freeze([...shellPolicyOverrides]) }
6304
- : {}),
6305
- ...(classifyAllShell ? { classifyAllShell: true } : {}),
6306
- });
6307
6330
  // Layer-by-layer explanation chain for a blocked command: which layers
6308
6331
  // were consulted and what each said (settings rules → shell policy →
6309
6332
  // approval gate). Attached to denial results so `/permissions denials`
@@ -6339,10 +6362,6 @@ async function executeToolInner(
6339
6362
  return chain;
6340
6363
  };
6341
6364
  const override = getRuntimeToolDescriptorByCommand(args.command);
6342
- let shellPolicy = evaluateShellCommandPolicy(
6343
- args.command,
6344
- shellPolicyOpts,
6345
- );
6346
6365
  let approvalOutcome = null;
6347
6366
  let approvalAuthorization = null;
6348
6367
  let approvalAuthorizationContext = null;
@@ -8705,7 +8724,11 @@ async function executeToolInner(
8705
8724
  // Pattern is model/user-supplied and flows into a shell — build the
8706
8725
  // command with it SAFELY quoted (see search-command.js). Raw interpolation
8707
8726
  // here was a command-injection bypass of the run_shell guards.
8708
- const built = buildSearchCommand({ pattern: args.pattern, isContent });
8727
+ const built = buildSearchCommand({
8728
+ pattern: args.pattern,
8729
+ isContent,
8730
+ regex: args.regex,
8731
+ });
8709
8732
  if (built.error) {
8710
8733
  return attachDescriptor({ error: built.error });
8711
8734
  }
@@ -8745,10 +8768,8 @@ async function executeToolInner(
8745
8768
  cwd: root,
8746
8769
  encoding: "utf8",
8747
8770
  timeout: 10000,
8748
- // Windows `findstr`/`dir /s` have no `head` cap (unlike the POSIX
8749
- // `| head -20`), so a large tree can blow past execSync's 1 MB
8750
- // default and throw ENOBUFS. Give it real headroom AND salvage the
8751
- // partial below — otherwise a busy repo silently reports "no matches".
8771
+ // Uncapped native search output can exceed execSync's 1 MB default.
8772
+ // Allow more headroom and preserve partial hits on ENOBUFS below.
8752
8773
  maxBuffer: 8 * 1024 * 1024,
8753
8774
  });
8754
8775
  _ingestSearchOutput(output, ictx);
@@ -13647,6 +13668,10 @@ async function _chatOpenAIStreaming(
13647
13668
  }
13648
13669
  } catch (err) {
13649
13670
  attachStreamRetryMetadata(err, retryMetadata);
13671
+ if (err?.code === CHAT_COMPLETIONS_STREAM_FAILED) {
13672
+ cancelProviderStreamReader(reader);
13673
+ throw err;
13674
+ }
13650
13675
  if (!ui.hasVisibleOutput() && !state.text && state.tools.length)
13651
13676
  err.noReplay = true;
13652
13677
  if (
@@ -18077,7 +18102,8 @@ export async function* agentLoop(messages, options) {
18077
18102
  earlyAuthorityDenial,
18078
18103
  );
18079
18104
  const preExecutionDenied =
18080
- earlyAuthorityDenial.code === TOOL_RECOVERY_PAUSED_CODE;
18105
+ earlyAuthorityDenial.code === TOOL_RECOVERY_PAUSED_CODE ||
18106
+ earlyAuthorityDenial.code === "CC_PLAN_TOOL_ARGS_NOT_APPROVED";
18081
18107
  if (preExecutionDenied) {
18082
18108
  // Declare the rejected request without an execution/ledger boundary
18083
18109
  // or its arguments. Consumers can pair the refusal by provider ID.
@@ -390,13 +390,15 @@ const CODING_AGENT_TOOL_CONTRACTS = Object.freeze([
390
390
  kind: "filesystem",
391
391
  tier: "mvp",
392
392
  description:
393
- "Search for files by name pattern or content. For a long text file, pass path and pattern: returns matching line/column positions, nearby context, and nextRead arguments for read_file. This streams the file instead of loading it into model context. Continue capped results with nextOffset as offset. Omit path for the existing directory search.",
393
+ "Find files by name or search for matching text. For one text file, supply path and a nonempty pattern to get line/column positions, nearby text, and nextRead arguments. Continue capped results with nextOffset as offset. To inspect a known file without a search term, use read_file with path, offset, and limit. For a directory search, omit path and set content_search:true to search file contents.",
394
394
  inputSchema: {
395
395
  type: "object",
396
396
  properties: {
397
397
  pattern: {
398
398
  type: "string",
399
- description: "Glob pattern or search string",
399
+ minLength: 1,
400
+ description:
401
+ "Nonempty filename pattern or text to match. For a single file, use at most 2048 characters.",
400
402
  },
401
403
  path: {
402
404
  type: "string",