chainlesschain 0.166.161 → 0.166.162

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 (36) hide show
  1. package/README.md +9 -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 +13 -0
  15. package/src/harness/background-task-command-runner.js +23 -25
  16. package/src/lib/background-agent-supervisor.js +3 -0
  17. package/src/lib/cowork-cron.js +115 -31
  18. package/src/lib/install-command-policy.js +23 -0
  19. package/src/lib/json-schema-output.js +12 -31
  20. package/src/lib/loop.js +30 -11
  21. package/src/lib/lsp/__tests__/code-intelligence.integration.test.js +17 -15
  22. package/src/lib/plan-mode.js +16 -0
  23. package/src/lib/plugin-runtime/install.js +111 -67
  24. package/src/lib/process-execution-broker/index.js +19 -9
  25. package/src/lib/public-ide-capability-manifest.js +88 -0
  26. package/src/lib/public-ide-capability-validation.js +24 -0
  27. package/src/lib/repl-denials.js +11 -0
  28. package/src/lib/search-command.js +13 -2
  29. package/src/lib/session-plan-approval.js +11 -2
  30. package/src/lib/status-line.cjs +3 -2
  31. package/src/lib/task-record.js +12 -1
  32. package/src/repl/agent-repl.js +195 -33
  33. package/src/runtime/agent-core.js +37 -17
  34. package/src/runtime/headless-runner.js +61 -4
  35. package/src/runtime/headless-stream.js +50 -2
  36. package/src/workers/background-agent-worker.js +11 -10
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { EventEmitter } from "events";
11
+ import { isDeepStrictEqual } from "node:util";
11
12
  import {
12
13
  createPlanSessionEvent,
13
14
  PLAN_PERSISTENCE_ERROR_CODES,
@@ -1234,6 +1235,21 @@ export class PlanModeManager extends EventEmitter {
1234
1235
  };
1235
1236
  }
1236
1237
 
1238
+ /** Enforce the parameters covered by a durable session approval. */
1239
+ allowsApprovedToolArgs(toolName, args) {
1240
+ if (!this.sessionId || !this.executionLock || READ_TOOLS.has(toolName))
1241
+ return true;
1242
+
1243
+ const item = this.currentPlan?.items.find(
1244
+ (candidate) =>
1245
+ candidate.tool === toolName &&
1246
+ this.executionLock.approvedItemIds.includes(candidate.id) &&
1247
+ (candidate.status === PlanStatus.APPROVED ||
1248
+ candidate.status === PlanStatus.EXECUTING),
1249
+ );
1250
+ return Boolean(item && isDeepStrictEqual(item.params, args));
1251
+ }
1252
+
1237
1253
  /**
1238
1254
  * Attribute a live tool call to the next approved item for that tool.
1239
1255
  * Read-only/helper calls that were not part of the approved plan remain
@@ -51,6 +51,7 @@ import {
51
51
  redactPluginSourceForDisplay,
52
52
  } from "../plugin-source-identity.js";
53
53
  import { assertRegistryResolutionAuthority } from "./remote-source.js";
54
+ import { normalizeInstallCommandResult } from "../install-command-policy.js";
54
55
  import {
55
56
  writePluginLock,
56
57
  buildPluginSbom,
@@ -794,10 +795,18 @@ function _withMaterializedSource(source, fn, opts = {}) {
794
795
  }
795
796
  return result;
796
797
  }
797
- const cloned = fetchGitRepo(git.url, git.ref, { cwd: opts.cwd });
798
+ let cloned;
799
+ let installCommand;
798
800
  try {
801
+ cloned = fetchGitRepo(git.url, git.ref, {
802
+ cwd: opts.cwd,
803
+ onInstallCommand(receipt) {
804
+ installCommand = receipt;
805
+ },
806
+ });
799
807
  const result = fn(cloned, git);
800
808
  if (result && typeof result === "object") {
809
+ if (installCommand) result.installCommand = installCommand;
801
810
  try {
802
811
  const cached = publishMarketplaceSourceCache(
803
812
  cloned,
@@ -816,9 +825,13 @@ function _withMaterializedSource(source, fn, opts = {}) {
816
825
  }
817
826
  }
818
827
  return result;
828
+ } catch (error) {
829
+ if (installCommand) error.installCommand = installCommand;
830
+ throw error;
819
831
  } finally {
820
832
  try {
821
- _deps.rmSync(path.dirname(cloned), { recursive: true, force: true });
833
+ if (cloned)
834
+ _deps.rmSync(path.dirname(cloned), { recursive: true, force: true });
822
835
  } catch {
823
836
  /* temp cleanup is best-effort */
