@abelxiaoxing/cadence 2.0.32 → 2.0.34

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.
@@ -24,7 +24,7 @@ Browser conversation mode is retained by the project owner, not by a browser-onl
24
24
 
25
25
  Native mode is branch-aware; browser mode follows its server-owned conversation identity.
26
26
  The browser and the terminal share the conversation itself (it is the same Pi session), but each keeps its own Cadence mode and plan approval: entering Cadence in one does not enter it in the other.
27
- A workflow started in either place appears as a card in that conversation in the browser.
27
+ A workflow started in either place appears in that conversation in the browser as one line after the turn it started in.
28
28
  A saved native mode is active only in a trusted interactive terminal; print/RPC sessions keep ordinary tools and can still exit with `/cadence exit`.
29
29
  In Pi, the agent panel lists workflow subagents and opens their transcripts; `cadence_status` can read one step's transcript.
30
30
  Resume and compaction retain the mode/context, not execution grants.
@@ -35,12 +35,16 @@ When an observation reply is lost, ask for status; do not infer that the action
35
35
  ## Models and project knowledge
36
36
 
37
37
  The first native use defaults to the current Pi provider/model/API/thinking selection.
38
- The selected preference is remembered in `<agent-dir>/cadence/settings.json` (normally `~/.pi/agent/cadence/settings.json`) and reused across projects.
39
- Ask Cadence to change its model in Pi, or use the model button beside the browser composer; it shows the current model and thinking level, and choosing from its list or thinking row takes effect at once for every conversation in the project.
38
+ Each conversation keeps its own working directory and exact provider/model/API/thinking preference.
39
+ Ask Cadence to change its model in Pi, or use the model button beside the browser composer; it changes future messages and plans in that conversation, not other conversations or admitted runs.
40
+ An explicit model choice is also remembered in `<agent-dir>/cadence/settings.json` (normally `~/.pi/agent/cadence/settings.json`) as the default for new conversations across projects; restoring an existing conversation does not replace that default.
40
41
  The browser restores an available saved preference on explicit Send and shows it dimmed until then; reads/login do not install a choice.
41
42
  With no choice and no saved preference, Send opens the model list and sends the message right after the choice.
42
43
  If no usable preference exists, choose once; an unreadable preference file falls back to the current Pi model, and choosing a model rewrites it.
43
- An accepted run keeps its original exact model.
44
+ An accepted message or workflow keeps its original directory and exact model, including while queued.
45
+ Different subdirectories of one repository can have independent conversations while sharing one checkout owner and execution gate.
46
+ Tools and check commands use the conversation directory; a plan's declared write paths stay relative to the displayed checkout root, including in isolated Git worktrees.
47
+ Changing the current conversation's model makes its older unaccepted plan require fresh planning/approval; changing another conversation's model does not.
44
48
  An unavailable remembered model is not silently substituted.
45
49
  Pi's original model and authentication sources remain authoritative; Cadence does not copy credentials.
46
50
 
@@ -105,7 +109,8 @@ System-service installation and remote access remain separate explicit operation
105
109
 
106
110
  `/cadence-history [run-id]` provides readonly diagnostics without model calls or service startup; see [History and diagnostics](history.md).
107
111
  The WebUI uses the same execution engine with a separate, context-bound browser confirmation path.
108
- Its main composer stays in the same conversation; the plan card, workflow progress and actual merge outcomes appear inline.
112
+ Its main composer stays in the same conversation; the plan card appears inline, and each workflow is one line after the turn it started in, showing what it is doing (with **Stop**) or how it ended: its merge commit, or the reason it did not complete.
113
+ Select the line to open the workflow's steps, checks, delivery and diagnostics in the main area; while it runs, the conversation's status names its phase.
109
114
  Research, implementation and review subagents are listed in the lower-left **Subagents** dock, together with legacy task children; selecting one (or **Open subagent context** on a step) opens its full transcript and retained result in the main area, and **Back to conversation** returns.
110
115
  Active workflows are listed under **Running conversations** with **Cancel workflow — request stop**; this includes native-started workflows, and an unavailable observation is not proof of no work.
111
116
  The old task creation/Save/Start/check/human-Review controls are retired on both clients and refused by the service.
@@ -115,11 +120,11 @@ Approval grants are neither stored in the browser nor restored after restart.
115
120
  Losing a response only observes its original command/run identity; it never retries execution.
116
121
  Exit does not stop accepted work, and **Cancel workflow — request stop** remains independent of conversation mode.
