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
@@ -5,7 +5,7 @@ import executionBroker from "../lib/process-execution-broker/index.js";
5
5
  const SUPPORTED_BOUNDARIES = new Set(["filesystem", "network"]);
6
6
 
7
7
  export const _backgroundTaskCommandDeps = {
8
- execSync: (...args) => executionBroker.execSync(...args),
8
+ exec: (...args) => executionBroker.exec(...args),
9
9
  execFile: (...args) => executionBroker.execFile(...args),
10
10
  issueLinuxWorkspaceSandboxExecutionContract: (...args) =>
11
11
  executionBroker.issueLinuxWorkspaceSandboxExecutionContract(...args),
@@ -116,6 +116,15 @@ function explicitShellInvocation(command) {
116
116
  return { file: "/bin/sh", args: ["-c", command] };
117
117
  }
118
118
 
119
+ function readCommandOutput(start) {
120
+ return new Promise((resolve, reject) => {
121
+ start((error, stdout) => {
122
+ if (error) reject(error);
123
+ else resolve(stdout);
124
+ });
125
+ });
126
+ }
127
+
119
128
  export function executeBackgroundTaskCommand({
120
129
  command,
121
130
  cwd,
@@ -158,15 +167,16 @@ export function executeBackgroundTaskCommand({
158
167
  encoding: "utf-8",
159
168
  timeout: 300000,
160
169
  maxBuffer: 10 * 1024 * 1024,
170
+ stdio: ["ignore", "pipe", "pipe"],
161
171
  origin: `background-task:command:${type || "unknown"}`,
162
172
  policy: "allow",
163
173
  scope: "background-task",
164
174
  };
165
175
  if (boundaries.length === 0) {
166
- return _backgroundTaskCommandDeps.execSync(command, {
167
- ...commonOptions,
168
- shell: true,
169
- });
176
+ // Keep the worker event loop free to send heartbeats while the shell runs.
177
+ return readCommandOutput((callback) =>
178
+ _backgroundTaskCommandDeps.exec(command, commonOptions, callback),
179
+ );
170
180
  }
171
181
 
172
182
  const binding = canonicalBinding(workspaceCwd, commonOptions.cwd, boundaries);
@@ -177,7 +187,6 @@ export function executeBackgroundTaskCommand({
177
187
  const spawnOptions = {
178
188
  ...commonOptions,
179
189
  cwd: binding.workingDirectory,
180
- stdio: ["ignore", "pipe", "pipe"],
181
190
  shell: false,
182
191
  sandboxPolicy,
183
192
  };
@@ -212,23 +221,12 @@ export function executeBackgroundTaskCommand({
212
221
  boundaries,
213
222
  );
214
223
  }
215
- return new Promise((resolve, reject) => {
216
- const options = {
217
- ...spawnOptions,
218
- ...(sandboxExecutionContract ? { sandboxExecutionContract } : {}),
219
- };
220
- try {
221
- _backgroundTaskCommandDeps.execFile(
222
- invocation.file,
223
- invocation.args,
224
- options,
225
- (error, stdout) => {
226
- if (error) reject(error);
227
- else resolve(stdout);
228
- },
229
- );
230
- } catch (error) {
231
- reject(error);
232
- }
233
- });
224
+ return readCommandOutput((callback) =>
225
+ _backgroundTaskCommandDeps.execFile(
226
+ invocation.file,
227
+ invocation.args,
228
+ { ...spawnOptions, sandboxExecutionContract },
229
+ callback,
230
+ ),
231
+ );
234
232
  }
@@ -52,6 +52,11 @@ const SUMMARY_CALL_ID_MAX_CHARS = 128;
52
52
  export const SUMMARY_INPUT_DEFAULT_MAX_CHARS = 24000;
53
53
  export const SUMMARY_INPUT_HARD_MAX_CHARS = 32000;
54
54
  const SUMMARY_INPUT_MIN_CHARS = 1024;
55
+ const localCompactionResults = new WeakSet();
56
+
57
+ export function isLocalCompactionResult(result) {
58
+ return localCompactionResults.has(result);
59
+ }
55
60
 
56
61
  function isCompactionArtifact(message) {
57
62
  const kind = getDurableSystemMessageProvenance(message)?.kind;
@@ -560,7 +565,11 @@ export class PromptCompressor {
560
565
  stats.abVariant = abVariant.variant;
561
566
  }
562
567
 
563
- return { messages: result, stats };
568
+ const outcome = { messages: result, stats };
569
+ if (summaryStats === null || summaryStats.summaryMode === "none") {
570
+ localCompactionResults.add(outcome);
571
+ }
572
+ return outcome;
564
573
  }
565
574
 
566
575
  shouldAutoCompact(messages) {
@@ -135,6 +135,22 @@ describe("openAIStream", () => {
135
135
  expect(await collect(openAIStream(args))).toEqual(["x"]);
136
136
  });
137
137
 
138
+ it("treats an explicit provider error as terminal without requiring a completion marker", async () => {
139
+ vi.stubGlobal(
140
+ "fetch",
141
+ mockFetch([
142
+ 'data: {"choices":[{"delta":{"content":"partial"}}]}\n',
143
+ 'data: {"error":{"message":"upstream connection reset"}}\n',
144
+ 'data: {"choices":[{"delta":{"content":"late"}}]}\n',
145
+ ]),
146
+ );
147
+ const stream = openAIStream(args);
148
+ expect(await stream.next()).toEqual({ done: false, value: "partial" });
149
+ await expect(stream.next()).rejects.toMatchObject({
150
+ code: "CC_CHAT_COMPLETIONS_STREAM_FAILED",
151
+ });
152
+ });
153
+
138
154
  it("throws on a non-ok response", async () => {
139
155
  vi.stubGlobal(
140
156
  "fetch",
@@ -2749,6 +2749,7 @@ export function resumeBackgroundAgent(id, prompt, options = {}) {
2749
2749
  : state.governance,
2750
2750
  launchProfile,
2751
2751
  apiKey: options.apiKey,
2752
+ restorePlanPermission: !options.launchProfileOverride,
2752
2753
  });
2753
2754
  }
2754
2755
 
@@ -2897,6 +2898,7 @@ export function launchBackgroundAgent({
2897
2898
  governance,
2898
2899
  launchProfile,
2899
2900
  apiKey,
2901
+ restorePlanPermission = false,
2900
2902
  }) {
2901
2903
  assertBackgroundArgvDurable(argv);
2902
2904
  assertBackgroundArgvDurable(followUpArgv, "background follow-up");
@@ -2981,6 +2983,7 @@ export function launchBackgroundAgent({
2981
2983
  },
2982
2984
  ...(worktreeState || {}),
2983
2985
  governance: governanceState,
2986
+ restorePlanPermission,
2984
2987
  // Present = interactive attach can start follow-up turns; absent = the
2985
2988
  // transport rejects prompts (log-only session).
2986
2989
  ...(Array.isArray(followUpArgv)
@@ -24,6 +24,9 @@ import {
24
24
  } from "./provider-protocol.js";
25
25
  import { appendTokenUsage } from "../harness/jsonl-session-store.js";
26
26
  import {
27
+ CHAT_COMPLETIONS_STREAM_FAILED,
28
+ cancelProviderStreamReader,
29
+ createChatCompletionsStreamError,
27
30
  isRetryableStreamError,
28
31
  STREAM_RETRY_BASE_MS,
29
32
  resolveStreamRetryMax,
@@ -332,8 +335,7 @@ export async function streamOpenAI(
332
335
  }
333
336
  try {
334
337
  const json = JSON.parse(data);
335
- if (options.requireCompletion && json.error)
336
- throw new Error("OpenAI stream returned an error");
338
+ if (json?.error) throw createChatCompletionsStreamError();
337
339
  const content = json.choices?.[0]?.delta?.content;
338
340
  if (content) {
339
341
  fullResponse += content;
@@ -353,6 +355,7 @@ export async function streamOpenAI(
353
355
  } catch (error) {
354
356
  if (
355
357
  options.requireCompletion ||
358
+ error?.code === CHAT_COMPLETIONS_STREAM_FAILED ||
356
359
  error?.isOutputBackpressureFailure === true
357
360
  )
358
361
  throw error;
@@ -362,8 +365,12 @@ export async function streamOpenAI(
362
365
  }
363
366
  }
364
367
  } catch (e) {
368
+ if (e?.code === CHAT_COMPLETIONS_STREAM_FAILED)
369
+ cancelProviderStreamReader(reader);
365
370
  throw attachStreamRetryMetadata(
366
- guard.stalled() && !isFormalBudgetError(e)
371
+ guard.stalled() &&
372
+ !isFormalBudgetError(e) &&
373
+ e?.code !== CHAT_COMPLETIONS_STREAM_FAILED
367
374
  ? new Error(
368
375
  `API stream stalled (no data in ${STREAM_STALL_MS / 1000}s)`,
369
376
  )
@@ -4,6 +4,7 @@ export const CODING_TASK_QUALITY_GUIDANCE = `Coding task quality:
4
4
  - Keep progress explanations to one or two sentences. Resolve uncertainty with targeted reads, reuse unchanged source already inspected, and put code directly in write/edit arguments.
5
5
  - Omitted or undelivered source has not been inspected. For an incomplete source excerpt, select a complete enclosing statement or container; a larger range or whole file within the tool limits may be necessary. Do not keep halving the same omitted page. For oversized output, select bounded fields or sections. If safe source remains unavailable, report that limitation without claiming completion.
6
6
  - Resolve each relative import from the destination file's directory. Read back completed files and fix newDiagnostics. A successful write proves persistence, not test execution or acceptance.
7
+ - Report a file as created, changed, moved, or removed only after a tool confirms the action and you verify the resulting workspace state. Report any missing requested change as incomplete.
7
8
  - Map every acceptance requirement to a fixture, real production call path and observable assertion. Positive and negative controls must reach the same boundary with unrelated prerequisites valid. Avoid mocks that bypass it; identify which assertion would fail without that boundary.
8
9
  - Derive case allocation from the user's requirements. A test-count cap does not waive coverage: merge redundant cases to cover gaps within the cap, authorized scope and remaining budget. Report unresolved gaps as incomplete.
9
10
  - Keep test fixtures and assertions within the runner's memory and time limits. For large binary payloads, assert lengths and use Buffer.equals or a digest for content checks; avoid deep matchers that enumerate every byte or print the entire payload on failure. Check boundary rejection before allocating a large body when the contract permits it.
@@ -9,8 +9,14 @@ import {
9
9
  canonicalDigest,
10
10
  InMemorySessionContextPort,
11
11
  getCompactionPlanRejection,
12
+ planContext,
12
13
  } from "@chainlesschain/context-memory-kernel";
13
14
  import { sessionExists } from "../../harness/jsonl-session-store.js";
15
+ import { isLocalCompactionResult } from "../../harness/prompt-compressor.js";
16
+ import {
17
+ buildExtractiveHandoff,
18
+ formatStructuredHandoff,
19
+ } from "../../harness/structured-handoff.js";
14
20
  import {
15
21
  contextItemsToMessages,
16
22
  createSummaryContextItem,
@@ -19,6 +25,7 @@ import {
19
25
  import { JsonlSessionContextPort } from "./jsonl-session-context-port.js";
20
26
  import { createCliContextMemoryRuntime } from "./runtime.js";
21
27
  import { imageTransportEstimate } from "../image-token-estimate.js";
28
+ import { fileReadProgressBody } from "../read-file-page.js";
22
29
  import { projectRuntimeTokenUsage } from "../runtime-usage-ledger.js";
23
30
  import { isCompactionHostBase } from "../compaction-host-provenance.js";
24
31
  import {
@@ -186,6 +193,11 @@ function kernelBudget(compressor, ephemeralTokens = 0, messages = []) {
186
193
  // Live host policy/retry text still consumes the provider window even
187
194
  // though it is deliberately absent from the durable authority partition.
188
195
  safetyMarginTokens: ephemeralTokens,
196
+ // Like provider planning, let conversation use the available input budget.
197
+ // The kernel still applies the global limit and reserves recovery capacity.
198
+ partitionCeilings: {
199
+ conversation: Math.max(0, inputBudget - ephemeralTokens),
200
+ },
189
201
  recoveryReserveTokens: Math.min(
190
202
  256,
191
203
  Math.max(1, Math.floor(inputBudget * 0.05)),
@@ -193,6 +205,44 @@ function kernelBudget(compressor, ephemeralTokens = 0, messages = []) {
193
205
  };
194
206
  }
195
207
 
208
+ function boundLocalHandoff(
209
+ item,
210
+ { items, planRequest, summaryOptions, droppedMessages, compressedMessages },
211
+ ) {
212
+ const droppedIds = new Set(
213
+ summaryOptions.parents.map(({ itemId }) => itemId),
214
+ );
215
+ const retained = items.filter(({ itemId }) => !droppedIds.has(itemId));
216
+ if (retained.length + droppedIds.size !== items.length) return item;
217
+
218
+ // Run the same planner as settlement so an already admissible handoff
219
+ // keeps its full contents. This preview has no write or provider effects.
220
+ const plan = planContext({ ...planRequest, items: [...retained, item] });
221
+ const omission = plan.dropped.find(({ itemId }) => itemId === item.itemId);
222
+ if (
223
+ !omission ||
224
+ !["input_budget", "partition_ceiling"].includes(omission.reason)
225
+ ) {
226
+ return item;
227
+ }
228
+
229
+ const handoff = formatStructuredHandoff(
230
+ buildExtractiveHandoff(droppedMessages, {
231
+ maxContentChars: Math.min(4000, plan.selectableBudget * 2),
232
+ }),
233
+ );
234
+ const bounded = createSummaryContextItem({
235
+ ...summaryOptions,
236
+ messages: [
237
+ { role: "assistant", content: `[Conversation Summary]\n${handoff}` },
238
+ ...compressedMessages.filter(
239
+ (message) => fileReadProgressBody(message) !== null,
240
+ ),
241
+ ],
242
+ });
243
+ return bounded.tokenEstimate < item.tokenEstimate ? bounded : item;
244
+ }
245
+
196
246
  function usageReceipt(stats, provider, model) {
197
247
  if (stats?.summaryUsageUnknown === true) {
198
248
  const error = new Error(
@@ -431,6 +481,22 @@ export async function compactLiveMessagesCanonical(
431
481
  const provider = options.provider || "provider.local";
432
482
  const model = options.model || "default";
433
483
  const memoryRevision = await runtime.memoryPort.getRevision();
484
+ const compactionPolicy = {
485
+ ...kernelBudget(
486
+ compressor,
487
+ messagesToContextItems(
488
+ ephemeralMessages.map(({ message }) => message),
489
+ { sessionId, allowExternalization: false },
490
+ ).reduce((total, item) => total + item.tokenEstimate, 0),
491
+ messages,
492
+ ),
493
+ sink: provider,
494
+ scopeAdmissions: [{ scope: "session", scopeId: sessionId }],
495
+ policyVersion: "cli-context-policy-v1",
496
+ modelProfile: model,
497
+ memoryRevision,
498
+ now: operationNow,
499
+ };
434
500
  let settledOutputItems = null;
435
501
  {
436
502
  const appendCompaction = runtime.sessionPort.appendCompaction.bind(
@@ -495,21 +561,8 @@ export async function compactLiveMessagesCanonical(
495
561
  receipt = await runtime.kernel.compactContext({
496
562
  operationId,
497
563
  sessionId,
498
- ...kernelBudget(
499
- compressor,
500
- messagesToContextItems(
501
- ephemeralMessages.map(({ message }) => message),
502
- { sessionId, allowExternalization: false },
503
- ).reduce((total, item) => total + item.tokenEstimate, 0),
504
- messages,
505
- ),
506
- sink: provider,
507
- scopeAdmissions: [{ scope: "session", scopeId: sessionId }],
508
- policyVersion: "cli-context-policy-v1",
509
- modelProfile: model,
510
- memoryRevision,
564
+ ...compactionPolicy,
511
565
  allowFallback: false,
512
- now: operationNow,
513
566
  metadata: {
514
567
  inputMessageCount: messages.length,
515
568
  originalTokens: estimatedTokens(messages),
@@ -530,15 +583,43 @@ export async function compactLiveMessagesCanonical(
530
583
  const reduced =
531
584
  Number(summaryStats.saved || 0) > 0 ||
532
585
  result.messages.length < droppedMessages.length;
533
- const item = reduced
586
+ const summaryOptions = {
587
+ parents: droppedItems,
588
+ operationId: context.operationId,
589
+ now: operationNow,
590
+ allowExternalization: persistentSession,
591
+ };
592
+ let item = reduced
534
593
  ? createSummaryContextItem({
594
+ ...summaryOptions,
535
595
  messages: result.messages,
536
- parents: droppedItems,
537
- operationId: context.operationId,
538
- now: operationNow,
539
- allowExternalization: persistentSession,
540
596
  })
541
597
  : null;
598
+ if (
599
+ item &&
600
+ summaryReceipt.outcome === "not_metered" &&
601
+ isLocalCompactionResult(result)
602
+ ) {
603
+ const bounded = boundLocalHandoff(item, {
604
+ items: initialItems,
605
+ planRequest: {
606
+ ...compactionPolicy,
607
+ sessionHead: context.inputHead,
608
+ },
609
+ summaryOptions,
610
+ droppedMessages,
611
+ compressedMessages: result.messages,
612
+ });
613
+ if (bounded !== item) {
614
+ item = bounded;
615
+ summaryStats = {
616
+ ...summaryStats,
617
+ summaryMode: "extractive-fallback",
618
+ degraded: true,
619
+ degradedReason: "local_handoff_over_budget",
620
+ };
621
+ }
622
+ }
542
623
  return {
543
624
  items: item ? [item] : [],
544
625
  usageReceipt: summaryReceipt,
@@ -1752,10 +1752,58 @@ function _ccronCheckT(from, to) {
1752
1752
  if (!a || !a.has(to))
1753
1753
  throw new Error(`invalid ccron tick transition ${from} → ${to}`);
1754
1754
  }
1755
- function _ccronCountActive(owner) {
1755
+ function expireCcronProfile(profile, now) {
1756
+ if (
1757
+ profile?.endsAt != null &&
1758
+ Date.parse(profile.endsAt) <= now &&
1759
+ !_ccronPTerminal.has(profile.status)
1760
+ ) {
1761
+ profile.status = CCRON_PROFILE_MATURITY_V2.ARCHIVED;
1762
+ profile.updatedAt = now;
1763
+ profile.archivedAt = now;
1764
+ profile.expiredAt = profile.endsAt;
1765
+ for (const tick of _ccronTsV2.values()) {
1766
+ if (
1767
+ tick.profileId === profile.id &&
1768
+ tick.status === CCRON_TICK_LIFECYCLE_V2.QUEUED
1769
+ ) {
1770
+ cancelCcronTickV2(tick.id, "profile-expired", now);
1771
+ }
1772
+ }
1773
+ }
1774
+ return profile;
1775
+ }
1776
+
1777
+ function snapshotCcronProfile(profile, now) {
1778
+ let nextRunAt = null;
1779
+ if (profile.status === CCRON_PROFILE_MATURITY_V2.ACTIVE) {
1780
+ try {
1781
+ const next = nextCoworkCronTime(profile.expr, now);
1782
+ if (
1783
+ next != null &&
1784
+ (profile.endsAt == null || next < Date.parse(profile.endsAt))
1785
+ ) {
1786
+ nextRunAt = new Date(next).toISOString();
1787
+ }
1788
+ } catch {
1789
+ // Legacy profiles can contain an expression that cannot predict a run.
1790
+ }
1791
+ }
1792
+ return {
1793
+ ...profile,
1794
+ state: profile.expiredAt ? "expired" : profile.status,
1795
+ expiresAction: profile.endsAt ? "retire" : null,
1796
+ nextRunAt,
1797
+ metadata: { ...profile.metadata },
1798
+ };
1799
+ }
1800
+
1801
+ function _ccronCountActive(owner, now) {
1756
1802
  let c = 0;
1757
- for (const p of _ccronPsV2.values())
1803
+ for (const profile of _ccronPsV2.values()) {
1804
+ const p = expireCcronProfile(profile, now);
1758
1805
  if (p.owner === owner && p.status === CCRON_PROFILE_MATURITY_V2.ACTIVE) c++;
1806
+ }
1759
1807
  return c;
1760
1808
  }
1761
1809
  function _ccronCountPending(profileId) {
@@ -1801,10 +1849,20 @@ export function _resetStateCoworkCronV2() {
1801
1849
  _ccronIdleMs = 30 * 24 * 60 * 60 * 1000;
1802
1850
  _ccronStuckMs = 60 * 1000;
1803
1851
  }
1804
- export function registerCcronProfileV2({ id, owner, expr, metadata } = {}) {
1852
+ export function registerCcronProfileV2({
1853
+ id,
1854
+ owner,
1855
+ expr,
1856
+ endsAt,
1857
+ metadata,
1858
+ } = {}) {
1805
1859
  if (!id || !owner) throw new Error("id and owner required");
1806
1860
  if (_ccronPsV2.has(id)) throw new Error(`ccron profile ${id} already exists`);
1807
1861
  const now = Date.now();
1862
+ const deadline = endsAt == null ? null : Date.parse(endsAt);
1863
+ if (deadline != null && !Number.isFinite(deadline)) {
1864
+ throw new Error("endsAt must be a valid timestamp");
1865
+ }
1808
1866
  const p = {
1809
1867
  id,
1810
1868
  owner,
@@ -1815,72 +1873,87 @@ export function registerCcronProfileV2({ id, owner, expr, metadata } = {}) {
1815
1873
  lastTouchedAt: now,
1816
1874
  activatedAt: null,
1817
1875
  archivedAt: null,
1876
+ endsAt: deadline == null ? null : new Date(deadline).toISOString(),
1818
1877
  metadata: { ...(metadata || {}) },
1819
1878
  };
1820
1879
  _ccronPsV2.set(id, p);
1821
- return { ...p, metadata: { ...p.metadata } };
1880
+ return snapshotCcronProfile(expireCcronProfile(p, now), now);
1822
1881
  }
1823
1882
  export function activateCcronProfileV2(id) {
1824
- const p = _ccronPsV2.get(id);
1883
+ const now = Date.now();
1884
+ const p = expireCcronProfile(_ccronPsV2.get(id), now);
1825
1885
  if (!p) throw new Error(`ccron profile ${id} not found`);
1826
1886
  const isInitial = p.status === CCRON_PROFILE_MATURITY_V2.PENDING;
1827
1887
  _ccronCheckP(p.status, CCRON_PROFILE_MATURITY_V2.ACTIVE);
1828
- if (isInitial && _ccronCountActive(p.owner) >= _ccronMaxActive)
1888
+ if (isInitial && _ccronCountActive(p.owner, now) >= _ccronMaxActive)
1829
1889
  throw new Error(`max active ccron profiles for owner ${p.owner} reached`);
1830
- const now = Date.now();
1831
1890
  p.status = CCRON_PROFILE_MATURITY_V2.ACTIVE;
1832
1891
  p.updatedAt = now;
1833
1892
  p.lastTouchedAt = now;
1834
1893
  if (!p.activatedAt) p.activatedAt = now;
1835
- return { ...p, metadata: { ...p.metadata } };
1894
+ return snapshotCcronProfile(p, now);
1836
1895
  }
1837
1896
  export function pauseCcronProfileV2(id) {
1838
- const p = _ccronPsV2.get(id);
1897
+ const now = Date.now();
1898
+ const p = expireCcronProfile(_ccronPsV2.get(id), now);
1839
1899
  if (!p) throw new Error(`ccron profile ${id} not found`);
1840
1900
  _ccronCheckP(p.status, CCRON_PROFILE_MATURITY_V2.PAUSED);
1841
1901
  p.status = CCRON_PROFILE_MATURITY_V2.PAUSED;
1842
- p.updatedAt = Date.now();
1843
- return { ...p, metadata: { ...p.metadata } };
1902
+ p.updatedAt = now;
1903
+ return snapshotCcronProfile(p, now);
1844
1904
  }
1845
1905
  export function archiveCcronProfileV2(id) {
1846
- const p = _ccronPsV2.get(id);
1906
+ const now = Date.now();
1907
+ const p = expireCcronProfile(_ccronPsV2.get(id), now);
1847
1908
  if (!p) throw new Error(`ccron profile ${id} not found`);
1848
1909
  _ccronCheckP(p.status, CCRON_PROFILE_MATURITY_V2.ARCHIVED);
1849
- const now = Date.now();
1850
1910
  p.status = CCRON_PROFILE_MATURITY_V2.ARCHIVED;
1851
1911
  p.updatedAt = now;
1852
1912
  if (!p.archivedAt) p.archivedAt = now;
1853
- return { ...p, metadata: { ...p.metadata } };
1913
+ return snapshotCcronProfile(p, now);
1854
1914
  }
1855
1915
  export function touchCcronProfileV2(id) {
1856
- const p = _ccronPsV2.get(id);
1916
+ const now = Date.now();
1917
+ const p = expireCcronProfile(_ccronPsV2.get(id), now);
1857
1918
  if (!p) throw new Error(`ccron profile ${id} not found`);
1858
1919
  if (_ccronPTerminal.has(p.status))
1859
1920
  throw new Error(`cannot touch terminal ccron profile ${id}`);
1860
- const now = Date.now();
1861
1921
  p.lastTouchedAt = now;
1862
1922
  p.updatedAt = now;
1863
- return { ...p, metadata: { ...p.metadata } };
1923
+ return snapshotCcronProfile(p, now);
1864
1924
  }
1865
1925
  export function getCcronProfileV2(id) {
1866
- const p = _ccronPsV2.get(id);
1867
- if (!p) return null;
1868
- return { ...p, metadata: { ...p.metadata } };
1926
+ const now = Date.now();
1927
+ const p = expireCcronProfile(_ccronPsV2.get(id), now);
1928
+ return p ? snapshotCcronProfile(p, now) : null;
1869
1929
  }
1870
1930
  export function listCcronProfilesV2() {
1871
- return [..._ccronPsV2.values()].map((p) => ({
1872
- ...p,
1873
- metadata: { ...p.metadata },
1874
- }));
1931
+ const now = Date.now();
1932
+ return [..._ccronPsV2.values()].map((p) =>
1933
+ snapshotCcronProfile(expireCcronProfile(p, now), now),
1934
+ );
1875
1935
  }
1876
1936
  export function createCcronTickV2({ id, profileId, tickAt, metadata } = {}) {
1877
1937
  if (!id || !profileId) throw new Error("id and profileId required");
1878
1938
  if (_ccronTsV2.has(id)) throw new Error(`ccron tick ${id} already exists`);
1879
- if (!_ccronPsV2.has(profileId))
1880
- throw new Error(`ccron profile ${profileId} not found`);
1939
+ const now = Date.now();
1940
+ const profile = expireCcronProfile(_ccronPsV2.get(profileId), now);
1941
+ if (!profile) throw new Error(`ccron profile ${profileId} not found`);
1942
+ if (profile.endsAt != null) {
1943
+ const suppliedTime = tickAt || now;
1944
+ const scheduledAt =
1945
+ typeof suppliedTime === "string" && !/^\d+$/u.test(suppliedTime)
1946
+ ? Date.parse(suppliedTime)
1947
+ : Number(suppliedTime);
1948
+ if (
1949
+ !Number.isFinite(scheduledAt) ||
1950
+ Math.max(now, scheduledAt) >= Date.parse(profile.endsAt)
1951
+ ) {
1952
+ throw new Error(`ccron tick must be scheduled before ${profile.endsAt}`);
1953
+ }
1954
+ }
1881
1955
  if (_ccronCountPending(profileId) >= _ccronMaxPending)
1882
1956
  throw new Error(`max pending ccron ticks for profile ${profileId} reached`);
1883
- const now = Date.now();
1884
1957
  const t = {
1885
1958
  id,
1886
1959
  profileId,
@@ -1900,6 +1973,10 @@ export function runningCcronTickV2(id) {
1900
1973
  if (!t) throw new Error(`ccron tick ${id} not found`);
1901
1974
  _ccronCheckT(t.status, CCRON_TICK_LIFECYCLE_V2.RUNNING);
1902
1975
  const now = Date.now();
1976
+ const profile = expireCcronProfile(_ccronPsV2.get(t.profileId), now);
1977
+ if (Date.parse(profile?.endsAt) <= now) {
1978
+ throw new Error(`ccron profile ${t.profileId} has expired`);
1979
+ }
1903
1980
  t.status = CCRON_TICK_LIFECYCLE_V2.RUNNING;
1904
1981
  t.updatedAt = now;
1905
1982
  if (!t.startedAt) t.startedAt = now;
@@ -1926,11 +2003,10 @@ export function failCcronTickV2(id, reason) {
1926
2003
  if (reason) t.metadata.failReason = String(reason);
1927
2004
  return { ...t, metadata: { ...t.metadata } };
1928
2005
  }
1929
- export function cancelCcronTickV2(id, reason) {
2006
+ export function cancelCcronTickV2(id, reason, now = Date.now()) {
1930
2007
  const t = _ccronTsV2.get(id);
1931
2008
  if (!t) throw new Error(`ccron tick ${id} not found`);
1932
2009
  _ccronCheckT(t.status, CCRON_TICK_LIFECYCLE_V2.CANCELLED);
1933
- const now = Date.now();
1934
2010
  t.status = CCRON_TICK_LIFECYCLE_V2.CANCELLED;
1935
2011
  t.updatedAt = now;
1936
2012
  if (!t.settledAt) t.settledAt = now;
@@ -1940,9 +2016,12 @@ export function cancelCcronTickV2(id, reason) {
1940
2016
  export function getCcronTickV2(id) {
1941
2017
  const t = _ccronTsV2.get(id);
1942
2018
  if (!t) return null;
2019
+ expireCcronProfile(_ccronPsV2.get(t.profileId), Date.now());
1943
2020
  return { ...t, metadata: { ...t.metadata } };
1944
2021
  }
1945
2022
  export function listCcronTicksV2() {
2023
+ const now = Date.now();
2024
+ for (const profile of _ccronPsV2.values()) expireCcronProfile(profile, now);
1946
2025
  return [..._ccronTsV2.values()].map((t) => ({
1947
2026
  ...t,
1948
2027
  metadata: { ...t.metadata },
@@ -1951,7 +2030,8 @@ export function listCcronTicksV2() {
1951
2030
  export function autoPauseIdleCcronProfilesV2({ now } = {}) {
1952
2031
  const t = now ?? Date.now();
1953
2032
  const flipped = [];
1954
- for (const p of _ccronPsV2.values())
2033
+ for (const profile of _ccronPsV2.values()) {
2034
+ const p = expireCcronProfile(profile, t);
1955
2035
  if (
1956
2036
  p.status === CCRON_PROFILE_MATURITY_V2.ACTIVE &&
1957
2037
  t - p.lastTouchedAt >= _ccronIdleMs
@@ -1960,6 +2040,7 @@ export function autoPauseIdleCcronProfilesV2({ now } = {}) {
1960
2040
  p.updatedAt = t;
1961
2041
  flipped.push(p.id);
1962
2042
  }
2043
+ }
1963
2044
  return { flipped, count: flipped.length };
1964
2045
  }
1965
2046
  export function autoFailStuckCcronTicksV2({ now } = {}) {
@@ -1980,10 +2061,13 @@ export function autoFailStuckCcronTicksV2({ now } = {}) {
1980
2061
  return { flipped, count: flipped.length };
1981
2062
  }
1982
2063
  export function getCoworkCronGovStatsV2() {
2064
+ const now = Date.now();
1983
2065
  const profilesByStatus = {};
1984
2066
  for (const v of Object.values(CCRON_PROFILE_MATURITY_V2))
1985
2067
  profilesByStatus[v] = 0;
1986
- for (const p of _ccronPsV2.values()) profilesByStatus[p.status]++;
2068
+ for (const p of _ccronPsV2.values()) {
2069
+ profilesByStatus[expireCcronProfile(p, now).status]++;
2070
+ }
1987
2071
  const ticksByStatus = {};
1988
2072
  for (const v of Object.values(CCRON_TICK_LIFECYCLE_V2)) ticksByStatus[v] = 0;
1989
2073
  for (const t of _ccronTsV2.values()) ticksByStatus[t.status]++;
@@ -23,10 +23,33 @@
23
23
  import fs from "node:fs";
24
24
  import os from "node:os";
25
25
  import path from "node:path";
26
+ import { createHash } from "node:crypto";
26
27
  import shellPolicy from "../runtime/coding-agent-shell-policy.cjs";
27
28
 
28
29
  const { splitCommandSegments, tokenizeShellCommand } = shellPolicy;
29
30
 
31
+ /** Normalize installer side effects into a stable machine-readable receipt. */
32
+ export function normalizeInstallCommandResult(value = null) {
33
+ const input = value && typeof value === "object" ? value : {};
34
+ const stderr = typeof input.stderr === "string" ? input.stderr : "";
35
+ const digest =
36
+ typeof input.stderrDigest === "string" && input.stderrDigest
37
+ ? input.stderrDigest
38
+ : createHash("sha256").update(stderr, "utf8").digest("hex");
39
+ const exitCode = Number.isSafeInteger(input.exitCode) ? input.exitCode : null;
40
+ return {
41
+ ran: input.ran === true || exitCode !== null || input.started === true,
42
+ exitCode,
43
+ timedOut: input.timedOut === true,
44
+ signaled: input.signaled === true || input.signal != null,
45
+ printedToStderr:
46
+ input.printedToStderr === true ||
47
+ stderr.length > 0 ||
48
+ input.stderrBytes > 0,
49
+ stderrDigest: digest,
50
+ };
51
+ }
52
+
30
53
  // Leading tokens that wrap the real command and must be stripped before the
31
54
  // binary is read: privilege elevation, env-var assignments, and `env`/`command`.
32
55
  const WRAPPER_TOKENS = new Set([