@abelxiaoxing/cadence 2.0.47 → 2.0.49

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.
@@ -58,6 +58,7 @@ export class CaptureState {
58
58
  this.bytes = 0;
59
59
  this.coverage = completeCoverage();
60
60
  this.selected = null;
61
+ this.retry = null;
61
62
  this.failed = false;
62
63
  this.request = request;
63
64
  this.contexts = new Set();
@@ -68,13 +69,17 @@ export class CaptureState {
68
69
  const e = frame.event;
69
70
  const control = controlEvent(e.kind);
70
71
  this.bytes += encodedBytes ?? utf8Bytes(canonicalJson(frame)) + 1;
72
+ // Counters are diagnostics, not a lifetime quota. Only unresolved state
73
+ // consumes the live protocol window; settled details are reclaimed below.
74
+ this[control ? "controlFrames" : "dataFrames"]++;
71
75
  if (
72
- ++this[control ? "controlFrames" : "dataFrames"] >
73
- (control ? LIMITS.controlFrames : LIMITS.dataFrames) ||
74
- this.bytes >
75
- LIMITS.childProtocolBytes - (control ? 0 : LIMITS.ownerControlBytes)
76
+ this.details.size +
77
+ this.messages.size +
78
+ this.calls.size +
79
+ this.blocks.size >
80
+ LIMITS.captureEntries
76
81
  )
77
- throw new ContractError("oversize");
82
+ throw new ContractError("capacity");
78
83
  const message = (id) => {
79
84
  const m = this.messages.get(id);
80
85
  requireFact(m);
@@ -106,8 +111,24 @@ export class CaptureState {
106
111
  break;
107
112
  case "message-start":
108
113
  requireFact(!this.messages.has(e.messageId));
109
- if (e.resultCallId !== null)
114
+ if (e.resultCallId !== null) {
110
115
  requireFact(this.calls.get(e.resultCallId)?.ended);
116
+ this.calls.delete(e.resultCallId);
117
+ }
118
+ // The previous response is no longer a final-result candidate. Keep
119
+ // unresolved calls, not all past messages or partial failed declarations.
120
+ if (e.role === "assistant") {
121
+ for (const [id, m] of this.messages)
122
+ if (m.ended) {
123
+ if (m.final) this.details.delete(m.final);
124
+ this.messages.delete(id);
125
+ }
126
+ for (const [id, c] of this.calls)
127
+ if (!c.started || c.ended) {
128
+ this.releaseCallDetails(id);
129
+ this.calls.delete(id);
130
+ }
131
+ }
111
132
  this.messages.set(e.messageId, {
112
133
  role: e.role,
113
134
  ended: false,
@@ -194,6 +215,8 @@ export class CaptureState {
194
215
  d.hash = null;
195
216
  d.ended = true;
196
217
  this.mergeCoverage(e.coverage);
218
+ if (["context", "handoff"].includes(d.descriptor.owner.kind))
219
+ this.details.delete(e.detailId);
197
220
  break;
198
221
  }
199
222
  case "message-text": {
@@ -229,6 +252,7 @@ export class CaptureState {
229
252
  requireFact(!m.finalIndices.has(e.index));
230
253
  m.finalIndices.add(e.index);
231
254
  }
255
+ if (e.argsDetailId) this.releaseDetail(e.argsDetailId);
232
256
  this.calls.set(e.callId, { ...e, started: false, ended: false });
233
257
  break;
234
258
  }
@@ -248,6 +272,8 @@ export class CaptureState {
248
272
  detail(e.argsDetailId, "tool-args", e.callId).descriptor.owner
249
273
  .stage === "execution-arguments",
250
274
  );
275
+ if (e.argsDetailId) this.releaseDetail(e.argsDetailId);
276
+ this.releaseCallDetails(e.callId);
251
277
  this.calls.set(e.callId, { ...old, ...e, started: true, ended: false });
252
278
  break;
253
279
  }
@@ -259,6 +285,7 @@ export class CaptureState {
259
285
  detail(e.detailId, "tool-update", e.callId).descriptor.owner.stage ===
260
286
  "update-snapshot",
261
287
  );
288
+ this.releaseDetail(e.detailId);
262
289
  break;
263
290
  case "tool-end": {
264
291
  const c = this.calls.get(e.callId);
@@ -276,6 +303,8 @@ export class CaptureState {
276
303
  detail(e.resultDetailId, "tool-result", e.callId).descriptor.owner
277
304
  .stage === "result",
278
305
  );
306
+ this.releaseDetail(e.resultDetailId);
307
+ this.releaseCallDetails(e.callId);
279
308
  this.calls.set(e.callId, {
280
309
  ...c,
281
310
  ...e,
@@ -307,6 +336,18 @@ export class CaptureState {
307
336
  m.ended = true;
308
337
  m.final = e.finalDetailId;
309
338
  m.stopReason = e.stopReason;
339
+ for (const [id, d] of this.details)
340
+ if (
341
+ d.descriptor.owner.messageId === e.messageId &&
342
+ id !== e.finalDetailId
343
+ )
344
+ this.releaseDetail(id);
345
+ // Omitted blocks have no detail record.
346
+ for (const [id, key] of this.blocks)
347
+ if (JSON.parse(key).messageId === e.messageId) this.blocks.delete(id);
348
+ m.finalIndices.clear();
349
+ m.finalHash = null;
350
+ if (m.role !== "assistant") this.messages.delete(e.messageId);
310
351
  break;
311
352
  }
312
353
  case "omitted-block":
@@ -326,6 +367,9 @@ export class CaptureState {
326
367
  omissions: [e.block.reason],
327
368
  });
328
369
  break;
370
+ case "model-retry":
371
+ this.retry = e.progress;
372
+ break;
329
373
  case "capture-status":
330
374
  this.mergeCoverage(e.coverage);
331
375
  break;
@@ -347,6 +391,7 @@ export class CaptureState {
347
391
  const m = message(e.messageId);
348
392
  requireFact(
349
393
  !this.failed &&
394
+ this.retry === null &&
350
395
  m.ended &&
351
396
  m.role === "assistant" &&
352
397
  m.stopReason === "stop" &&
@@ -366,6 +411,19 @@ export class CaptureState {
366
411
  this.position = position;
367
412
  return frame;
368
413
  }
414
+ releaseCallDetails(callId) {
415
+ for (const [id, d] of this.details)
416
+ if (d.descriptor.owner.callId === callId && d.ended)
417
+ this.releaseDetail(id);
418
+ for (const [id, key] of this.blocks)
419
+ if (JSON.parse(key).callId === callId) this.blocks.delete(id);
420
+ }
421
+ releaseDetail(id) {
422
+ const d = this.details.get(id);
423
+ if (d?.descriptor.owner.blockId)
424
+ this.blocks.delete(d.descriptor.owner.blockId);
425
+ this.details.delete(id);
426
+ }
369
427
  mergeCoverage(c) {
370
428
  this.coverage.observed =
371
429
  c.observed === "incomplete" ? "incomplete" : this.coverage.observed;
@@ -492,7 +550,6 @@ export class CaptureEmitter {
492
550
  lease.release();
493
551
  throw error;
494
552
  }
495
- let timer;
496
553
  const original = new Promise((resolve, reject) => {
497
554
  this.output.write(line, (error) =>
498
555
  error ? reject(new ContractError("unavailable")) : resolve(),
@@ -501,13 +558,11 @@ export class CaptureEmitter {
501
558
  this.pending.add(original);
502
559
  const settled = original.then(
503
560
  () => {
504
- clearTimeout(timer);
505
561
  this.queuedBytes -= bytes;
506
562
  lease.release();
507
563
  this.pending.delete(original);
508
564
  },
509
565
  () => {
510
- clearTimeout(timer);
511
566
  this.queuedBytes -= bytes;
512
567
  lease.release();
513
568
  this.pending.delete(original);
@@ -515,19 +570,11 @@ export class CaptureEmitter {
515
570
  this.onFailure();
516
571
  },
517
572
  );
518
- // Reporting timeout never refunds an outstanding original write.
519
- const wait = Promise.race([
520
- original,
521
- new Promise((_, reject) => {
522
- timer = setTimeout(() => {
523
- this.onFailure();
524
- reject(new ContractError("recording-exhausted"));
525
- }, LIMITS.recordingStallMs);
526
- }),
527
- ]);
528
- wait.catch(() => {});
573
+ // Slow output is backpressure, not failure. The original callback alone
574
+ // releases its charge; a real stream error still fails capture.
575
+ original.catch(() => {});
529
576
  settled.catch(() => {});
530
- return wait;
577
+ return original;
531
578
  }
532
579
  async drain() {
533
580
  await Promise.allSettled([...this.pending]);
@@ -792,6 +839,8 @@ export class SdkCapture {
792
839
  ended: false,
793
840
  resultLinked: false,
794
841
  };
842
+ if (this.calls.length >= LIMITS.captureEntries)
843
+ throw new ContractError("capacity");
795
844
  this.calls.push(call);
796
845
  return call;
797
846
  }
@@ -938,13 +987,15 @@ export class SdkCapture {
938
987
  return detailId;
939
988
  }
940
989
  async event(event) {
941
- if (++this.events > LIMITS.sdkEvents) throw new ContractError("oversize");
990
+ this.events++;
942
991
  const type = own(event, "type");
943
992
  if (typeof type !== "string") throw new ContractError();
944
993
  switch (type) {
945
994
  case "message_start": {
946
995
  requireFact(this.current === null);
947
996
  const message = own(event, "message");
997
+ if (own(message, "role") === "assistant")
998
+ this.calls = this.calls.filter((c) => c.started && !c.ended);
948
999
  const rawRole = own(message, "role");
949
1000
  const role = rawRole === "toolResult" ? "tool-result" : rawRole;
950
1001
  requireFact(
@@ -959,7 +1010,10 @@ export class SdkCapture {
959
1010
  )
960
1011
  : [];
961
1012
  const call = matches.length === 1 ? matches[0] : null;
962
- if (call) call.resultLinked = true;
1013
+ if (call) {
1014
+ call.resultLinked = true;
1015
+ this.calls = this.calls.filter((c) => c !== call);
1016
+ }
963
1017
  this.current = {
964
1018
  id: randomUUID(),
965
1019
  role,
@@ -0,0 +1,339 @@
1
+ import {
2
+ bool,
3
+ canonicalJson,
4
+ closed,
5
+ decodeModelRetry,
6
+ integer,
7
+ list,
8
+ oneOf,
9
+ text,
10
+ } from "./worker-public.mjs";
11
+ import { own } from "./worker-redaction.mjs";
12
+
13
+ /** Service exceptions only. Pi owns defaults and user/project setting merges.
14
+ * No cache-warming requests or second provider retry layer in owned workers. */
15
+ export const WORKER_POLICY = Object.freeze({
16
+ retry: { provider: { maxRetries: 0 } },
17
+ cacheWarming: "off",
18
+ httpIdleTimeoutMs: 0,
19
+ });
20
+ export const WORKER_SETTINGS_BYTES = 32768;
21
+
22
+ /** Public SDK factories are the source of built-in/default tool identities. */
23
+ export function defaultWorkerTools(pi, cwd) {
24
+ const edit = pi.createCodingTools(cwd).map((tool) => tool.name);
25
+ const readonly = pi.createReadOnlyTools(cwd).map((tool) => tool.name);
26
+ return {
27
+ edit,
28
+ readonly,
29
+ available: [
30
+ ...new Set([...edit, ...readonly, pi.createPowerShellTool(cwd).name]),
31
+ ],
32
+ };
33
+ }
34
+
35
+ /** Resolve a selected model through Pi's public getters, not a second merge or
36
+ * settings-default implementation. Only execution preferences cross the pipe;
37
+ * package/extension/auth/model discovery settings never do. */
38
+ export function resolveWorkerRuntime(manager, model, defaults) {
39
+ if (manager.drainErrors().length)
40
+ throw new Error("Pi settings could not be read");
41
+ const effective = manager.getSettings();
42
+ const selected = manager.getDefaultTools();
43
+ const tools = selected ?? defaults.edit;
44
+ if (
45
+ !Array.isArray(tools) ||
46
+ tools.some((name) => !defaults.available.includes(name))
47
+ )
48
+ throw new Error("Configured Pi tools are unavailable in service workers");
49
+ const provider = manager.getProviderRetrySettings();
50
+ return decodeWorkerRuntime({
51
+ projectTrusted: manager.isProjectTrusted(),
52
+ tools: {
53
+ edit: tools,
54
+ readonly:
55
+ selected === undefined
56
+ ? defaults.readonly
57
+ : tools.filter((name) => defaults.readonly.includes(name)),
58
+ },
59
+ settings: {
60
+ compaction: manager.getCompactionSettings(model),
61
+ retry: {
62
+ ...manager.getRetrySettings(),
63
+ provider: {
64
+ ...WORKER_POLICY.retry.provider,
65
+ maxRetryDelayMs: provider.maxRetryDelayMs,
66
+ ...(provider.timeoutMs === undefined
67
+ ? {}
68
+ : { timeoutMs: provider.timeoutMs }),
69
+ },
70
+ },
71
+ // A product default, not a replacement for an explicit Pi request policy.
72
+ httpIdleTimeoutMs:
73
+ effective.httpIdleTimeoutMs === undefined
74
+ ? WORKER_POLICY.httpIdleTimeoutMs
75
+ : manager.getHttpIdleTimeoutMs(),
76
+ ...(manager.getWebSocketConnectTimeoutMs() === undefined
77
+ ? {}
78
+ : {
79
+ websocketConnectTimeoutMs: manager.getWebSocketConnectTimeoutMs(),
80
+ }),
81
+ transport: manager.getTransport(),
82
+ ...(manager.getThinkingBudgets() === undefined
83
+ ? {}
84
+ : { thinkingBudgets: manager.getThinkingBudgets() }),
85
+ images: {
86
+ autoResize: manager.getImageAutoResize(),
87
+ blockImages: manager.getBlockImages(),
88
+ },
89
+ ...(manager.getShellPath() === undefined
90
+ ? {}
91
+ : { shellPath: manager.getShellPath() }),
92
+ ...(manager.getShellCommandPrefix() === undefined
93
+ ? {}
94
+ : { shellCommandPrefix: manager.getShellCommandPrefix() }),
95
+ cacheWarming: WORKER_POLICY.cacheWarming,
96
+ },
97
+ });
98
+ }
99
+
100
+ /** Closed, bounded private runtime snapshot; it grants no tool authority. */
101
+ export function decodeWorkerRuntime(value) {
102
+ // JSON also removes omitted SDK getter fields. The wire owns plain data only.
103
+ const v = JSON.parse(canonicalJson(value, WORKER_SETTINGS_BYTES));
104
+ const o = closed(v, ["projectTrusted", "tools", "settings"]);
105
+ const t = closed(o.tools, ["edit", "readonly"]);
106
+ const r = o.settings;
107
+ const s = closed(r, [
108
+ "compaction",
109
+ "retry",
110
+ "httpIdleTimeoutMs",
111
+ "transport",
112
+ "images",
113
+ "cacheWarming",
114
+ ...[
115
+ "websocketConnectTimeoutMs",
116
+ "thinkingBudgets",
117
+ "shellPath",
118
+ "shellCommandPrefix",
119
+ ].filter((key) => Object.hasOwn(r ?? {}, key)),
120
+ ]);
121
+ const c = closed(s.compaction, [
122
+ "enabled",
123
+ "reserveTokens",
124
+ "keepRecentTokens",
125
+ ]);
126
+ const retry = closed(s.retry, [
127
+ "enabled",
128
+ "maxRetries",
129
+ "baseDelayMs",
130
+ "maxAgentDelayMs",
131
+ "provider",
132
+ ]);
133
+ const provider = closed(retry.provider, [
134
+ "maxRetries",
135
+ "maxRetryDelayMs",
136
+ ...(Object.hasOwn(retry.provider ?? {}, "timeoutMs") ? ["timeoutMs"] : []),
137
+ ]);
138
+ const images = closed(s.images, ["autoResize", "blockImages"]);
139
+ const milliseconds = (v) => integer(v, 0, 2147483647);
140
+ const names = (v) => {
141
+ const result = list(v, 64, (name) => text(name, 128, true));
142
+ if (new Set(result).size !== result.length)
143
+ throw new Error("Duplicate Pi tool selection");
144
+ return result;
145
+ };
146
+ const budgets = s.thinkingBudgets;
147
+ if (budgets !== undefined) {
148
+ closed(
149
+ budgets,
150
+ ["minimal", "low", "medium", "high"].filter((key) =>
151
+ Object.hasOwn(budgets, key),
152
+ ),
153
+ );
154
+ for (const value of Object.values(budgets)) integer(value, 0);
155
+ }
156
+ if (s.cacheWarming !== "off" || provider.maxRetries !== 0)
157
+ throw new Error("Invalid service policy");
158
+ return {
159
+ projectTrusted: bool(o.projectTrusted),
160
+ tools: { edit: names(t.edit), readonly: names(t.readonly) },
161
+ settings: {
162
+ compaction: {
163
+ enabled: bool(c.enabled),
164
+ reserveTokens: integer(c.reserveTokens, 0),
165
+ keepRecentTokens: integer(c.keepRecentTokens, 0),
166
+ },
167
+ retry: {
168
+ enabled: bool(retry.enabled),
169
+ maxRetries: integer(retry.maxRetries, 0),
170
+ baseDelayMs: milliseconds(retry.baseDelayMs),
171
+ maxAgentDelayMs: milliseconds(retry.maxAgentDelayMs),
172
+ provider: {
173
+ maxRetries: 0,
174
+ maxRetryDelayMs: milliseconds(provider.maxRetryDelayMs),
175
+ ...(provider.timeoutMs === undefined
176
+ ? {}
177
+ : { timeoutMs: milliseconds(provider.timeoutMs) }),
178
+ },
179
+ },
180
+ httpIdleTimeoutMs: milliseconds(s.httpIdleTimeoutMs),
181
+ ...(s.websocketConnectTimeoutMs === undefined
182
+ ? {}
183
+ : {
184
+ websocketConnectTimeoutMs: milliseconds(
185
+ s.websocketConnectTimeoutMs,
186
+ ),
187
+ }),
188
+ transport: oneOf(s.transport, [
189
+ "auto",
190
+ "sse",
191
+ "websocket",
192
+ "websocket-cached",
193
+ ]),
194
+ ...(budgets === undefined ? {} : { thinkingBudgets: budgets }),
195
+ images: {
196
+ autoResize: bool(images.autoResize),
197
+ blockImages: bool(images.blockImages),
198
+ },
199
+ ...(s.shellPath === undefined
200
+ ? {}
201
+ : { shellPath: text(s.shellPath, 4096) }),
202
+ ...(s.shellCommandPrefix === undefined
203
+ ? {}
204
+ : { shellCommandPrefix: text(s.shellCommandPrefix, 8192) }),
205
+ cacheWarming: "off",
206
+ },
207
+ };
208
+ }
209
+
210
+ export function describeWorkerRuntime(runtime) {
211
+ const { settings: s, tools } = runtime;
212
+ return `Pi runtime: project settings ${runtime.projectTrusted ? "trusted" : "not loaded"}; tools ${tools.edit.join(", ") || "none"}; readonly ${tools.readonly.join(", ") || "none"}; auto-compaction ${s.compaction.enabled ? "on" : "off"} (reserve ${s.compaction.reserveTokens}, keep ${s.compaction.keepRecentTokens}); request retries ${s.retry.enabled ? s.retry.maxRetries : "off"}; HTTP idle ${s.httpIdleTimeoutMs === 0 ? "disabled" : `${s.httpIdleTimeoutMs}ms`}; shell ${s.shellPath || s.shellCommandPrefix ? "configured" : "default"}. Provider retries and cache warming are off.`;
213
+ }
214
+
215
+ /** Observation only: AgentSession owns classification, backoff and continuation.
216
+ * Session listeners are synchronous. CaptureEmitter reserves/enqueues before
217
+ * returning its promise; every rejection is handled without leaking SDK text. */
218
+ export class WorkerModelState {
219
+ requestPrepared = false;
220
+ actualResponseStatus = "UNKNOWN";
221
+ retryAttempts = 0;
222
+ progress = null;
223
+ constructor(emit, fail) {
224
+ this.emit = emit;
225
+ this.fail = fail;
226
+ }
227
+ publish(progress) {
228
+ this.progress = progress;
229
+ try {
230
+ return Promise.resolve(this.emit({ kind: "model-retry", progress }));
231
+ } catch (error) {
232
+ return Promise.reject(error);
233
+ }
234
+ }
235
+ event(event) {
236
+ try {
237
+ const type = own(event, "type");
238
+ let pending;
239
+ if (type === "auto_retry_start") {
240
+ const progress = decodeModelRetry({
241
+ phase: "waiting",
242
+ attempt: own(event, "attempt"),
243
+ maxAttempts: own(event, "maxAttempts"),
244
+ delayMs: own(event, "delayMs"),
245
+ });
246
+ this.retryAttempts = progress.attempt;
247
+ pending = this.publish(progress);
248
+ } else if (type === "auto_retry_end" && this.progress) {
249
+ // This event is not proof of success, native closure or task completion.
250
+ pending = this.publish(null);
251
+ }
252
+ pending?.catch(() => this.fail());
253
+ } catch {
254
+ this.fail();
255
+ }
256
+ }
257
+ async beginRequest() {
258
+ // Each attempt owns its observations, including one that gets no response.
259
+ this.requestPrepared = false;
260
+ this.actualResponseStatus = "UNKNOWN";
261
+ if (!this.progress) {
262
+ this.retryAttempts = 0;
263
+ return;
264
+ }
265
+ try {
266
+ await this.publish({ ...this.progress, phase: "requesting", delayMs: 0 });
267
+ } catch (error) {
268
+ this.fail();
269
+ throw error;
270
+ }
271
+ }
272
+ }
273
+
274
+ /** One private, sequential request at a time. Replies contain credentials only
275
+ * on the owner/child IPC pipe, never in capture or a tool result. No retry here.
276
+ * SDK availability checks and prompt/request auth can overlap in ONE worker;
277
+ * worker-reservation limits are not an admission limit for these callers.
278
+ * Await their originals in order, keeping at most one owner request in flight.
279
+ * Abort is owned by the session; disconnect is a real loss of its auth owner. */
280
+ export function ownerAuth(channel, retain, fail = () => {}) {
281
+ let sequence = 0;
282
+ let pending;
283
+ let tail = Promise.resolve();
284
+ let closed = false;
285
+ const disconnect = () => {
286
+ closed = true;
287
+ if (pending) fail("owner-auth-lost");
288
+ pending?.reject(new Error("Owner authentication channel disconnected"));
289
+ pending = undefined;
290
+ };
291
+ const message = (value) => {
292
+ if (value?.kind !== "auth" || !pending || value.id !== pending.id) return;
293
+ const waiting = pending;
294
+ pending = undefined;
295
+ if (!value.ok || !value.auth?.ok) {
296
+ fail("owner-auth-refused");
297
+ waiting.reject(new Error("Owner authentication refused"));
298
+ return;
299
+ }
300
+ retain(value.auth);
301
+ waiting.resolve(value.auth);
302
+ };
303
+ channel.on("message", message);
304
+ channel.on("disconnect", disconnect);
305
+ return {
306
+ resolve() {
307
+ if (closed || !channel.connected)
308
+ return Promise.reject(new Error("Owner authentication unavailable"));
309
+ const original = tail.then(
310
+ () =>
311
+ new Promise((resolve, reject) => {
312
+ if (closed || !channel.connected) {
313
+ reject(new Error("Owner authentication unavailable"));
314
+ return;
315
+ }
316
+ const id = ++sequence;
317
+ pending = { id, resolve, reject };
318
+ try {
319
+ channel.send({ kind: "auth", id }, (error) => {
320
+ if (error) disconnect();
321
+ });
322
+ } catch {
323
+ disconnect();
324
+ }
325
+ }),
326
+ );
327
+ tail = original.then(
328
+ () => {},
329
+ () => {},
330
+ );
331
+ return original;
332
+ },
333
+ close() {
334
+ disconnect();
335
+ channel.removeListener("message", message);
336
+ channel.removeListener("disconnect", disconnect);
337
+ },
338
+ };
339
+ }