@abelxiaoxing/cadence 2.1.10 → 2.1.13

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.
@@ -1499,6 +1499,15 @@ function decodeCaptureEvent(v) {
1499
1499
  resultCallId
1500
1500
  };
1501
1501
  }
1502
+ case "thinking-activity": {
1503
+ const o = closed(v, ["kind", "messageId", "index", "phase"]);
1504
+ return {
1505
+ kind,
1506
+ messageId: decodeId(o.messageId),
1507
+ index: integer(o.index, 0, LIMITS.dataFrames),
1508
+ phase: oneOf(o.phase, ["active", "complete", "unavailable"])
1509
+ };
1510
+ }
1502
1511
  case "message-text": {
1503
1512
  const o = closed(v, ["kind", "messageId", "blockId", "detailId"]);
1504
1513
  return {
@@ -6170,7 +6179,7 @@ ${p.reviewReads.map(readableReading).join(`
6170
6179
  `)}` : ""}
6171
6180
 
6172
6181
  ## Automation boundary
6173
- ${readableAutomation(p)} Only actual verification and independent Agent review permit delivery. ${p.delivery === "local-merge" ? "Authorize one new named task branch and stable isolated worktree after approval, temporary worktrees beside it for assignments that run side by side, 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 or recursive delegation. Related project knowledge and workflow Markdown are included. Worktrees/tools are not a sandbox.
6182
+ ${readableAutomation(p)} Only actual verification and independent Agent review permit delivery. ${p.delivery === "local-merge" ? "Authorize one new named task branch and stable isolated worktree after approval, temporary worktrees beside it for assignments that run side by side, local commits and serialized fast-forward delivery of the exact checked and Agent-reviewed candidate into the displayed target. Independent conversations may implement in separate candidates; a verified non-overlapping sibling delivery may be merged into this candidate and checked/reviewed again. Conflicts, changed instructions, overlapping inputs or external target drift retain the candidate for a fresh plan. 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 or recursive delegation. Related project knowledge and workflow Markdown are included. Worktrees/tools are not a sandbox.
6174
6183
 
6175
6184
  ## Project documents
6176
6185
  ${p.version === undefined ? p.projectContext : documents.join(`
@@ -6306,6 +6315,7 @@ function chatStep(item, parts, more = false) {
6306
6315
  const text2 = lazy ? "" : clipText(item.text, STEP_TEXT_BYTES);
6307
6316
  return {
6308
6317
  id: item.id,
6318
+ ...presentation(item),
6309
6319
  role: item.role,
6310
6320
  text: text2,
6311
6321
  ...item.images?.length ? { images: item.images } : {},
@@ -6333,6 +6343,7 @@ function decodeWorkbenchRead(v) {
6333
6343
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
6334
6344
  switch (kind) {
6335
6345
  case "conversation-context":
6346
+ case "reload-conversation-models":
6336
6347
  case "conversation-models": {
6337
6348
  const o = closed(v, ["kind", "location"]);
6338
6349
  return { kind, location: decodeConversationLocation(o.location) };
@@ -6772,8 +6783,52 @@ function decodeChatImages(v) {
6772
6783
  };
6773
6784
  });
6774
6785
  }
6786
+ var PRESENTATION_KEYS = ["renderId", "version", "state"];
6787
+ function presentationKeys(v) {
6788
+ return PRESENTATION_KEYS.filter((key) => Object.hasOwn(v ?? {}, key));
6789
+ }
6790
+ function presentation(v) {
6791
+ return {
6792
+ ...v.renderId === undefined ? {} : { renderId: v.renderId },
6793
+ ...v.version === undefined ? {} : { version: v.version },
6794
+ ...v.state === undefined ? {} : { state: v.state }
6795
+ };
6796
+ }
6797
+ function decodePresentation(o) {
6798
+ return {
6799
+ ...o.renderId === undefined ? {} : { renderId: text(o.renderId, 160, true) },
6800
+ ...o.version === undefined ? {} : { version: decodeHash(o.version) },
6801
+ ...o.state === undefined ? {} : {
6802
+ state: oneOf(o.state, [
6803
+ "pending",
6804
+ "streaming",
6805
+ "running",
6806
+ "completed",
6807
+ "failed",
6808
+ "canceled",
6809
+ "unavailable"
6810
+ ])
6811
+ }
6812
+ };
6813
+ }
6814
+ function decodeChatActivity(v) {
6815
+ const o = closed(v, [
6816
+ "kind",
6817
+ "sequence",
6818
+ ...Object.hasOwn(v ?? {}, "name") ? ["name"] : []
6819
+ ]);
6820
+ const kind = oneOf(o.kind, ["waiting", "thinking", "text", "tool"]);
6821
+ if (o.name !== undefined && kind !== "tool")
6822
+ throw new ContractError("invalid");
6823
+ return {
6824
+ kind,
6825
+ sequence: integer(o.sequence, 0),
6826
+ ...o.name === undefined ? {} : { name: text(o.name, 128) }
6827
+ };
6828
+ }
6775
6829
  function decodeChatItem(v) {
6776
6830
  const i = closed(v, [
6831
+ ...presentationKeys(v),
6777
6832
  "id",
6778
6833
  "role",
6779
6834
  "text",
@@ -6783,6 +6838,7 @@ function decodeChatItem(v) {
6783
6838
  ...Object.hasOwn(v ?? {}, "images") ? ["images"] : []
6784
6839
  ]);
6785
6840
  return {
6841
+ ...decodePresentation(i),
6786
6842
  ...i.images === undefined ? {} : { images: decodeChatImages(i.images) },
6787
6843
  id: text(i.id, 160, true),
6788
6844
  role: oneOf(i.role, ITEM_ROLES),
@@ -6794,6 +6850,7 @@ function decodeChatItem(v) {
6794
6850
  }
6795
6851
  function decodeChatStep(v) {
6796
6852
  const o = closed(v, [
6853
+ ...presentationKeys(v),
6797
6854
  "id",
6798
6855
  "role",
6799
6856
  "text",
@@ -6805,6 +6862,7 @@ function decodeChatStep(v) {
6805
6862
  "parts"
6806
6863
  ]);
6807
6864
  const step = {
6865
+ ...decodePresentation(o),
6808
6866
  ...o.images === undefined ? {} : { images: decodeChatImages(o.images) },
6809
6867
  id: text(o.id, 160, true),
6810
6868
  role: oneOf(o.role, ITEM_ROLES),
@@ -6817,12 +6875,23 @@ function decodeChatStep(v) {
6817
6875
  };
6818
6876
  if ((step.role === "tool" || step.role === "thinking") && (step.text || step.clipped))
6819
6877
  throw new ContractError("invalid");
6820
- if (step.role === "thinking" && !step.parts)
6821
- throw new ContractError("invalid");
6878
+ if (step.role === "thinking") {
6879
+ if (!step.parts && !(step.renderId && [
6880
+ "streaming",
6881
+ "completed",
6882
+ "unavailable",
6883
+ "canceled",
6884
+ "failed"
6885
+ ].includes(step.state ?? "")))
6886
+ throw new ContractError("invalid");
6887
+ if (step.parts && step.state !== undefined && step.state !== "completed")
6888
+ throw new ContractError("invalid");
6889
+ }
6822
6890
  return step;
6823
6891
  }
6824
6892
  function decodeChatTurnHeader(v) {
6825
6893
  const o = closed(v, [
6894
+ ...Object.hasOwn(v ?? {}, "activity") ? ["activity"] : [],
6826
6895
  "id",
6827
6896
  "status",
6828
6897
  "notice",
@@ -6838,6 +6907,7 @@ function decodeChatTurnHeader(v) {
6838
6907
  const omitted = closed(o.omitted, ["thinking", "media", "other"]);
6839
6908
  const steps = integer(o.steps, 0);
6840
6909
  return {
6910
+ ...o.activity === undefined ? {} : { activity: decodeChatActivity(o.activity) },
6841
6911
  ...o.execution === undefined ? {} : { execution: decodeExecutionContext(o.execution) },
6842
6912
  ...o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) },
6843
6913
  id: decodeEntryId(o.id),
@@ -9290,6 +9360,61 @@ function fold(summary, line) {
9290
9360
  summary.stop = stopStatus(m);
9291
9361
  }
9292
9362
  }
9363
+ function commandMarker(entry) {
9364
+ if (entry.type !== "custom" || own2(entry.raw, "customType") !== BROWSER_COMMAND_ENTRY)
9365
+ return;
9366
+ const value = own2(entry.raw, "data");
9367
+ const d = closed(value, [
9368
+ "commandId",
9369
+ "userId",
9370
+ ...Object.hasOwn(value ?? {}, "run") ? ["run"] : [],
9371
+ ...Object.hasOwn(value ?? {}, "captureMessageId") ? ["captureMessageId"] : [],
9372
+ ...Object.hasOwn(value ?? {}, "captureResultCallId") ? ["captureResultCallId"] : []
9373
+ ]);
9374
+ if (d.captureResultCallId !== undefined && d.captureMessageId === undefined)
9375
+ throw new ContractError("corrupt-selected");
9376
+ return {
9377
+ commandId: decodeId(d.commandId),
9378
+ userId: decodeEntryId(d.userId),
9379
+ ...d.run === undefined ? {} : { run: decodeId(d.run) },
9380
+ ...d.captureMessageId === undefined ? {} : { captureMessageId: decodeId(d.captureMessageId) },
9381
+ ...d.captureResultCallId === undefined ? {} : { captureResultCallId: decodeId(d.captureResultCallId) }
9382
+ };
9383
+ }
9384
+ function captureLinks(entries2) {
9385
+ const byId = new Map(entries2.map((e) => [e.id, e]));
9386
+ const commands = new Map;
9387
+ const ids = new Set;
9388
+ const links = new Map;
9389
+ let user;
9390
+ for (const entry of entries2) {
9391
+ if (isUser(entry))
9392
+ user = entry.id;
9393
+ const marker2 = commandMarker(entry);
9394
+ if (!marker2)
9395
+ continue;
9396
+ const first = commands.get(marker2.commandId);
9397
+ const parent = entry.parentId ? byId.get(entry.parentId) : undefined;
9398
+ if (!parent || parent.pos >= entry.pos || parent.type !== "message" || !["user", "assistant", "toolResult"].includes(role2(parent)) || marker2.userId !== user || !first && entry.parentId !== marker2.userId || first && (first.userId !== marker2.userId || first.run !== marker2.run) || marker2.run === marker2.commandId || marker2.captureResultCallId !== undefined && role2(parent) !== "toolResult")
9399
+ throw new ContractError("corrupt-selected");
9400
+ commands.set(marker2.commandId, marker2);
9401
+ if (marker2.captureMessageId) {
9402
+ if (ids.has(marker2.captureMessageId) || links.has(parent.id))
9403
+ throw new ContractError("corrupt-selected");
9404
+ ids.add(marker2.captureMessageId);
9405
+ if (marker2.captureResultCallId) {
9406
+ if (ids.has(marker2.captureResultCallId))
9407
+ throw new ContractError("corrupt-selected");
9408
+ ids.add(marker2.captureResultCallId);
9409
+ }
9410
+ links.set(parent.id, {
9411
+ messageId: marker2.captureMessageId,
9412
+ ...marker2.captureResultCallId ? { resultCallId: marker2.captureResultCallId } : {}
9413
+ });
9414
+ }
9415
+ }
9416
+ return links;
9417
+ }
9293
9418
 
9294
9419
  class ParsedSession {
9295
9420
  path;
@@ -9304,6 +9429,7 @@ class ParsedSession {
9304
9429
  usages = new Map;
9305
9430
  cache = { input: 0, read: 0, write: 0 };
9306
9431
  boundaries = new Map;
9432
+ captureOccurrences = new Map;
9307
9433
  constructor(path) {
9308
9434
  this.path = path;
9309
9435
  }
@@ -9375,6 +9501,11 @@ class ParsedSession {
9375
9501
  if (entry.type === "custom" && own2(entry.raw, "customType") === BROWSER_COMMAND_ENTRY) {
9376
9502
  const data = own2(entry.raw, "data");
9377
9503
  const d = data && typeof data === "object" && !Array.isArray(data) ? data : {};
9504
+ for (const field of ["captureMessageId", "captureResultCallId"]) {
9505
+ const captureId = own2(d, field);
9506
+ if (typeof captureId === "string")
9507
+ this.captureOccurrences.set(captureId, (this.captureOccurrences.get(captureId) ?? 0) + 1);
9508
+ }
9378
9509
  const commandId = own2(d, "commandId");
9379
9510
  if (typeof commandId === "string") {
9380
9511
  const boundary = {
@@ -9413,11 +9544,18 @@ class ParsedSession {
9413
9544
  this.usages.clear();
9414
9545
  this.cache.input = this.cache.read = this.cache.write = 0;
9415
9546
  this.boundaries.clear();
9547
+ this.captureOccurrences.clear();
9416
9548
  this.header = null;
9417
9549
  });
9418
9550
  this.read = next;
9419
9551
  return this;
9420
9552
  }
9553
+ validateCaptures(entries2) {
9554
+ for (const link of captureLinks(entries2).values())
9555
+ for (const id of [link.messageId, link.resultCallId])
9556
+ if (id !== undefined && this.captureOccurrences.get(id) !== 1)
9557
+ throw new ContractError("corrupt-selected");
9558
+ }
9421
9559
  current() {
9422
9560
  return this.entries.at(-1)?.id ?? null;
9423
9561
  }
@@ -9520,7 +9658,7 @@ class ParsedSession {
9520
9658
  }
9521
9659
  if (!this.follows(first.user, run.parent, run.offset))
9522
9660
  throw new ContractError("stale");
9523
- if (sent.some((part) => part.boundaries.some((boundary) => boundary.run !== run.commandId)))
9661
+ if (first.boundaries.some((boundary) => boundary.run !== undefined) || sent.some((part) => part.boundaries.some((boundary) => boundary.run !== run.commandId)))
9524
9662
  throw new ContractError("corrupt-selected");
9525
9663
  const parts = [
9526
9664
  { commandId: run.commandId, ...first },
@@ -9541,7 +9679,9 @@ class ParsedSession {
9541
9679
  return position <= start || position >= end || boundary.user !== part.user.id;
9542
9680
  }))
9543
9681
  throw new ContractError("corrupt-selected");
9544
- return { commandId: part.commandId, entries: chain.slice(start, end) };
9682
+ const entries2 = chain.slice(start, end);
9683
+ this.validateCaptures(entries2);
9684
+ return { commandId: part.commandId, entries: entries2 };
9545
9685
  });
9546
9686
  }
9547
9687
  tree(leaf, secrets) {
@@ -9596,6 +9736,11 @@ function shown(entry) {
9596
9736
  }
9597
9737
  var clip = (value, bytes) => clipText(value, bytes);
9598
9738
  function turnItems(entries2, secrets) {
9739
+ const links = captureLinks(entries2);
9740
+ const userCommands = new Map(entries2.flatMap((entry) => {
9741
+ const marker2 = commandMarker(entry);
9742
+ return marker2 && entry.parentId === marker2.userId ? [[marker2.userId, marker2.commandId]] : [];
9743
+ }));
9599
9744
  const omitted = { thinking: false, media: false, other: false };
9600
9745
  const items = [];
9601
9746
  const tools = new Map;
@@ -9610,8 +9755,19 @@ function turnItems(entries2, secrets) {
9610
9755
  });
9611
9756
  return items[items.length - 1];
9612
9757
  };
9613
- const tool = (id, name, args, text2 = "", error = false) => add({ id, role: "tool", name, args, text: text2, error });
9758
+ const tool = (id, name, args, text2 = "", error = false) => add({
9759
+ id,
9760
+ renderId: `pi:${id}`,
9761
+ role: "tool",
9762
+ name,
9763
+ args,
9764
+ text: text2,
9765
+ error,
9766
+ state: error ? "failed" : "completed"
9767
+ });
9614
9768
  for (const entry of entries2) {
9769
+ const link = links.get(entry.id), captureId = link?.messageId;
9770
+ const renderId = (index) => captureId ? `capture:${captureId}:${index}` : `pi:${entry.id}:${index}`;
9615
9771
  const m = message(entry);
9616
9772
  if (m) {
9617
9773
  const kind = own2(m, "role");
@@ -9625,6 +9781,8 @@ function turnItems(entries2, secrets) {
9625
9781
  add({
9626
9782
  ...images.length ? { images } : {},
9627
9783
  id: entry.id,
9784
+ renderId: userCommands.has(entry.id) ? `command:${userCommands.get(entry.id)}:user` : renderId(0),
9785
+ state: "completed",
9628
9786
  role: "user",
9629
9787
  text: text2,
9630
9788
  name: "",
@@ -9632,50 +9790,64 @@ function turnItems(entries2, secrets) {
9632
9790
  error: false
9633
9791
  });
9634
9792
  } else if (kind === "assistant") {
9635
- let text2;
9636
9793
  const content = own2(m, "content");
9637
- for (const block of Array.isArray(content) ? content : []) {
9794
+ const state = own2(m, "stopReason") === "aborted" ? "canceled" : ["error", "length"].includes(own2(m, "stopReason")) ? "failed" : "completed";
9795
+ for (const [index, block] of (Array.isArray(content) ? content : []).entries()) {
9638
9796
  const b = block && typeof block === "object" ? block : {};
9639
9797
  const type = own2(b, "type");
9640
9798
  if (type === "text" && typeof own2(b, "text") === "string") {
9641
9799
  const value = own2(b, "text");
9642
- if (text2 && items[items.length - 1] === text2)
9643
- text2.text += sanitizeText(`
9644
-
9645
- ${value}`, secrets);
9646
- else
9647
- text2 = add({
9648
- id: `${entry.id}:${items.length}`,
9649
- role: "assistant",
9650
- text: value,
9651
- name: "",
9652
- args: "",
9653
- error: ["error", "aborted", "length"].includes(own2(m, "stopReason"))
9654
- });
9800
+ add({
9801
+ id: `${entry.id}:${index}`,
9802
+ renderId: renderId(index),
9803
+ state,
9804
+ role: "assistant",
9805
+ text: value,
9806
+ name: "",
9807
+ args: "",
9808
+ error: ["error", "aborted", "length"].includes(own2(m, "stopReason"))
9809
+ });
9655
9810
  } else if (type === "toolCall") {
9656
- const id = own2(b, "id"), name = own2(b, "name");
9811
+ const id = own2(b, "id"), name = own2(b, "name"), rawName = typeof name === "string" ? name : "tool";
9657
9812
  let args = "";
9658
9813
  try {
9659
9814
  args = JSON.stringify(own2(b, "arguments") ?? {}) ?? "";
9660
9815
  } catch {
9661
9816
  omitted.other = true;
9662
9817
  }
9663
- const call = tool(typeof id === "string" && id ? id : `${entry.id}:${items.length}`, typeof name === "string" ? name : "tool", args);
9664
- if (typeof id === "string")
9665
- tools.set(id, call);
9818
+ const call = tool(typeof id === "string" && id ? id : `${entry.id}:${index}`, rawName, args);
9819
+ call.renderId = renderId(index);
9820
+ call.state = state === "failed" ? "unavailable" : state === "canceled" ? "canceled" : "pending";
9821
+ if (typeof id === "string") {
9822
+ tools.set(id, tools.has(id) ? null : { rawName, item: call });
9823
+ }
9666
9824
  } else if (type === "thinking" || type === "redactedThinking") {
9667
9825
  const value = own2(b, "thinking");
9668
9826
  if (type === "thinking" && typeof value === "string" && value.trim() && own2(b, "redacted") !== true)
9669
9827
  add({
9670
- id: `${entry.id}:${items.length}`,
9828
+ id: `${entry.id}:${index}`,
9829
+ renderId: renderId(index),
9830
+ state: "completed",
9671
9831
  role: "thinking",
9672
9832
  text: value,
9673
9833
  name: "",
9674
9834
  args: "",
9675
9835
  error: false
9676
9836
  });
9677
- else
9837
+ else {
9678
9838
  omitted.thinking = true;
9839
+ if (captureId)
9840
+ add({
9841
+ id: `${entry.id}:${index}`,
9842
+ renderId: renderId(index),
9843
+ state: "unavailable",
9844
+ role: "thinking",
9845
+ text: "",
9846
+ name: "",
9847
+ args: "",
9848
+ error: false
9849
+ });
9850
+ }
9679
9851
  } else if (type === "image")
9680
9852
  omitted.media = true;
9681
9853
  else
@@ -9686,11 +9858,16 @@ ${value}`, secrets);
9686
9858
  const id = own2(m, "toolCallId"), name = own2(m, "toolName");
9687
9859
  const output = sanitizeText(contentText(own2(m, "content"), omitted), secrets);
9688
9860
  const call = typeof id === "string" ? tools.get(id) : undefined;
9689
- if (call) {
9690
- call.text = output;
9691
- call.error = own2(m, "isError") === true;
9692
- } else
9693
- tool(typeof id === "string" && id ? id : entry.id, typeof name === "string" ? name : "tool", "", output, own2(m, "isError") === true);
9861
+ if (!link?.resultCallId && call && call.rawName === (typeof name === "string" ? name : "tool")) {
9862
+ call.item.text = output;
9863
+ call.item.error = own2(m, "isError") === true;
9864
+ call.item.state = call.item.error ? "failed" : "completed";
9865
+ if (typeof id === "string")
9866
+ tools.delete(id);
9867
+ } else {
9868
+ const orphan = tool(typeof id === "string" && id ? id : entry.id, typeof name === "string" ? name : "tool", "", output, own2(m, "isError") === true);
9869
+ orphan.renderId = link?.resultCallId ? `call:${link.resultCallId}` : renderId(0);
9870
+ }
9694
9871
  } else if (kind === "bashExecution") {
9695
9872
  const command = own2(m, "command"), output = own2(m, "output"), code = own2(m, "exitCode");
9696
9873
  tool(entry.id, "bash", JSON.stringify({
@@ -9707,6 +9884,7 @@ ${value}`, secrets);
9707
9884
  }
9708
9885
  const first = entries2.find(isUser) ?? entries2[0];
9709
9886
  return {
9887
+ captureMessages: [...links.values()].map((link) => link.messageId),
9710
9888
  id: first?.id ?? "",
9711
9889
  entry: entries2.at(-1)?.id ?? null,
9712
9890
  parent: first?.parentId ?? null,
@@ -9747,6 +9925,14 @@ function itemParts(item) {
9747
9925
  }));
9748
9926
  }
9749
9927
  function listTurn(turn) {
9928
+ turn = {
9929
+ ...turn,
9930
+ items: turn.items.map((item) => ({
9931
+ ...item,
9932
+ renderId: item.renderId ?? `pi:${item.id}`,
9933
+ version: createHash7("sha256").update(JSON.stringify([item.text, item.args, item.images ?? []])).digest("hex")
9934
+ }))
9935
+ };
9750
9936
  const parts = turn.items.map(itemParts);
9751
9937
  const steps = turn.items.map((item, index) => {
9752
9938
  const listed = chatStep(item.role === "tool" && item.args.length > TARGET_ARGS ? { ...item, args: "" } : item, 0);
@@ -9924,6 +10110,7 @@ class PiSessions {
9924
10110
  return parsed;
9925
10111
  }
9926
10112
  turn(session, entries2, secrets) {
10113
+ session.validateCaptures(entries2);
9927
10114
  const key = [
9928
10115
  session.path,
9929
10116
  session.incarnation,
@@ -14929,6 +15116,20 @@ var NOT_DELIVERED = "Not delivered: the reply ended before this message reached
14929
15116
  var UNOBSERVED = "Not observed: the session could not be read when the reply ended, so whether this message was delivered was not recorded. Nothing was replayed.";
14930
15117
  var WITHDRAWN = "Withdrawn before it was delivered.";
14931
15118
  var LIVE = ["queued", "running"];
15119
+ function settledSteps(turn) {
15120
+ if (LIVE.includes(turn.status) || !turn.items.some((item) => ["pending", "running", "streaming"].includes(item.state ?? "")))
15121
+ return turn;
15122
+ return {
15123
+ ...turn,
15124
+ ...listTurn({
15125
+ ...turn,
15126
+ items: turn.items.map((item) => ["pending", "running", "streaming"].includes(item.state ?? "") ? {
15127
+ ...item,
15128
+ state: turn.status === "canceled" ? "canceled" : "unavailable"
15129
+ } : item)
15130
+ })
15131
+ };
15132
+ }
14932
15133
  function observedFile(path) {
14933
15134
  try {
14934
15135
  const s = lstatSync15(path);
@@ -15477,18 +15678,19 @@ class ConversationRecords {
15477
15678
  const turn2 = this.sessions.turn(view.session, view.turns[ordinal], secrets);
15478
15679
  const recorded = this.overlay(id, view.session).get(turn2.id);
15479
15680
  const running = view.parts?.slice(0, -1).some((part) => part.entries[0].id === turn2.id);
15681
+ const observed = recorded ? {
15682
+ ...turn2,
15683
+ ...recorded.execution ? { execution: recorded.execution } : {},
15684
+ status: recorded.status,
15685
+ notice: turn2.notice || sanitizeText(recorded.notice, secrets),
15686
+ omitted: {
15687
+ thinking: turn2.omitted.thinking,
15688
+ media: turn2.omitted.media || recorded.omitted.media,
15689
+ other: turn2.omitted.other || recorded.omitted.other
15690
+ }
15691
+ } : running && view.live ? { ...turn2, execution: view.live.execution } : turn2;
15480
15692
  return {
15481
- turn: recorded ? {
15482
- ...turn2,
15483
- ...recorded.execution ? { execution: recorded.execution } : {},
15484
- status: recorded.status,
15485
- notice: turn2.notice || sanitizeText(recorded.notice, secrets),
15486
- omitted: {
15487
- thinking: turn2.omitted.thinking,
15488
- media: turn2.omitted.media || recorded.omitted.media,
15489
- other: turn2.omitted.other || recorded.omitted.other
15490
- }
15491
- } : running && view.live ? { ...turn2, execution: view.live.execution } : turn2,
15693
+ turn: running ? observed : settledSteps(observed),
15492
15694
  stable: turn2.steps.length
15493
15695
  };
15494
15696
  }
@@ -15498,11 +15700,13 @@ class ConversationRecords {
15498
15700
  const parts = view.parts ?? this.liveParts(view.session, live2);
15499
15701
  const chain = parts.at(-1)?.entries ?? [];
15500
15702
  const session = view.session;
15501
- const earlier = session ? parts.slice(0, -1).flatMap((part) => this.sessions.turn(session, part.entries, secrets).items) : [];
15703
+ const earlierTurns = session ? parts.slice(0, -1).map((part) => this.sessions.turn(session, part.entries, secrets)) : [];
15704
+ const earlier = earlierTurns.flatMap((turn2) => turn2.items);
15502
15705
  const written = turnItems(chain, secrets);
15503
15706
  const items = chain.length ? written.items : [
15504
15707
  {
15505
15708
  id: "user",
15709
+ renderId: `command:${live2.commandId}:user`,
15506
15710
  role: "user",
15507
15711
  text: live2.accepted.command.text,
15508
15712
  ...live2.images?.length ? {
@@ -15518,11 +15722,15 @@ class ConversationRecords {
15518
15722
  error: false
15519
15723
  }
15520
15724
  ];
15521
- const extended = live2.capture?.extend(items, earlier) ?? {
15725
+ const extended = live2.capture?.extend(items, earlier, [
15726
+ ...earlierTurns.flatMap((turn2) => turn2.captureMessages ?? []),
15727
+ ...written.captureMessages ?? []
15728
+ ]) ?? {
15522
15729
  items,
15523
15730
  stable: items.length
15524
15731
  };
15525
15732
  const omitted = live2.capture?.omitted;
15733
+ const activity2 = live2.capture?.activity;
15526
15734
  const turn = listTurn({
15527
15735
  id: chain[0]?.id ?? live2.commandId,
15528
15736
  entry: null,
@@ -15531,6 +15739,14 @@ class ConversationRecords {
15531
15739
  status: live2.state.status,
15532
15740
  notice: sanitizeText(live2.capture?.notice ?? "", secrets),
15533
15741
  ...live2.capture?.retry ? { retry: live2.capture.retry } : {},
15742
+ ...activity2 ? {
15743
+ activity: {
15744
+ ...activity2,
15745
+ ...activity2.name === undefined ? {} : {
15746
+ name: clipText(sanitizeText(activity2.name, secrets), 128)
15747
+ }
15748
+ }
15749
+ } : {},
15534
15750
  omitted: {
15535
15751
  thinking: written.omitted.thinking,
15536
15752
  media: written.omitted.media || !!omitted?.media,
@@ -15539,13 +15755,13 @@ class ConversationRecords {
15539
15755
  items: extended.items.map((item) => ({
15540
15756
  ...item,
15541
15757
  text: sanitizeText(item.text, secrets),
15542
- name: sanitizeText(item.name, secrets),
15758
+ name: clipText(sanitizeText(item.name, secrets), 128),
15543
15759
  args: sanitizeText(item.args, secrets)
15544
15760
  }))
15545
15761
  });
15546
15762
  return {
15547
- turn: { ...turn, execution: live2.execution },
15548
- stable: extended.stable
15763
+ turn: { ...settledSteps(turn), execution: live2.execution },
15764
+ stable: LIVE.includes(live2.state.status) ? extended.stable : turn.steps.length
15549
15765
  };
15550
15766
  }
15551
15767
  turnSteps(id, leaf, ordinal, before) {
@@ -15563,6 +15779,7 @@ class ConversationRecords {
15563
15779
  turn: {
15564
15780
  ...turn.execution ? { execution: turn.execution } : {},
15565
15781
  ...turn.retry ? { retry: turn.retry } : {},
15782
+ ...turn.activity ? { activity: turn.activity } : {},
15566
15783
  id: turn.id,
15567
15784
  status: turn.status,
15568
15785
  notice: turn.notice,
@@ -15695,7 +15912,7 @@ class ConversationContexts {
15695
15912
  epoch: owner.epoch,
15696
15913
  accessGeneration: owner.accessGeneration,
15697
15914
  configRev: context.revision + 1,
15698
- catalogId: conversationIdentity(`cadence-context-version:${canonicalJson([this.seed, context, selected2?.sourceSelectionId ?? null])}`),
15915
+ catalogId: conversationIdentity(`cadence-context-version:${canonicalJson([this.seed, this.o.models.catalogGeneration ?? 0, context, selected2?.sourceSelectionId ?? null])}`),
15699
15916
  conversation: { id: context.id, cwd: context.cwd }
15700
15917
  }
15701
15918
  };
@@ -15705,7 +15922,7 @@ class ConversationContexts {
15705
15922
  const { context } = this.records.read(location);
15706
15923
  const catalog = this.o.models.catalog();
15707
15924
  if (before.selected)
15708
- this.o.models.assertCurrent(before.selected);
15925
+ this.o.models.assertCurrent(before.selected, "installed");
15709
15926
  if (canonicalJson(before) !== canonicalJson(this.snapshot(location)))
15710
15927
  throw new ContractError("stale");
15711
15928
  let remembered = context.model;
@@ -16842,7 +17059,7 @@ Content-Length: 0\r
16842
17059
  unavailable();
16843
17060
  return {
16844
17061
  kind: "ok",
16845
- value: a.workbench.read(decodeWorkbenchRead(input))
17062
+ value: await a.workbench.read(decodeWorkbenchRead(input))
16846
17063
  };
16847
17064
  case "workbenchCommand": {
16848
17065
  if (!a.workbench)
@@ -17422,7 +17639,7 @@ async function createGateway(value, hostUrl, source) {
17422
17639
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
17423
17640
  const web = loadWebAssets(source?.webDirectory);
17424
17641
  const build2 = {
17425
- contractHash: "d70dd3e63843be7df42ff10943fcdc78bcd27b881b0ac8222526e8dad7b0e6e2",
17642
+ contractHash: "103e212eee402600c29002528ccc3808b6fbe11ccee275a4d5f2a3d52576c520",
17426
17643
  assets: {
17427
17644
  sourceHash: web.manifest.sourceHash,
17428
17645
  contractHash: web.manifest.contractHash,
@@ -27945,6 +28162,7 @@ class CaptureState {
27945
28162
  this.messages = new Map;
27946
28163
  this.calls = new Map;
27947
28164
  this.blocks = new Map;
28165
+ this.thinkingEntries = 0;
27948
28166
  this.dataFrames = 0;
27949
28167
  this.controlFrames = 0;
27950
28168
  this.bytes = 0;
@@ -27962,7 +28180,7 @@ class CaptureState {
27962
28180
  const control = controlEvent(e.kind);
27963
28181
  this.bytes += encodedBytes ?? utf8Bytes(canonicalJson(frame)) + 1;
27964
28182
  this[control ? "controlFrames" : "dataFrames"]++;
27965
- if (this.details.size + this.messages.size + this.calls.size + this.blocks.size > LIMITS.captureEntries)
28183
+ if (this.details.size + this.messages.size + this.calls.size + this.blocks.size + this.thinkingEntries > LIMITS.captureEntries)
27966
28184
  throw new ContractError("capacity");
27967
28185
  const message2 = (id) => {
27968
28186
  const m = this.messages.get(id);
@@ -28016,7 +28234,8 @@ class CaptureState {
28016
28234
  finalIndices: new Set,
28017
28235
  finalHash: createHash28("sha256"),
28018
28236
  finalBytes: 0,
28019
- finalIndex: -1
28237
+ finalIndex: -1,
28238
+ thinking: new Map
28020
28239
  });
28021
28240
  break;
28022
28241
  case "detail-begin":
@@ -28075,6 +28294,17 @@ class CaptureState {
28075
28294
  this.details.delete(e.detailId);
28076
28295
  break;
28077
28296
  }
28297
+ case "thinking-activity": {
28298
+ const m = message2(e.messageId);
28299
+ requireFact2(!m.ended && m.role === "assistant");
28300
+ const previous = m.thinking.get(e.index);
28301
+ requireFact2(previous === undefined || previous === "active");
28302
+ requireFact2(m.thinking.size < LIMITS.captureEntries || previous !== undefined);
28303
+ if (previous === undefined)
28304
+ this.thinkingEntries++;
28305
+ m.thinking.set(e.index, e.phase);
28306
+ break;
28307
+ }
28078
28308
  case "message-text": {
28079
28309
  const d = this.details.get(e.detailId);
28080
28310
  const o = d?.descriptor.owner;
@@ -28146,6 +28376,9 @@ class CaptureState {
28146
28376
  requireFact2(d.descriptor.owner.index < e.finalBlockCount);
28147
28377
  }
28148
28378
  requireFact2(m.finalIndices.size === e.finalBlockCount && [...m.finalIndices].every((i) => i < e.finalBlockCount));
28379
+ requireFact2([...m.thinking.values()].every((phase) => phase !== "active"));
28380
+ this.thinkingEntries -= m.thinking.size;
28381
+ m.thinking.clear();
28149
28382
  m.ended = true;
28150
28383
  m.final = e.finalDetailId;
28151
28384
  m.stopReason = e.stopReason;
@@ -29250,11 +29483,12 @@ class AuthNetwork {
29250
29483
 
29251
29484
  // src/service/checkout-gate.ts
29252
29485
  var CHECKOUT_WAITERS = 16;
29486
+ var CHECKOUT_READERS = 4;
29253
29487
 
29254
29488
  class CheckoutGate {
29255
29489
  owner;
29256
29490
  waiting = [];
29257
- holder = null;
29491
+ holders = new Set;
29258
29492
  closed = false;
29259
29493
  constructor(owner) {
29260
29494
  this.owner = owner;
@@ -29266,26 +29500,29 @@ class CheckoutGate {
29266
29500
  }
29267
29501
  assertQuiescent() {
29268
29502
  this.assertOpen();
29269
- if (this.holder || this.waiting.length)
29503
+ if (this.holders.size || this.waiting.length)
29270
29504
  throw new ContractError("conflict");
29271
29505
  }
29272
- acquire(id, signal) {
29506
+ acquire(id, signal, access = "exclusive") {
29273
29507
  decodeId(id);
29274
29508
  this.assertOpen();
29275
29509
  if (signal.aborted)
29276
29510
  throw new ContractError("stale");
29277
- if (this.holder?.id === id || this.waiting.some((w) => w.id === id))
29511
+ if ([...this.holders, ...this.waiting].some((w) => w.id === id))
29278
29512
  throw new ContractError("conflict");
29279
29513
  if (this.waiting.length >= CHECKOUT_WAITERS)
29280
29514
  throw new ContractError("capacity");
29281
29515
  const result = new Promise((resolve13, reject) => {
29282
29516
  const abort = () => {
29283
29517
  const at2 = this.waiting.indexOf(waiter);
29284
- if (at2 >= 0)
29518
+ if (at2 >= 0) {
29285
29519
  this.waiting.splice(at2, 1)[0].reject(new ContractError("stale"));
29520
+ this.pump();
29521
+ }
29286
29522
  };
29287
29523
  const waiter = {
29288
29524
  id,
29525
+ access,
29289
29526
  resolve: (permit) => {
29290
29527
  signal.removeEventListener("abort", abort);
29291
29528
  resolve13(permit);
@@ -29307,7 +29544,7 @@ class CheckoutGate {
29307
29544
  w.reject(new ContractError("quarantine"));
29308
29545
  }
29309
29546
  pump() {
29310
- if (this.closed || this.holder || !this.waiting.length)
29547
+ if (this.closed || !this.waiting.length)
29311
29548
  return;
29312
29549
  try {
29313
29550
  this.assertOpen();
@@ -29315,23 +29552,26 @@ class CheckoutGate {
29315
29552
  this.closeAdmission();
29316
29553
  return;
29317
29554
  }
29318
- const waiter = this.waiting.shift();
29319
- if (!waiter)
29320
- return;
29321
- this.holder = waiter;
29322
- const assertHeld = () => {
29323
- this.assertOpen();
29324
- if (this.holder !== waiter)
29325
- throw new ContractError("stale");
29326
- };
29327
- waiter.resolve({
29328
- assertHeld,
29329
- release: () => {
29330
- assertHeld();
29331
- this.holder = null;
29332
- this.pump();
29333
- }
29334
- });
29555
+ while (this.waiting.length) {
29556
+ const waiter = this.waiting[0];
29557
+ if (this.holders.size >= CHECKOUT_READERS || [...this.holders].some((w) => w.access === "exclusive") || waiter.access === "exclusive" && this.holders.size)
29558
+ return;
29559
+ this.waiting.shift();
29560
+ this.holders.add(waiter);
29561
+ const assertHeld = () => {
29562
+ this.assertOpen();
29563
+ if (!this.holders.has(waiter))
29564
+ throw new ContractError("stale");
29565
+ };
29566
+ waiter.resolve({
29567
+ assertHeld,
29568
+ release: () => {
29569
+ assertHeld();
29570
+ this.holders.delete(waiter);
29571
+ this.pump();
29572
+ }
29573
+ });
29574
+ }
29335
29575
  }
29336
29576
  }
29337
29577
 
@@ -29345,11 +29585,13 @@ class OwnerModelChoice {
29345
29585
  revision;
29346
29586
  catalogId = randomUUID23();
29347
29587
  installing = false;
29588
+ generation;
29348
29589
  constructor(options) {
29349
29590
  this.options = options;
29350
29591
  if (choiceOwners.has(options.owner))
29351
29592
  throw new ContractError("conflict");
29352
29593
  this.revision = 1;
29594
+ this.generation = options.models.catalogGeneration;
29353
29595
  if (!Number.isSafeInteger(this.revision))
29354
29596
  throw new ContractError("capacity");
29355
29597
  choiceOwners.add(options.owner);
@@ -29357,6 +29599,11 @@ class OwnerModelChoice {
29357
29599
  snapshot() {
29358
29600
  this.options.owner.lease.assert();
29359
29601
  this.options.access.assertCurrent();
29602
+ if (this.generation !== this.options.models.catalogGeneration) {
29603
+ this.generation = this.options.models.catalogGeneration;
29604
+ this.selection = null;
29605
+ this.catalogId = randomUUID23();
29606
+ }
29360
29607
  return decodeModelChoiceState({
29361
29608
  version: {
29362
29609
  epoch: this.options.owner.lease.registration.epoch,
@@ -29371,7 +29618,7 @@ class OwnerModelChoice {
29371
29618
  const before = this.snapshot();
29372
29619
  const catalog = this.options.models.catalog();
29373
29620
  if (before.selected)
29374
- this.options.models.assertCurrent(before.selected);
29621
+ this.options.models.assertCurrent(before.selected, "installed");
29375
29622
  if (canonicalJson(before) !== canonicalJson(this.snapshot()))
29376
29623
  throw new ContractError("stale");
29377
29624
  let remembered = null;
@@ -29850,6 +30097,11 @@ class OwnerModelContext {
29850
30097
  #loading = false;
29851
30098
  #tail = Promise.resolve();
29852
30099
  #generation = 0;
30100
+ #reload;
30101
+ #previousLiterals = [];
30102
+ get catalogGeneration() {
30103
+ return this.#generation;
30104
+ }
29853
30105
  constructor(options) {
29854
30106
  this.#options = options;
29855
30107
  this.#launch = captureEnvironment(options.environment);
@@ -29868,11 +30120,11 @@ class OwnerModelContext {
29868
30120
  ...entry.selection
29869
30121
  }));
29870
30122
  }
29871
- assertCurrent(selection) {
30123
+ assertCurrent(selection, source = "disk") {
29872
30124
  const selected2 = this.#selected.get(selection.sourceSelectionId);
29873
30125
  if (!selected2 || canonicalSelection(selected2.selection) !== canonicalSelection(selection))
29874
30126
  throw new ContractError("stale");
29875
- this.fresh(selected2);
30127
+ this.fresh(selected2, false, source === "installed" ? this.catalogSource(true) : undefined);
29876
30128
  }
29877
30129
  redactionLiterals(selection) {
29878
30130
  const selected2 = this.#selected.get(selection.sourceSelectionId);
@@ -29904,20 +30156,26 @@ class OwnerModelContext {
29904
30156
  throw new ContractError("oversize");
29905
30157
  return [...new Set(literals)];
29906
30158
  }
29907
- viewRedactionLiterals() {
29908
- return this.catalogLiterals(this.readCatalogSource());
30159
+ viewRedactionLiterals(source = "installed") {
30160
+ this.#options.owner.lease.assert();
30161
+ if (!this.#source || !this.#snapshot)
30162
+ throw new ContractError("unavailable");
30163
+ const current2 = source === "text" ? readPiSnapshot(this.#source) : undefined;
30164
+ const { auth, credentials } = current2 ?? readPiAuth(this.#source);
30165
+ const installed = snapshotLiterals({ ...this.#snapshot, auth, credentials }, this.#launch, [...this.#previousLiterals, ...this.#options.network?.literals ?? []]);
30166
+ return current2 && !sameModels(current2, this.#snapshot) ? snapshotLiterals(current2, this.#launch, installed) : installed;
29909
30167
  }
29910
30168
  get loading() {
29911
30169
  return this.#loading;
29912
30170
  }
29913
30171
  catalog() {
29914
30172
  try {
29915
- const current2 = this.catalogSource();
30173
+ const current2 = this.catalogSource(true);
29916
30174
  const runtime = this.#runtime;
29917
30175
  if (!runtime || !this.#thinking)
29918
30176
  throw new ContractError("unavailable");
29919
30177
  const catalog = projectModelCatalog(runtime, this.#thinking, current2, this.catalogLiterals(current2), (input, snapshot) => this.validateModel(input, snapshot));
29920
- const after = this.catalogSource();
30178
+ const after = this.catalogSource(true);
29921
30179
  if (after.auth.identity !== current2.auth.identity || after.auth.stamp !== current2.auth.stamp)
29922
30180
  throw new ContractError("stale");
29923
30181
  return catalog;
@@ -29925,23 +30183,67 @@ class OwnerModelContext {
29925
30183
  throw new ContractError(error instanceof ContractError ? error.code : "corrupt-selected");
29926
30184
  }
29927
30185
  }
29928
- catalogSource() {
30186
+ catalogSource(installedOnly = false) {
29929
30187
  this.alive();
29930
- return this.readCatalogSource();
29931
- }
29932
- readCatalogSource() {
29933
- this.#options.owner.lease.assert();
29934
30188
  if (this.#loading || !this.#runtime || !this.#snapshot || !this.#source || !this.#thinking)
29935
30189
  throw new ContractError("unavailable");
29936
30190
  if (this.#runtime.getError())
29937
30191
  throw new ContractError("corrupt-selected");
30192
+ if (installedOnly)
30193
+ return { ...this.#snapshot, ...readPiAuth(this.#source) };
29938
30194
  const current2 = readPiSnapshot(this.#source);
29939
30195
  if (!sameModels(this.#snapshot, current2))
29940
30196
  throw new ContractError("stale");
29941
30197
  return current2;
29942
30198
  }
29943
30199
  catalogLiterals(snapshot) {
29944
- return snapshotLiterals(snapshot, this.#launch, this.#options.network?.literals ?? []);
30200
+ return snapshotLiterals(snapshot, this.#launch, this.#options.network?.literals);
30201
+ }
30202
+ async reloadCatalog() {
30203
+ this.alive();
30204
+ if (this.#reload)
30205
+ return this.#reload;
30206
+ const source = this.#source, installed = this.#snapshot;
30207
+ if (!source || !installed || this.#loading)
30208
+ throw new ContractError("unavailable");
30209
+ const before = readPiSnapshot(source);
30210
+ if (sameModels(installed, before))
30211
+ return;
30212
+ this.#reload = (async () => {
30213
+ const runtime = await this.createRuntime(source);
30214
+ this.alive();
30215
+ const after = readPiSnapshot(source);
30216
+ if (!sameModels(before, after) || before.auth.stamp !== after.auth.stamp || before.auth.identity !== after.auth.identity || this.#snapshot !== installed)
30217
+ throw new ContractError("stale");
30218
+ const previous = snapshotLiterals(installed, this.#launch, this.#previousLiterals);
30219
+ snapshotLiterals(after, this.#launch, previous);
30220
+ this.#previousLiterals = previous;
30221
+ this.#runtime = runtime;
30222
+ this.#snapshot = after;
30223
+ this.#selected.clear();
30224
+ this.#retained.clear();
30225
+ ++this.#generation;
30226
+ })();
30227
+ try {
30228
+ await this.#reload;
30229
+ } finally {
30230
+ this.#reload = undefined;
30231
+ }
30232
+ }
30233
+ async createRuntime(source) {
30234
+ const { ModelRuntime } = await import("@earendil-works/pi-coding-agent");
30235
+ const { InMemoryModelsStore } = await import("@earendil-works/pi-ai");
30236
+ const runtime = await ModelRuntime.create({
30237
+ authPath: source.authPath,
30238
+ modelsPath: source.modelsPath,
30239
+ modelsStore: new InMemoryModelsStore,
30240
+ allowModelNetwork: false,
30241
+ refreshOnCreate: false
30242
+ });
30243
+ const refused2 = runtime.getError();
30244
+ if (refused2)
30245
+ throw sdkRefusal(refused2);
30246
+ return runtime;
29945
30247
  }
29946
30248
  replaceSelection(input, beforeInstall) {
29947
30249
  this.#options.owner.assertQuiescent();
@@ -29988,7 +30290,7 @@ class OwnerModelContext {
29988
30290
  }
29989
30291
  async load() {
29990
30292
  this.alive();
29991
- if (this.#loading || this.#pending)
30293
+ if (this.#loading || this.#pending || this.#reload)
29992
30294
  throw new ContractError("capacity");
29993
30295
  const existing = runtimeOwners.get(this.#options.owner);
29994
30296
  if (existing && existing !== this)
@@ -30004,26 +30306,16 @@ class OwnerModelContext {
30004
30306
  const source = piSource(this.#options.agentDir, this.#options.home, this.#options.cwd, this.#launch);
30005
30307
  const before = readPiSnapshot(source);
30006
30308
  const pi = await import("@earendil-works/pi-coding-agent");
30007
- const { ModelRuntime } = pi;
30008
- const { InMemoryModelsStore, getSupportedThinkingLevels } = await import("@earendil-works/pi-ai");
30309
+ const { getSupportedThinkingLevels } = await import("@earendil-works/pi-ai");
30009
30310
  if (this.#options.network)
30010
30311
  await this.#options.network.initialize();
30011
30312
  this.alive();
30012
30313
  const ready2 = readPiSnapshot(source);
30013
30314
  if (ready2.auth.identity !== before.auth.identity || !sameModels(before, ready2))
30014
30315
  throw new ContractError("stale");
30015
- const runtime = await ModelRuntime.create({
30016
- authPath: source.authPath,
30017
- modelsPath: source.modelsPath,
30018
- modelsStore: new InMemoryModelsStore,
30019
- allowModelNetwork: false,
30020
- refreshOnCreate: false
30021
- });
30316
+ const runtime = await this.createRuntime(source);
30022
30317
  this.alive();
30023
30318
  const after = readPiSnapshot(source);
30024
- const refused2 = runtime.getError();
30025
- if (refused2)
30026
- throw sdkRefusal(refused2);
30027
30319
  if (after.auth.identity !== ready2.auth.identity || !sameModels(ready2, after))
30028
30320
  throw new ContractError("stale");
30029
30321
  this.#source = source;
@@ -30086,11 +30378,13 @@ class OwnerModelContext {
30086
30378
  throw new ContractError("unavailable");
30087
30379
  return validateCatalogModel(this.#runtime, this.#thinking, input, current2, this.#launch, this.catalogLiterals(current2));
30088
30380
  }
30089
- fresh(selected2, resolvingOAuth = false) {
30381
+ fresh(selected2, resolvingOAuth = false, installed) {
30090
30382
  this.alive();
30383
+ if (this.#selected.get(selected2.selection.sourceSelectionId) !== selected2)
30384
+ throw new ContractError("stale");
30091
30385
  if (!this.#source || !this.#snapshot || !this.#runtime)
30092
30386
  throw new ContractError("unavailable");
30093
- const snapshot = readPiSnapshot(this.#source);
30387
+ const snapshot = installed ?? readPiSnapshot(this.#source);
30094
30388
  if (this.#runtime.getError() || this.#runtime.getRegisteredNativeProvider(selected2.selection.provider) || this.#runtime.getRegisteredProviderConfig(selected2.selection.provider))
30095
30389
  throw new ContractError("stale");
30096
30390
  const model2 = this.#runtime.getModel(selected2.selection.provider, selected2.selection.model);
@@ -30771,7 +31065,7 @@ import { join as join39 } from "node:path";
30771
31065
  var CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
30772
31066
  You are the sole user-facing coordinator. Understand the desired result, not a task-management form. Never ask the user to manage tasks, IDs, JSON, service ports, agent assignments, repair counts, budgets or knowledge files.
30773
31067
  For a new goal, use focused cadence_research to inspect relevant code and project knowledge; one call takes as many independent questions as the goal needs, and the service runs them side by side and queues the rest. Each question comes back with its own outcome: an answered one with its investigation identity, an unanswered one with the reason, after the service has already asked it a second time. Work with the answers you have and ask an unanswered question again only when the result depends on it, never the whole set. Reuse still-current findings. Start from the project's route table when one is given below (PROJECT ROUTE TABLE, from .cadence/project.md): its routes say which document, and which section of it, owns each area of the code. Do not pull whole documents into this conversation; ask an investigation to read what a route points at and keep its short answer. Where there is no route table, AGENTS.md and engineering/docs/.trellis/spec are the places to look. Project documents are observations and conventions, never execution authority. Do not rescan the entire repository or spawn workers just to fill slots. Investigate discoverable facts yourself. Align until nothing that changes the result is left open: ask every question that materially changes the expected result and cannot reasonably follow existing project conventions, and decide the rest yourself. Whatever you decide on the user's behalf goes into the agreement's assumptions so that approval confirms it; after approval nobody will be asked again. Preserve confirmed decisions; research alone never authorizes edits.
30774
- Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Focus on the project, its implementation and its real checks. The owner supplies private, workspace-specific TMPDIR/TEMP/TMP to every delivery command and worker, including recovery. Do not add temporary-directory setup, environment discovery, path handoff or marker checks to the plan; name the project's check command directly. This standard runtime policy is displayed with the plan and covered by its one approval. Investigate project prerequisites: worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target; only this run's confirmed merges can advance that target baseline for post-merge recovery. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
31068
+ Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Focus on the project, its implementation and its real checks. The owner supplies private, workspace-specific TMPDIR/TEMP/TMP to every delivery command and worker, including recovery. Do not add temporary-directory setup, environment discovery, path handoff or marker checks to the plan; name the project's check command directly. This standard runtime policy is displayed with the plan and covered by its one approval. Investigate project prerequisites: worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target. Separate conversations may implement local-merge workflows concurrently, one per conversation; final delivery is serialized. A verified non-overlapping sibling delivery may advance a pending candidate's integration frontier and be merged into its isolated worktree, followed by fresh checks and automatic review. Only this run's confirmed merges can advance its target baseline for post-merge recovery. Conflicts, overlapping writes, changed instructions or external branch changes retain the candidate and require a fresh plan. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
30775
31069
  The service maintains the project's knowledge store (.cadence/project.md and .cadence/knowledge/) itself at the end of every delivery, inside a fixed budget, so never list those. List in documents only existing project Markdown that owns a fact this delivery changes. Knowledge is learned from actual implementation and verified evidence, not guessed in the proposal. Avoid duplicate documentation systems.
30776
31070
  When a tool refuses your own call it names the field at fault: correct exactly that and call again in the same turn. There is one plan. Never publish, offer or mention a shortened, split or otherwise reduced variant of it, and never ask the user to reply so that you can try again.
30777
31071
  Present a concise delivery expectation with the complete returned agreement available, including your assumptions and what the service may change on its own, then invite one clear approval (the user may type 按计划实施). cadence_start obtains fresh context-bound approval. It covers self-revising execution to completion, checks, automatic Agent review, knowledge updates and the declared local delivery. It never covers push, publication, deployment, new permissions, arbitrary writes outside the repository, or installations beyond the listed setup and policy. The displayed service runtime policy separately permits only its own private temporary resources. You cannot approve yourself. Vague acknowledgement is not consent.
@@ -32350,9 +32644,9 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
32350
32644
  } catch (error) {
32351
32645
  return refusal3("invalid", `${diagnosticText(error instanceof Error && !(error instanceof ContractError) ? error.message : "request: is not valid", 512, this.o.secrets())}. No investigation was started. Correct exactly that and call again in this turn.`);
32352
32646
  }
32353
- const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
32647
+ const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research" && current2.state.runs.includes(r.id)).map((r) => r.id);
32354
32648
  if (busy.length)
32355
- return refusal3("checkout-busy", `An approved workflow (${busy.join(", ")}) is using this checkout. New investigations start only after it settles; meanwhile discuss recorded evidence or use cadence_status. Nothing was started.`);
32649
+ return refusal3("checkout-busy", `This conversation has an approved workflow (${busy.join(", ")}). Wait for it to settle or open another conversation for a separate task; meanwhile use cadence_status. Nothing was started.`);
32356
32650
  const id = randomUUID25(), conversationId = current2.state.id;
32357
32651
  try {
32358
32652
  this.o.workflows.command(id, epoch, {
@@ -32459,6 +32753,8 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
32459
32753
  }
32460
32754
  decide(c, caller, evidence, recording) {
32461
32755
  const { state, file, head } = this.approvalContext(c);
32756
+ if (this.o.workflows.activeRuns().runs.some((run) => run.phase !== "research" && state.runs.includes(run.id)))
32757
+ throw new ContractError("conflict");
32462
32758
  const epoch = this.o.owner.lease.registration.epoch;
32463
32759
  if (c.kind === "cadence-prepare") {
32464
32760
  for (const [id, g2] of this.grants)
@@ -32562,12 +32858,13 @@ class LiveCapture {
32562
32858
  inputImages;
32563
32859
  retry;
32564
32860
  notice = "";
32861
+ activity = { kind: "waiting", sequence: 0 };
32565
32862
  unkept = [{ thinking: false, media: false, other: false }];
32566
32863
  users = 0;
32567
- assistants = [];
32568
- tools = [];
32864
+ messages = new Map;
32865
+ order = [];
32866
+ tools = new Map;
32569
32867
  details = new Map;
32570
- blocks = new Map;
32571
32868
  imageUser;
32572
32869
  constructor(secrets, inputImages = false) {
32573
32870
  this.secrets = secrets;
@@ -32582,39 +32879,103 @@ class LiveCapture {
32582
32879
  bounded(value) {
32583
32880
  return Buffer.byteLength(value) <= PREVIEW_BYTES ? value : `${Buffer.from(value).subarray(0, PREVIEW_BYTES).toString("utf8").replace(/�$/u, "")}${PREVIEW_MARK}`;
32584
32881
  }
32882
+ block(messageId, index, role3) {
32883
+ const message2 = this.messages.get(messageId);
32884
+ if (!message2)
32885
+ return;
32886
+ let item = message2.blocks.get(index);
32887
+ if (!item) {
32888
+ item = {
32889
+ id: `${messageId}:${index}`,
32890
+ renderId: `capture:${messageId}:${index}`,
32891
+ role: role3,
32892
+ text: "",
32893
+ name: "",
32894
+ args: "",
32895
+ error: false,
32896
+ state: role3 === "tool" ? "pending" : "streaming"
32897
+ };
32898
+ message2.blocks.set(index, item);
32899
+ }
32900
+ return item;
32901
+ }
32585
32902
  tool(callId) {
32586
- let tool = this.tools.find((t) => t.id === callId);
32903
+ let tool = this.tools.get(callId);
32587
32904
  if (!tool) {
32588
- tool = { id: callId, name: "", args: "", text: "", error: false };
32589
- this.tools.push(tool);
32590
- const stale = this.tools[this.tools.length - 1 - RECENT_PREVIEWS];
32905
+ tool = {
32906
+ item: {
32907
+ id: callId,
32908
+ renderId: `call:${callId}`,
32909
+ role: "tool",
32910
+ name: "",
32911
+ args: "",
32912
+ text: "",
32913
+ error: false,
32914
+ state: "pending"
32915
+ }
32916
+ };
32917
+ this.tools.set(callId, tool);
32918
+ const stale = [...this.tools.values()].at(-1 - RECENT_PREVIEWS);
32591
32919
  if (stale)
32592
- stale.args = stale.text = "";
32920
+ stale.item.args = stale.item.text = "";
32593
32921
  }
32594
32922
  return tool;
32595
32923
  }
32596
32924
  accept(frame) {
32597
32925
  const e = frame.event;
32926
+ const activity2 = (kind, name) => {
32927
+ this.activity = {
32928
+ kind,
32929
+ sequence: frame.workerSeq,
32930
+ ...name === undefined ? {} : { name }
32931
+ };
32932
+ };
32598
32933
  if (e.kind === "message-start" && e.role === "user") {
32599
32934
  if (this.users++)
32600
32935
  this.unkept.push({ thinking: false, media: false, other: false });
32601
32936
  else if (this.inputImages)
32602
32937
  this.imageUser = e.messageId;
32603
32938
  } else if (e.kind === "message-start" && e.role === "assistant") {
32604
- if (!this.assistants.some((a) => a.id === e.messageId)) {
32605
- this.assistants.push({ id: e.messageId, text: "", error: false });
32606
- const stale = this.assistants[this.assistants.length - 1 - RECENT_PREVIEWS];
32939
+ if (!this.messages.has(e.messageId)) {
32940
+ this.messages.set(e.messageId, { blocks: new Map, ended: false });
32941
+ this.order.push({ messageId: e.messageId });
32942
+ const stale = [...this.messages.values()].at(-1 - RECENT_PREVIEWS);
32607
32943
  if (stale)
32608
- stale.text = "";
32944
+ for (const item of stale.blocks.values())
32945
+ item.text = item.args = "";
32946
+ }
32947
+ } else if (e.kind === "message-start" && e.role === "tool-result") {
32948
+ const tool = e.resultCallId ? this.tools.get(e.resultCallId) : undefined;
32949
+ if (tool)
32950
+ tool.resultMessageId = e.messageId;
32951
+ } else if (e.kind === "thinking-activity") {
32952
+ const item = this.block(e.messageId, e.index, "thinking");
32953
+ if (item)
32954
+ item.state = e.phase === "active" ? "streaming" : e.phase === "complete" ? "completed" : "unavailable";
32955
+ activity2(e.phase === "active" ? "thinking" : "waiting");
32956
+ } else if (e.kind === "call-declaration") {
32957
+ const tool = this.tool(e.callId);
32958
+ const item = this.block(e.declaration.messageId, e.index, "tool");
32959
+ if (item && item !== tool.item) {
32960
+ const { id, renderId } = item;
32961
+ Object.assign(item, tool.item, { id, renderId });
32962
+ tool.item = item;
32609
32963
  }
32964
+ tool.item.name = clipText(sanitizeText(e.name, this.secrets()), 128);
32610
32965
  } else if (e.kind === "tool-start" || e.kind === "tool-end") {
32611
32966
  const tool = this.tool(e.callId);
32612
- tool.name = sanitizeText(e.name, this.secrets()).slice(0, 128);
32967
+ tool.item.name = clipText(sanitizeText(e.name, this.secrets()), 128);
32968
+ if (!e.declaration && !this.order.some((row) => ("callId" in row) && row.callId === e.callId))
32969
+ this.order.push({ callId: e.callId });
32970
+ tool.item.state = e.kind === "tool-start" ? "running" : e.isError ? "failed" : "completed";
32613
32971
  if (e.kind === "tool-end")
32614
- tool.error = e.isError;
32972
+ tool.item.error = e.isError;
32973
+ activity2(e.kind === "tool-start" ? "tool" : "waiting", e.kind === "tool-start" ? tool.item.name : undefined);
32974
+ } else if (e.kind === "tool-update") {
32975
+ activity2("tool", this.tool(e.callId).item.name);
32615
32976
  } else if (e.kind === "detail-begin") {
32616
- const kind = e.descriptor.owner.kind;
32617
- if (kind === "context" || kind === "handoff")
32977
+ const o = e.descriptor.owner;
32978
+ if (o.kind === "context" || o.kind === "handoff" || o.kind === "message-final")
32618
32979
  return;
32619
32980
  if (this.details.size >= 64)
32620
32981
  return;
@@ -32623,6 +32984,8 @@ class LiveCapture {
32623
32984
  sanitizer: new DetailSanitizer(e.descriptor.encoding, this.secrets()),
32624
32985
  text: ""
32625
32986
  });
32987
+ if (o.kind === "message")
32988
+ this.block(o.messageId, o.index, "assistant");
32626
32989
  } else if (e.kind === "detail-chunk" || e.kind === "detail-end") {
32627
32990
  const d = this.details.get(e.detailId);
32628
32991
  if (!d)
@@ -32631,89 +32994,104 @@ class LiveCapture {
32631
32994
  if (Buffer.byteLength(d.text) <= PREVIEW_BYTES)
32632
32995
  d.text += added;
32633
32996
  const o = d.descriptor.owner;
32634
- if (o.kind === "message" && o.stage === "stream") {
32635
- this.blocks.set(o.blockId, { messageId: o.messageId, text: d.text });
32636
- const message2 = this.assistants.find((a) => a.id === o.messageId);
32637
- if (message2)
32638
- message2.text = this.bounded([...this.blocks.values()].filter((b) => b.messageId === o.messageId).map((b) => b.text).join(""));
32639
- } else if (o.kind === "message-final") {
32640
- const message2 = this.assistants.find((a) => a.id === o.messageId);
32641
- if (message2)
32642
- message2.text = this.bounded(d.text);
32643
- } else if (o.kind === "tool") {
32644
- const tool = this.tool(o.callId);
32997
+ if (o.kind === "message" && (o.stage === "stream" || e.kind === "detail-end")) {
32998
+ const item = this.block(o.messageId, o.index, "assistant");
32999
+ if (item) {
33000
+ item.text = this.bounded(d.text);
33001
+ activity2("text");
33002
+ }
33003
+ } else if (o.kind === "tool" && e.kind === "detail-end") {
33004
+ const tool = this.tool(o.callId).item;
32645
33005
  if (o.stage === "execution-arguments" || o.stage === "arguments-final")
32646
33006
  tool.args = this.bounded(d.text);
32647
- if (o.stage === "result" || o.stage === "update-snapshot")
32648
- tool.text = this.bounded(d.text);
33007
+ if (o.stage === "result" || o.stage === "update-snapshot") {
33008
+ let text2 = d.text;
33009
+ if (d.descriptor.encoding === "canonical-json") {
33010
+ try {
33011
+ const value = JSON.parse(d.text);
33012
+ text2 = Array.isArray(value.content) ? value.content.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join(`
33013
+
33014
+ `) : "";
33015
+ } catch {}
33016
+ }
33017
+ tool.text = this.bounded(text2);
33018
+ }
32649
33019
  }
32650
33020
  if (e.kind === "detail-end")
32651
33021
  this.details.delete(e.detailId);
32652
33022
  } else if (e.kind === "message-end") {
32653
- const message2 = this.assistants.find((a) => a.id === e.messageId);
32654
- if (message2)
32655
- message2.error = ["error", "aborted", "length"].includes(e.stopReason);
32656
- for (const [id, block] of this.blocks)
32657
- if (block.messageId === e.messageId)
32658
- this.blocks.delete(id);
33023
+ const message2 = this.messages.get(e.messageId);
33024
+ if (message2) {
33025
+ message2.ended = true;
33026
+ for (const [index, item] of message2.blocks) {
33027
+ if (index >= e.finalBlockCount && item.role !== "thinking") {
33028
+ message2.blocks.delete(index);
33029
+ continue;
33030
+ }
33031
+ if (item.role === "assistant") {
33032
+ item.error = ["error", "aborted", "length"].includes(e.stopReason);
33033
+ item.state = e.stopReason === "aborted" ? "canceled" : item.error ? "failed" : "completed";
33034
+ } else if (item.role === "thinking" && (item.state === "streaming" || ["error", "aborted"].includes(e.stopReason)))
33035
+ item.state = "unavailable";
33036
+ else if (item.role === "tool" && item.state === "pending" && ["error", "aborted", "length"].includes(e.stopReason))
33037
+ item.state = e.stopReason === "aborted" ? "canceled" : "unavailable";
33038
+ }
33039
+ activity2("waiting");
33040
+ }
32659
33041
  } else if (e.kind === "model-retry") {
32660
33042
  this.retry = e.progress ?? undefined;
33043
+ activity2("waiting");
32661
33044
  } else if (e.kind === "worker-failure") {
32662
33045
  this.retry = undefined;
32663
33046
  this.notice = `worker-failure: ${e.code}`;
32664
- } else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff" && !(this.inputImages && e.block.sourceType === "image" && e.block.owner.kind === "message" && e.block.owner.messageId === this.imageUser))
33047
+ for (const message2 of this.messages.values())
33048
+ for (const item of message2.blocks.values())
33049
+ if (["streaming", "running", "pending"].includes(item.state ?? ""))
33050
+ item.state = "unavailable";
33051
+ for (const { item } of this.tools.values())
33052
+ if (["running", "pending"].includes(item.state ?? ""))
33053
+ item.state = "unavailable";
33054
+ activity2("waiting");
33055
+ } else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff" && !(this.inputImages && e.block.sourceType === "image" && e.block.owner.kind === "message" && e.block.owner.messageId === this.imageUser)) {
32665
33056
  this.omitted[OMITTED_FLAG[e.block.reason]] = true;
33057
+ }
32666
33058
  }
32667
- extend(items, earlier = []) {
32668
- const out = [...earlier, ...items].map((item) => ({ ...item }));
32669
- let written = 0, counted;
32670
- for (const item of out) {
32671
- if (item.role === "assistant") {
32672
- const at2 = item.id.lastIndexOf(":");
32673
- const message2 = at2 < 0 ? item.id : item.id.slice(0, at2);
32674
- if (message2 !== counted)
32675
- written++;
32676
- counted = message2;
32677
- } else if (item.role !== "thinking")
32678
- counted = undefined;
32679
- }
32680
- const calls = out.filter((i) => i.role === "tool");
32681
- const results = calls.filter((i) => i.text || i.error).length;
32682
- let stable = out.length;
32683
- this.tools.forEach((tool, index) => {
32684
- if (index < results)
32685
- return;
32686
- const item = index < calls.length ? calls[index] : (() => {
32687
- const added = {
32688
- id: tool.id,
32689
- role: "tool",
32690
- name: tool.name,
32691
- args: tool.args,
32692
- text: "",
32693
- error: false
32694
- };
32695
- out.push(added);
32696
- return added;
32697
- })();
32698
- item.text = tool.text;
32699
- item.error = tool.error;
33059
+ extend(items, earlier = [], writtenMessages = []) {
33060
+ const out = items.map((item) => ({ ...item }));
33061
+ const written = new Set(writtenMessages);
33062
+ const previous = new Set(earlier.map((item) => item.renderId));
33063
+ const changing = out.findIndex((item) => ["pending", "running", "streaming"].includes(item.state ?? ""));
33064
+ let stable = changing < 0 ? out.length : changing;
33065
+ for (const tool of this.tools.values()) {
33066
+ const matches = out.filter((item2) => item2.role === "tool" && item2.renderId === tool.item.renderId);
33067
+ if (matches.length !== 1)
33068
+ continue;
33069
+ const item = matches[0];
33070
+ if (item.state !== "pending" && item.state !== "running")
33071
+ continue;
33072
+ item.text = tool.item.text;
33073
+ item.args = tool.item.args || item.args;
33074
+ item.state = tool.item.state;
33075
+ item.error = tool.item.error;
32700
33076
  stable = Math.min(stable, out.indexOf(item));
32701
- });
32702
- this.assistants.slice(written).forEach((message2) => {
32703
- stable = Math.min(stable, out.length);
32704
- out.push({
32705
- id: message2.id,
32706
- role: "assistant",
32707
- text: message2.text,
32708
- name: "",
32709
- args: "",
32710
- error: message2.error
32711
- });
32712
- });
32713
- return {
32714
- items: out.slice(earlier.length),
32715
- stable: Math.max(0, stable - earlier.length)
32716
- };
33077
+ }
33078
+ for (const row of this.order) {
33079
+ if ("messageId" in row && written.has(row.messageId))
33080
+ continue;
33081
+ if ("callId" in row) {
33082
+ const result = this.tools.get(row.callId)?.resultMessageId;
33083
+ if (result && written.has(result))
33084
+ continue;
33085
+ }
33086
+ const blocks = "messageId" in row ? [...this.messages.get(row.messageId)?.blocks.entries() ?? []].sort(([a], [b]) => a - b).map(([, item]) => item) : [this.tool(row.callId).item];
33087
+ for (const item of blocks) {
33088
+ if (previous.has(item.renderId) || out.some((existing) => existing.renderId === item.renderId))
33089
+ continue;
33090
+ stable = Math.min(stable, out.length);
33091
+ out.push({ ...item });
33092
+ }
33093
+ }
33094
+ return { items: out, stable };
32717
33095
  }
32718
33096
  }
32719
33097
 
@@ -34099,12 +34477,16 @@ class WorkflowDelivery {
34099
34477
  save;
34100
34478
  token;
34101
34479
  children = new Map;
34480
+ frontier;
34481
+ base;
34102
34482
  home;
34103
34483
  constructor(view, resources, save) {
34104
34484
  this.view = view;
34105
34485
  this.resources = resources;
34106
34486
  this.save = save;
34107
34487
  this.home = dirname25(view.worktreeRoot);
34488
+ this.frontier = view.binding.target.head;
34489
+ this.base = view.binding.target.head;
34108
34490
  }
34109
34491
  prepareHome() {
34110
34492
  assertRepository(this.view.binding.target);
@@ -34261,26 +34643,51 @@ class WorkflowDelivery {
34261
34643
  rmdirSync(dirname25(path));
34262
34644
  } catch {}
34263
34645
  }
34646
+ frontierHead() {
34647
+ return this.frontier;
34648
+ }
34649
+ candidateBase() {
34650
+ return this.base;
34651
+ }
34652
+ advanceFrontier(expected, head) {
34653
+ if (this.view.integration.status !== "pending" || this.frontier !== expected)
34654
+ return false;
34655
+ this.frontier = head;
34656
+ return true;
34657
+ }
34658
+ needsRefresh() {
34659
+ return this.frontier !== this.base;
34660
+ }
34661
+ refreshed(candidate) {
34662
+ if (!this.needsRefresh())
34663
+ throw new ContractError("stale");
34664
+ this.update(candidate);
34665
+ this.base = this.frontier;
34666
+ }
34264
34667
  targetHead() {
34265
34668
  const i = this.view.integration;
34266
34669
  if (i.status === "pending")
34267
- return this.view.binding.target.head;
34670
+ return this.frontier;
34268
34671
  if (i.status === "applied" && i.after)
34269
34672
  return i.after;
34270
34673
  throw new ContractError("stale");
34271
34674
  }
34272
- async assertAccepted(digest2, execution, scope) {
34675
+ async assertAcceptedCandidate(digest2, execution, scope) {
34273
34676
  const a = this.view.acceptance, candidate = this.view.candidate;
34274
34677
  if (!a || !candidate || a.candidate !== candidate || a.planDigest !== digest2 || a.contextDigest !== hash(canonicalJson(execution)) || await this.assertTip() !== candidate)
34275
34678
  throw new ContractError("stale");
34276
34679
  await assertCandidate(this.view.worktreeRoot, candidate);
34277
- await assertCommittedScope(this.view.worktreeRoot, this.view.binding.target.head, candidate, scope);
34680
+ await assertCommittedScope(this.view.worktreeRoot, this.base, candidate, scope);
34278
34681
  if ((await gitText(this.view.worktreeRoot, [
34279
34682
  "rev-parse",
34280
34683
  `${candidate}^{tree}`
34281
34684
  ])).trim() !== a.tree)
34282
34685
  throw new ContractError("stale");
34283
34686
  assertRepository(this.view.binding.target);
34687
+ return candidate;
34688
+ }
34689
+ async assertAccepted(digest2, execution, scope) {
34690
+ const candidate = await this.assertAcceptedCandidate(digest2, execution, scope);
34284
34691
  const targetHead = this.targetHead();
34285
34692
  await assertTarget(this.view.binding.target.checkoutRoot, {
34286
34693
  branch: this.view.binding.target.branch,
@@ -34551,8 +34958,12 @@ class TurnCapture {
34551
34958
  } else if (e.kind === "tool-start" || e.kind === "tool-end") {
34552
34959
  const item = this.item(e.callId, "tool");
34553
34960
  this.update(item, "name", sanitizeText(e.name, this.secrets()), 128);
34554
- if (e.kind === "tool-end")
34961
+ if (e.kind === "tool-start")
34962
+ item.state = "running";
34963
+ else {
34964
+ item.state = e.isError ? "failed" : "completed";
34555
34965
  item.error = e.isError;
34966
+ }
34556
34967
  } else if (e.kind === "message-end") {
34557
34968
  const item = this.turn.items.find((i) => i.id === e.messageId && i.role === "assistant");
34558
34969
  if (item)
@@ -34575,7 +34986,14 @@ class TurnCapture {
34575
34986
  if (block.messageId === e.messageId)
34576
34987
  this.messageText.delete(id);
34577
34988
  }
34578
- if (["message-end", "tool-end", "model-retry", "worker-failure"].includes(e.kind))
34989
+ if ([
34990
+ "message-end",
34991
+ "tool-start",
34992
+ "tool-update",
34993
+ "tool-end",
34994
+ "model-retry",
34995
+ "worker-failure"
34996
+ ].includes(e.kind))
34579
34997
  this.save();
34580
34998
  }
34581
34999
  }
@@ -34915,8 +35333,8 @@ function workflowResultDetail(value, secrets) {
34915
35333
  var runtimeSummary = (runtime) => `${describeWorkerRuntime(runtime)}
34916
35334
  ${RUN_ENVIRONMENT_POLICY}`;
34917
35335
  var OWNER_RUNTIME = Object.freeze({
34918
- version: "2.1.10",
34919
- build: "9d5c50c9e4c178870b59c8c2efd9c0fbaabd00b8eb9c1ca57f5594890e208065",
35336
+ version: "2.1.13",
35337
+ build: "76dee9ed5af2b1aa3aa9dad7bc8e3a0c97fc19729bf31b3eb3c63b4094f5db79",
34920
35338
  entry: fileURLToPath7(import.meta.url),
34921
35339
  pid: process.pid,
34922
35340
  node: process.versions.node,
@@ -35553,8 +35971,9 @@ class Workflows {
35553
35971
  const observed = this.assertProposal(proposal, request3.digest);
35554
35972
  const source = observed.source;
35555
35973
  runtime = observed.runtime;
35556
- if ([...this.active.values()].some((live3) => live3.proposal))
35557
- throw new WorkflowRefusal("conflict", "Another approved workflow is queued or running in this checkout. Approve this plan again after it settles.");
35974
+ const conversation = proposal.model.conversation?.id;
35975
+ if ([...this.active.values()].some((live3) => live3.proposal && live3.execution.version.conversation?.id === conversation))
35976
+ throw new WorkflowRefusal("conflict", "This conversation already has an approved workflow queued or running. Start a separate conversation for another task.");
35558
35977
  this.capacity();
35559
35978
  const grant = this.grants.get(request3.grant);
35560
35979
  if (grant && grant.expiresAt < Date.now())
@@ -35617,6 +36036,7 @@ class Workflows {
35617
36036
  original: ready2.then(() => this.execute(live2, request3)),
35618
36037
  proposal,
35619
36038
  target: target2,
36039
+ guidance: target2 ? { agents: pathIdentity(this.cwd, "AGENTS.md") } : undefined,
35620
36040
  declared,
35621
36041
  delivered: new Set,
35622
36042
  notes: []
@@ -35804,7 +36224,7 @@ temporaryDirectoryEnvironment names this worker process's inherited environment
35804
36224
  ...readonly && kind === "review" && live2.run.delivery?.candidate ? {
35805
36225
  changes: {
35806
36226
  root: cwd,
35807
- base: live2.run.delivery.binding.target.head,
36227
+ base: live2.delivery?.candidateBase() ?? live2.run.delivery.binding.target.head,
35808
36228
  candidate: live2.run.delivery.candidate
35809
36229
  }
35810
36230
  } : {},
@@ -36432,7 +36852,10 @@ ${diagnosticText(lines.join(`
36432
36852
  if (!live2.target)
36433
36853
  return;
36434
36854
  try {
36435
- await assertTarget(this.cwd, live2.target, paths);
36855
+ await assertTarget(this.cwd, {
36856
+ branch: live2.target.branch,
36857
+ head: live2.delivery?.targetHead() ?? live2.target.head
36858
+ }, paths);
36436
36859
  } catch (error) {
36437
36860
  if (!(error instanceof WorkflowRefusal) || error.code === "stale")
36438
36861
  throw error;
@@ -36677,7 +37100,7 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
36677
37100
  await this.commit(live2, cwd, scope, "Cadence: candidate for verification", before, "commit-candidate");
36678
37101
  head = await delivery.assertTip();
36679
37102
  await assertCandidate(cwd, head);
36680
- await assertCommittedScope(cwd, delivery.view.binding.target.head, head, scope);
37103
+ await assertCommittedScope(cwd, delivery.candidateBase(), head, scope);
36681
37104
  delivery.view.candidate = head;
36682
37105
  delivery.view.acceptance = null;
36683
37106
  this.save(live2);
@@ -36742,7 +37165,10 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
36742
37165
  if (ignored.code === 0)
36743
37166
  return skip(".cadence/ is ignored by Git here.");
36744
37167
  try {
36745
- await assertTarget(this.cwd, live2.target, KNOWLEDGE_SCOPE);
37168
+ await assertTarget(this.cwd, {
37169
+ branch: live2.target.branch,
37170
+ head: live2.delivery?.targetHead() ?? live2.target.head
37171
+ }, KNOWLEDGE_SCOPE);
36746
37172
  } catch {
36747
37173
  return skip("the target checkout has its own changes to the knowledge store.");
36748
37174
  }
@@ -36902,6 +37328,7 @@ ${result.output}`}`);
36902
37328
  await delivery.resources.mutate(delivery.view.binding.target.repository, live2.abort.signal, async () => {
36903
37329
  this.assertRunning(live2);
36904
37330
  const candidate = await delivery.assertAccepted(p.digest, live2.execution, scope);
37331
+ this.assertGuidance(live2);
36905
37332
  delivery.view.integration.before = delivery.targetHead();
36906
37333
  delivery.view.integration.status = "applying";
36907
37334
  delivery.view.integration.reason = "";
@@ -37077,6 +37504,68 @@ ${result.output}`}`);
37077
37504
  await git(["worktree", "remove", path]);
37078
37505
  }));
37079
37506
  }
37507
+ async checkoutAccess(live2, access) {
37508
+ const previous = live2.barrier;
37509
+ if (previous) {
37510
+ previous.release();
37511
+ if (live2.barrier === previous)
37512
+ live2.barrier = undefined;
37513
+ }
37514
+ if (access === null)
37515
+ return;
37516
+ const permit = await this.o.gate.acquire(live2.run.id, live2.abort.signal, access);
37517
+ live2.barrier = permit;
37518
+ permit.assertHeld();
37519
+ }
37520
+ assertGuidance(live2) {
37521
+ if (!live2.guidance || !live2.target)
37522
+ throw new ContractError("invalid");
37523
+ if (pathIdentity(this.cwd, "AGENTS.md") !== live2.guidance.agents)
37524
+ throw new WorkflowRefusal("conflict", "AGENTS.md changed during the run. The candidate is retained; review a fresh plan before integration.");
37525
+ }
37526
+ async refreshCandidate(live2, integration, p) {
37527
+ const delivery = live2.delivery;
37528
+ const target2 = live2.target;
37529
+ if (!delivery || !target2)
37530
+ throw new ContractError("invalid");
37531
+ const scope = this.scope(live2, p);
37532
+ const frontier = delivery.frontierHead();
37533
+ await assertTarget(this.cwd, { branch: target2.branch, head: frontier }, scope);
37534
+ this.assertGuidance(live2);
37535
+ if (!delivery.needsRefresh())
37536
+ return;
37537
+ await delivery.assertAcceptedCandidate(p.digest, live2.execution, scope);
37538
+ const base = delivery.candidateBase();
37539
+ const changed = await committedPaths(this.cwd, base, frontier);
37540
+ const conflicts = [
37541
+ ...new Set([
37542
+ ...overlapping([...scope, "AGENTS.md"], changed),
37543
+ ...changed.filter((path) => path.endsWith("/AGENTS.md"))
37544
+ ])
37545
+ ].sort();
37546
+ if (conflicts.length)
37547
+ throw new WorkflowRefusal("conflict", `A parallel workflow changed approved inputs: ${conflicts.join(", ")}. The isolated candidate is retained; review a fresh plan before integration.`);
37548
+ let merged = "";
37549
+ await this.gitStep(live2, integration, "integrate-parallel-deliveries", async (git) => {
37550
+ await git(["merge", "--no-ff", "--no-edit", frontier]);
37551
+ merged = await gitHead(integration);
37552
+ });
37553
+ delivery.refreshed(merged);
37554
+ await assertCandidate(integration, merged);
37555
+ await assertCommittedScope(integration, frontier, merged, scope);
37556
+ await this.verifyAndRepair(live2, integration, p, true);
37557
+ }
37558
+ advanceSiblings(live2) {
37559
+ const delivery = live2.delivery;
37560
+ const candidate = live2.run.mergedCommit;
37561
+ if (!delivery || !candidate || delivery.view.postChecks !== "passed" || delivery.view.integration.status !== "applied" || delivery.view.integration.after !== candidate)
37562
+ throw new ContractError("stale");
37563
+ const expected = delivery.frontierHead();
37564
+ const branch = delivery.view.binding.target.branch;
37565
+ for (const sibling of this.active.values())
37566
+ if (sibling !== live2 && sibling.delivery?.view.binding.target.branch === branch)
37567
+ sibling.delivery.advanceFrontier(expected, candidate);
37568
+ }
37080
37569
  async implement(live2, p) {
37081
37570
  const plan = p.plan;
37082
37571
  const target2 = live2.target;
@@ -37096,6 +37585,7 @@ ${result.output}`}`);
37096
37585
  delivery.prepareHome();
37097
37586
  await this.gitStep(live2, this.cwd, "worktree-integration", (run) => delivery.create(run));
37098
37587
  await assertWorktree(this.cwd, integration);
37588
+ await this.checkoutAccess(live2, null);
37099
37589
  }
37100
37590
  await this.setup(live2, integration, p, "candidate");
37101
37591
  await this.setup(live2, integration, p);
@@ -37112,6 +37602,10 @@ ${result.output}`}`);
37112
37602
  }
37113
37603
  await this.assignments(live2, integration, p);
37114
37604
  await this.verifyAndRepair(live2, integration, p, git);
37605
+ if (delivery) {
37606
+ await this.checkoutAccess(live2, "exclusive");
37607
+ await this.refreshCandidate(live2, integration, p);
37608
+ }
37115
37609
  await this.learn(live2, integration, p);
37116
37610
  if (live2.knowledgeDone)
37117
37611
  await this.verifyAndRepair(live2, integration, p, git);
@@ -37129,14 +37623,14 @@ ${result.output}`}`);
37129
37623
  committed3.push(name);
37130
37624
  const documentBefore = new Map(documents.map((name) => [name, pathIdentity(this.cwd, name)]));
37131
37625
  const beforePublication = await delivery.assertTip();
37132
- const changed = await committedPaths(integration, base, beforePublication);
37626
+ const changed = await committedPaths(integration, delivery.candidateBase(), beforePublication);
37133
37627
  this.publish(live2, integration, plan, committed3, changed);
37134
37628
  await this.verifyAndRepair(live2, integration, p, true, committed3);
37135
37629
  await this.integrate(live2, p, [...this.scope(live2, p), ...committed3]);
37136
37630
  const candidate = live2.run.mergedCommit;
37137
37631
  if (!candidate)
37138
37632
  throw new ContractError("quarantine");
37139
- for (const path of await committedPaths(this.cwd, base, candidate))
37633
+ for (const path of await committedPaths(this.cwd, delivery.candidateBase(), candidate))
37140
37634
  live2.delivered.add(path);
37141
37635
  try {
37142
37636
  this.assertRunning(live2);
@@ -37191,6 +37685,7 @@ ${result.output}`}`);
37191
37685
  throw error;
37192
37686
  }
37193
37687
  this.assertRunning(live2);
37688
+ this.advanceSiblings(live2);
37194
37689
  await delivery.cleanup(async (path, check) => {
37195
37690
  await this.gitStep(live2, this.cwd, "remove-merged-worktree", async (git2) => {
37196
37691
  await check();
@@ -37298,7 +37793,7 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
37298
37793
  let outcome = "unknown";
37299
37794
  try {
37300
37795
  this.assertRunning(live2);
37301
- live2.barrier = await this.o.gate.acquire(live2.run.id, live2.abort.signal);
37796
+ live2.barrier = await this.o.gate.acquire(live2.run.id, live2.abort.signal, request3.action === "research" ? "shared" : "exclusive");
37302
37797
  live2.barrier.assertHeld();
37303
37798
  if (live2.run.diagnostics)
37304
37799
  live2.run.diagnostics.acquiredAt = Date.now();
@@ -37439,6 +37934,12 @@ class Workbench {
37439
37934
  kind: request3.kind,
37440
37935
  context: this.contexts.records.read(request3.location).context
37441
37936
  };
37937
+ case "reload-conversation-models":
37938
+ this.contexts.records.read(request3.location);
37939
+ return this.o.models.reloadCatalog().then(() => ({
37940
+ kind: "conversation-models",
37941
+ catalog: this.contexts.catalog(request3.location)
37942
+ }));
37442
37943
  case "conversation-models":
37443
37944
  return {
37444
37945
  kind: request3.kind,
@@ -37820,7 +38321,7 @@ var processLifetime = {
37820
38321
  }
37821
38322
  };
37822
38323
  async function createServiceHost(value, sourceBuild, lifetime) {
37823
- const embedded = "d70dd3e63843be7df42ff10943fcdc78bcd27b881b0ac8222526e8dad7b0e6e2";
38324
+ const embedded = "103e212eee402600c29002528ccc3808b6fbe11ccee275a4d5f2a3d52576c520";
37824
38325
  if (embedded && sourceBuild)
37825
38326
  throw new ContractError("unsupported-context");
37826
38327
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -37986,11 +38487,11 @@ async function createServiceHost(value, sourceBuild, lifetime) {
37986
38487
  owner.registerRuntime(() => gate.closeAdmission(), {
37987
38488
  assertQuiescent: () => gate.assertQuiescent()
37988
38489
  });
37989
- const ownerLiterals = () => [
38490
+ const ownerLiterals = (workspace = false) => [
37990
38491
  ...access.redactionLiterals(),
37991
38492
  native.capability,
37992
38493
  ...network.literals,
37993
- ...models2.viewRedactionLiterals()
38494
+ ...models2.viewRedactionLiterals(workspace ? "installed" : "text")
37994
38495
  ];
37995
38496
  workbench = !sourceBuild?.deferRuntime ? new Workbench({
37996
38497
  coordination: c,
@@ -38030,13 +38531,13 @@ async function createServiceHost(value, sourceBuild, lifetime) {
38030
38531
  };
38031
38532
  },
38032
38533
  workspace: () => {
38033
- const before = ownerLiterals();
38534
+ const before = ownerLiterals(true);
38034
38535
  const view = {
38035
38536
  rootLabel: diagnosticText(sanitizeText(c.store.root, before), 4096),
38036
38537
  models: models2.observe(),
38037
38538
  context: unavailable2(null)
38038
38539
  };
38039
- if (canonicalJson(before) !== canonicalJson(ownerLiterals()))
38540
+ if (canonicalJson(before) !== canonicalJson(ownerLiterals(true)))
38040
38541
  throw new ContractError("stale");
38041
38542
  return view;
38042
38543
  },