117
122
  There is no generic browser shell/PTY, service management/recovery or checkpoint pause/resume feature.
118
- Conversation response completion is distinct from workflow completion; read the workflow card for actual delivery/check outcomes.
123
+ Conversation response completion is distinct from workflow completion; read the workflow's line and view for actual delivery/check outcomes.
119
124
 
120
125
  ### Research scope, timing and retained results
121
126
 
122
- Each research call accepts one or two questions and optional specific `roots` (default: the selected project directory).
127
+ Each research call accepts one or two questions and optional specific `roots` (default: the conversation directory).
123
128
  Provide the actual investigation directory, especially for large mounted/backup trees; do not begin by enumerating `/` or broad parent directories.
124
129
  Research tools are readonly and bounded.
125
130
  Search limits and omitted coverage are reported explicitly; a partial search does not prove that no other matching file exists.
package/docs/history.md CHANGED
@@ -5,9 +5,9 @@ History is evidence, not a second task manager or renewed execution consent.
5
5
 
6
6
  ## Current workflows
7
7
 
8
- - In the conversation, open a workflow's steps to see actual checks, Agent review, delivery and failures.
8
+ - In the conversation, select a workflow's line to open its steps: actual checks, Agent review, delivery and failures.
9
9
  **Open subagent context** shows the retained transcript; **Read retained step result** reads the retained result rather than its clipped status preview.
10
- - A workflow belongs to the conversation that started it, in the browser or in the terminal, and its card stays there.
10
+ - A workflow belongs to the conversation that started it, in the browser or in the terminal, and its line stays after the turn it started in.
11
11
  An active workflow is also listed under **Running conversations** in the browser sidebar.
12
12
  - In a trusted Pi terminal, `/cadence-history` lists workflows without asking a model.
13
13
  The listing is paged in ID order, not chronological order; larger histories show scan progress first, and **Continue scanning** resumes it.
@@ -26,7 +26,7 @@ Automatic Agent review is never human review, and a check's actual exit is indep
26
26
  Browser conversations are the project's Pi sessions, the same files `pi -r` and `/resume` list in the terminal.
27
27
  The browser sidebar lists sessions started in either place, newest first, and labels where each one started.
28
28
  A conversation can be continued from either side: open it in the browser, or run `/resume` (or `pi --session <id>`) in the terminal.
29
- Only sessions started in the project's root folder are listed, and only those of the account the service runs as.
29
+ Sessions from the selected checkout and its conversation directories are listed, and only those of the account the service runs as.
30
30
 
31
31
  Pi keeps a session as a tree.
32
32
  When a message continues an earlier point, the session gains a branch instead of losing anything:
@@ -40,7 +40,10 @@ If the browser continues it meanwhile, the terminal says so; run `/resume` and c
40
40
  A message sent in the terminal first starts a new branch from where the terminal is.
41
41
 
42
42
  Sessions are stored as Pi writes them, including tool output; the browser redacts the service's credentials from what it shows.
43
- Browser conversations from before 2.0.31 are added to the shared history only when you choose **Add them to the shared history** in the sidebar; the old records are kept.
43
+ Old Cadence conversations from before the shared Pi-session store are no longer supported.
44
+ There is no import or migration command: start a new conversation.
45
+ Existing files are preserved, not deleted or reset; their IDs cannot be silently reused for empty sessions.
46
+ This does not retire ordinary Pi session history.
44
47
 
45
48
  ## Existing task archives
46
49
 
@@ -48,7 +51,8 @@ The old `/cadence-inspect` interface and browser **Legacy task** creation route
48
51
  Old create, Save, Generate, Start, check and human-Review requests are refused by the service, including from stale clients.
49
52
  There is no feature flag to re-enable them.
50
53
 
51
- Existing task summaries, private history and task-to-conversation links are preserved without migration, reset or cleanup.
54
+ Existing task summaries, private history and stored task-to-conversation links are preserved without migration, reset or cleanup.
55
+ Navigation back to the unsupported old conversations is removed.
52
56
  Use **Retained task history** in `/cadence-history`, or select a retained task in the browser:
53
57
 
54
58
  - Read recorded plans, runs, children, checks, changes and human Review evidence.
@@ -43,19 +43,28 @@ cadence project open /srv/project --agent-dir /root/.pi/agent --state-home /root
43
43
  Without a path, `project open` uses the current directory; a missing directory refuses unless `--create` was supplied.
