@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.
@@ -18,8 +18,12 @@ import {
18
18
  } from "@earendil-works/pi-ai";
19
19
  import {
20
20
  createAgentSession,
21
+ createCodingTools,
21
22
  createExtensionRuntime,
22
23
  createLocalBashOperations,
24
+ createLocalPowerShellOperations,
25
+ createPowerShellTool,
26
+ createReadOnlyTools,
23
27
  ModelRuntime,
24
28
  SessionManager,
25
29
  SettingsManager,
@@ -32,6 +36,13 @@ import {
32
36
  WEBUI_SESSION_ENTRY,
33
37
  } from "./session-entries.mjs";
34
38
  import { CaptureEmitter, SdkCapture } from "./worker-capture.mjs";
39
+ import {
40
+ decodeWorkerRuntime,
41
+ defaultWorkerTools,
42
+ ownerAuth,
43
+ resolveWorkerRuntime,
44
+ WorkerModelState,
45
+ } from "./worker-model.mjs";
35
46
  import {
36
47
  closed,
37
48
  decodeWorkerPublicRequest,
@@ -61,9 +72,12 @@ const adapters = {
61
72
  };
62
73
  let session;
63
74
  let toolkit;
64
- let ownsCoordinatorChannel = false;
75
+ let authChannel;
76
+ let ownsChannel = false;
65
77
  let ownedAgent;
66
78
  let unsubscribe;
79
+ let unsubscribeRetry;
80
+ let modelState;
67
81
  let emitter;
68
82
  let capture;
69
83
  let ingress;
@@ -75,8 +89,6 @@ let modelOutputBytes = 0;
75
89
  let stage = "guards";
76
90
  let failure;
77
91
  let terminalStopReason = "UNKNOWN";
78
- let requestPrepared = false;
79
- let actualResponseStatus = "UNKNOWN";
80
92
  let preflight = "UNKNOWN";
81
93
  let cleanupFailures = 0; // Bit flags: unsubscribe=1, abort=2, session/tool dispose=4, owned close=8.
82
94
  let pendingAbort;
@@ -102,7 +114,12 @@ const fail = (where, category) => {
102
114
  ? "cleanup"
103
115
  : where === "network"
104
116
  ? "network"
105
- : ["prompt", "preflight", "assistant-final"].includes(where)
117
+ : [
118
+ "prompt",
119
+ "preflight",
120
+ "assistant-final",
121
+ "auth-model",
122
+ ].includes(where)
106
123
  ? "prompt"
107
124
  : "capture",
108
125
  })
@@ -190,30 +207,22 @@ const emitFailure = () => {
190
207
  const line = `${JSON.stringify({
191
208
  ...failure,
192
209
  outcome: "failed",
193
- sdkEvents: Math.min(sdkEvents, LIMITS.sdkEvents + 1),
210
+ sdkEvents: sdkEvents,
194
211
  inputBytes: Math.min(inputBytes, 128 * 1024 + 1),
195
- modelOutputBytes: Math.min(modelOutputBytes, LIMITS.childProtocolBytes + 1),
196
- protocolBytes: Math.min(
197
- bytes + (emitter?.state.bytes ?? 0),
198
- LIMITS.childProtocolBytes + 1,
199
- ),
212
+ modelOutputBytes: modelOutputBytes,
213
+ protocolBytes: bytes + (emitter?.state.bytes ?? 0),
200
214
  terminalStopReason,
201
215
  preflight,
202
- requestPrepared,
203
- actualResponseStatus,
216
+ requestPrepared: modelState?.requestPrepared ?? false,
217
+ actualResponseStatus: modelState?.actualResponseStatus ?? "UNKNOWN",
218
+ retryAttempts: modelState?.retryAttempts ?? 0,
204
219
  cleanupFailures,
205
220
  cleanupSettled,
206
221
  })}\n`;
207
- // Diagnostic output shares the existing aggregate cap, not a new allowance.
222
+ // Fixed-size diagnostics, independent of cumulative protocol traffic.
208
223
  const write = (text) => {
209
- const size = Buffer.byteLength(text);
210
- if (
211
- bytes + (emitter?.state.bytes ?? 0) + size <=
212
- LIMITS.childProtocolBytes
213
- ) {
214
- bytes += size;
215
- process.stderr.write(text);
216
- }
224
+ bytes += Buffer.byteLength(text);
225
+ process.stderr.write(text);
217
226
  };
218
227
  if (Buffer.byteLength(line) <= 512) write(line);
219
228
  if (cleanupSettled)
@@ -265,6 +274,8 @@ try {
265
274
  "cwd",
266
275
  "model",
267
276
  "auth",
277
+ ...(Object.hasOwn(parsed ?? {}, "runtime") ? ["runtime"] : []),
278
+ ...(Object.hasOwn(parsed ?? {}, "ownerAuth") ? ["ownerAuth"] : []),
268
279
  ...(Object.hasOwn(parsed ?? {}, "conversation") ? ["conversation"] : []),
269
280
  ...(Object.hasOwn(parsed ?? {}, "investigation") ? ["investigation"] : []),
270
281
  ]);
@@ -303,7 +314,7 @@ try {
303
314
  const investigation =
304
315
  envelope.investigation === undefined
305
316
  ? null
306
- : closed(envelope.investigation, ["roots", "timeoutMs"]);
317
+ : closed(envelope.investigation, ["roots"]);
307
318
  if (
308
319
  investigation &&
309
320
  (!Array.isArray(investigation.roots) ||
@@ -311,10 +322,7 @@ try {
311
322
  investigation.roots.length > 8 ||
312
323
  investigation.roots.some(
313
324
  (p) => typeof p !== "string" || !p || p.length > 4096,
314
- ) ||
315
- !Number.isSafeInteger(investigation.timeoutMs) ||
316
- investigation.timeoutMs < 100 ||
317
- investigation.timeoutMs > LIMITS.workerMs)
325
+ ))
318
326
  )
319
327
  refuse("parse", "invalid-investigation");
320
328
  const publicRequest = decodeWorkerPublicRequest(envelope.request);
@@ -366,31 +374,81 @@ try {
366
374
  model.api !== publicRequest.model.api
367
375
  )
368
376
  refuse("auth-model", "unsupported-model");
377
+ stage = "settings";
378
+ const workerRuntime =
379
+ envelope.runtime === undefined
380
+ ? resolveWorkerRuntime(
381
+ SettingsManager.inMemory(),
382
+ model,
383
+ defaultWorkerTools(
384
+ { createCodingTools, createReadOnlyTools, createPowerShellTool },
385
+ cwd,
386
+ ),
387
+ )
388
+ : decodeWorkerRuntime(envelope.runtime);
369
389
  stage = "setup";
370
390
  const api = await adapters[model.api]();
371
- if (proxy) {
372
- stage = "network";
373
- try {
374
- // SDK/adapter imports can reset native startup routing. Configure only
375
- // this disposable child, using our declared public peer after imports.
376
- const { EnvHttpProxyAgent, setGlobalDispatcher, getGlobalDispatcher } =
377
- await import("undici");
378
- if (
379
- typeof EnvHttpProxyAgent !== "function" ||
380
- typeof setGlobalDispatcher !== "function" ||
381
- typeof getGlobalDispatcher !== "function"
382
- )
383
- refuse("network", "unsupported-network");
384
- ownedAgent = new EnvHttpProxyAgent(proxy);
385
- // Retain ownership even when installation or its identity check fails.
386
- setGlobalDispatcher(ownedAgent);
387
- if (getGlobalDispatcher() !== ownedAgent)
388
- refuse("network", "unsupported-network");
389
- } catch {
391
+ stage = "network";
392
+ try {
393
+ // SDK settings supply request timeouts, not the CLI's dispatcher setup.
394
+ // Own both direct and proxy stream-idle timeouts in this disposable child.
395
+ const {
396
+ Agent,
397
+ EnvHttpProxyAgent,
398
+ setGlobalDispatcher,
399
+ getGlobalDispatcher,
400
+ } = await import("undici");
401
+ if (
402
+ typeof (proxy ? EnvHttpProxyAgent : Agent) !== "function" ||
403
+ typeof setGlobalDispatcher !== "function" ||
404
+ typeof getGlobalDispatcher !== "function"
405
+ )
390
406
  refuse("network", "unsupported-network");
391
- }
407
+ const timeouts = {
408
+ headersTimeout: workerRuntime.settings.httpIdleTimeoutMs,
409
+ bodyTimeout: workerRuntime.settings.httpIdleTimeoutMs,
410
+ };
411
+ ownedAgent = proxy
412
+ ? new EnvHttpProxyAgent({ ...proxy, ...timeouts })
413
+ : new Agent(timeouts);
414
+ // Retain ownership even when installation or its identity check fails.
415
+ setGlobalDispatcher(ownedAgent);
416
+ if (getGlobalDispatcher() !== ownedAgent)
417
+ refuse("network", "unsupported-network");
418
+ } catch {
419
+ refuse("network", "unsupported-network");
392
420
  }
393
421
  stage = "setup";
422
+ const secrets = [
423
+ auth.apiKey ?? "",
424
+ ...Object.values(auth.headers ?? {}).filter((v) => typeof v === "string"),
425
+ ...Object.values(auth.env ?? {}),
426
+ ...(proxy ? [proxy.httpProxy] : []),
427
+ ];
428
+ if (
429
+ envelope.ownerAuth !== undefined &&
430
+ (envelope.ownerAuth !== true || !process.send)
431
+ )
432
+ refuse("parse", "invalid-auth-channel");
433
+ ownsChannel = coordinator || envelope.ownerAuth === true;
434
+ if (envelope.ownerAuth === true) {
435
+ authChannel = ownerAuth(
436
+ process,
437
+ (next) => {
438
+ for (const value of [
439
+ next.apiKey,
440
+ ...Object.values(next.headers ?? {}),
441
+ ...Object.values(next.env ?? {}),
442
+ ])
443
+ if (typeof value === "string" && value && !secrets.includes(value))
444
+ secrets.push(value);
445
+ },
446
+ (category) => fail("auth-model", category),
447
+ );
448
+ process.once("disconnect", () => {
449
+ if (session && !cleanupSettled) abortForFailure();
450
+ });
451
+ }
394
452
  const runtime = await ModelRuntime.create({
395
453
  credentials: new InMemoryCredentialStore(),
396
454
  modelsStore: new InMemoryModelsStore(),
@@ -406,14 +464,17 @@ try {
406
464
  auth: {
407
465
  apiKey: {
408
466
  name: "Resolved parent request",
409
- resolve: async () => ({
410
- auth: {
411
- apiKey: auth.apiKey,
412
- headers: auth.headers,
413
- baseUrl: auth.baseUrl,
414
- },
415
- env: auth.env,
416
- }),
467
+ resolve: async () => {
468
+ const current = authChannel ? await authChannel.resolve() : auth;
469
+ return {
470
+ auth: {
471
+ apiKey: current.apiKey,
472
+ headers: current.headers,
473
+ baseUrl: current.baseUrl,
474
+ },
475
+ env: current.env,
476
+ };
477
+ },
417
478
  },
418
479
  },
419
480
  }),
@@ -441,12 +502,6 @@ try {
441
502
  throw new Error("Discovery disabled");
442
503
  },
443
504
  };
444
- const secrets = [
445
- auth.apiKey ?? "",
446
- ...Object.values(auth.headers ?? {}).filter((v) => typeof v === "string"),
447
- ...Object.values(auth.env ?? {}),
448
- ...(proxy ? [proxy.httpProxy] : []),
449
- ];
450
505
  const captureFailure = () => {
451
506
  fail("events", "event-projection-failed");
452
507
  abortForFailure();
@@ -468,6 +523,7 @@ try {
468
523
  ? openConversation(target, workspace.cwd, model, requestedThinkingLevel)
469
524
  : SessionManager.inMemory(workspace.cwd);
470
525
  toolkit = createWorkerToolkit({
526
+ runtime: workerRuntime,
471
527
  workspace,
472
528
  purpose: publicRequest.purpose,
473
529
  changes: publicRequest.changes,
@@ -476,9 +532,9 @@ try {
476
532
  secrets,
477
533
  fail: captureFailure,
478
534
  createLocalBashOperations,
535
+ createLocalPowerShellOperations,
479
536
  queue: emitter.queue,
480
537
  });
481
- ownsCoordinatorChannel = coordinator;
482
538
  const created = await createAgentSession({
483
539
  ...toolkit.sessionOptions,
484
540
  agentDir: workspace.cwd,
@@ -494,11 +550,7 @@ try {
494
550
  )
495
551
  : resourceLoader,
496
552
  sessionManager: manager,
497
- settingsManager: SettingsManager.inMemory({
498
- compaction: { enabled: false },
499
- retry: { enabled: false },
500
- cacheWarming: "off",
501
- }),
553
+ settingsManager: SettingsManager.inMemory(workerRuntime.settings),
502
554
  });
503
555
  session = created.session;
504
556
  let effectiveThinkingLevel;
@@ -515,14 +567,37 @@ try {
515
567
  effectiveThinkingLevel !== requestedThinkingLevel
516
568
  )
517
569
  refuse("session", "model-substitution");
518
- // Adapter retry defaults are not workflow retries; explicitly disable both.
570
+ // A selected tool must really be active. SDK/extension defaults cannot
571
+ // silently substitute, add, or discard the owner's inherited tool set.
572
+ const activeTools = session.getActiveToolNames();
573
+ if (
574
+ activeTools.length !== toolkit.sessionOptions.tools.length ||
575
+ toolkit.sessionOptions.tools.some((name) => !activeTools.includes(name))
576
+ )
577
+ refuse("session", "tool-substitution");
578
+ modelState = new WorkerModelState(
579
+ (event) => emitter.emit(event),
580
+ captureFailure,
581
+ );
582
+ unsubscribeRetry = session.subscribe((event) => modelState.event(event));
583
+ // AgentSession alone retries a failed model response. No provider retries,
584
+ // second prompt, worker restart, model substitution or tool replay.
519
585
  const stream = session.agent.streamFunction;
520
- session.agent.streamFunction = (selected, context, options) => {
586
+ session.agent.streamFunction = async (selected, context, options) => {
587
+ await modelState.beginRequest();
588
+ if (failure) refuse("events", "event-projection-failed");
589
+ if (
590
+ selected.id !== model.id ||
591
+ selected.provider !== model.provider ||
592
+ selected.api !== model.api ||
593
+ session.thinkingLevel !== requestedThinkingLevel
594
+ )
595
+ refuse("session", "model-substitution");
521
596
  const snapshot = { ...options, maxRetries: 0 };
522
597
  const { onPayload, onResponse } = snapshot;
523
598
  snapshot.onPayload = function (...args) {
524
599
  // Preparation is not proof of sending, an HTTP response or inference.
525
- requestPrepared = true;
600
+ modelState.requestPrepared = true;
526
601
  return onPayload == null
527
602
  ? undefined
528
603
  : Reflect.apply(onPayload, this, args);
@@ -530,11 +605,11 @@ try {
530
605
  snapshot.onResponse = function (...args) {
531
606
  // Observation must not bypass the original callback, even for a bad peer.
532
607
  // Public HTTP hook only; WS transports may never report a status here.
533
- actualResponseStatus = "UNKNOWN";
608
+ modelState.actualResponseStatus = "UNKNOWN";
534
609
  try {
535
610
  const status = args[0]?.status;
536
611
  if (Number.isInteger(status) && status >= 100 && status <= 599)
537
- actualResponseStatus = status;
612
+ modelState.actualResponseStatus = status;
538
613
  } catch {
539
614
  // Do not inspect/coerce the response or exception.
540
615
  }
@@ -561,7 +636,6 @@ try {
561
636
  unsubscribe = session.agent.subscribe(async (event) => {
562
637
  try {
563
638
  sdkEvents++;
564
- if (sdkEvents > LIMITS.sdkEvents) refuse("outputbounds", "event-bound");
565
639
  if (own(event, "type") === "message_update") {
566
640
  const update = own(event, "assistantMessageEvent");
567
641
  const type = own(update, "type");
@@ -569,8 +643,6 @@ try {
569
643
  const delta = own(update, "delta");
570
644
  if (typeof delta !== "string") throw new Error("Malformed SDK event");
571
645
  modelOutputBytes += Buffer.byteLength(delta);
572
- if (modelOutputBytes > LIMITS.childProtocolBytes)
573
- refuse("outputbounds", "model-output-bound");
574
646
  }
575
647
  }
576
648
  if (own(event, "type") === "message_end") {
@@ -688,7 +760,7 @@ try {
688
760
  publicRequest.context,
689
761
  ...(!conversation && kind !== "code"
690
762
  ? [
691
- `Investigation roots: ${JSON.stringify(workspace.roots)}. Relative file-tool paths use the first root; select other roots explicitly. Start with these paths rather than broad parent trees. Total worker deadline: ${investigation?.timeoutMs ?? LIMITS.workerMs}ms, including model and tool time; activity never extends it. Report observed evidence, truncation and unresolved questions honestly.`,
763
+ `Investigation roots: ${JSON.stringify(workspace.roots)}. Relative file-tool paths use the first root; select other roots explicitly. Start with these paths rather than broad parent trees. There is no total runtime deadline. Report observed evidence, truncation and unresolved questions honestly.`,
692
764
  ]
693
765
  : []),
694
766
  ...publicRequest.handoff.inputs.map(
@@ -708,6 +780,8 @@ try {
708
780
  },
709
781
  });
710
782
  stage = "assistant-final";
783
+ if (!failure && terminalStopReason === "error")
784
+ refuse("assistant-final", "model-request-failed");
711
785
  if (failure || terminalStopReason !== "stop" || ingress.frames !== 0)
712
786
  refuse("assistant-final", "terminal-incomplete");
713
787
  await capture.final();
@@ -732,14 +806,16 @@ try {
732
806
  fail("cleanup", "cleanup-failure");
733
807
  }
734
808
  })();
735
- const unsubscribing = (async () => {
736
- try {
737
- await unsubscribe?.();
738
- } catch {
739
- cleanupFailures |= 1;
740
- fail("cleanup", "cleanup-failure");
741
- }
742
- })();
809
+ const unsubscribing = Promise.all(
810
+ [unsubscribeRetry, unsubscribe].map(async (stopListening) => {
811
+ try {
812
+ await stopListening?.();
813
+ } catch {
814
+ cleanupFailures |= 1;
815
+ fail("cleanup", "cleanup-failure");
816
+ }
817
+ }),
818
+ );
743
819
  const aborting = (async () => {
744
820
  if (!session) return;
745
821
  try {
@@ -786,5 +862,6 @@ try {
786
862
  // A failed diagnostic write cannot print an arbitrary exception or repair failure.
787
863
  process.exitCode = 1;
788
864
  }
789
- if (ownsCoordinatorChannel && process.connected) process.disconnect();
865
+ authChannel?.close();
866
+ if (ownsChannel && process.connected) process.disconnect();
790
867
  }
@@ -1,4 +1,5 @@
1
1
  import { IMAGE_LIMITS, IMAGE_TYPES } from "../../image-content.mjs";
2
+ import { decodeModelRetry, type ModelRetry } from "../../worker-public.mjs";
2
3
  /** Finite, authenticated workbench API. Ordinary chat is not task admission. */
3
4
  import {
4
5
  bool,
@@ -257,6 +258,8 @@ export interface ChatItem {
257
258
  }
258
259
  export interface ChatTurn {
259
260
  execution?: ExecutionContext;
261
+ /** Active model-request recovery only; never a persisted resumption command. */
262
+ retry?: ModelRetry;
260
263
  id: string;
261
264
  epoch: string;
262
265
  status: ChatStatus;
@@ -288,6 +291,7 @@ export interface ChatStep {
288
291
  /** One turn of a conversation branch: a user message and what followed it. */
289
292
  export interface ChatTurnHeader {
290
293
  execution?: ExecutionContext;
294
+ retry?: ModelRetry;
291
295
  /** The user message's session entry id; a browser command id while Pi has not
292
296
  * written that message yet. */
293
297
  id: string;
@@ -884,6 +888,7 @@ export function decodeChatTurn(v: unknown): ChatTurn {
884
888
  ...(current ? ["omitted"] : []),
885
889
  ...(paged ? ["transcript"] : []),
886
890
  ...(Object.hasOwn(v ?? {}, "execution") ? ["execution"] : []),
891
+ ...(Object.hasOwn(v ?? {}, "retry") ? ["retry"] : []),
887
892
  ]);
888
893
  const transcript = paged ? closed(o.transcript, ["pages"]) : null;
889
894
  const omitted = current
@@ -893,6 +898,7 @@ export function decodeChatTurn(v: unknown): ChatTurn {
893
898
  ...(o.execution === undefined
894
899
  ? {}
895
900
  : { execution: decodeExecutionContext(o.execution) }),
901
+ ...(o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) }),
896
902
  id: decodeId(o.id),
897
903
  epoch: decodeId(o.epoch),
898
904
  status: oneOf(o.status, statuses),
@@ -982,6 +988,7 @@ function decodeChatTurnHeader(v: unknown): ChatTurnHeader {
982
988
  "steps",
983
989
  "stable",
984
990
  ...(Object.hasOwn(v ?? {}, "execution") ? ["execution"] : []),
991
+ ...(Object.hasOwn(v ?? {}, "retry") ? ["retry"] : []),
985
992
  "entry",
986
993
  "at",
987
994
  ]);
@@ -991,6 +998,7 @@ function decodeChatTurnHeader(v: unknown): ChatTurnHeader {
991
998
  ...(o.execution === undefined
992
999
  ? {}
993
1000
  : { execution: decodeExecutionContext(o.execution) }),
1001
+ ...(o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) }),
994
1002
  id: decodeEntryId(o.id),
995
1003
  entry: nullable(o.entry, decodeEntryId),
996
1004
  at: integer(o.at, 0),
@@ -32,7 +32,7 @@ export const WORKFLOW_LIMITS = {
32
32
  export interface WorkflowCheck {
33
33
  name: string;
34
34
  command: string;
35
- timeoutMs: number;
35
+ timeoutMs?: number;
36
36
  }
37
37
  export interface WorkflowTask {
38
38
  id: string;
@@ -109,7 +109,12 @@ export interface WorkflowProposal {
109
109
  plan: WorkflowPlan;
110
110
  cwd: string;
111
111
  checkoutRoot?: string;
112
- display?: { model: string; branch: string; baseCommit: string };
112
+ display?: {
113
+ model: string;
114
+ branch: string;
115
+ baseCommit: string;
116
+ runtime?: string;
117
+ };
113
118
  }
114
119
  export interface WorkflowTiming {
115
120
  createdAt: number;
@@ -118,7 +123,7 @@ export interface WorkflowTiming {
118
123
  stopRequestedAt: number | null;
119
124
  closedAt: number | null;
120
125
  settledAt: number | null;
121
- timeoutMs: number;
126
+ timeoutMs?: number;
122
127
  stopReason: string | null;
123
128
  }
124
129
  export interface WorkflowDiagnostics {
@@ -260,11 +265,17 @@ const taskId = (v: unknown, strict = false) => {
260
265
  return s;
261
266
  };
262
267
  export function decodeWorkflowCheck(v: unknown): WorkflowCheck {
263
- const o = closed(v, ["name", "command", "timeoutMs"]);
268
+ const o = closed(v, [
269
+ "name",
270
+ "command",
271
+ ...(Object.hasOwn(v ?? {}, "timeoutMs") ? ["timeoutMs"] : []),
272
+ ]);
264
273
  return {
265
274
  name: text(o.name, 128, true),
266
275
  command: text(o.command, 4096, true),
267
- timeoutMs: integer(o.timeoutMs, 100, 1_200_000),
276
+ ...(o.timeoutMs === undefined
277
+ ? {}
278
+ : { timeoutMs: integer(o.timeoutMs, 100, 2_147_483_647) }),
268
279
  };
269
280
  }
270
281
  export function workflowOrder(tasks: WorkflowTask[]): WorkflowTask[] {
@@ -616,8 +627,16 @@ export function decodeWorkflowProposal(v: unknown): WorkflowProposal {
616
627
  ...(modern
617
628
  ? {
618
629
  display: (() => {
619
- const d = closed(o.display, ["model", "branch", "baseCommit"]);
630
+ const d = closed(o.display, [
631
+ "model",
632
+ "branch",
633
+ "baseCommit",
634
+ ...(Object.hasOwn(o.display ?? {}, "runtime") ? ["runtime"] : []),
635
+ ]);
620
636
  return {
637
+ ...(d.runtime === undefined
638
+ ? {}
639
+ : { runtime: text(d.runtime, 4096, true) }),
621
640
  model: text(d.model, 1024, true),
622
641
  branch: text(d.branch, 1024),
623
642
  baseCommit: text(d.baseCommit, 64),
@@ -834,7 +853,7 @@ export function readableWorkflowPlan(p: WorkflowPlan): string {
834
853
  )
835
854
  .join(
836
855
  "\n\n",
837
- )}\n\n## Setup (explicitly authorized commands)\n${p.setup.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "None; no dependency installation or copying."}\n\n## Baseline verification\n${p.baselineChecks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "No separate baseline checks declared."}\n\n## Verification\n${p.checks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n")}\n\n## Automation boundary\n${p.version === 2 ? "Authorize diagnosis, partial-work continuation, task splitting and alternative implementations within these goals, decisions, write paths and exact setup/check commands. No fixed repair-round or delivery-duration quota. Only actual verification and independent Agent review permit delivery." : `Historical fixed pipeline: at most ${p.repairAttempts} repair rounds.`} ${p.delivery === "local-merge" ? "Authorize one new named task branch and stable isolated worktree after approval, local commits and fast-forward delivery of the exact checked and Agent-reviewed candidate into the displayed target. Keep the task branch; retain any worktree with uncommitted, untracked or ignored residue." : "Direct working-copy edits; failures leave actual edits for inspection. No Git commit or merge."} No push, publication, deployment, unplanned installation or recursive delegation. Related project knowledge and workflow Markdown are included. Worktrees/tools are not a sandbox.\n\n## Project knowledge\n${p.version === 2 ? p.knowledge?.join("\n") || "No documentation edits authorized; existing knowledge is still read." : p.projectContext}\n`;
856
+ )}\n\n## Setup (explicitly authorized commands)\n${p.setup.map((c) => `${c.name}: ${c.command} (${c.timeoutMs === undefined ? "no timeout" : `${c.timeoutMs}ms`})`).join("\n") || "None; no dependency installation or copying."}\n\n## Baseline verification\n${p.baselineChecks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs === undefined ? "no timeout" : `${c.timeoutMs}ms`})`).join("\n") || "No separate baseline checks declared."}\n\n## Verification\n${p.checks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs === undefined ? "no timeout" : `${c.timeoutMs}ms`})`).join("\n")}\n\n## Automation boundary\n${p.version === 2 ? "Authorize diagnosis, partial-work continuation, task splitting and alternative implementations within these goals, decisions, write paths and exact setup/check commands. No fixed repair-round or delivery-duration quota. Only actual verification and independent Agent review permit delivery." : `Historical fixed pipeline: at most ${p.repairAttempts} repair rounds.`} ${p.delivery === "local-merge" ? "Authorize one new named task branch and stable isolated worktree after approval, local commits and fast-forward delivery of the exact checked and Agent-reviewed candidate into the displayed target. Keep the task branch; retain any worktree with uncommitted, untracked or ignored residue." : "Direct working-copy edits; failures leave actual edits for inspection. No Git commit or merge."} No push, publication, deployment, unplanned installation or recursive delegation. Related project knowledge and workflow Markdown are included. Worktrees/tools are not a sandbox.\n\n## Project knowledge\n${p.version === 2 ? p.knowledge?.join("\n") || "No documentation edits authorized; existing knowledge is still read." : p.projectContext}\n`;
838
857
  }
839
858
 
840
859
  const timestamp = (v: unknown) => integer(v, 0, 8640000000000000);
@@ -846,7 +865,7 @@ function decodeWorkflowTiming(v: unknown): WorkflowTiming {
846
865
  "stopRequestedAt",
847
866
  "closedAt",
848
867
  "settledAt",
849
- "timeoutMs",
868
+ ...(Object.hasOwn(v ?? {}, "timeoutMs") ? ["timeoutMs"] : []),
850
869
  "stopReason",
851
870
  ]);
852
871
  return {
@@ -856,8 +875,12 @@ function decodeWorkflowTiming(v: unknown): WorkflowTiming {
856
875
  stopRequestedAt: nullable(o.stopRequestedAt, timestamp),
857
876
  closedAt: nullable(o.closedAt, timestamp),
858
877
  settledAt: nullable(o.settledAt, timestamp),
859
- timeoutMs: integer(o.timeoutMs, 100, 1200000),
860
- stopReason: nullable(o.stopReason, (v) => text(v, 32, true)),
878
+ ...(o.timeoutMs === undefined
879
+ ? {}
880
+ : { timeoutMs: integer(o.timeoutMs, 100, 2_147_483_647) }),
881
+ // Current summaries include source and target; old short outcome labels
882
+ // remain readable without inventing provenance for them.
883
+ stopReason: nullable(o.stopReason, (v) => text(v, 320, true)),
861
884
  };
862
885
  }
863
886
  function decodeWorkflowDiagnostics(v: unknown): WorkflowDiagnostics {
@@ -900,7 +923,7 @@ export function workflowDiagnostics(run: WorkflowRun): string {
900
923
  ...run.steps.flatMap((s) =>
901
924
  s.timing
902
925
  ? [
903
- `${s.id}: preparing ${at(s.timing.createdAt)} · prepared ${at(s.timing.preparedAt)} · spawned ${at(s.timing.startedAt)} · stop ${at(s.timing.stopRequestedAt)} (${s.timing.stopReason ?? "none"}) · direct child closed ${at(s.timing.closedAt)} · settled ${at(s.timing.settledAt)} · total process budget ${s.timing.timeoutMs}ms${s.runtime ? ` · worker SDK ${s.runtime.sdkVersion} · worker hash ${s.runtime.workerHash}` : ""}`,
926
+ `${s.id}: preparing ${at(s.timing.createdAt)} · prepared ${at(s.timing.preparedAt)} · spawned ${at(s.timing.startedAt)} · stop ${at(s.timing.stopRequestedAt)} (${s.timing.stopReason ?? "none"}) · direct child closed ${at(s.timing.closedAt)} · settled ${at(s.timing.settledAt)} · ${s.timing.timeoutMs === undefined ? "no total runtime deadline" : `historical process budget ${s.timing.timeoutMs}ms`}${s.runtime ? ` · worker SDK ${s.runtime.sdkVersion} · worker hash ${s.runtime.workerHash}` : ""}`,
904
927
  ]
905
928
  : [],
906
929
  ),