@abelxiaoxing/cadence 2.0.47 → 2.0.48

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.
@@ -17,7 +17,6 @@ export const LIMITS = Object.freeze({
17
17
  wsClientFrameBytes: 16 * 1024,
18
18
  startWaitMs: 10_000,
19
19
  stopWaitMs: 60_000,
20
- authWaitMs: 30_000,
21
20
  authValidityMarginMs: 120_000,
22
21
  browserLifetimeMs: 12 * 60 * 60 * 1000,
23
22
  terminateGraceMs: 1000,
@@ -34,10 +33,10 @@ export const LIMITS = Object.freeze({
34
33
  frameBytes: 64 * 1024,
35
34
  chunkBytes: 8 * 1024,
36
35
  detailBytes: 32 * 1024 * 1024,
37
- childProtocolBytes: 128 * 1024 * 1024,
38
36
  dataFrames: 100_000,
39
37
  controlFrames: 256,
40
- sdkEvents: 1_000_000,
38
+ // Live unresolved protocol state only; settled history does not consume it.
39
+ captureEntries: 4096,
41
40
  workerQueueBytes: 4 * 1024 * 1024,
42
41
  workerQueueFrames: 1024,
43
42
  ownerQueueBytes: 8 * 1024 * 1024,
@@ -45,13 +44,8 @@ export const LIMITS = Object.freeze({
45
44
  // Transform queue headroom, not the separate per-episode disk reservation.
46
45
  ownerControlBytes: 1024 * 1024,
47
46
  ownerControlFrames: 256,
48
- recordingStallMs: 5000,
49
47
  episodes: 8,
50
- queuedAssignments: 128,
51
48
  childReservations: 2,
52
- episodeMs: 6 * 60 * 60 * 1000,
53
- readyWaitMs: 10 * 60 * 1000,
54
- workerMs: 1_200_000,
55
49
  artifactPartBytes: 256 * 1024,
56
50
  progressBatchMs: 100,
57
51
  progressBatchBytes: 256 * 1024,
@@ -659,7 +653,7 @@ export function checkSelection(v) {
659
653
  kind: oneOf(o.kind, ["configured", "manual"]),
660
654
  name: text(o.name, 128, true),
661
655
  command: text(o.command, 4096, true),
662
- timeoutMs: integer(o.timeoutMs, 100, LIMITS.workerMs),
656
+ timeoutMs: integer(o.timeoutMs, 100, 1_200_000),
663
657
  };
664
658
  // Same visible-command policy as task-types; that legacy decoder uses Node Buffer and permits extra keys.
665
659
  // biome-ignore lint/suspicious/noControlCharactersInRegex: executable confirmations must be visibly representable
@@ -990,8 +984,25 @@ export function assertWorkerEnvelopeSize(serialized) {
990
984
  if (utf8Bytes(serialized) > LIMITS.workerRequestBytes)
991
985
  throw new ContractError("oversize");
992
986
  }
987
+ export function decodeStopCause(v) {
988
+ const o = closed(v, ["source", "reason", "target"]);
989
+ return {
990
+ source: oneOf(o.source, [
991
+ "user",
992
+ "service",
993
+ "owner",
994
+ "command",
995
+ "worker",
996
+ "coordinator",
997
+ "unknown",
998
+ ]),
999
+ reason: text(o.reason, 128, true),
1000
+ target: text(o.target, 128, true),
1001
+ };
1002
+ }
993
1003
  export function decodeNativeSettlement(v) {
994
1004
  const o = closed(v, [
1005
+ ...(Object.hasOwn(v ?? {}, "stop") ? ["stop"] : []),
995
1006
  "outcome",
996
1007
  "closure",
997
1008
  "exitCode",
@@ -1003,6 +1014,7 @@ export function decodeNativeSettlement(v) {
1003
1014
  "capture",
1004
1015
  ]);
1005
1016
  const r = {
1017
+ ...(o.stop === undefined ? {} : { stop: decodeStopCause(o.stop) }),
1006
1018
  outcome: oneOf(o.outcome, [
1007
1019
  "completed",
1008
1020
  "failed",
@@ -1223,6 +1235,20 @@ function sourceId(v) {
1223
1235
  if (!/^[a-zA-Z0-9_-]+$/.test(s)) invalid();
1224
1236
  return s;
1225
1237
  }
1238
+ /** Credential-free progress, not a successful response or permission to replay. */
1239
+ export function decodeModelRetry(v) {
1240
+ const o = closed(v, ["phase", "attempt", "maxAttempts", "delayMs"]);
1241
+ const maxAttempts = integer(o.maxAttempts, 1);
1242
+ const progress = {
1243
+ phase: oneOf(o.phase, ["waiting", "requesting"]),
1244
+ attempt: integer(o.attempt, 1, maxAttempts),
1245
+ maxAttempts,
1246
+ delayMs: integer(o.delayMs, 0, 2147483647),
1247
+ };
1248
+ if (progress.phase === "requesting" && progress.delayMs !== 0)
1249
+ throw new ContractError("invalid");
1250
+ return progress;
1251
+ }
1226
1252
  export function decodeCaptureEvent(v) {
1227
1253
  const kind = tag(v);
1228
1254
  switch (kind) {
@@ -1415,6 +1441,10 @@ export function decodeCaptureEvent(v) {
1415
1441
  coverage: decodeCoverage(o.coverage),
1416
1442
  };
1417
1443
  }
1444
+ case "model-retry": {
1445
+ const o = closed(v, ["kind", "progress"]);
1446
+ return { kind, progress: nullable(o.progress, decodeModelRetry) };
1447
+ }
1418
1448
  case "capture-status": {
1419
1449
  const o = closed(v, ["kind", "coverage"]);
1420
1450
  return { kind, coverage: decodeCoverage(o.coverage) };
@@ -1459,11 +1489,7 @@ export function decodeCaptureFrame(v) {
1459
1489
  return {
1460
1490
  protocol: literal(o.protocol, WORKER_PROTOCOL),
1461
1491
  childRunId: decodeId(o.childRunId),
1462
- workerSeq: integer(
1463
- o.workerSeq,
1464
- 1,
1465
- LIMITS.dataFrames + LIMITS.controlFrames,
1466
- ),
1492
+ workerSeq: integer(o.workerSeq, 1, Number.MAX_SAFE_INTEGER),
1467
1493
  observedMs: integer(o.observedMs),
1468
1494
  event: decodeCaptureEvent(o.event),
1469
1495
  };
@@ -1492,6 +1518,7 @@ export function advanceCapture(position, input) {
1492
1518
  }
1493
1519
  export function decodeCheckNativeSettlement(v) {
1494
1520
  const o = closed(v, [
1521
+ ...(Object.hasOwn(v ?? {}, "stop") ? ["stop"] : []),
1495
1522
  "outcome",
1496
1523
  "closure",
1497
1524
  "exitCode",
@@ -1500,6 +1527,7 @@ export function decodeCheckNativeSettlement(v) {
1500
1527
  "stdin",
1501
1528
  ]);
1502
1529
  const r = {
1530
+ ...(o.stop === undefined ? {} : { stop: decodeStopCause(o.stop) }),
1503
1531
  outcome: oneOf(o.outcome, [
1504
1532
  "completed",
1505
1533
  "failed",
@@ -1675,8 +1703,8 @@ export function decodeWorkerCompletion(v) {
1675
1703
  }
1676
1704
  export function decodeSourceRange(v) {
1677
1705
  const o = closed(v, ["first", "last", "firstObservedMs", "lastObservedMs"]);
1678
- const first = integer(o.first, 1, LIMITS.dataFrames + LIMITS.controlFrames);
1679
- const last = integer(o.last, first, LIMITS.dataFrames + LIMITS.controlFrames);
1706
+ const first = integer(o.first, 1, Number.MAX_SAFE_INTEGER);
1707
+ const last = integer(o.last, first, Number.MAX_SAFE_INTEGER);
1680
1708
  const firstObservedMs = integer(o.firstObservedMs);
1681
1709
  const lastObservedMs = integer(o.lastObservedMs, firstObservedMs);
1682
1710
  if (first === last && firstObservedMs !== lastObservedMs) invalid();
@@ -1,5 +1,9 @@
1
1
  /** Trusted capability composition. No discovery, plugin claims or model-selected
2
2
  * permissions. Role prompts do not grant tools; the validated owner request does. */
3
+ import {
4
+ createBashToolDefinition,
5
+ createPowerShellToolDefinition,
6
+ } from "@earendil-works/pi-coding-agent";
3
7
  import { Type } from "typebox";
4
8
  import { createChangeTools } from "./change-tools.mjs";
5
9
  import { createCoordinatorTools } from "./coordinator-tools.mjs";
@@ -8,43 +12,12 @@ import {
8
12
  RESEARCH_INSTRUCTIONS,
9
13
  } from "./research-tools.mjs";
10
14
  import { sanitizeText } from "./worker-redaction.mjs";
11
- import { captureBash } from "./worker-tools.mjs";
12
-
13
- const policies = Object.freeze({
14
- edit: Object.freeze(["files", "shell"]),
15
- research: Object.freeze(["observation"]),
16
- diagnosis: Object.freeze(["observation"]),
17
- review: Object.freeze(["observation"]),
18
- coordination: Object.freeze(["coordination"]),
19
- });
20
- // One reviewed registry, not a public runtime plugin interface. An observation
21
- // bundle may add tools without teaching the SDK bootstrap another list of names.
22
- const bundles = {
23
- files: () => ({
24
- names: ["read", "grep", "find", "ls", "write", "edit"],
25
- tools: [],
26
- }),
27
- shell: ({ workspace, secrets, fail, createLocalBashOperations, queue }) => ({
28
- tools: [
29
- captureBash(
30
- workspace.cwd,
31
- secrets,
32
- fail,
33
- createLocalBashOperations,
34
- queue,
35
- ),
36
- ],
37
- }),
38
- observation: ({ workspace }) => createResearchTools(workspace),
39
- changes: ({ changes }) => createChangeTools(changes),
40
- coordination: () => createCoordinatorTools(),
41
- };
15
+ import { captureShell } from "./worker-tools.mjs";
42
16
 
43
17
  export function createWorkerToolkit(options) {
44
18
  const { purpose, coordinator = false } = options;
45
19
  if (
46
- !Object.hasOwn(policies, purpose) ||
47
- purpose === "coordination" ||
20
+ !["edit", "research", "diagnosis", "review"].includes(purpose) ||
48
21
  (coordinator && purpose !== "research")
49
22
  )
50
23
  throw new Error("Invalid worker capability selection");
@@ -55,11 +28,58 @@ export function createWorkerToolkit(options) {
55
28
  options.changes.root !== options.workspace.roots[0])
56
29
  )
57
30
  throw new Error("Invalid review capability binding");
58
- const capabilities = options.changes
59
- ? Object.freeze([...policies[purpose], "changes"])
60
- : policies[coordinator ? "coordination" : purpose];
61
- const owned = capabilities.map((capability) => bundles[capability](options));
62
- const customTools = owned.flatMap((bundle) => bundle.tools);
31
+ const runtime = options.runtime;
32
+ if (!runtime) throw new Error("Worker runtime settings are required");
33
+ const readonly = purpose !== "edit";
34
+ const names = [...runtime.tools[readonly ? "readonly" : "edit"]];
35
+ const owned = [];
36
+ const customTools = [];
37
+ if (coordinator) {
38
+ const bridge = createCoordinatorTools();
39
+ owned.push(bridge);
40
+ customTools.push(...bridge.tools);
41
+ names.splice(0, names.length, ...bridge.tools.map((tool) => tool.name));
42
+ } else if (readonly) {
43
+ const observation = createResearchTools(
44
+ options.workspace,
45
+ names,
46
+ runtime.settings,
47
+ );
48
+ owned.push(observation);
49
+ customTools.push(...observation.tools);
50
+ } else {
51
+ for (const name of names.filter((name) =>
52
+ ["bash", "powershell"].includes(name),
53
+ )) {
54
+ const bash = name === "bash";
55
+ const definition = (
56
+ bash ? createBashToolDefinition : createPowerShellToolDefinition
57
+ )(options.workspace.cwd);
58
+ const operations = () =>
59
+ bash
60
+ ? options.createLocalBashOperations({
61
+ shellPath: runtime.settings.shellPath,
62
+ })
63
+ : options.createLocalPowerShellOperations();
64
+ customTools.push(
65
+ captureShell(
66
+ options.workspace.cwd,
67
+ options.secrets,
68
+ options.fail,
69
+ operations,
70
+ options.queue,
71
+ definition,
72
+ bash ? runtime.settings.shellCommandPrefix : undefined,
73
+ ),
74
+ );
75
+ }
76
+ }
77
+ if (options.changes) {
78
+ const changes = createChangeTools(options.changes);
79
+ owned.push(changes);
80
+ customTools.push(...changes.tools);
81
+ names.push(...changes.tools.map((tool) => tool.name));
82
+ }
63
83
  if (options.reporting && !coordinator && purpose === "edit")
64
84
  customTools.push({
65
85
  name: "cadence_report",
@@ -92,9 +112,6 @@ export function createWorkerToolkit(options) {
92
112
  return { content: [{ type: "text", text }], details: undefined };
93
113
  },
94
114
  });
95
- const names = owned.flatMap(
96
- (bundle) => bundle.names ?? bundle.tools.map((tool) => tool.name),
97
- );
98
115
  if (options.reporting && !coordinator && purpose === "edit")
99
116
  names.push("cadence_report");
100
117
  if (new Set(names).size !== names.length)
@@ -103,10 +120,7 @@ export function createWorkerToolkit(options) {
103
120
  let closed = false,
104
121
  closing;
105
122
  return {
106
- capabilities,
107
- instructions: capabilities.includes("observation")
108
- ? RESEARCH_INSTRUCTIONS
109
- : "",
123
+ instructions: readonly && !coordinator ? RESEARCH_INSTRUCTIONS : "",
110
124
  // Explicit allowlists are required by the installed public Pi SDK. Omitting
111
125
  // one would enable its defaults, not mean "only our custom capabilities".
112
126
  sessionOptions: {
@@ -136,7 +150,7 @@ export function createWorkerToolkit(options) {
136
150
  "edit",
137
151
  ].includes(tool.name);
138
152
  // Stock file tools may reject an abort observer before their real
139
- // I/O finishes. Join this admitted call under the worker deadline,
153
+ // I/O finishes. Join this admitted call to its actual settlement,
140
154
  // then suppress its result if canceled. Pi grep already waits for
141
155
  // child close on abort, so preserve its stop signal like shell and
142
156
  // changes; no mutation is replayed.
@@ -1,4 +1,3 @@
1
- import { Type } from "typebox";
2
1
  import { ContractError, LIMITS } from "./worker-public.mjs";
3
2
  import {
4
3
  measureData,
@@ -11,23 +10,20 @@ import {
11
10
  /** Matches the stock bash renderer's update throttle. */
12
11
  const UPDATE_INTERVAL_MS = 100;
13
12
 
14
- /** No stock bash definition/OutputAccumulator: raw output is never spilled. */
15
- export function captureBash(
13
+ /** Pi shell definitions/backends with a bounded redacted accumulator instead
14
+ * of the stock raw-spill accumulator. No command allowlist or lifetime quota. */
15
+ export function captureShell(
16
16
  cwd,
17
17
  secrets,
18
18
  fail,
19
- createLocalBashOperations,
19
+ operations,
20
20
  queue,
21
+ definition,
22
+ commandPrefix,
21
23
  ) {
22
24
  return {
23
- name: "bash",
24
- label: "bash",
25
- description:
26
- "Execute a shell command in the working directory. Output is bounded and redacted; no raw spill file.",
27
- parameters: Type.Object({
28
- command: Type.String(),
29
- timeout: Type.Optional(Type.Number()),
30
- }),
25
+ ...definition,
26
+ description: `Execute ${definition.name} in the fixed working directory, with an optional per-command timeout in seconds. Output is redacted and retained as a labelled bounded tail; no raw spill file.`,
31
27
  async execute(_id, args, signal, onUpdate) {
32
28
  const command = own(args, "command"),
33
29
  timeout = own(args, "timeout");
@@ -40,7 +36,7 @@ export function captureBash(
40
36
  const abort = () => local.abort();
41
37
  const prefix = queue.reserve(
42
38
  secrets.reduce((n, value) => n + Buffer.byteLength(value), 0) * 4 +
43
- 65536,
39
+ 256 * 1024,
44
40
  );
45
41
  signal?.addEventListener("abort", abort, { once: true });
46
42
  if (signal?.aborted) abort();
@@ -48,31 +44,29 @@ export function captureBash(
48
44
  const sanitizer = new TextSanitizer(secrets);
49
45
  let output = "",
50
46
  sourceBytes = 0,
51
- failed = false;
47
+ failed = false,
48
+ truncated = false;
52
49
  const append = (text) => {
53
- if (
54
- Buffer.byteLength(output) + Buffer.byteLength(text) >
55
- LIMITS.detailBytes
56
- )
57
- throw new ContractError("oversize");
58
- // The redacted accumulator is Cadence-owned retention too, not an
59
- // uncharged escape from the shared queue. No raw spill on exhaustion.
60
- prefix.grow(Buffer.byteLength(text));
61
50
  output += text;
51
+ if (Buffer.byteLength(output) > 65536) {
52
+ truncated = true;
53
+ output = Buffer.from(output).subarray(-65536).toString("utf8");
54
+ if (output.startsWith("\uFFFD")) output = output.slice(1);
55
+ }
62
56
  };
63
57
  const refuse = () => {
64
58
  failed = true;
65
59
  local.abort();
66
60
  fail();
67
61
  };
68
- // Previews only: the final result carries every byte. Windows pipes
62
+ // Bounded previews and a labelled redacted tail; no raw spill or log quota. Windows pipes
69
63
  // deliver chatty output as thousands of small chunks, and each update is
70
64
  // a durable capture detail, so throttle like the stock bash renderer.
71
65
  let lastUpdate = Number.NEGATIVE_INFINITY;
72
66
  let pending;
73
67
  const publish = () => {
74
68
  pending = undefined;
75
- if (failed) return;
69
+ if (failed || queue.bytes > LIMITS.workerQueueBytes / 2) return;
76
70
  lastUpdate = performance.now();
77
71
  try {
78
72
  let tail = output.slice(-4096);
@@ -94,32 +88,44 @@ export function captureBash(
94
88
  }
95
89
  };
96
90
  try {
97
- const result = await createLocalBashOperations().exec(command, cwd, {
98
- signal: local.signal,
99
- timeout,
100
- onData(data) {
101
- if (failed) return;
102
- let raw;
103
- try {
104
- raw = queue.reserve(data.length * 12);
105
- // Charge original bytes synchronously BEFORE decoding/copying.
106
- sourceBytes += data.length;
107
- if (
108
- data.length > LIMITS.workerQueueBytes ||
109
- sourceBytes > LIMITS.detailBytes
110
- )
111
- throw new ContractError("oversize");
112
- append(sanitizer.write(decoder.decode(data, { stream: true })));
113
- const since = performance.now() - lastUpdate;
114
- if (since >= UPDATE_INTERVAL_MS) publish();
115
- else pending ??= setTimeout(publish, UPDATE_INTERVAL_MS - since);
116
- } catch {
117
- refuse();
118
- } finally {
119
- raw?.release();
120
- }
91
+ const started = performance.now();
92
+ const result = await operations().exec(
93
+ commandPrefix ? `${commandPrefix}\n${command}` : command,
94
+ cwd,
95
+ {
96
+ signal: local.signal,
97
+ timeout,
98
+ onData(data) {
99
+ if (failed) return;
100
+ let raw;
101
+ try {
102
+ sourceBytes += data.length;
103
+ // A pipe chunk is processed in bounded slices; cumulative log
104
+ // volume does not have authority to stop the command.
105
+ for (let at = 0; at < data.length; at += 8192) {
106
+ raw = queue.reserve(8192 * 12);
107
+ append(
108
+ sanitizer.write(
109
+ decoder.decode(data.subarray(at, at + 8192), {
110
+ stream: true,
111
+ }),
112
+ ),
113
+ );
114
+ raw.release();
115
+ raw = undefined;
116
+ }
117
+ const since = performance.now() - lastUpdate;
118
+ if (since >= UPDATE_INTERVAL_MS) publish();
119
+ else
120
+ pending ??= setTimeout(publish, UPDATE_INTERVAL_MS - since);
121
+ } catch {
122
+ refuse();
123
+ } finally {
124
+ raw?.release();
125
+ }
126
+ },
121
127
  },
122
- });
128
+ );
123
129
  try {
124
130
  append(sanitizer.write(decoder.decode()));
125
131
  append(sanitizer.end());
@@ -127,17 +133,31 @@ export function captureBash(
127
133
  fail();
128
134
  throw new ContractError();
129
135
  }
136
+ if (truncated)
137
+ output = `[Output truncated; retained redacted tail of ${sourceBytes} observed bytes.]\n${output}`;
130
138
  if (failed) throw new ContractError("capacity");
131
139
  if (result.exitCode === null) throw new ContractError("unavailable");
132
- // Match the public stock tool's nonzero result/error semantics. The SDK
133
- // turns a throw into isError; this is never a parent check receipt.
134
- if (result.exitCode !== 0)
135
- throw new Error(
136
- `${output}\nCommand exited with code ${result.exitCode}`,
137
- );
138
140
  return {
139
- content: [{ type: "text", text: output || "(no output)" }],
140
- details: {},
141
+ content: [
142
+ {
143
+ type: "text",
144
+ text:
145
+ result.exitCode === 0
146
+ ? output || "(no output)"
147
+ : `${output}\nCommand exited with code ${result.exitCode}`,
148
+ },
149
+ ],
150
+ ...(result.exitCode === 0 ? {} : { isError: true }),
151
+ structuredContent: {
152
+ output,
153
+ truncated,
154
+ exit_code: result.exitCode,
155
+ wall_time_seconds:
156
+ Math.round((performance.now() - started) / 100) / 10,
157
+ },
158
+ details: truncated
159
+ ? { truncation: { observedBytes: sourceBytes } }
160
+ : {},
141
161
  };
142
162
  } finally {
143
163
  // No preview may follow the result.