44
44
  The project may be a Git checkout or an ordinary directory, including spaces and Unicode names; it need not be inside `~/cadence` or the package directory.
45
45
  The command explicitly starts a detached owner, or observes the already running exact owner; it never creates a task, chooses a model, renews a grant or starts a worker.
46
- New projects bind port0 and retain the resulting positive port, avoiding the default17423 collision; existing selections keep their exact port, cwd, agent sources and history.
47
- The JSON result reports the canonical workspace, actual task cwd and endpoint; the private entry link is printed separately to stderr, like `server install`.
46
+ New projects bind port0 and retain the resulting positive port, avoiding the default17423 collision; existing selections keep their exact port, saved default cwd, agent sources and history.
47
+ The JSON result reports the canonical checkout, saved default cwd and endpoint; each conversation supplies its own execution cwd, rather than changing this owner setting; the private entry link is printed separately to stderr, like `server install`.
48
48
  Keep that link private.
49
49
  Open Pi in the same project and use `/cadence` for the native client; explicit `cadence stop --workspace <path>` stops only that project.
50
50
  Opening another project never changes the cwd or cancels work in the former one.
51
+ Different folders of one checkout share its owner and execution gate, but conversations keep independent directories and model choices; an admitted run keeps its original snapshot.
52
+ The owner launches from the checkout root.
53
+ A removed saved default subdirectory does not prevent other conversation directories from starting; no old conversation is redirected or rewritten.
51
54
  The default workbench routes all associated projects through one origin, including a configured HTTPS proxy.
