@abelxiaoxing/cadence 2.0.50 → 2.1.0

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.
@@ -1,16 +1,7 @@
1
1
  // Isolated SDK child, not Pi CLI startup. Task discovery stays disabled;
2
2
  // ordinary conversations explicitly load only context/skills, never extensions.
3
3
  import { createHash } from "node:crypto";
4
- import {
5
- closeSync,
6
- constants,
7
- createReadStream,
8
- fstatSync,
9
- openSync,
10
- readFileSync,
11
- readSync,
12
- writeSync,
13
- } from "node:fs";
4
+ import { createReadStream, readFileSync } from "node:fs";
14
5
  import {
15
6
  createProvider,
16
7
  InMemoryCredentialStore,
@@ -35,7 +26,9 @@ import {
35
26
  BROWSER_COMMAND_ENTRY,
36
27
  WEBUI_SESSION_ENTRY,
37
28
  } from "./session-entries.mjs";
29
+ import { terminateLastLine } from "./session-file.mjs";
38
30
  import { CaptureEmitter, SdkCapture } from "./worker-capture.mjs";
31
+ import { conversationInputs } from "./worker-inputs.mjs";
39
32
  import {
40
33
  decodeWorkerRuntime,
41
34
  defaultWorkerTools,
@@ -77,6 +70,8 @@ let ownsChannel = false;
77
70
  let ownedAgent;
78
71
  let unsubscribe;
79
72
  let unsubscribeRetry;
73
+ let unsubscribeInputs;
74
+ let inputs;
80
75
  let modelState;
81
76
  let emitter;
82
77
  let capture;
@@ -141,32 +136,24 @@ const refuse = (where, category) => {
141
136
  fail(where, category);
142
137
  throw new Error("Worker refused");
143
138
  };
144
- const abortForFailure = () => {
145
- // Attach a rejection handler immediately, including synchronous SDK throws.
146
- // Do not let fire-and-forget abort print a secret-bearing unhandled rejection.
147
- pendingAbort ??= (async () => {
148
- try {
149
- await session.abort();
150
- } catch {
151
- cleanupFailures |= 2;
152
- fail("cleanup", "cleanup-failure");
153
- }
154
- })();
139
+ const abortSession = async () => {
140
+ try {
141
+ await session.abort();
142
+ } catch {
143
+ cleanupFailures |= 2;
144
+ fail("cleanup", "cleanup-failure");
145
+ }
155
146
  };
156
- /** A torn final line (a writer killed mid-line) would swallow the next entry. */
157
- const terminateLastLine = (file) => {
158
- const fd = openSync(
159
- file,
160
- constants.O_RDWR | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0),
161
- );
147
+ const abortForFailure = () => {
148
+ // A stopped or failed turn delivers no further message.
162
149
  try {
163
- const size = fstatSync(fd).size;
164
- const last = Buffer.alloc(1);
165
- if (size > 0 && readSync(fd, last, 0, 1, size - 1) === 1 && last[0] !== 10)
166
- writeSync(fd, "\n");
167
- } finally {
168
- closeSync(fd);
150
+ inputs?.stop();
151
+ } catch {
152
+ fail("cleanup", "cleanup-failure");
169
153
  }
154
+ // Attach a rejection handler immediately, including synchronous SDK throws.
155
+ // Do not let fire-and-forget abort print a secret-bearing unhandled rejection.
156
+ pendingAbort ??= abortSession();
170
157
  };
171
158
  /** The project's Pi session a browser turn writes, as the terminal shares it:
172
159
  * continued from the entry the browser showed, so a session that moved on
@@ -631,11 +618,24 @@ try {
631
618
  session.agent.state.tools = ingress.wrap(
632
619
  toolkit.wrap(session.agent.state.tools),
633
620
  );
634
- const initialLeaf = conversation ? manager.getLeafId() : null;
621
+ if (conversation && process.send) {
622
+ inputs = conversationInputs(process, session, (category) => {
623
+ fail("events", category);
624
+ abortForFailure();
625
+ });
626
+ unsubscribeInputs = session.subscribe((event) => inputs.event(event));
627
+ }
628
+ // The browser message whose entries Pi is writing: this run's own, then
629
+ // each one sent into it, from the moment Pi writes that message.
630
+ let command = publicRequest.runId;
631
+ let initialLeaf = conversation ? manager.getLeafId() : null;
635
632
  let recordedUser = null;
636
633
  unsubscribe = session.agent.subscribe(async (event) => {
637
634
  try {
638
635
  sdkEvents++;
636
+ // A stop requested before this run existed found nothing to abort.
637
+ if (pendingAbort && own(event, "type") === "agent_start")
638
+ void abortSession();
639
639
  if (own(event, "type") === "message_update") {
640
640
  const update = own(event, "assistantMessageEvent");
641
641
  const type = own(update, "type");
@@ -663,15 +663,23 @@ try {
663
663
  )
664
664
  refuse("events", "event-projection-failed");
665
665
  if (own(message, "role") === "user") {
666
- if (recordedUser !== null)
667
- refuse("events", "event-projection-failed");
666
+ if (recordedUser !== null) {
667
+ // Within a reply Pi delivers only the steers it was handed, in
668
+ // that order: this message is the oldest one outstanding.
669
+ const steered = inputs?.delivered();
670
+ if (!steered) refuse("events", "event-projection-failed");
671
+ command = steered.id;
672
+ }
668
673
  recordedUser = entry.id;
669
674
  }
670
675
  if (recordedUser === null)
671
676
  refuse("events", "event-projection-failed");
672
677
  manager.appendCustomEntry(BROWSER_COMMAND_ENTRY, {
673
- commandId: publicRequest.runId,
678
+ commandId: command,
674
679
  userId: recordedUser,
680
+ ...(command === publicRequest.runId
681
+ ? {}
682
+ : { run: publicRequest.runId }),
675
683
  });
676
684
  }
677
685
  if (own(message, "role") === "assistant") {
@@ -779,17 +787,36 @@ try {
779
787
  if (!accepted) fail("preflight", "preflight-rejected");
780
788
  },
781
789
  });
782
- stage = "assistant-final";
783
- if (!failure && terminalStopReason === "error")
784
- refuse("assistant-final", "model-request-failed");
785
- if (failure || terminalStopReason !== "stop" || ingress.frames !== 0)
786
- refuse("assistant-final", "terminal-incomplete");
790
+ for (;;) {
791
+ stage = "assistant-final";
792
+ if (!failure && terminalStopReason === "error")
793
+ refuse("assistant-final", "model-request-failed");
794
+ if (
795
+ failure ||
796
+ pendingAbort ||
797
+ terminalStopReason !== "stop" ||
798
+ ingress.frames !== 0
799
+ )
800
+ refuse("assistant-final", "terminal-incomplete");
801
+ // Only a reply that ended normally is followed by a waiting message: it
802
+ // is this worker's next prompt, never one Pi continues into by itself.
803
+ const next = inputs?.next();
804
+ if (!next) break;
805
+ stage = "prompt";
806
+ command = next.id;
807
+ recordedUser = null;
808
+ initialLeaf = manager.getLeafId();
809
+ terminalStopReason = "UNKNOWN";
810
+ await session.prompt(next.text, { expandPromptTemplates: false });
811
+ }
787
812
  await capture.final();
788
813
  await emitter.drain();
789
814
  } catch {
790
815
  // The stage is a location, not a complete diagnosis of an SDK/provider cause.
791
816
  fail(stage, stage === "parse" ? "parse-failed" : "sdk-failure");
792
817
  } finally {
818
+ // No message arriving from here on is delivered.
819
+ inputs?.close();
793
820
  try {
794
821
  capture?.dispose();
795
822
  } catch {
@@ -807,24 +834,18 @@ try {
807
834
  }
808
835
  })();
809
836
  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
- }),
837
+ [unsubscribeRetry, unsubscribeInputs, unsubscribe].map(
838
+ async (stopListening) => {
839
+ try {
840
+ await stopListening?.();
841
+ } catch {
842
+ cleanupFailures |= 1;
843
+ fail("cleanup", "cleanup-failure");
844
+ }
845
+ },
846
+ ),
818
847
  );
819
- const aborting = (async () => {
820
- if (!session) return;
821
- try {
822
- await session.abort();
823
- } catch {
824
- cleanupFailures |= 2;
825
- fail("cleanup", "cleanup-failure");
826
- }
827
- })();
848
+ const aborting = session ? abortSession() : undefined;
828
849
  const disposing = (async () => {
829
850
  if (!session) return;
830
851
  try {
@@ -78,6 +78,8 @@ export interface ModelChoiceState {
78
78
  }
79
79
  export interface ModelCandidate {
80
80
  images?: boolean;
81
+ /** The model's context window in tokens, when its source states one. */
82
+ contextWindow?: number;
81
83
  provider: string;
82
84
  model: string;
83
85
  api: ModelSelection["api"] | null;
@@ -145,9 +147,13 @@ export function decodeModelCandidate(value: unknown): ModelCandidate {
145
147
  "thinking",
146
148
  "eligibility",
147
149
  ...(Object.hasOwn(value ?? {}, "images") ? ["images"] : []),
150
+ ...(Object.hasOwn(value ?? {}, "contextWindow") ? ["contextWindow"] : []),
148
151
  ]);
149
152
  const candidate: ModelCandidate = {
150
153
  ...(o.images === undefined ? {} : { images: bool(o.images) }),
154
+ ...(o.contextWindow === undefined
155
+ ? {}
156
+ : { contextWindow: integer(o.contextWindow, 1) }),
151
157
  provider: text(o.provider, 128, true),
152
158
  model: text(o.model, 256, true),
153
159
  api: nullable(o.api, (v) => oneOf(v, modelApis)),
@@ -110,7 +110,12 @@ export type WorkbenchRead =
110
110
  | { kind: "workflow-transcript"; id: string; stepId: string }
111
111
  | { kind: "workflow"; id: string; before?: number }
112
112
  | { kind: "conversation-active" }
113
- | { kind: "conversations"; after?: ChatCursor | null }
113
+ | {
114
+ kind: "conversations";
115
+ after?: ChatCursor | null;
116
+ /** Lists only archived conversations, which the history otherwise omits. */
117
+ archived?: true;
118
+ }
114
119
  | {
115
120
  kind: "conversation";
116
121
  id: string;
@@ -142,6 +147,18 @@ export type WorkbenchRead =
142
147
  | { kind: "projects" };
143
148
  /** Maximum UTF-8 bytes of one explicit conversation Send. */
144
149
  export const CONVERSATION_SEND_BYTES = 16 * 1024;
150
+ /** Code points of a conversation name: as many as a listed title shows. */
151
+ export const CONVERSATION_NAME_CHARS = 100;
152
+ /** Messages one running reply takes besides its own, withdrawn ones included;
153
+ * with that message they stay within a session's command index. */
154
+ export const RUN_INPUTS = 32;
155
+ /** Messages sent into one running reply that may be undelivered at a time. */
156
+ export const WAITING_INPUTS = 8;
157
+ /** Encoded bytes of a waiting message's text a conversation read states. */
158
+ export const PENDING_TEXT_BYTES = 256;
159
+ /** Encoded bytes of an undelivered message's text a conversation read states:
160
+ * a whole message unless most of it needs escaping. */
161
+ export const UNDELIVERED_TEXT_BYTES = 2 * CONVERSATION_SEND_BYTES;
145
162
  export type ImageSend = Extract<
146
163
  WorkbenchCommand,
147
164
  { kind: "send" | "cadence-send" }
@@ -224,6 +241,30 @@ export type WorkbenchCommand =
224
241
  images?: string[];
225
242
  model: ChoiceVersion;
226
243
  }
244
+ | {
245
+ /** A message for a reply that is running: `turnId` is that reply's
246
+ * command, as `summary.live` names it. `steer` reaches the model at
247
+ * Pi's next opportunity, after the tool calls in progress and before
248
+ * its next request; `queue` is sent once the reply has ended normally.
249
+ * It takes the reply's directory and model, and carries no images. */
250
+ kind: "conversation-input";
251
+ commandId: string;
252
+ conversationId: string;
253
+ turnId: string;
254
+ epoch: string;
255
+ mode: "steer" | "queue";
256
+ text: string;
257
+ }
258
+ | {
259
+ /** Withdraws a `conversation-input` that still waits: `inputId` is its
260
+ * command. One already handed to Pi or delivered refuses as `conflict`. */
261
+ kind: "conversation-input-cancel";
262
+ commandId: string;
263
+ conversationId: string;
264
+ turnId: string;
265
+ epoch: string;
266
+ inputId: string;
267
+ }
227
268
  | {
228
269
  kind: "interrupt";
229
270
  commandId: string;
@@ -231,6 +272,21 @@ export type WorkbenchCommand =
231
272
  turnId: string;
232
273
  epoch: string;
233
274
  }
275
+ | {
276
+ kind: "conversation-rename";
277
+ commandId: string;
278
+ conversationId: string;
279
+ /** One trimmed line, exactly as Pi will record it; empty clears the name,
280
+ * so the title is the first message again. */
281
+ name: string;
282
+ }
283
+ | {
284
+ kind: "conversation-archive";
285
+ commandId: string;
286
+ conversationId: string;
287
+ /** Whether the history list leaves this conversation out. */
288
+ archived: boolean;
289
+ }
234
290
  | { kind: "open-project"; commandId: string; path: string; epoch: string };
235
291
  export type ChatStatus =
236
292
  | "queued"
@@ -250,7 +306,9 @@ export interface ChatImage {
250
306
  export interface ChatItem {
251
307
  images?: ChatImage[];
252
308
  id: string;
253
- role: "user" | "assistant" | "tool";
309
+ /** `thinking` is one readable thinking block of an assistant message, in its
310
+ * recorded place; its signature is never returned. */
311
+ role: "user" | "assistant" | "tool" | "thinking";
254
312
  text: string;
255
313
  name: string;
256
314
  args: string;
@@ -267,18 +325,23 @@ export interface ChatTurn {
267
325
  notice: string;
268
326
  /** Immutable full-transcript pages; items above are only the latest preview. */
269
327
  transcript?: { pages: number };
270
- /** Content kinds observed and not retained; never written into `notice`.
328
+ /** Content kinds observed and not shown; never written into `notice`.
329
+ * `thinking` in a conversation turn is thinking Pi stored unreadable
330
+ * (redacted or without text), since readable thinking is an item; in a
331
+ * workflow transcript it is thinking the capture did not retain.
271
332
  * `other` is a block of a type Cadence does not recognize. */
272
333
  omitted: { thinking: boolean; media: boolean; other: boolean };
273
334
  }
274
335
  /** One recorded item of a turn as listed. A listing never carries a tool's
275
- * arguments or output and keeps at most `STEP_TEXT_BYTES` of message text;
276
- * the full item is read per step with `conversation-step`, one part at a time. */
336
+ * arguments or output or a thinking block's text, and keeps at most
337
+ * `STEP_TEXT_BYTES` of message text; the full item is read per step with
338
+ * `conversation-step`, one part at a time. */
277
339
  export interface ChatStep {
278
340
  images?: ChatImage[];
279
341
  id: string;
280
342
  role: ChatItem["role"];
281
- /** User or assistant text, a prefix of it when `clipped`; empty for tools. */
343
+ /** User or assistant text, a prefix of it when `clipped`; empty for tools
344
+ * and thinking. */
282
345
  text: string;
283
346
  clipped: boolean;
284
347
  name: string;
@@ -303,17 +366,40 @@ export interface ChatTurnHeader {
303
366
  stable: number;
304
367
  /** The turn's last session entry: a new branch can continue from it. */
305
368
  entry: string | null;
369
+ /** The session entry the turn's user message continues, as Pi recorded it
370
+ * (null: the session's root); the admitted message's own while Pi has not
371
+ * written that message. A message sent with this head starts a branch
372
+ * beside the turn. Absent from a service that predates it. */
373
+ parent?: string | null;
306
374
  /** When the turn began (epoch ms), 0 when unrecorded. */
307
375
  at: number;
308
376
  }
377
+ /** Context size as of the last completed model response on a branch: the
378
+ * tokens that response reported for the model that gave it, without Pi's
379
+ * estimate of what followed. `tokens` is null when a compaction came after
380
+ * that response, so the size is unknown until the next one. */
381
+ export interface ChatContext {
382
+ tokens: number | null;
383
+ provider: string;
384
+ model: string;
385
+ }
309
386
  /** A browser message that left nothing in the session, shown after the branch
310
- * it was sent from: a refusal before any model call or a Cadence control reply. */
387
+ * it was sent from: a refusal before any model call, a Cadence control reply,
388
+ * or a message sent into a reply that ended before delivering it. */
311
389
  export interface ChatAttempt {
312
390
  commandId: string;
313
391
  text: string;
314
392
  status: ChatStatus;
315
393
  notice: string;
316
394
  }
395
+ /** A message sent into a running reply that has not reached the model: shown
396
+ * beside the reply, never as a turn. */
397
+ export interface ChatPending {
398
+ commandId: string;
399
+ mode: "steer" | "queue";
400
+ /** At most `PENDING_TEXT_BYTES` of it, encoded. */
401
+ text: string;
402
+ }
317
403
  /** A user message in a session's tree, linked to the nearest earlier one. */
318
404
  export interface ChatTreeNode {
319
405
  id: string;
@@ -376,13 +462,15 @@ export function chatStep(
376
462
  more = false,
377
463
  ): ChatStep {
378
464
  const tool = item.role === "tool";
379
- const text = tool ? "" : clipText(item.text, STEP_TEXT_BYTES);
465
+ // Read on demand: neither a tool's output nor thinking is in a listing.
466
+ const lazy = tool || item.role === "thinking";
467
+ const text = lazy ? "" : clipText(item.text, STEP_TEXT_BYTES);
380
468
  return {
381
469
  id: item.id,
382
470
  role: item.role,
383
471
  text,
384
472
  ...(item.images?.length ? { images: item.images } : {}),
385
- clipped: !tool && (more || text !== item.text),
473
+ clipped: !lazy && (more || text !== item.text),
386
474
  name: item.name,
387
475
  target: tool ? clipText(toolTarget(item.args), TARGET_BYTES) : "",
388
476
  error: item.error,
@@ -410,6 +498,8 @@ export interface ChatSummary {
410
498
  cadence?: boolean;
411
499
  /** The browser reply in progress, which Stop interrupts. */
412
500
  live?: { commandId: string; epoch: string };
501
+ /** Present only for a conversation the history list leaves out. */
502
+ archived?: true;
413
503
  }
414
504
  export interface FileEntry {
415
505
  name: string;
@@ -472,6 +562,19 @@ export type WorkbenchResult =
472
562
  attempt: ChatAttempt | null;
473
563
  /** Accepted browser commands, not inferred from session entry changes. */
474
564
  commands?: string[];
565
+ /** For the branch read, a live turn's written entries included. Absent
566
+ * when no model response is within the reader's walk of the branch end,
567
+ * or the service predates it. */
568
+ context?: ChatContext;
569
+ /** Messages sent into the reply in progress that have not been
570
+ * delivered, oldest first; one Pi does not hold yet can be withdrawn.
571
+ * Absent when there are none. */
572
+ pending?: ChatPending[];
573
+ /** Messages sent into the branch's last reply that ended without their
574
+ * delivery, oldest first, each with its reason; nothing sends them
575
+ * again. Shown, like `attempt`, until the branch moves on. Absent when
576
+ * there are none. */
577
+ undelivered?: ChatAttempt[];
475
578
  }
476
579
  | {
477
580
  kind: "conversation-tree";
@@ -626,11 +729,18 @@ export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
626
729
  };
627
730
  }
628
731
  case "conversations": {
629
- const after = Object.hasOwn(v as object, "after");
630
- const o = closed(v, ["kind", ...(after ? ["after"] : [])]);
732
+ const after = Object.hasOwn(v as object, "after"),
733
+ archived = Object.hasOwn(v as object, "archived");
734
+ const o = closed(v, [
735
+ "kind",
736
+ ...(after ? ["after"] : []),
737
+ ...(archived ? ["archived"] : []),
738
+ ]);
739
+ if (archived && o.archived !== true) throw new ContractError("invalid");
631
740
  return {
632
741
  kind,
633
742
  ...(after ? { after: nullable(o.after, decodeChatCursor) } : {}),
743
+ ...(archived ? { archived: true as const } : {}),
634
744
  };
635
745
  }
636
746
  case "conversation-active":
@@ -659,6 +769,16 @@ export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
659
769
  }
660
770
  }
661
771
  }
772
+ /** A name Pi records unchanged: one line, trimmed, without control
773
+ * characters, at most `CONVERSATION_NAME_CHARS` code points. */
774
+ function decodeConversationName(v: unknown): string {
775
+ const name = text(v, 4 * CONVERSATION_NAME_CHARS);
776
+ if (name !== name.trim() || /\p{Cc}/u.test(name))
777
+ throw new ContractError("invalid");
778
+ if ([...name].length > CONVERSATION_NAME_CHARS)
779
+ throw new ContractError("oversize");
780
+ return name;
781
+ }
662
782
  export function decodeWorkbenchCommand(v: unknown): WorkbenchCommand {
663
783
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
664
784
  if (kind === "conversation-model") {
@@ -851,21 +971,57 @@ export function decodeWorkbenchCommand(v: unknown): WorkbenchCommand {
851
971
  model: decodeChoiceVersion(o.model),
852
972
  };
853
973
  }
854
- if (kind === "interrupt") {
974
+ if (
975
+ kind === "interrupt" ||
976
+ kind === "conversation-input" ||
977
+ kind === "conversation-input-cancel"
978
+ ) {
855
979
  const o = closed(v, [
856
980
  "kind",
857
981
  "commandId",
858
982
  "conversationId",
859
983
  "turnId",
860
984
  "epoch",
985
+ ...(kind === "conversation-input"
986
+ ? ["mode", "text"]
987
+ : kind === "conversation-input-cancel"
988
+ ? ["inputId"]
989
+ : []),
861
990
  ]);
862
- return {
863
- kind,
991
+ const run = {
864
992
  commandId: decodeId(o.commandId),
865
993
  conversationId: decodeSessionId(o.conversationId),
866
994
  turnId: decodeId(o.turnId),
867
995
  epoch: decodeId(o.epoch),
868
996
  };
997
+ if (kind === "conversation-input")
998
+ return {
999
+ kind,
1000
+ ...run,
1001
+ mode: oneOf(o.mode, ["steer", "queue"]),
1002
+ text: text(o.text, CONVERSATION_SEND_BYTES, true),
1003
+ };
1004
+ return kind === "interrupt"
1005
+ ? { kind, ...run }
1006
+ : { kind, ...run, inputId: decodeId(o.inputId) };
1007
+ }
1008
+ if (kind === "conversation-rename") {
1009
+ const o = closed(v, ["kind", "commandId", "conversationId", "name"]);
1010
+ return {
1011
+ kind,
1012
+ commandId: decodeId(o.commandId),
1013
+ conversationId: decodeSessionId(o.conversationId),
1014
+ name: decodeConversationName(o.name),
1015
+ };
1016
+ }
1017
+ if (kind === "conversation-archive") {
1018
+ const o = closed(v, ["kind", "commandId", "conversationId", "archived"]);
1019
+ return {
1020
+ kind,
1021
+ commandId: decodeId(o.commandId),
1022
+ conversationId: decodeSessionId(o.conversationId),
1023
+ archived: bool(o.archived),
1024
+ };
869
1025
  }
870
1026
 
871
1027
  const o = closed(v, ["kind", "commandId", "path", "epoch"]);
@@ -914,6 +1070,7 @@ export function decodeChatTurn(v: unknown): ChatTurn {
914
1070
  items: list(o.items, 256, decodeChatItem),
915
1071
  };
916
1072
  }
1073
+ const ITEM_ROLES = ["user", "assistant", "tool", "thinking"] as const;
917
1074
  function decodeChatImages(v: unknown): ChatImage[] {
918
1075
  return list(v, Number.MAX_SAFE_INTEGER, (value) => {
919
1076
  const o = closed(value, [
@@ -945,7 +1102,7 @@ export function decodeChatItem(v: unknown): ChatItem {
945
1102
  return {
946
1103
  ...(i.images === undefined ? {} : { images: decodeChatImages(i.images) }),
947
1104
  id: text(i.id, 160, true),
948
- role: oneOf(i.role, ["user", "assistant", "tool"]),
1105
+ role: oneOf(i.role, ITEM_ROLES),
949
1106
  text: text(i.text, 256 * 1024),
950
1107
  name: text(i.name, 128),
951
1108
  args: text(i.args, 64 * 1024),
@@ -967,7 +1124,7 @@ function decodeChatStep(v: unknown): ChatStep {
967
1124
  const step = {
968
1125
  ...(o.images === undefined ? {} : { images: decodeChatImages(o.images) }),
969
1126
  id: text(o.id, 160, true),
970
- role: oneOf(o.role, ["user", "assistant", "tool"]),
1127
+ role: oneOf(o.role, ITEM_ROLES),
971
1128
  text: text(o.text, STEP_TEXT_BYTES),
972
1129
  clipped: bool(o.clipped),
973
1130
  name: text(o.name, 128),
@@ -975,7 +1132,13 @@ function decodeChatStep(v: unknown): ChatStep {
975
1132
  error: bool(o.error),
976
1133
  parts: integer(o.parts, 0),
977
1134
  };
978
- if (step.role === "tool" && (step.text || step.clipped))
1135
+ if (
1136
+ (step.role === "tool" || step.role === "thinking") &&
1137
+ (step.text || step.clipped)
1138
+ )
1139
+ throw new ContractError("invalid");
1140
+ // A thinking block is listed only when it has text to read.
1141
+ if (step.role === "thinking" && !step.parts)
979
1142
  throw new ContractError("invalid");
980
1143
  return step;
981
1144
  }
@@ -990,6 +1153,7 @@ function decodeChatTurnHeader(v: unknown): ChatTurnHeader {
990
1153
  ...(Object.hasOwn(v ?? {}, "execution") ? ["execution"] : []),
991
1154
  ...(Object.hasOwn(v ?? {}, "retry") ? ["retry"] : []),
992
1155
  "entry",
1156
+ ...(Object.hasOwn(v ?? {}, "parent") ? ["parent"] : []),
993
1157
  "at",
994
1158
  ]);
995
1159
  const omitted = closed(o.omitted, ["thinking", "media", "other"]);
@@ -1001,6 +1165,9 @@ function decodeChatTurnHeader(v: unknown): ChatTurnHeader {
1001
1165
  ...(o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) }),
1002
1166
  id: decodeEntryId(o.id),
1003
1167
  entry: nullable(o.entry, decodeEntryId),
1168
+ ...(o.parent === undefined
1169
+ ? {}
1170
+ : { parent: nullable(o.parent, decodeEntryId) }),
1004
1171
  at: integer(o.at, 0),
1005
1172
  status: oneOf(o.status, statuses),
1006
1173
  notice: text(o.notice, 1024),
@@ -1025,8 +1192,11 @@ export function decodeChatSummary(v: unknown): ChatSummary {
1025
1192
  "origin",
1026
1193
  ...(has("cadence") ? ["cadence"] : []),
1027
1194
  ...(has("live") ? ["live"] : []),
1195
+ ...(has("archived") ? ["archived"] : []),
1028
1196
  ]);
1029
1197
  const live = has("live") ? closed(o.live, ["commandId", "epoch"]) : null;
1198
+ if (has("archived") && o.archived !== true)
1199
+ throw new ContractError("invalid");
1030
1200
  return {
1031
1201
  id: decodeSessionId(o.id),
1032
1202
  title: text(o.title, 512, true),
@@ -1043,6 +1213,7 @@ export function decodeChatSummary(v: unknown): ChatSummary {
1043
1213
  },
1044
1214
  }
1045
1215
  : {}),
1216
+ ...(has("archived") ? { archived: true as const } : {}),
1046
1217
  };
1047
1218
  }
1048
1219
  function decodeChatAttempt(v: unknown): ChatAttempt {
@@ -1054,6 +1225,22 @@ function decodeChatAttempt(v: unknown): ChatAttempt {
1054
1225
  notice: text(o.notice, 1024),
1055
1226
  };
1056
1227
  }
1228
+ function decodeChatPending(v: unknown): ChatPending {
1229
+ const o = closed(v, ["commandId", "mode", "text"]);
1230
+ return {
1231
+ commandId: decodeId(o.commandId),
1232
+ mode: oneOf(o.mode, ["steer", "queue"]),
1233
+ text: text(o.text, PENDING_TEXT_BYTES),
1234
+ };
1235
+ }
1236
+ function decodeChatContext(v: unknown): ChatContext {
1237
+ const o = closed(v, ["tokens", "provider", "model"]);
1238
+ return {
1239
+ tokens: nullable(o.tokens, (n) => integer(n, 1)),
1240
+ provider: text(o.provider, 128),
1241
+ model: text(o.model, 256),
1242
+ };
1243
+ }
1057
1244
  function decodeChatTreeNode(v: unknown): ChatTreeNode {
1058
1245
  const o = closed(v, ["id", "parent", "text", "at", "leaf", "current"]);
1059
1246
  return {
@@ -1213,6 +1400,9 @@ export function decodeWorkbenchResult(v: unknown): WorkbenchResult {
1213
1400
  "runs",
1214
1401
  "attempt",
1215
1402
  ...(Object.hasOwn(v ?? {}, "commands") ? ["commands"] : []),
1403
+ ...(Object.hasOwn(v ?? {}, "context") ? ["context"] : []),
1404
+ ...(Object.hasOwn(v ?? {}, "pending") ? ["pending"] : []),
1405
+ ...(Object.hasOwn(v ?? {}, "undelivered") ? ["undelivered"] : []),
1216
1406
  ]);
1217
1407
  const summary = nullable(o.summary, decodeChatSummary),
1218
1408
  turns = integer(o.turns, 0);
@@ -1222,6 +1412,17 @@ export function decodeWorkbenchResult(v: unknown): WorkbenchResult {
1222
1412
  ...(o.commands === undefined
1223
1413
  ? {}
1224
1414
  : { commands: list(o.commands, 64, decodeId) }),
1415
+ ...(o.context === undefined
1416
+ ? {}
1417
+ : { context: decodeChatContext(o.context) }),
1418
+ ...(o.pending === undefined
1419
+ ? {}
1420
+ : { pending: list(o.pending, WAITING_INPUTS, decodeChatPending) }),
1421
+ ...(o.undelivered === undefined
1422
+ ? {}
1423
+ : {
1424
+ undelivered: list(o.undelivered, WAITING_INPUTS, decodeChatAttempt),
1425
+ }),
1225
1426
  summary,
1226
1427
  leaf: nullable(o.leaf, decodeEntryId),
1227
1428
  continues: bool(o.continues),