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
@@ -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
  }
@@ -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)
@@ -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([
@@ -286,12 +286,7 @@ const SINGLE_SUBSCHEMA_KEYWORDS = [
286
286
  "unevaluatedProperties",
287
287
  ];
288
288
 
289
- const ARRAY_SUBSCHEMA_KEYWORDS = [
290
- "allOf",
291
- "anyOf",
292
- "oneOf",
293
- "prefixItems",
294
- ];
289
+ const ARRAY_SUBSCHEMA_KEYWORDS = ["allOf", "anyOf", "oneOf", "prefixItems"];
295
290
 
296
291
  const MAP_SUBSCHEMA_KEYWORDS = [
297
292
  "$defs",
@@ -322,11 +317,7 @@ function resolveSchemaUri(reference, baseUri) {
322
317
  }
323
318
  }
324
319
 
325
- function scanSchemaDocument(
326
- schema,
327
- retrievalUri,
328
- { references, resources },
329
- ) {
320
+ function scanSchemaDocument(schema, retrievalUri, { references, resources }) {
330
321
  const seen = new Set();
331
322
 
332
323
  function visit(node, inheritedBase) {
@@ -547,8 +538,8 @@ async function fetchExternalSchema(
547
538
  const schema = parseExternalSchema(raw, uri);
548
539
  const bytes =
549
540
  Number.isFinite(response?.bytes) && response.bytes >= 0
550
- ? response.bytes
551
- : Buffer.byteLength(JSON.stringify(schema), "utf8");
541
+ ? response.bytes
542
+ : Buffer.byteLength(JSON.stringify(schema), "utf8");
552
543
  if (bytes > maxDocumentBytes) {
553
544
  throw new Error(
554
545
  `External JSON Schema "${uri}" exceeds ${maxDocumentBytes} bytes`,
@@ -556,9 +547,7 @@ async function fetchExternalSchema(
556
547
  }
557
548
  let retrievalUri = uri;
558
549
  if (responseEnvelope && response?.url) {
559
- retrievalUri = withoutFragment(
560
- resolveSchemaUri(String(response.url), uri),
561
- );
550
+ retrievalUri = withoutFragment(resolveSchemaUri(String(response.url), uri));
562
551
  const redirected = new URL(retrievalUri);
563
552
  const redirectPolicy = checkAllowed(retrievalUri, {
564
553
  allowedDomains,
@@ -584,11 +573,7 @@ async function fetchExternalSchema(
584
573
  * Remote references are HTTPS-only and use the shared DNS-rebinding/SSRF-safe
585
574
  * fetch path with bounded document count, bytes, redirects and timeout.
586
575
  */
587
- export async function loadSchemaFileWithRefs(
588
- fs,
589
- schemaFile,
590
- options = {},
591
- ) {
576
+ export async function loadSchemaFileWithRefs(fs, schemaFile, options = {}) {
592
577
  const schema = loadSchemaFile(fs, schemaFile);
593
578
  if (!schema || typeof schema !== "object") return schema;
594
579
 
@@ -605,16 +590,13 @@ export async function loadSchemaFileWithRefs(
605
590
  const allowedDomains = Array.isArray(options.allowedDomains)
606
591
  ? options.allowedDomains
607
592
  : ["*"];
608
- const maxDocuments =
609
- options.maxDocuments ?? DEFAULT_MAX_EXTERNAL_DOCUMENTS;
593
+ const maxDocuments = options.maxDocuments ?? DEFAULT_MAX_EXTERNAL_DOCUMENTS;
610
594
  const maxDocumentBytes =
611
595
  options.maxDocumentBytes ?? DEFAULT_MAX_EXTERNAL_DOCUMENT_BYTES;
612
596
  const maxTotalBytes =
613
597
  options.maxTotalBytes ?? DEFAULT_MAX_EXTERNAL_TOTAL_BYTES;
614
- const timeoutMs =
615
- options.timeoutMs ?? DEFAULT_EXTERNAL_TIMEOUT_MS;
616
- const fetchSchema =
617
- options.fetchSchema || _deps.webFetch;
598
+ const timeoutMs = options.timeoutMs ?? DEFAULT_EXTERNAL_TIMEOUT_MS;
599
+ const fetchSchema = options.fetchSchema || _deps.webFetch;
618
600
 
619
601
  const references = new Map();
620
602
  const resources = new Set();
@@ -626,8 +608,7 @@ export async function loadSchemaFileWithRefs(
626
608
 
627
609
  while (true) {
628
610
  const uri = [...references.keys()].find(
629
- (candidate) =>
630
- !resources.has(candidate) && !fetched.has(candidate),
611
+ (candidate) => !resources.has(candidate) && !fetched.has(candidate),
631
612
  );
632
613
  if (!uri) break;
633
614
  if (fetched.size >= maxDocuments) {
@@ -655,8 +636,7 @@ export async function loadSchemaFileWithRefs(
655
636
  );
656
637
  }
657
638
  assertExternalSchemaIsValid(loaded.schema, uri);
658
- const redirected =
659
- loaded.retrievalUri && loaded.retrievalUri !== uri;
639
+ const redirected = loaded.retrievalUri && loaded.retrievalUri !== uri;
660
640
  if (redirected) {
661
641
  registry[loaded.retrievalUri] = loaded.schema;
662
642
  registry[uri] = { $ref: loaded.retrievalUri };
@@ -726,6 +706,7 @@ export async function runJsonSchemaConstrained(cfg = {}) {
726
706
  writeErr,
727
707
  },
728
708
  );
709
+ if (outcome?.exitCode) return outcome.exitCode;
729
710
  const raw =
730
711
  String(outcome?.result ?? captured ?? "").trim() || captured.trim();
731
712
  lastRaw = raw;
package/src/lib/loop.js CHANGED
@@ -13,6 +13,7 @@
13
13
 
14
14
  /** Multipliers for the duration suffixes we accept. */
15
15
  const DURATION_UNITS = { ms: 1, s: 1000, m: 60000, h: 3600000 };
16
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
16
17
 
17
18
  /**
18
19
  * Parse a human interval ("30s", "5m", "1.5h", "500ms") into milliseconds.
@@ -169,17 +170,22 @@ export function makeSleep(signal) {
169
170
  clearTimeout(t);
170
171
  resolve();
171
172
  };
172
- t = setTimeout(() => {
173
- // Normal completion: drop the abort listener so it can't accumulate on
174
- // a shared signal across rounds. A long `cc loop` reuses one
175
- // AbortController for the whole run, and `{once:true}` only removes the
176
- // listener if it FIRES — a sleep that completes normally never aborts,
177
- // so without this each round would leak a dangling listener (N rounds →
178
- // N retained closures + a MaxListenersExceededWarning past 10).
179
- signal?.removeEventListener("abort", onAbort);
180
- resolve();
181
- }, ms);
173
+ let remaining = ms;
174
+ const wait = () => {
175
+ const chunk = Math.min(remaining, MAX_TIMER_DELAY_MS);
176
+ t = setTimeout(() => {
177
+ remaining -= chunk;
178
+ if (remaining > 0) {
179
+ wait();
180
+ return;
181
+ }
182
+ // A normally completed round must release its abort listener.
183
+ signal?.removeEventListener("abort", onAbort);
184
+ resolve();
185
+ }, chunk);
186
+ };
182
187
  signal?.addEventListener("abort", onAbort, { once: true });
188
+ wait();
183
189
  });
184
190
  }
185
191
 
@@ -192,11 +198,14 @@ export function makeSleep(signal) {
192
198
  * @param {(n:number)=>Promise<{exitCode?:number, output?:string}>} opts.runIteration
193
199
  * @param {number} opts.intervalMs default delay between iterations (>= 0)
194
200
  * @param {number} [opts.maxIterations] stop after N rounds (>= 1)
201
+ * @param {number|null} [opts.endsAt] epoch-ms deadline for dispatching rounds
195
202
  * @param {boolean} [opts.untilExitZero] stop once a round exits with code 0
196
203
  * @param {RegExp} [opts.untilRegex] stop once a round's output matches
197
204
  * @param {(ms:number)=>Promise<void>} [opts.sleep] injectable delay
198
205
  * @param {()=>boolean} [opts.shouldStop] external stop probe (e.g. SIGINT)
199
206
  * @param {(n:number, res:object)=>void} [opts.onIteration] per-round hook
207
+ * @param {(nextRunAt:number|null)=>void} [opts.onWait] next eligible dispatch
208
+ * @param {()=>number} [opts.now] injectable clock
200
209
  * @param {number} [opts.startIndex] iterations already done (resume)
201
210
  * @returns {Promise<{iterations:number, stoppedBy:string, results:object[]}>}
202
211
  * `iterations` is cumulative (startIndex + rounds run this call);
@@ -206,11 +215,14 @@ export async function runLoop({
206
215
  runIteration,
207
216
  intervalMs,
208
217
  maxIterations,
218
+ endsAt = null,
209
219
  untilExitZero = false,
210
220
  untilRegex = null,
211
221
  sleep,
212
222
  shouldStop,
213
223
  onIteration,
224
+ onWait,
225
+ now = Date.now,
214
226
  startIndex = 0,
215
227
  }) {
216
228
  if (typeof runIteration !== "function") {
@@ -227,6 +239,9 @@ export async function runLoop({
227
239
  if (shouldStop && shouldStop()) {
228
240
  return { iterations: i, stoppedBy: "signal", results };
229
241
  }
242
+ if (endsAt != null && now() >= endsAt) {
243
+ return { iterations: i, stoppedBy: "expired", results };
244
+ }
230
245
 
231
246
  i += 1;
232
247
  const res = (await runIteration(i)) || {};
@@ -261,6 +276,10 @@ export async function runLoop({
261
276
  const nextMs = Number.isFinite(res.nextDelayMs)
262
277
  ? res.nextDelayMs
263
278
  : intervalMs;
264
- await delay(nextMs);
279
+ const waitingSince = now();
280
+ const nextRunAt = waitingSince + nextMs;
281
+ const wakeAt = endsAt == null ? nextRunAt : Math.min(nextRunAt, endsAt);
282
+ onWait?.(endsAt == null || nextRunAt < endsAt ? nextRunAt : null);
283
+ await delay(Math.max(0, wakeAt - waitingSince));
265
284
  }
266
285
  }
@@ -20,7 +20,7 @@ const suite = serverAvailable ? describe : describe.skip;
20
20
 
21
21
  if (!serverAvailable) {
22
22
  // Make the skip reason obvious in test output.
23
- // eslint-disable-next-line no-console
23
+
24
24
  console.warn(
25
25
  "[lsp.integration] SKIP — no `typescript-language-server` on PATH. " +
26
26
  "Install it to run real LSP integration coverage.",
@@ -74,21 +74,23 @@ suite("CodeIntelligence against a real typescript-language-server", () => {
74
74
  }
75
75
  });
76
76
 
77
- it("resolves a cross-file definition", async () => {
78
- // `add` usage in main.ts (line 3, col 15) → declaration in math.ts
79
- const res = await ci.definition(path.join(tmp, "src", "main.ts"), 3, 15);
80
- expect(res.available).toBe(true);
81
- expect(res.locations.length).toBeGreaterThan(0);
82
- expect(res.locations.some((l) => l.file.endsWith("math.ts"))).toBe(true);
83
- }, 30000);
77
+ it("serves simultaneous definition and references queries on cold start", async () => {
78
+ const main = path.join(tmp, "src", "main.ts");
79
+ const math = path.join(tmp, "src", "math.ts");
80
+ const [definition, references] = await Promise.all([
81
+ ci.definition(main, 3, 15),
82
+ ci.references(math, 1, 17),
83
+ ]);
84
84
 
85
- it("finds all references to a symbol across files", async () => {
86
- // `add` declaration in math.ts (line 1, col 17)
87
- const res = await ci.references(path.join(tmp, "src", "math.ts"), 1, 17);
88
- expect(res.available).toBe(true);
89
- // declaration + import + call site
90
- expect(res.locations.length).toBeGreaterThanOrEqual(2);
91
- expect(res.locations.some((l) => l.file.endsWith("main.ts"))).toBe(true);
85
+ expect(definition.available).toBe(true);
86
+ expect(
87
+ definition.locations.map((item) => path.basename(item.file)),
88
+ ).toContain("math.ts");
89
+ expect(references.available).toBe(true);
90
+ expect(references.locations.length).toBeGreaterThanOrEqual(2);
91
+ expect(
92
+ references.locations.map((item) => path.basename(item.file)),
93
+ ).toContain("main.ts");
92
94
  }, 30000);
93
95
 
94
96
  it("reports diagnostics for an undefined name", async () => {