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
@@ -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
  }
@@ -103,8 +103,11 @@ export class ReadFileLoopGuard {
103
103
  }
104
104
  }
105
105
  for (const entry of this.progress.values()) {
106
+ let delivered = false;
107
+ let undelivered = 0;
106
108
  for (const pending of entry.pendingPages) {
107
109
  if (this.isPageVisible(pending.page)) {
110
+ delivered = true;
108
111
  entry.confirmedSpans = mergeSpan(
109
112
  entry.confirmedSpans,
110
113
  pending.page.readSpan,
@@ -117,11 +120,16 @@ export class ReadFileLoopGuard {
117
120
  };
118
121
  }
119
122
  } else {
120
- entry.undeliveredReads++;
123
+ undelivered++;
121
124
  if (pending.reread) entry.rereads.delete(pending.reread);
122
125
  if (pending.restoring) entry.contextRestoreOffered = false;
123
126
  }
124
127
  }
128
+ // Reset the streak only when a pending read is visible to the provider.
129
+ // An older page in the prompt cannot reset a failed new read.
130
+ entry.undeliveredReads = delivered
131
+ ? 0
132
+ : entry.undeliveredReads + undelivered;
125
133
  entry.pendingPages = [];
126
134
  // Execution reserves ranges synchronously for parallel reads. Only
127
135
  // source actually selected for the provider becomes historical coverage.
@@ -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
  }
@@ -56,6 +56,21 @@ function defaultRunner(file, args, input = undefined) {
56
56
  timeout: 15000,
57
57
  ...(input !== undefined ? { input } : {}),
58
58
  });
59
+ if (result.error || result.signal) {
60
+ const reason = result.error?.code ?? result.signal;
61
+ const code =
62
+ typeof reason === "string" && /^[A-Z][A-Z0-9_]{0,39}$/u.test(reason)
63
+ ? reason
64
+ : "SECRET_STORE_COMMAND_FAILED";
65
+ const message =
66
+ code === "ETIMEDOUT"
67
+ ? "secret store command timed out"
68
+ : "secret store command failed";
69
+ const error = new Error(`${message} (${code})`);
70
+ error.code = code;
71
+ error.exitCode = result.status;
72
+ throw error;
73
+ }
59
74
  if (result.status !== 0) {
60
75
  const error = new Error(
61
76
  String(result.stderr || "secret store command failed").trim(),
@@ -202,11 +217,21 @@ function createDpapiBackend({
202
217
  key = normalizeSecretIdentifier(key, "secret key");
203
218
  const encoded = load()[key];
204
219
  if (!encoded) return null;
205
- const plain = runner(
206
- "powershell.exe",
207
- ["-NoProfile", "-NonInteractive", "-Command", DPAPI_UNPROTECT_SCRIPT],
208
- encoded,
209
- ).trim();
220
+ const unprotect = () =>
221
+ runner(
222
+ "powershell.exe",
223
+ ["-NoProfile", "-NonInteractive", "-Command", DPAPI_UNPROTECT_SCRIPT],
224
+ encoded,
225
+ ).trim();
226
+ let plain;
227
+ try {
228
+ plain = unprotect();
229
+ } catch (error) {
230
+ if (error?.code !== "ETIMEDOUT") throw error;
231
+ // A cold PowerShell start can time out. DPAPI unprotect only reads the
232
+ // encrypted value, so one retry is safe before reporting a failure.
233
+ plain = unprotect();
234
+ }
210
235
  return Buffer.from(plain, "base64").toString("utf8");
211
236
  },
212
237
  delete(key) {
@@ -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 = {
@@ -24,6 +24,26 @@ import { isFormalBudgetError } from "./formal-budget-errors.js";
24
24
  export const STREAM_RETRY_MAX = 2;
25
25
  export const STREAM_RETRY_BASE_MS = 400;
26
26
  export const STREAM_RETRY_MAX_DELAY_MS = 60_000;
27
+ export const CHAT_COMPLETIONS_STREAM_FAILED =
28
+ "CC_CHAT_COMPLETIONS_STREAM_FAILED";
29
+
30
+ export function createChatCompletionsStreamError() {
31
+ return Object.assign(
32
+ new Error("OpenAI-compatible stream returned a provider error"),
33
+ {
34
+ code: CHAT_COMPLETIONS_STREAM_FAILED,
35
+ noReplay: true,
36
+ },
37
+ );
38
+ }
39
+
40
+ export function cancelProviderStreamReader(reader) {
41
+ try {
42
+ void Promise.resolve(reader.cancel?.()).catch(() => {});
43
+ } catch {
44
+ // Preserve the provider error even if the transport cannot be cancelled.
45
+ }
46
+ }
27
47
 
28
48
  function isFailureStatus(status) {
29
49
  return Number.isInteger(status) && status >= 400 && status <= 599;
@@ -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
  }
@@ -12,9 +12,14 @@ export function searchTextFile(file, options = {}) {
12
12
  timeout = 5000,
13
13
  encoding = "utf8",
14
14
  } = options;
15
+ if (typeof pattern !== "string" || !pattern) {
16
+ return Promise.resolve({
17
+ error: "A nonempty pattern is required for text search",
18
+ code: "ERR_TEXT_SEARCH_OPTIONS",
19
+ hint: "Supply the text you want to find as pattern. To inspect a known file without a search term, use read_file with path, offset, and limit.",
20
+ });
21
+ }
15
22
  if (
16
- typeof pattern !== "string" ||
17
- !pattern ||
18
23
  pattern.length > 2048 ||
19
24
  !Number.isSafeInteger(offset) ||
20
25
  offset < 0 ||