824
837
  }
@@ -1987,13 +2000,17 @@ export function fetchGitRepo(url, ref, options = {}) {
1987
2000
  const executable = resolveTrustedGitExecutable(cwd);
1988
2001
  const base = _deps.mkdtempSync(path.join(os.tmpdir(), "cc-plugin-git-"));
1989
2002
  const dir = path.join(base, "repo");
2003
+ const stderrHash = crypto.createHash("sha256");
2004
+ let printedToStderr = false;
2005
+ let ran = false;
2006
+ let lastProcess;
1990
2007
  const run = (args) => {
1991
2008
  const hardenedArgs = hardenedPluginGitArgs(args, { url, cwd });
1992
2009
  const auditRedactArgIndexes = hardenedArgs.flatMap((argument, index) =>
1993
2010
  argument === url || (ref != null && argument === ref) ? [index] : [],
1994
2011
  );
1995
2012
  try {
1996
- return _deps.spawnSync(executable, hardenedArgs, {
2013
+ lastProcess = _deps.spawnSync(executable, hardenedArgs, {
1997
2014
  cwd: base,
1998
2015
  encoding: "utf8",
1999
2016
  env: hardenedPluginGitEnvironment(),
@@ -2006,8 +2023,16 @@ export function fetchGitRepo(url, ref, options = {}) {
2006
2023
  auditRedactArgIndexes,
2007
2024
  });
2008
2025
  } catch (error) {
2009
- return { error, status: null, stdout: "", stderr: "" };
2026
+ lastProcess = { error, status: null, stdout: "", stderr: "" };
2010
2027
  }
2028
+ if (lastProcess.stderr?.length) {
2029
+ printedToStderr = true;
2030
+ stderrHash.update(lastProcess.stderr);
2031
+ }
2032
+ ran ||= Boolean(
2033
+ lastProcess.pid || lastProcess.signal || lastProcess.status != null,
2034
+ );
2035
+ return lastProcess;
2011
2036
  };
2012
2037
 
2013
2038
  // Reduce host-specific checkout differences before the v2 inventory hashes
@@ -2027,35 +2052,56 @@ export function fetchGitRepo(url, ref, options = {}) {
2027
2052
  const cloneArgs = [...canonicalCheckoutArgs, "clone", "--depth", "1"];
2028
2053
  if (ref) cloneArgs.push("--branch", ref);
2029
2054
  cloneArgs.push(url, dir);
2030
- let res = run(cloneArgs);
2031
- if (res.error && res.error.code === "ENOENT") {
2032
- throw new Error("git is not installed (needed to fetch a remote plugin)");
2033
- }
2034
- if (res.error) {
2035
- throw new Error(
2036
- `git process failed for ${redactPluginSourceForDisplay(url)}`,
2037
- );
2038
- }
2039
- if (res.status !== 0) {
2040
- // A commit SHA can't be used with --branch/--depth; retry with a full clone
2041
- // then checkout the ref explicitly.
2042
- if (ref) {
2043
- try {
2044
- _deps.rmSync(dir, { recursive: true, force: true });
2045
- } catch {
2046
- /* ignore */
2047
- }
2048
- const full = run([...canonicalCheckoutArgs, "clone", url, dir]);
2049
- if (!full.error && full.status === 0) {
2050
- const co = run([...canonicalCheckoutArgs, "-C", dir, "checkout", ref]);
2051
- if (co.status === 0) return dir;
2055
+ try {
2056
+ const res = run(cloneArgs);
2057
+ if (res.error?.code === "ENOENT") {
2058
+ throw new Error("git is not installed (needed to fetch a remote plugin)");
2059
+ }
2060
+ if (res.error) {
2061
+ throw new Error(
2062
+ `git process failed for ${redactPluginSourceForDisplay(url)}`,
2063
+ );
2064
+ }
2065
+ if (res.status !== 0) {
2066
+ // A commit SHA can't be used with --branch/--depth; retry with a full clone
2067
+ // then checkout the ref explicitly.
2068
+ if (ref) {
2069
+ try {
2070
+ _deps.rmSync(dir, { recursive: true, force: true });
2071
+ } catch {
2072
+ /* ignore */
2073
+ }
2074
+ const full = run([...canonicalCheckoutArgs, "clone", url, dir]);
2075
+ if (!full.error && full.status === 0) {
2076
+ const co = run([
2077
+ ...canonicalCheckoutArgs,
2078
+ "-C",
2079
+ dir,
2080
+ "checkout",
2081
+ ref,
2082
+ ]);
2083
+ if (!co.error && co.status === 0) return dir;
2084
+ }
2052
2085
  }
2086
+ throw new Error(
2087
+ `git clone failed for ${redactPluginSourceForDisplay(url)} (git exited ${lastProcess.status})`,
2088
+ );
2089
+ }
2090
+ return dir;
2091
+ } finally {
2092
+ if (lastProcess) {
2093
+ options.onInstallCommand?.(
2094
+ normalizeInstallCommandResult({
2095
+ ran,
2096
+ exitCode: lastProcess.status,
2097
+ timedOut: lastProcess.error?.code === "ETIMEDOUT",
2098
+ signal: lastProcess.signal,
2099
+ printedToStderr,
2100
+ stderrDigest: stderrHash.digest("hex"),
2101
+ }),
2102
+ );
2053
2103
  }
2054
- throw new Error(
2055
- `git clone failed for ${redactPluginSourceForDisplay(url)} (git exited ${res.status})`,
2056
- );
2057
2104
  }
2058
- return dir;
2059
2105
  }
2060
2106
 
2061
2107
  /**
@@ -3390,17 +3436,17 @@ function sameSourceAuthority(current, candidate) {
3390
3436
  if (current.type === "registry") {
3391
3437
  return Boolean(
3392
3438
  current.sourceDigest &&
3393
- candidate.sourceDigest &&
3394
- current.sourceDigest === candidate.sourceDigest &&
3395
- current.resolvedSourceDigest &&
3396
- candidate.resolvedSourceDigest &&
3397
- current.resolvedSourceDigest === candidate.resolvedSourceDigest,
3439
+ candidate.sourceDigest &&
3440
+ current.sourceDigest === candidate.sourceDigest &&
3441
+ current.resolvedSourceDigest &&
3442
+ candidate.resolvedSourceDigest &&
3443
+ current.resolvedSourceDigest === candidate.resolvedSourceDigest,
3398
3444
  );
3399
3445
  }
3400
3446
  return Boolean(
3401
3447
  current.sourceDigest &&
3402
- candidate.sourceDigest &&
3403
- current.sourceDigest === candidate.sourceDigest,
3448
+ candidate.sourceDigest &&
3449
+ current.sourceDigest === candidate.sourceDigest,
3404
3450
  );
3405
3451
  }
3406
3452
 
@@ -3996,8 +4042,8 @@ function assertCatalogRemoteArtifactBindings(metadata) {
3996
4042
  const expectedSignature = expectations.signature || {};
3997
4043
  const expectsRemoteSignature = Boolean(
3998
4044
  expectedSignature.url &&
3999
- expectedSignature.publicKeyUrl &&
4000
- expectedSignature.publicKeySha256,
4045
+ expectedSignature.publicKeyUrl &&
4046
+ expectedSignature.publicKeySha256,
4001
4047
  );
4002
4048
  if (expectsRemoteSignature !== Boolean(evidence.signature)) {
4003
4049
  throw new Error(
@@ -5626,9 +5672,9 @@ function samePointerState(left, right) {
5626
5672
  if (!left.present) return true;
5627
5673
  return Boolean(
5628
5674
  Buffer.isBuffer(left.bytes) &&
5629
- Buffer.isBuffer(right.bytes) &&
5630
- left.bytes.equals(right.bytes) &&
5631
- sameFileGeneration(left.generation, right.generation),
5675
+ Buffer.isBuffer(right.bytes) &&
5676
+ left.bytes.equals(right.bytes) &&
5677
+ sameFileGeneration(left.generation, right.generation),
5632
5678
  );
5633
5679
  }
5634
5680
 
@@ -5666,9 +5712,9 @@ function sameLifecycleFileState(left, right) {
5666
5712
  if (!left.present) return true;
5667
5713
  return Boolean(
5668
5714
  Buffer.isBuffer(left.bytes) &&
5669
- Buffer.isBuffer(right.bytes) &&
5670
- left.bytes.equals(right.bytes) &&
5671
- sameFileGeneration(left.generation, right.generation),
5715
+ Buffer.isBuffer(right.bytes) &&
5716
+ left.bytes.equals(right.bytes) &&
5717
+ sameFileGeneration(left.generation, right.generation),
5672
5718
  );
5673
5719
  }
5674
5720
 
@@ -5716,11 +5762,11 @@ function serializePluginNameState(state) {
5716
5762
  function samePluginNameState(left, right) {
5717
5763
  return Boolean(
5718
5764
  left &&
5719
- right &&
5720
- sameFileGeneration(left.generation, right.generation) &&
5721
- left.payloadDigest === right.payloadDigest &&
5722
- left.fileCount === right.fileCount &&
5723
- left.totalBytes === right.totalBytes,
5765
+ right &&
5766
+ sameFileGeneration(left.generation, right.generation) &&
5767
+ left.payloadDigest === right.payloadDigest &&
5768
+ left.fileCount === right.fileCount &&
5769
+ left.totalBytes === right.totalBytes,
5724
5770
  );
5725
5771
  }
5726
5772
 
@@ -5743,8 +5789,8 @@ function lifecycleFileContentMatches(left, right) {
5743
5789
  if (!left.present) return true;
5744
5790
  return Boolean(
5745
5791
  Buffer.isBuffer(left.bytes) &&
5746
- Buffer.isBuffer(right.bytes) &&
5747
- left.bytes.equals(right.bytes),
5792
+ Buffer.isBuffer(right.bytes) &&
5793
+ left.bytes.equals(right.bytes),
5748
5794
  );
5749
5795
  }
5750
5796
 
@@ -5810,9 +5856,7 @@ function hasRetainedLifecycleRecovery(nameDir) {
5810
5856
  function authoritativeTransactionCleanupPending(cleanup) {
5811
5857
  return Boolean(
5812
5858
  cleanup?.cleanupPending === true &&
5813
- /^\.(?:install|uninstall)-/u.test(
5814
- path.basename(cleanup.cleanupPath || ""),
5815
- ),
5859
+ /^\.(?:install|uninstall)-/u.test(path.basename(cleanup.cleanupPath || "")),
5816
5860
  );
5817
5861
  }
5818
5862
 
@@ -5902,22 +5946,22 @@ function fileGeneration(stat) {
5902
5946
  function sameFileGeneration(left, right) {
5903
5947
  return Boolean(
5904
5948
  left &&
5905
- right &&
5906
- left.dev === right.dev &&
5907
- left.ino === right.ino &&
5908
- left.birthtimeMs === right.birthtimeMs &&
5909
- left.mtimeMs === right.mtimeMs &&
5910
- left.size === right.size,
5949
+ right &&
5950
+ left.dev === right.dev &&
5951
+ left.ino === right.ino &&
5952
+ left.birthtimeMs === right.birthtimeMs &&
5953
+ left.mtimeMs === right.mtimeMs &&
5954
+ left.size === right.size,
5911
5955
  );
5912
5956
  }
5913
5957
 
5914
5958
  function sameInstalledVersionState(left, right) {
5915
5959
  return Boolean(
5916
5960
  left &&
5917
- right &&
5918
- sameFileGeneration(left.generation, right.generation) &&
5919
- left.payloadDigest === right.payloadDigest &&
5920
- left.sourceDigest === right.sourceDigest,
5961
+ right &&
5962
+ sameFileGeneration(left.generation, right.generation) &&
5963
+ left.payloadDigest === right.payloadDigest &&
5964
+ left.sourceDigest === right.sourceDigest,
5921
5965
  );
5922
5966
  }
5923
5967
 
@@ -5999,8 +6043,8 @@ function activePointerMatchesSnapshot(transaction) {
5999
6043
  if (!snapshot.present) return true;
6000
6044
  return Boolean(
6001
6045
  Buffer.isBuffer(current.bytes) &&
6002
- Buffer.isBuffer(snapshot.bytes) &&
6003
- current.bytes.equals(snapshot.bytes),
6046
+ Buffer.isBuffer(snapshot.bytes) &&
6047
+ current.bytes.equals(snapshot.bytes),
6004
6048
  );
6005
6049
  }
6006
6050
 
@@ -5753,17 +5753,27 @@ class ProcessExecutionBroker extends EventEmitter {
5753
5753
  const cb = typeof options === "function" ? options : callback;
5754
5754
  if (this._requiresExplicitLinuxWorkspaceShell(opts.cwd || process.cwd())) {
5755
5755
  const invocation = this._explicitLinuxShellInvocation(command, opts);
5756
- return this.spawn(invocation.command, invocation.args, {
5756
+ return this.execFile(
5757
+ invocation.command,
5758
+ invocation.args,
5759
+ {
5760
+ ...opts,
5761
+ shell: false,
5762
+ origin: opts.origin || "shell:exec",
5763
+ },
5764
+ cb,
5765
+ );
5766
+ }
5767
+ return this.execFile(
5768
+ command,
5769
+ [],
5770
+ {
5757
5771
  ...opts,
5758
- shell: false,
5772
+ shell: true,
5759
5773
  origin: opts.origin || "shell:exec",
5760
- });
5761
- }
5762
- return this.spawn(command, [], {
5763
- ...opts,
5764
- shell: true,
5765
- origin: opts.origin || "shell:exec",
5766
- });
5774
+ },
5775
+ cb,
5776
+ );
5767
5777
  }
5768
5778
 
5769
5779
  execSync(command, options = {}) {
@@ -188,6 +188,94 @@ export const PUBLIC_IDE_CAPABILITY_MANIFEST = freeze({
188
188
  commandHelpIndex: "packages/cli/src/command-help-index.json",
189
189
  requiredCommands: ["doctor", "ide"],
190
190
  doctorCommands: ["doctor", "ide doctor"],
191
+ directCommands: {
192
+ tasks: {
193
+ entrypoint: "packages/cli/src/index.js",
194
+ source: "packages/cli/src/commands/tasks.js",
195
+ registrar: "registerTasksCommand",
196
+ },
197
+ },
198
+ automation: {
199
+ taskProjection: {
200
+ commands: ["tasks"],
201
+ fields: [
202
+ "tasks[].taskId",
203
+ "tasks[].parentTaskId",
204
+ "tasks[].source",
205
+ "tasks[].state",
206
+ "tasks[].waitingOn",
207
+ "tasks[].endsAt",
208
+ "tasks[].nextRunAt",
209
+ "tasks[].expiresAction",
210
+ "tasks[].stopPath",
211
+ "tasks[].stopEvents",
212
+ "tasks[].orphanRisk",
213
+ "tasks[].permissionProfileDigest",
214
+ ],
215
+ guides: ["docs-site/docs/chainlesschain/cli-agent.md"],
216
+ },
217
+ statusLine: {
218
+ commands: ["agent"],
219
+ fields: [
220
+ "task.state",
221
+ "task.approvals_pending",
222
+ "task.mcp_errors",
223
+ "task.schedule_ends_at",
224
+ "context.visible",
225
+ "context.threshold",
226
+ ],
227
+ guides: ["docs-site/docs/chainlesschain/cli-agent.md"],
228
+ },
229
+ installCommand: {
230
+ commands: [
231
+ "plugin add",
232
+ "plugin upgrade",
233
+ "plugin install",
234
+ "skill add",
235
+ "mcp add",
236
+ ],
237
+ fields: [
238
+ "installCommand.ran",
239
+ "installCommand.exitCode",
240
+ "installCommand.timedOut",
241
+ "installCommand.signaled",
242
+ "installCommand.printedToStderr",
243
+ "installCommand.stderrDigest",
244
+ ],
245
+ guides: [
246
+ "docs-site/docs/chainlesschain/cli-plugin.md",
247
+ "docs-site/docs/chainlesschain/skills.md",
248
+ "docs-site/docs/chainlesschain/cli-mcp.md",
249
+ ],
250
+ },
251
+ headlessPersistence: {
252
+ commands: ["agent"],
253
+ fields: [
254
+ "is_error",
255
+ "subtype",
256
+ "persistence.phase",
257
+ "persistence.fs_code",
258
+ ],
259
+ guides: ["docs-site/docs/chainlesschain/cli-agent.md"],
260
+ },
261
+ runnerStartup: {
262
+ commands: ["status"],
263
+ fields: [
264
+ "runner.startup.orderedAt",
265
+ "runner.startup.registeredAt",
266
+ "runner.startup.firstSessionAdmittedAt",
267
+ "runner.startup.order_to_registered_seconds",
268
+ "runner.startup.registered_to_first_session_seconds",
269
+ "runner.startup.order_to_first_session_seconds",
270
+ ],
271
+ guides: ["docs-site/docs/chainlesschain/cli-status.md"],
272
+ },
273
+ sessionFork: {
274
+ commands: ["session fork"],
275
+ fields: ["sessionId", "forkedFrom"],
276
+ guides: ["docs-site/docs/chainlesschain/ide-plugin.md"],
277
+ },
278
+ },
191
279
  },
192
280
  vscode: {
193
281
  commandContribution: "packages/vscode-extension/package.json",
@@ -287,12 +287,36 @@ export function validatePublicIdeSurfaces({
287
287
  const cliCommands = (commandManifest.commands || []).map(
288
288
  (entry) => entry.name,
289
289
  );
290
+ const cliAutomationCommands = new Set(cliCommands);
291
+ for (const [name, route] of Object.entries(cli.directCommands || {})) {
292
+ const { entrypoint, source, registrar } = route;
293
+ requireFile(entrypoint);
294
+ requireFile(source);
295
+ if (
296
+ existsSync(join(repoRoot, entrypoint)) &&
297
+ existsSync(join(repoRoot, source)) &&
298
+ read(repoRoot, entrypoint).includes(`${registrar}(program)`) &&
299
+ read(repoRoot, source).includes(`.command(${JSON.stringify(name)})`)
300
+ ) {
301
+ cliAutomationCommands.add(name);
302
+ } else {
303
+ fail(`Direct CLI command registration is missing: ${name}`);
304
+ }
305
+ }
290
306
  for (const command of cli.requiredCommands) {
291
307
  if (!cliCommands.includes(command))
292
308
  fail(`CLI command manifest is missing: ${command}`);
293
309
  if (!helpIndex.commands?.[command])
294
310
  fail(`CLI help index is missing: ${command}`);
295
311
  }
312
+ for (const { commands, guides } of Object.values(cli.automation || {})) {
313
+ for (const command of commands) {
314
+ const [name] = command.split(" ");
315
+ if (!cliAutomationCommands.has(name))
316
+ fail(`CLI automation command is missing: ${command}`);
317
+ }
318
+ for (const guide of guides) requireFile(guide);
319
+ }
296
320
  if (!String(helpIndex.commands?.ide || "").includes("doctor")) {
297
321
  fail("CLI `ide` help no longer advertises the `ide doctor` subcommand");
298
322
  }
@@ -17,6 +17,17 @@
17
17
  /** Keep the most recent N denials per session (bounded ring buffer). */
18
18
  export const MAX_RECENT_DENIALS = 20;
19
19
 
20
+ export const DESTRUCTIVE_SHELL_DENIAL_CODE = "CC_DESTRUCTIVE_SHELL_DENIED";
21
+
22
+ export function isDestructiveShellDenial(event) {
23
+ const policy = event.result?.shellCommandPolicy;
24
+ return (
25
+ event.tool === "run_shell" &&
26
+ policy?.allowed === false &&
27
+ policy.ruleId === "dangerous-delete"
28
+ );
29
+ }
30
+
20
31
  /** Error-message prefixes agent-core attaches to a blocked tool call. */
21
32
  const DENIAL_PREFIX = /^\s*\[(Shell Policy|Permission|ApprovalGate|Hook)\]/;
22
33
 
@@ -29,12 +29,14 @@ export function shquotePosix(s) {
29
29
  * @param {object} a
30
30
  * @param {string} a.pattern the raw search pattern
31
31
  * @param {boolean} a.isContent content search (grep/findstr) vs filename
32
+ * @param {boolean} [a.regex] request regex mode explicitly on Windows
32
33
  * @param {string} [a.platform=process.platform]
33
34
  * @returns {{cmd:string}|{error:string}}
34
35
  */
35
36
  export function buildSearchCommand({
36
37
  pattern,
37
38
  isContent,
39
+ regex,
38
40
  platform = process.platform,
39
41
  }) {
40
42
  if (typeof pattern !== "string" || pattern.length === 0) {
@@ -42,6 +44,13 @@ export function buildSearchCommand({
42
44
  }
43
45
  const pat = pattern;
44
46
 
47
+ if (isContent && /[\r\n]/.test(pat)) {
48
+ return {
49
+ error:
50
+ "Directory content search requires a single-line pattern. Use path for multiline search in a file.",
51
+ };
52
+ }
53
+
45
54
  if (platform === "win32") {
46
55
  // cmd.exe has no reliable way to escape an embedded double-quote, and the
47
56
  // pattern is double-quoted below — so reject a literal `"` (rare in a search
@@ -55,14 +64,16 @@ export function buildSearchCommand({
55
64
  }
56
65
  return {
57
66
  cmd: isContent
58
- ? `findstr /s /i /n "${pat}" *`
67
+ ? `findstr /s /i /n${regex === true ? " /r" : ""} "${pat}" *`
59
68
  : `dir /s /b "*${pat}*" 2>NUL`,
60
69
  };
61
70
  }
62
71
 
72
+ // Preserve grep's exit status so a syntax or read error reaches the caller.
73
+ // The caller already bounds captured stdout and the returned matches.
63
74
  return {
64
75
  cmd: isContent
65
- ? `grep -r -l -i ${shquotePosix(pat)} . --include="*" 2>/dev/null | head -20`
76
+ ? `grep -r -l -i -e ${shquotePosix(pat)} . --include="*" 2>/dev/null`
66
77
  : `find . -name ${shquotePosix(`*${pat}*`)} -type f 2>/dev/null | head -20`,
67
78
  };
68
79
  }
@@ -24,7 +24,11 @@ function approvalFor(manager, lock) {
24
24
  };
25
25
  }
26
26
 
27
- export function openSessionPlan(sessionId, requestedMode) {
27
+ export function openSessionPlan(
28
+ sessionId,
29
+ requestedMode,
30
+ { permissionModeIsFallback = false } = {},
31
+ ) {
28
32
  const manager = new PlanModeManager({ sessionId });
29
33
  const lock = manager.getExecutionLock();
30
34
  if (!lock && !sessionExists(sessionId))
@@ -52,11 +56,16 @@ export function openSessionPlan(sessionId, requestedMode) {
52
56
  verified?.permissionProfileDigest !== approval.permissionProfileDigest
53
57
  )
54
58
  throw new Error("The saved plan has no matching session approval receipt");
55
- if (requestedMode !== undefined && requestedMode !== lock.permissionMode)
59
+ if (
60
+ !permissionModeIsFallback &&
61
+ requestedMode !== undefined &&
62
+ requestedMode !== lock.permissionMode
63
+ )
56
64
  throw new Error(
57
65
  "Requested permission mode conflicts with the approved plan",
58
66
  );
59
67
  if (
68
+ manager.lastEvent?.type === "plan-execution-started" ||
60
69
  manager.currentPlan.items.some(
61
70
  (item) => item.status === PlanStatus.EXECUTING,
62
71
  )
@@ -95,14 +95,15 @@ function buildContext({
95
95
  } = {}) {
96
96
  const used = Math.max(0, Number(usedTokens) || 0);
97
97
  const window = Math.max(0, Number(contextWindow) || 0);
98
- const pct = window > 0 ? Math.min(100, Math.round((used / window) * 100)) : 0;
98
+ const usageRatio = window > 0 ? used / window : 0;
99
+ const pct = Math.min(100, Math.round(usageRatio * 100));
99
100
  const threshold = Math.max(
100
101
  0,
101
102
  Math.min(100, Number(contextUsageThreshold) || 0),
102
103
  );
103
104
  const context = { used_tokens: used, window, pct };
104
105
  if (contextUsageThreshold !== undefined) {
105
- context.visible = window > 0 && pct >= threshold;
106
+ context.visible = window > 0 && usageRatio >= threshold / 100;
106
107
  context.threshold = threshold;
107
108
  }
108
109
  const result = {
@@ -127,6 +127,13 @@ export function toTaskRecord(value, source = "unknown", options = {}) {
127
127
  createdAt,
128
128
  );
129
129
  const endsAt = timestamp(input.endsAt ?? input.expiresAt ?? input.expiryAt);
130
+ const nextRunAt = timestamp(input.nextRunAt ?? input.nextAt ?? input.dueAt);
131
+ const scheduleHasClosed =
132
+ normalizedSource === "schedule" &&
133
+ (TERMINAL.has(state) ||
134
+ (endsAt != null &&
135
+ nextRunAt != null &&
136
+ Date.parse(nextRunAt) >= Date.parse(endsAt)));
130
137
  const taskId = stableId(
131
138
  input,
132
139
  options.fallbackId || `${normalizedSource}-unknown`,
@@ -168,12 +175,15 @@ export function toTaskRecord(value, source = "unknown", options = {}) {
168
175
  null,
169
176
  ),
170
177
  createdAt,
171
- nextRunAt: timestamp(input.nextRunAt ?? input.nextAt ?? input.dueAt),
178
+ nextRunAt: scheduleHasClosed ? null : nextRunAt,
172
179
  expiresAction:
173
180
  input.expiresAction ??
174
181
  input.onExpire ??
175
182
  (normalizedSource === "schedule" && endsAt ? "retire" : null),
176
183
  ...(input.orphanRisk === true ? { orphanRisk: true } : {}),
184
+ ...(Array.isArray(input.stopEvents) && input.stopEvents.length > 0
185
+ ? { stopEvents: input.stopEvents }
186
+ : {}),
177
187
  terminal: TERMINAL.has(state),
178
188
  rawSource: normalizedSource === "unknown" ? input : undefined,
179
189
  };
@@ -276,6 +286,7 @@ export function collectTaskRecords(options = {}) {
276
286
  status: "expired",
277
287
  waitingOn: null,
278
288
  stopPath: null,
289
+ nextRunAt: null,
279
290
  terminal: true,
280
291
  });
281
292
  }