52
- Its project picker browses directory names readonly (`~` names the service account's home); only **Open this folder**, or one click on a recent project, starts or reuses an owner, without admitting a task or model call.
55
+ Its picker browses directory names readonly (`~` names the service account's home); **Use this folder**, or one click on a recent directory, only selects it.
56
+ Send starts or reuses that directory's owner when needed; there is no separate Open step, boot installation or automatic message replay.
57
+ If no usable saved model is available, that Send waits for an explicit model choice.
58
+ Cancelling the choice or leaving the conversation does not send the waiting message.
59
+ If the conversation cannot be read, Send can prepare execution but cannot infer its context: review the restored conversation and send again.
60
+ Preparation failure keeps the draft; an owner may already have started, but the message was not sent.
61
+ If the actual Send reply is lost instead, its original command is observed, never resubmitted automatically.
53
62
  Project navigation remounts only the browser client; the original owner's work continues.
54
63
  Browser proxy traffic keeps browser authority and the owner's own attachments, CSRF/build checks, grants and history proofs; native management routes and local-capability headers are not forwarded.
55
- The gateway also refuses the legacy project-level Open command, so every opening is associated through the workbench instead of returning an independent backend token link.
64
+ The gateway also refuses the legacy project-level Open command, so every Send preparation is associated through the workbench instead of returning an independent backend token link.
56
65
  The gateway's token, backend cookies and native capabilities are never returned in project DTOs or stored in browser localStorage.
57
66
  Token rotation retires and detaches its exact browser attachments without cancelling admitted work.
58
- The private account state stores bounded project references and opening receipts, not copied worktrees, Pi profiles or imported transcripts.
67
+ The private account state stores bounded directory references and startup/association preparation receipts, not copied worktrees, Pi profiles or imported transcripts.
59
68
  Private coordination/Pi credential directories and foreign-owned project selections are refused.
60
69
  Direct project entry links remain available as a compatibility route; that route alone still uses separate loopback project entries.
61
70
  Git subdirectories and aliases resolve to the same checkout, while overlapping parent/child owners still refuse.
@@ -101,9 +110,14 @@ A definition whose project directory was removed gets a readable refusal (exit78
101
110
  The `upgrade` command (Linux) installs the latest version, or exactly `--to VERSION`, with npm and restarts; see [Restart and upgrade from the WebUI](#restart-and-upgrade-from-the-webui) for its steps.
102
111
  Commands that change the service (`install`, `restart`, `stop`, `uninstall`, `upgrade`) refuse with `inside-service` when they run inside the service they would stop, for example from a tool of its own agent: stopping a systemd unit ends every process in it, so the command would die before it started the service again.
103
112
  Use the WebUI or a terminal outside the service instead.
104
- `stop` joins the workbench's accepted openings and associated exact-epoch project owners, then closes the entry; unrelated project owners stay independent.
113
+ `stop` joins the workbench's accepted Send preparations and associated exact-epoch project owners, then closes the entry; unrelated project owners stay independent.
105
114
  An associated owner that is not running (or whose directory is gone) has nothing to stop; one whose Stop is unconfirmed keeps its own state, and the workbench still stops.
106
115
  Project-specific `stop --workspace <path>` remains scoped to that owner.
116
+ While the unified entry is running, a stopped associated project's ordinary/Cadence conversation history and mode remain readable; this does not start the project, restore approval or resume interrupted work.
117
+ Its page explains that Send prepares execution and retains drafts.
118
+ Send the next message directly; a new owner connection does not clear the conversation or approve a saved plan.
119
+ Selecting or browsing an independent running owner does not make whole-workbench Stop manage it; explicit Send preparation does.
120
+ Direct project links, legacy task details and workflow details still require their project owner.
107
121
  The generated registration stays for the next boot or login.
108
122
  `uninstall` stops it orderly and deletes only what Cadence generated; workspace, state home, history, linger and Pi sources stay.
109
123
  Because npm runs no uninstall script, uninstall the service before `npm uninstall -g`; a left-behind definition fails to start once its CLI path disappears.
@@ -272,7 +286,7 @@ At sign-out or shutdown Windows ends the owner without orderly Stop: running wor
272
286
 
273
287
  - `alive` requires an authenticated exact-epoch reply.
274
288
  It is not a PID probe.
275
- `actions:false` can mean that no owner model has been explicitly selected yet.
289
+ `actions:false` can describe the unscoped owner model slot; conversation model readiness is separate, not permission to execute a plan.
276
290
  - Disconnect this page (the WebUI More menu), browser close and Pi quit detach clients; admitted work continues.
277
291
  Use the client's **Cancel** for a run or management **stop** for the service.
278
292
  - Stop closes admission and waits original processes, credential writes, history writes, already-started publication continuations, owned networking and listener closure before releasing fences.
@@ -288,12 +302,12 @@ At sign-out or shutdown Windows ends the owner without orderly Stop: running wor
288
302
  Their mode bits are not checked: Pi creates its agent directory with your umask (0755, or 0775 under umask 002), and Cadence's own state stays 0700 regardless.
289
303
  `models.json` may use only fields the pinned SDK supports.
290
304
  `supportsMidConvoSystemMessages` from newer Pi is accepted because the pinned SDK has no system-role conversation message; other unknown fields refuse rather than being silently ignored.
291
- The owner model choice offers every thinking level the pinned SDK supports for a model, `off` through `xhigh` and `max`; a model whose `thinkingLevelMap` maps only `max` (as some DeepSeek configurations do) is chosen at `max`, and a child runs only at exactly that level.
305
+ The conversation model picker offers every thinking level the pinned SDK supports for a model, `off` through `xhigh` and `max`; a model whose `thinkingLevelMap` maps only `max` (as some DeepSeek configurations do) is chosen at `max`, and a child runs only at exactly that level.
292
306
  A model whose provider or model ID contains a known credential value is withheld from the catalog, since showing the ID would reveal that value; the catalog says how many models are withheld, and the rest stay selectable.
293
307
  Credential values are `auth.json` keys, `models.json` `apiKey` and header values (and the variables they name) and service-environment variables whose names contain `KEY`, `TOKEN`, `SECRET`, `PASS`, `AUTH` or `COOKIE`.
294
308
  The common Ollama placeholder `"apiKey": "ollama"` under a provider named `ollama` is such a case: give the placeholder a value that matches no provider or model ID (for example `"local-no-auth"`), then restart the service.
295
309
  The owner loads `models.json` once at start: after it changes, the model catalog, the chosen model and the workspace view refuse as `stale` (credential changes in `auth.json` are read fresh).
296
- Restart the service to reload it (`cadence server restart`, or `stop` then `start`), then choose the owner model again.
310
+ Restart the service to reload it (`cadence server restart`, or `stop` then `start`), then explicitly Send or choose the conversation model again; retained preferences are not erased.
297
311
  - A foreground owner can be managed from another terminal.
298
312
  Ctrl-C, SIGTERM, machine crash or terminal destruction is **not** the authenticated orderly Stop route: running work is interrupted, and the next start recovers the owner automatically.
299
313
  A recovered `stopped` registration records that the old owner was proven gone, not that its interrupted work completed.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.0.32",
3
+ "version": "2.0.34",
4
4
  "description": "Conversation-driven Pi workspace: persistent native and WebUI workflows, explicit plan approval, checks and local delivery.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -74,6 +74,7 @@
74
74
  "src/service/contracts/workbench.ts",
75
75
  "src/cadence-mode.ts",
76
76
  "src/cadence-preferences.ts",
77
+ "src/conversation-identity.ts",
77
78
  "src/service/contracts/workflow.ts",
78
79
  "src/cadence-instructions.ts",
79
80
  "src/coordinator-tools.mjs",
@@ -22,6 +22,7 @@ import {
22
22
  NativeConnection,
23
23
  projectStopCommand,
24
24
  } from "./native-client.ts";
25
+ import { decodeSessionId } from "./service/contracts/models.ts";
25
26
  import type { ChatTurn } from "./service/contracts/workbench.ts";
26
27
  import {
27
28
  decodeWorkflowPlan,
@@ -45,7 +46,7 @@ import {
45
46
  } from "./service-contract.ts";
46
47
  import { CADENCE_MODE_ENTRY } from "./session-entries.mjs";
47
48
  import { diagnosticText } from "./verification-diagnostics.ts";
48
- import { effectiveWorkspace } from "./workspace.ts";
49
+ import { effectiveWorkspace, resolveWorkspace } from "./workspace.ts";
49
50
 
50
51
  export { CADENCE_MODE_ENTRY };
51
52
 
@@ -83,6 +84,9 @@ const idle = (): CadenceModeState => ({
83
84
  proposal: null,
84
85
  previousTools: [],
85
86
  });
87
+ function readableProposal(proposal: WorkflowProposal): string {
88
+ return `Working directory: ${proposal.cwd}\nCheckout root (declared write paths): ${proposal.checkoutRoot ?? proposal.cwd}\nModel: ${proposal.display?.model ?? "not recorded"}\n\n${readableWorkflowPlan(proposal.plan)}`;
89
+ }
86
90
  /** Session restoration restores mode/context, NEVER a grant, pending command or action replay. */
87
91
  export function restoreCadenceMode(
88
92
  entries: readonly { type: string; customType?: string; data?: unknown }[],
@@ -387,6 +391,13 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
387
391
  const summarize = (run: WorkflowRun) =>
388
392
  `Cadence ${run.status} • ${run.goal}\nRun: ${run.id}\n${workflowDiagnostics(run)}\n${run.steps.map((s) => `${s.kind} ${s.id}: ${s.status}${s.exitCode === null ? "" : ` (exit ${s.exitCode})`}\n${s.text}${s.truncated ? "\n[Preview truncated; full result retained by owner.]" : ""}`).join("\n")}\n${run.notice}${run.mergedCommit ? `\nLocal merge: ${run.mergedCommit}` : ""}${run.status === "unknown" ? "\nOutcome unknown: neither completed nor failed. Its actual effects are not inferred, and the owner keeps any fences." : ""}\nAutomatic review is not human review. Cadence mode remains enabled.`;
389
393
  const agentDir = () => getAgentDir();
394
+ const conversation = (ctx: ExtensionContext) => {
395
+ const cwd = resolveWorkspace(ctx.cwd).cwd;
396
+ return {
397
+ id: decodeSessionId(ctx.sessionManager.getSessionId()),
398
+ cwd,
399
+ };
400
+ };
390
401
  const launchOwner = async (ctx: ExtensionContext) => {
391
402
  if (process.env.CADENCE_AUTOSTART === "0")
392
403
  throw new Error(
@@ -485,13 +496,23 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
485
496
  if (selecting) return selecting;
486
497
  const expected = generation;
487
498
  const operation = (async () => {
488
- const catalog = value(await client().models());
499
+ const location = conversation(ctx);
500
+ const catalog = value(await client().models(undefined, location));
489
501
  if (generation !== expected) throw new ContractError("stale");
502
+ if (catalog.selected) return;
503
+ const observed = value(
504
+ await client().workbenchRead({
505
+ kind: "conversation-context",
506
+ location,
507
+ }),
508
+ );
509
+ if (generation !== expected || observed.kind !== "conversation-context")
510
+ throw new ContractError("stale");
490
511
  const preferences = new CadencePreferences(agentDir());
491
512
  let saved: ModelSelector | null = null,
492
513
  unreadable = false;
493
514
  try {
494
- saved = preferences.read();
515
+ saved = observed.context.model ?? preferences.read();
495
516
  } catch {
496
517
  unreadable = true;
497
518
  if (!warnedPreferences) {
@@ -514,23 +535,17 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
514
535
  : null);
515
536
  if (!selected)
516
537
  throw new Error("Choose a Pi model before entering Cadence.");
517
- const same =
518
- catalog.selected &&
519
- canonicalJson({
520
- provider: catalog.selected.provider,
521
- model: catalog.selected.model,
522
- api: catalog.selected.api,
523
- thinking: catalog.selected.thinking,
524
- }) === canonicalJson(selected);
525
- if (!same) {
526
- value(
527
- await client().chooseModel({
528
- expected: catalog.version,
529
- choice: selected,
530
- }),
531
- );
532
- if (generation !== expected) throw new ContractError("stale");
533
- }
538
+ value(
539
+ await client().workbenchCommand({
540
+ kind: "restore-model",
541
+ commandId: randomUUID(),
542
+ epoch: catalog.version.epoch,
543
+ location,
544
+ expected: catalog.version,
545
+ choice: selected,
546
+ }),
547
+ );
548
+ if (generation !== expected) throw new ContractError("stale");
534
549
  if (!saved && !unreadable)
535
550
  try {
536
551
  preferences.save(selected);
@@ -966,7 +981,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
966
981
  Type.Array(
967
982
  Type.String({
968
983
  description:
969
- "Specific investigation directories; defaults to project cwd. Avoid filesystem roots and broad parent trees.",
984
+ "Specific investigation directories, relative to this conversation's cwd by default. Avoid filesystem roots and broad parent trees.",
970
985
  }),
971
986
  { minItems: 1, maxItems: 8 },
972
987
  ),
@@ -978,7 +993,9 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
978
993
  await connect(ctx);
979
994
  claim.assertCurrent();
980
995
  const notice = await requireSettledRun(ctx, claim);
981
- const model = value(await client().models()).version;
996
+ const model = value(
997
+ await client().models(undefined, conversation(ctx)),
998
+ ).version;
982
999
  const commandId = randomUUID(),
983
1000
  before = state.runId;
984
1001
  let sent = false,
@@ -1065,7 +1082,8 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1065
1082
  {
1066
1083
  action: "propose",
1067
1084
  plan,
1068
- model: value(await client().models()).version,
1085
+ model: value(await client().models(undefined, conversation(ctx)))
1086
+ .version,
1069
1087
  },
1070
1088
  undefined,
1071
1089
  undefined,
@@ -1075,7 +1093,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1075
1093
  state.proposal = response.proposal;
1076
1094
  persist();
1077
1095
  status("awaiting plan approval");
1078
- const shown = readableWorkflowPlan(response.proposal.plan);
1096
+ const shown = readableProposal(response.proposal);
1079
1097
  const redacted =
1080
1098
  canonicalJson(response.proposal.plan) !== canonicalJson(plan);
1081
1099
  // The plan is displayed by this tool's own result: a message sent now
@@ -1127,6 +1145,11 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1127
1145
  const proposal = state.proposal;
1128
1146
  if (!proposal)
1129
1147
  throw new Error("No current plan. Clarify and propose it first.");
1148
+ if (
1149
+ canonicalJson(proposal.model.conversation ?? null) !==
1150
+ canonicalJson(conversation(ctx))
1151
+ )
1152
+ throw new ContractError("stale");
1130
1153
  const expected = generation;
1131
1154
  const fromInput =
1132
1155
  permission?.id === proposal.id &&
@@ -1139,7 +1162,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1139
1162
  !(await confirm(
1140
1163
  ctx,
1141
1164
  "Implement this plan automatically?",
1142
- `${readableWorkflowPlan(proposal.plan)}\nProject: ${proposal.cwd}\nNo push or deployment. Keeping the discussion changes nothing.`,
1165
+ `${readableProposal(proposal)}\nNo push or deployment. Keeping the discussion changes nothing.`,
1143
1166
  "Keep discussing (do not start)",
1144
1167
  "Start this exact plan",
1145
1168
  ))
@@ -1167,9 +1190,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1167
1190
  );
1168
1191
  if (
1169
1192
  prepared.type !== "grant" ||
1170
- canonicalJson(prepared.proposal.plan) !==
1171
- canonicalJson(proposal.plan) ||
1172
- prepared.proposal.cwd !== proposal.cwd
1193
+ canonicalJson(prepared.proposal) !== canonicalJson(proposal)
1173
1194
  )
1174
1195
  throw new ContractError("stale");
1175
1196
  const commandId = randomUUID(),
@@ -1331,22 +1352,31 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1331
1352
  name: "cadence_model",
1332
1353
  label: "Remember Cadence model",
1333
1354
  description:
1334
- "Change the global Cadence model preference through a real user selection. Ordinary usage reuses the remembered model.",
1355
+ "Change this conversation's Cadence model through a real user selection; remember it as the default for new conversations. Accepted runs keep their original model.",
1335
1356
  parameters: Type.Object({}),
1336
1357
  async execute(_id, _input, _signal, _update, ctx) {
1337
1358
  active(ctx);
1359
+ const expected = generation,
1360
+ location = conversation(ctx);
1361
+ const current = () => {
1362
+ active(ctx);
1363
+ if (generation !== expected) throw new ContractError("stale");
1364
+ };
1338
1365
  // Preference selection must never block observation/cancellation or the picker.
1339
1366
  await connect(ctx, false);
1340
- const catalog = value(await client().models());
1367
+ current();
1368
+ const catalog = value(await client().models(undefined, location));
1369
+ current();
1341
1370
  const models = catalog.entries.filter(
1342
1371
  (m) => m.eligibility === "candidate" && m.api,
1343
1372
  );
1344
1373
  const labels = models.map((m) => `${m.provider}/${m.model} (${m.api})`);
1345
1374
  const selected = await pick(
1346
1375
  ctx,
1347
- "Cadence model (remembered across projects)",
1376
+ "Cadence model (this conversation; default for new conversations)",
1348
1377
  labels,
1349
1378
  );
1379
+ current();
1350
1380
  if (!selected) return result("Model unchanged.");
1351
1381
  const model = models[labels.indexOf(selected)];
1352
1382
  const thinking = await pick(
@@ -1354,6 +1384,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1354
1384
  "Thinking",
1355
1385
  model.thinking.filter((t) => t.selectable).map((t) => t.level),
1356
1386
  );
1387
+ current();
1357
1388
  if (!thinking) return result("Model unchanged.");
1358
1389
  const choice: ModelSelector = decodeModelSelector({
1359
1390
  provider: model.provider,
@@ -1362,11 +1393,15 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1362
1393
  thinking,
1363
1394
  });
1364
1395
  value(
1365
- await client().chooseModel({
1366
- expected: catalog.version,
1367
- choice,
1368
- }),
1396
+ await client().chooseModel(
1397
+ {
1398
+ expected: catalog.version,
1399
+ choice,
1400
+ },
1401
+ location,
1402
+ ),
1369
1403
  );
1404
+ current();
1370
1405
  // An explicit selection may atomically rewrite a corrupt preference.
1371
1406
  new CadencePreferences(agentDir()).choose(choice);
1372
1407
  warnedPreferences = false;
@@ -0,0 +1,7 @@
1
+ /** Domain-separated stable identities for native sessions and context versions.
2
+ * These identify public context, never credentials, grants or native capabilities. */
3
+ import { createHash } from "node:crypto";
4
+ export function conversationIdentity(identity: string): string {
5
+ const h = createHash("sha256").update(identity).digest("hex");
6
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;
7
+ }
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "3305384b10bb0c658565426ec2291d0237533cb9ae7aeb1d63f42ac8824b0c82",
5
+ "641cf7f91bc6f38839e9bb82e9db67d733ab0cded0a2eee0deb0d1ec29539ae1",
6
6
  } as const;
@@ -27,7 +27,10 @@ import {
27
27
  import { conversationResources } from "./conversation-resources.mjs";
28
28
  import { coordinatorTools } from "./coordinator-tools.mjs";
29
29
  import { researchClock, researchTools } from "./research-tools.mjs";
30
- import { WEBUI_SESSION_ENTRY } from "./session-entries.mjs";
30
+ import {
31
+ BROWSER_COMMAND_ENTRY,
32
+ WEBUI_SESSION_ENTRY,
33
+ } from "./session-entries.mjs";
31
34
  import { CaptureEmitter, SdkCapture } from "./worker-capture.mjs";
32
35
  import {
33
36
  closed,
@@ -561,6 +564,8 @@ try {
561
564
  if (session.agent.toolExecution !== "sequential")
562
565
  refuse("session", "capture-unsupported");
563
566
  session.agent.state.tools = ingress.wrap(session.agent.state.tools);
567
+ const initialLeaf = conversation ? manager.getLeafId() : null;
568
+ let recordedUser = null;
564
569
  unsubscribe = session.agent.subscribe(async (event) => {
565
570
  try {
566
571
  sdkEvents++;
@@ -578,6 +583,33 @@ try {
578
583
  }
579
584
  if (own(event, "type") === "message_end") {
580
585
  const message = own(event, "message");
586
+ if (
587
+ conversation &&
588
+ ["user", "assistant", "toolResult"].includes(own(message, "role"))
589
+ ) {
590
+ // Public core subscribers are awaited in registration order. The
591
+ // AgentSession's earlier subscriber has persisted this message.
592
+ // Each boundary names this worker's own prefix; a terminal append
593
+ // after it is never claimed by walking arbitrary descendants.
594
+ const entry = manager.getLeafEntry();
595
+ if (
596
+ entry?.type !== "message" ||
597
+ entry.message.role !== own(message, "role") ||
598
+ entry.id === initialLeaf
599
+ )
600
+ refuse("events", "event-projection-failed");
601
+ if (own(message, "role") === "user") {
602
+ if (recordedUser !== null)
603
+ refuse("events", "event-projection-failed");
604
+ recordedUser = entry.id;
605
+ }
606
+ if (recordedUser === null)
607
+ refuse("events", "event-projection-failed");
608
+ manager.appendCustomEntry(BROWSER_COMMAND_ENTRY, {
609
+ commandId: publicRequest.runId,
610
+ userId: recordedUser,
611
+ });
612
+ }
581
613
  if (own(message, "role") === "assistant") {
582
614
  const reason = own(message, "stopReason");
583
615
  terminalStopReason = [
@@ -20,7 +20,53 @@ import {
20
20
  thinkingLevels,
21
21
  } from "./domain.ts";
22
22
 
23
+ /** A conversation's identity: the Pi session id shared with the terminal. */
24
+ export function decodeSessionId(v: unknown): string {
25
+ const s = text(v, 128, true);
26
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(s)) invalid();
27
+ return s;
28
+ }
29
+
30
+ /** A conversation location is not an execution grant or a filesystem sandbox. */
31
+ export interface ConversationLocation {
32
+ id: string;
33
+ cwd: string;
34
+ }
35
+ export interface ConversationContext extends ConversationLocation {
36
+ revision: number;
37
+ model: ModelSelector | null;
38
+ }
39
+ export interface ExecutionContext {
40
+ cwd: string;
41
+ checkoutRoot: string;
42
+ version: ChoiceVersion;
43
+ model: ModelSelection | null;
44
+ }
45
+ export function decodeConversationLocation(v: unknown): ConversationLocation {
46
+ const o = closed(v, ["id", "cwd"]);
47
+ return { id: decodeSessionId(o.id), cwd: text(o.cwd, 4096, true) };
48
+ }
49
+ export function decodeConversationContext(v: unknown): ConversationContext {
50
+ const o = closed(v, ["id", "cwd", "revision", "model"]);
51
+ return {
52
+ id: decodeSessionId(o.id),
53
+ cwd: text(o.cwd, 4096, true),
54
+ revision: integer(o.revision, 0, Number.MAX_SAFE_INTEGER - 1),
55
+ model: nullable(o.model, decodeModelSelector),
56
+ };
57
+ }
58
+ export function decodeExecutionContext(v: unknown): ExecutionContext {
59
+ const o = closed(v, ["cwd", "checkoutRoot", "version", "model"]);
60
+ return {
61
+ cwd: text(o.cwd, 4096, true),
62
+ checkoutRoot: text(o.checkoutRoot, 4096, true),
63
+ version: decodeChoiceVersion(o.version),
64
+ model: nullable(o.model, decodeModelSelection),
65
+ };
66
+ }
23
67
  export interface ChoiceVersion {
68
+ /** Omitted only by explicit low-level native default-slot requests and retained records. */
69
+ conversation?: ConversationLocation;
24
70
  epoch: string;
25
71
  accessGeneration: number;
26
72
  configRev: number;
@@ -60,8 +106,12 @@ export function decodeChoiceVersion(value: unknown): ChoiceVersion {
60
106
  "accessGeneration",
61
107
  "configRev",
62
108
  "catalogId",
109
+ ...(Object.hasOwn(value ?? {}, "conversation") ? ["conversation"] : []),
63
110
  ]);
64
111
  return {
112
+ ...(o.conversation === undefined
113
+ ? {}
114
+ : { conversation: decodeConversationLocation(o.conversation) }),
65
115
  epoch: decodeId(o.epoch),
66
116
  accessGeneration: integer(o.accessGeneration, 1),
67
117
  configRev: integer(o.configRev, 1),