@abelxiaoxing/cadence 2.0.21 → 2.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,28 @@
1
1
  /** Persistent, branch-aware conversation mode. No execution owner lives in Pi. */
2
2
  import { randomUUID } from "node:crypto";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
5
3
  import { fileURLToPath } from "node:url";
6
- import type {
7
- ExtensionAPI,
8
- ExtensionContext,
4
+ import {
5
+ type ExtensionAPI,
6
+ type ExtensionContext,
7
+ getAgentDir,
8
+ getMarkdownTheme,
9
9
  } from "@earendil-works/pi-coding-agent";
10
- import { Key, matchesKey } from "@earendil-works/pi-tui";
10
+ import {
11
+ type Component,
12
+ Key,
13
+ Markdown,
14
+ matchesKey,
15
+ Text,
16
+ } from "@earendil-works/pi-tui";
11
17
  import { Type } from "typebox";
12
18
  import { CADENCE_INSTRUCTIONS as INSTRUCTIONS } from "./cadence-instructions.ts";
13
19
  import { CadencePreferences } from "./cadence-preferences.ts";
14
- import { departure, NativeConnection } from "./native-client.ts";
20
+ import {
21
+ departure,
22
+ NativeConnection,
23
+ projectStopCommand,
24
+ } from "./native-client.ts";
25
+ import type { ChatTurn } from "./service/contracts/workbench.ts";
15
26
  import {
16
27
  decodeWorkflowPlan,
17
28
  readableWorkflowPlan,
@@ -25,12 +36,17 @@ import {
25
36
  ContractError,
26
37
  canonicalJson,
27
38
  decodeModelSelector,
39
+ type ErrorCode,
28
40
  type ModelSelector,
41
+ type PublicError,
29
42
  type Reply,
30
43
  } from "./service-contract.ts";
31
44
  import { effectiveWorkspace } from "./task-store.ts";
45
+ import { diagnosticText } from "./verification-diagnostics.ts";
32
46
 
33
47
  export const CADENCE_MODE_ENTRY = "cadence-conversation-mode/1";
48
+ const CONTEXT = "cadence-mode-context";
49
+ const READY = "cadence-mode-ready";
34
50
  const TOOLS = [
35
51
  "cadence_research",
36
52
  "cadence_plan",
@@ -39,6 +55,16 @@ const TOOLS = [
39
55
  "cadence_cancel",
40
56
  "cadence_model",
41
57
  ];
58
+ const EXIT_HINT =
59
+ "type `退出 Cadence` or `exit cadence`, or run `/cadence exit`";
60
+ /** Native additions to the shared conversation policy. */
61
+ const NATIVE =
62
+ "PI TERMINAL: The user leaves Cadence mode by typing 退出 Cadence or exit cadence, or by running /cadence exit; you cannot exit for them, so tell them exactly this when they ask. Approval is the user's own typed 按计划实施 or the Start dialog. Workflow subagents appear in Pi's agent panel; cadence_status with a stepId (and transcript: true) reads one step's retained result or transcript.";
63
+ /** An Enter that closes a model-opened dialog must arrive after it settled. */
64
+ export const DIALOG_SETTLE_MS = 250;
65
+ /** Each Pi process tells the user once per project about an owner it started. */
66
+ const announcedOwners = new Set<string>();
67
+
42
68
  export interface CadenceModeState {
43
69
  enabled: boolean;
44
70
  cwd: string;
@@ -84,10 +110,12 @@ export function restoreCadenceMode(
84
110
  }
85
111
  return state;
86
112
  }
87
- /** Raw terminal evidence is ephemeral, never supplied by model/tool text or paste. */
113
+ /** Raw terminal evidence is ephemeral, never supplied by model/tool text or
114
+ * paste. Pi trims what it submits, so comparisons use the trimmed text. */
88
115
  export class CadenceUserInput {
89
116
  private value: { text: string; at: number } | undefined;
90
117
  private pasting = false;
118
+ private dialog: { opened: number; fresh: boolean } | undefined;
91
119
  clear() {
92
120
  this.value = undefined;
93
121
  }
@@ -98,46 +126,99 @@ export class CadenceUserInput {
98
126
  this.pasting = false;
99
127
  return;
100
128
  }
101
- if (!this.pasting && eligible && matchesKey(data, Key.enter))
102
- this.value = { text, at };
129
+ if (this.pasting || !matchesKey(data, Key.enter)) return;
130
+ if (this.dialog) {
131
+ // Only a typed Enter after the dialog settled may confirm it; a
132
+ // type-ahead Enter meant for the editor never does.
133
+ if (at - this.dialog.opened >= DIALOG_SETTLE_MS) this.dialog.fresh = true;
134
+ return;
135
+ }
136
+ if (eligible) this.value = { text, at };
137
+ }
138
+ openDialog(at = Date.now()) {
139
+ this.clear();
140
+ this.dialog = { opened: at, fresh: false };
141
+ }
142
+ /** True only when a fresh typed Enter was seen while the dialog was open. */
143
+ closeDialog(): boolean {
144
+ const fresh = this.dialog?.fresh === true;
145
+ this.dialog = undefined;
146
+ return fresh;
103
147
  }
104
148
  consumeCommand(args: string, at = Date.now()) {
105
- const v = this.value;
149
+ const typed = this.value?.text.trim();
106
150
  if (
107
- !v ||
108
- !/^\/cadence(?:[ \t]+[^\r\n]*)?$/u.test(v.text) ||
109
- v.text.replace(/^\/cadence[ \t]*/u, "") !== args
151
+ !typed ||
152
+ !/^\/cadence(?:[ \t]+[^\r\n]*)?$/u.test(typed) ||
153
+ typed.replace(/^\/cadence[ \t]*/u, "") !== args.trim()
110
154
  ) {
111
155
  this.clear();
112
156
  return false;
113
157
  }
114
- return this.consume(v.text, at);
158
+ return this.consume(typed, at);
115
159
  }
116
160
  consume(text: string, at = Date.now()) {
117
161
  const v = this.value;
118
162
  this.clear();
119
- return !!v && v.text === text && at >= v.at && at - v.at < 1500;
163
+ return (
164
+ !!v && v.text.trim() === text.trim() && at >= v.at && at - v.at < 1500
165
+ );
120
166
  }
121
167
  }
122
168
  const approved = (s: string) =>
123
169
  /^(?:按(?:这个|本)?计划(?:开始)?(?:执行|实施)|确认(?:计划并)?(?:执行|实施)|approve and execute)[。.!!]?$/iu.test(
124
170
  s.trim(),
125
171
  );
126
- const exiting = (s: string) =>
127
- /^(?:退出\s*cadence|关闭\s*cadence(?:模式)?|exit cadence)$/iu.test(s.trim());
172
+ export const exiting = (s: string) =>
173
+ /^(?:(?:退出|关闭)\s*cadence(?:\s*模式)?|exit\s+cadence(?:\s+mode)?)[。.!!]?$/iu.test(
174
+ s.trim(),
175
+ );
176
+ const EXIT_ARGS = new Set(["exit", "off", "quit", "退出", "关闭"]);
128
177
  const result = (text: string) => ({
129
178
  content: [{ type: "text" as const, text }],
130
179
  details: undefined,
131
180
  });
132
- const value = <T>(reply: Reply<T>): T => {
133
- if (reply.kind !== "ok") throw new ContractError(reply.error.code);
134
- return reply.value;
135
- };
181
+ /** A refused reply keeps its proven effect: only `none` restores state. */
182
+ class CadenceRefusal extends ContractError {
183
+ constructor(
184
+ code: ErrorCode,
185
+ readonly effect: PublicError["effect"],
186
+ ) {
187
+ super(code);
188
+ }
189
+ }
190
+ const definite = (error: unknown) =>
191
+ error instanceof CadenceRefusal && error.effect === "none";
192
+ /** Codes after which the attachment itself may be dead or superseded. A
193
+ * restarted owner on the same port answers the old capability with
194
+ * `forbidden`/`unauthenticated`; the registry check decides whether to drop it. */
195
+ const DETACHED = new Set([
196
+ "unavailable",
197
+ "stale",
198
+ "unsupported-context",
199
+ "forbidden",
200
+ "unauthenticated",
201
+ ]);
136
202
  const guard = (ctx: ExtensionContext) =>
137
203
  ctx.mode === "tui" &&
138
204
  ctx.hasUI &&
139
205
  ctx.isProjectTrusted() &&
140
206
  process.env.CADENCE_SUBAGENT_CHILD !== "1";
207
+ const clip = (text: string, max: number) =>
208
+ text.length > max ? `${text.slice(0, max)}\n… (truncated)` : text;
209
+ /** One retained step transcript as bounded readable text for the model. */
210
+ export function transcriptText(turn: ChatTurn | null): string {
211
+ if (!turn) return "No retained transcript for this step.";
212
+ const lines = [`Transcript (${turn.status})`];
213
+ for (const item of turn.items)
214
+ lines.push(
215
+ item.role === "tool"
216
+ ? `tool ${item.name}${item.error ? " (error)" : ""} ${clip(item.args, 512)}\n→ ${clip(item.text, 4096)}`
217
+ : `${item.role}: ${clip(item.text, 8192)}`,
218
+ );
219
+ if (turn.notice) lines.push(turn.notice);
220
+ return clip(lines.join("\n\n"), 48 * 1024);
221
+ }
141
222
  const CHECK = Type.Object({
142
223
  name: Type.String(),
143
224
  command: Type.String(),
@@ -168,6 +249,32 @@ const PLAN = Type.Object({
168
249
  Type.Literal("working-copy"),
169
250
  ]),
170
251
  });
252
+ /** The exact plan text, shown in full whether or not tool output is expanded.
253
+ * Markdown needs Pi's initialized theme; plain text is the fallback. */
254
+ function planComponent(text: string): Component {
255
+ const clean = diagnosticText(text, Number.MAX_SAFE_INTEGER);
256
+ const plain = new Text(clean, 0, 0);
257
+ let markdown: Markdown | undefined;
258
+ try {
259
+ markdown = new Markdown(clean, 0, 0, getMarkdownTheme());
260
+ } catch {
261
+ markdown = undefined;
262
+ }
263
+ return {
264
+ render(width) {
265
+ try {
266
+ if (markdown) return markdown.render(width);
267
+ } catch {
268
+ markdown = undefined;
269
+ }
270
+ return plain.render(width);
271
+ },
272
+ invalidate() {
273
+ markdown?.invalidate();
274
+ plain.invalidate();
275
+ },
276
+ };
277
+ }
171
278
 
172
279
  export function registerCadenceMode(pi: ExtensionAPI): void {
173
280
  let state = idle(),
@@ -175,88 +282,183 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
175
282
  generation = 0;
176
283
  let permission: { id: string; digest: string; at: number } | undefined;
177
284
  let allowStart = false,
178
- connecting: Promise<void> | undefined;
285
+ reattach = false;
286
+ let attaching: Promise<void> | undefined,
287
+ selecting: Promise<void> | undefined;
179
288
  let unsubscribe: (() => void) | undefined,
180
289
  poll: ReturnType<typeof setInterval> | undefined;
181
- let polling = false;
182
- // Host action methods are unavailable during extension discovery/loading.
183
- let normalTools: string[] = [];
290
+ let polling = false,
291
+ warnedPreferences = false;
292
+ /** Tools to restore while this session shows only Cadence tools. */
293
+ let applied: string[] | undefined;
294
+ /** A run whose unknown outcome the user explicitly observed. */
295
+ let acknowledgedUnknown: string | undefined;
296
+ /** Workflow results that finished while Pi was busy, appended once idle. */
297
+ let pending: { generation: number; content: string }[] = [];
184
298
  const raw = new CadenceUserInput(),
185
299
  connection = new NativeConnection();
186
300
  const client = () => {
187
301
  if (!connection.client) throw new ContractError("unavailable");
188
302
  return connection.client;
189
303
  };
190
- const persist = () => pi.appendEntry(CADENCE_MODE_ENTRY, state);
304
+ const value = <T>(reply: Reply<T>): T => {
305
+ if (reply.kind === "ok") return reply.value;
306
+ if (DETACHED.has(reply.error.code)) reattach = true;
307
+ throw new CadenceRefusal(reply.error.code, reply.error.effect);
308
+ };
309
+ // Proposal bodies stay in tool results; the entry restores mode only.
310
+ const persist = () =>
311
+ pi.appendEntry(CADENCE_MODE_ENTRY, { ...state, proposal: null });
312
+ /** Mode is engaged only in the trusted interactive terminal it belongs to;
313
+ * elsewhere (print/RPC/untrusted) a saved mode is inert, never a lock. */
314
+ const engaged = (ctx: ExtensionContext) =>
315
+ state.enabled && guard(ctx) && ctx.cwd === state.cwd;
191
316
  const status = (text = "ready") =>
192
317
  context?.ui.setStatus(
193
318
  "cadence",
194
- state.enabled ? `Cadence • ${text}` : undefined,
319
+ !state.enabled
320
+ ? undefined
321
+ : context && engaged(context)
322
+ ? `Cadence • ${text}`
323
+ : "Cadence • inactive here",
195
324
  );
325
+ const hide = () => {
326
+ const current = pi.getActiveTools();
327
+ if (current.some((n) => TOOLS.includes(n)))
328
+ pi.setActiveTools(current.filter((n) => !TOOLS.includes(n)));
329
+ };
330
+ const release = () => {
331
+ if (!applied) return;
332
+ const previous = applied;
333
+ applied = undefined;
334
+ pi.setActiveTools(previous);
335
+ };
336
+ const engage = () => {
337
+ if (!applied) {
338
+ const current = pi.getActiveTools().filter((n) => !TOOLS.includes(n));
339
+ applied = state.previousTools.length ? state.previousTools : current;
340
+ }
341
+ pi.setActiveTools(TOOLS);
342
+ };
196
343
  const stopPolling = () => {
197
344
  clearInterval(poll);
198
345
  poll = undefined;
199
346
  };
200
347
  const active = (ctx: ExtensionContext) => {
201
- if (!state.enabled || !guard(ctx) || ctx.cwd !== state.cwd)
202
- throw new ContractError("forbidden");
348
+ if (!state.enabled)
349
+ throw new Error(
350
+ "Cadence mode is off in this conversation. Accepted work, if any, continues in the project owner.",
351
+ );
352
+ if (!engaged(ctx)) throw new ContractError("forbidden");
203
353
  context = ctx;
204
354
  };
205
355
  const summarize = (run: WorkflowRun) =>
206
- `Cadence ${run.status} • ${run.goal}\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}` : ""}\nAutomatic review is not human review. Cadence mode remains enabled.`;
207
- const agentDir = () =>
208
- process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
209
- const connect = async (ctx: ExtensionContext, selectModel = true) => {
210
- active(ctx);
211
- if (connecting) return connecting;
356
+ `Cadence ${run.status} • ${run.goal}\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.`;
357
+ const agentDir = () => getAgentDir();
358
+ const launchOwner = async (ctx: ExtensionContext) => {
359
+ if (process.env.CADENCE_AUTOSTART === "0")
360
+ throw new Error(
361
+ "On-demand owner startup is disabled by CADENCE_AUTOSTART=0. Start the project explicitly or change that preference.",
362
+ );
363
+ // service-cli needs Node; a compiled or Bun-run Pi has no Node execPath.
364
+ const bun = !!process.versions.bun;
365
+ // Explicit mode entry/current user Send only. No install or boot registration.
366
+ const launched = await pi.exec(
367
+ bun ? "node" : process.execPath,
368
+ [
369
+ fileURLToPath(new URL("./service-cli.mjs", import.meta.url)),
370
+ "project",
371
+ "open",
372
+ ctx.cwd,
373
+ "--agent-dir",
374
+ agentDir(),
375
+ ],
376
+ { timeout: 20000 },
377
+ );
378
+ // A signal (including the timeout) reports code 0 from Pi's exec.
379
+ if (launched.killed || launched.code !== 0)
380
+ throw new Error(
381
+ `Cadence project owner could not start${launched.killed ? " before its startup deadline" : ""}.${bun ? " Pi runs on Bun here; on-demand startup needs Node.js 22.19+ on PATH." : ""} No install, fallback or uncertain-lock cleanup was attempted. Use cadence-service diagnose --workspace <path> for details.`,
382
+ );
383
+ let workspace = effectiveWorkspace(ctx.cwd).workspace;
384
+ try {
385
+ const report = JSON.parse(
386
+ launched.stdout.trim().split("\n").at(-1) ?? "",
387
+ );
388
+ if (typeof report?.workspace === "string") workspace = report.workspace;
389
+ } catch {
390
+ // The command succeeded; only the optional path detail is missing.
391
+ }
392
+ if (!announcedOwners.has(workspace)) {
393
+ announcedOwners.add(workspace);
394
+ ctx.ui.notify(
395
+ `Cadence started a background project owner for ${workspace}. It keeps running after Pi exits so accepted work can finish; it is not a boot service. Stop it explicitly with: ${projectStopCommand(workspace)}`,
396
+ "info",
397
+ );
398
+ }
399
+ };
400
+ /** Attach once; a dead, superseded or half-made attachment is replaced on
401
+ * the next call. A live owner and its configuration are never replaced. */
402
+ const ensureAttached = (ctx: ExtensionContext) => {
403
+ if (attaching) return attaching;
212
404
  const expected = generation;
213
405
  const check = () => {
214
406
  active(ctx);
215
407
  if (generation !== expected) throw new ContractError("stale");
216
408
  };
217
- const operation = async () => {
218
- if (!connection.client) {
219
- const coordination = new ServiceCoordination(
220
- effectiveWorkspace(ctx.cwd).workspace,
221
- );
222
- const observed = coordination.inspect();
223
- if (
224
- (observed.status === "absent" || observed.status === "stopped") &&
225
- allowStart
226
- ) {
227
- if (process.env.CADENCE_AUTOSTART === "0")
228
- throw new Error(
229
- "On-demand owner startup is disabled by CADENCE_AUTOSTART=0. Start the project explicitly or change that preference.",
230
- );
231
- // Explicit mode entry/current user Send only. No install or boot registration.
232
- const launched = await pi.exec(
233
- process.execPath,
234
- [
235
- fileURLToPath(new URL("./service-cli.mjs", import.meta.url)),
236
- "project",
237
- "open",
238
- ctx.cwd,
239
- "--agent-dir",
240
- agentDir(),
241
- ],
242
- { timeout: 20000 },
243
- );
244
- check();
245
- if (launched.code !== 0)
246
- throw new Error(
247
- "Cadence project owner could not start. No install, fallback or uncertain-lock cleanup was attempted. Use cadence-service diagnose for details.",
248
- );
249
- }
250
- await connection.attach(ctx.cwd);
409
+ const operation = (async () => {
410
+ const broken =
411
+ !!connection.client &&
412
+ (reattach || !connection.session || !connection.compatible());
413
+ if (connection.client && !broken) return;
414
+ reattach = false;
415
+ if (broken) connection.forgetSuperseded(ctx.cwd);
416
+ const observed = new ServiceCoordination(
417
+ effectiveWorkspace(ctx.cwd).workspace,
418
+ ).inspect();
419
+ if (
420
+ (observed.status === "absent" || observed.status === "stopped") &&
421
+ allowStart
422
+ ) {
423
+ await launchOwner(ctx);
251
424
  check();
252
425
  }
253
- if (!connection.client || !connection.compatible())
254
- throw new ContractError("unsupported-context");
255
- if (!selectModel) return;
256
- const catalog = value(await connection.client.models());
426
+ try {
427
+ await connection.attach(ctx.cwd);
428
+ } catch (error) {
429
+ reattach = true;
430
+ throw error;
431
+ }
257
432
  check();
433
+ })();
434
+ attaching = operation;
435
+ return operation.finally(() => {
436
+ if (attaching === operation) attaching = undefined;
437
+ });
438
+ };
439
+ /** The remembered (or current Pi) model on the owner, shared in flight, so
440
+ * a model-selecting caller never inherits an attach-only connection. */
441
+ const ensureModel = (ctx: ExtensionContext) => {
442
+ if (selecting) return selecting;
443
+ const expected = generation;
444
+ const operation = (async () => {
445
+ const catalog = value(await client().models());
446
+ if (generation !== expected) throw new ContractError("stale");
258
447
  const preferences = new CadencePreferences(agentDir());
259
- const saved = preferences.read();
448
+ let saved: ModelSelector | null = null,
449
+ unreadable = false;
450
+ try {
451
+ saved = preferences.read();
452
+ } catch {
453
+ unreadable = true;
454
+ if (!warnedPreferences) {
455
+ warnedPreferences = true;
456
+ ctx.ui.notify(
457
+ `Cadence model preference ${preferences.path} is unreadable; using the current Pi model. Ask Cadence to change its model to rewrite that file.`,
458
+ "warning",
459
+ );
460
+ }
461
+ }
260
462
  const selected =
261
463
  saved ??
262
464
  (ctx.model
@@ -279,26 +481,47 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
279
481
  }) === canonicalJson(selected);
280
482
  if (!same) {
281
483
  value(
282
- await connection.client.chooseModel({
484
+ await client().chooseModel({
283
485
  expected: catalog.version,
284
486
  choice: selected,
285
487
  }),
286
488
  );
287
- check();
489
+ if (generation !== expected) throw new ContractError("stale");
288
490
  }
289
- if (!saved) preferences.save(selected);
290
- };
291
- connecting = operation();
292
- try {
293
- await connecting;
294
- } finally {
295
- connecting = undefined;
491
+ if (!saved && !unreadable)
492
+ try {
493
+ preferences.save(selected);
494
+ } catch {
495
+ // Remembering is optional; the owner already uses this model.
496
+ }
497
+ })();
498
+ selecting = operation;
499
+ return operation.finally(() => {
500
+ if (selecting === operation) selecting = undefined;
501
+ });
502
+ };
503
+ const connect = async (ctx: ExtensionContext, selectModel = true) => {
504
+ active(ctx);
505
+ await ensureAttached(ctx);
506
+ if (!connection.client || !connection.compatible()) {
507
+ reattach = true;
508
+ let stop = "its explicit stop command";
509
+ try {
510
+ stop = projectStopCommand(effectiveWorkspace(ctx.cwd).workspace);
511
+ } catch {
512
+ // The guidance keeps its generic wording.
513
+ }
514
+ throw new Error(
515
+ `unsupported-context: the running Cadence project owner does not match this Cadence build or its WebUI assets. Nothing was started or replaced. When no accepted work is running, stop it with ${stop}; the next Cadence use starts the matching version.`,
516
+ );
296
517
  }
518
+ if (selectModel) await ensureModel(ctx);
297
519
  };
298
520
  const request = async (
299
521
  ctx: ExtensionContext,
300
522
  input: WorkflowRequest,
301
523
  commandId = randomUUID(),
524
+ sending?: () => void,
302
525
  ): Promise<WorkflowResponse> => {
303
526
  await connect(
304
527
  ctx,
@@ -306,14 +529,15 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
306
529
  );
307
530
  if (!connection.client || !connection.session)
308
531
  throw new ContractError("unavailable");
309
- const r = value(
310
- await connection.client.workbenchCommand({
311
- kind: "workflow",
312
- commandId,
313
- epoch: connection.session.epoch,
314
- request: input,
315
- }),
316
- );
532
+ const command = {
533
+ kind: "workflow" as const,
534
+ commandId,
535
+ epoch: connection.session.epoch,
536
+ request: input,
537
+ };
538
+ // Everything before this point had no owner effect.
539
+ sending?.();
540
+ const r = value(await connection.client.workbenchCommand(command));
317
541
  if (r.kind !== "workflow") throw new ContractError("invalid");
318
542
  const response = r.response;
319
543
  if (
@@ -321,11 +545,10 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
321
545
  (response.type !== "run" || response.run.id !== commandId)) ||
322
546
  (input.action === "cancel" &&
323
547
  (response.type !== "run" || response.run.id !== input.runId)) ||
548
+ // The owner may redact credential-like text; its proposal is the exact
549
+ // plan that would run and is what the user sees and approves.
324
550
  (input.action === "propose" &&
325
- (response.type !== "proposal" ||
326
- response.proposal.id !== commandId ||
327
- canonicalJson(response.proposal.plan) !==
328
- canonicalJson(input.plan))) ||
551
+ (response.type !== "proposal" || response.proposal.id !== commandId)) ||
329
552
  (input.action === "prepare" &&
330
553
  (response.type !== "grant" ||
331
554
  response.proposal.id !== input.proposalId ||
@@ -334,29 +557,83 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
334
557
  throw new ContractError("unavailable");
335
558
  return response;
336
559
  };
560
+ /** A run, or proof that the owner never accepted it: a reachable owner that
561
+ * has no record of the ID and does not list it as active. */
337
562
  const observe = async (
338
563
  ctx: ExtensionContext,
339
564
  id: string,
340
- ): Promise<WorkflowRun> => {
565
+ ): Promise<{ run: WorkflowRun } | { absent: true }> => {
341
566
  await connect(ctx, false);
342
- if (!connection.client) throw new ContractError("unavailable");
343
- const r = value(
344
- await connection.client.workbenchRead({ kind: "workflow", id }),
345
- );
567
+ const reply = await client().workbenchRead({ kind: "workflow", id });
568
+ if (reply.kind === "error" && reply.error.code === "unavailable") {
569
+ const roster = await client().workbenchRead({ kind: "workflow-active" });
570
+ if (
571
+ roster.kind === "ok" &&
572
+ roster.value.kind === "workflow-active" &&
573
+ !roster.value.runs.some((run) => run.id === id)
574
+ )
575
+ return { absent: true };
576
+ }
577
+ const r = value(reply);
346
578
  if (
347
579
  r.kind !== "workflow" ||
348
580
  r.response.type !== "run" ||
349
581
  r.response.run.id !== id
350
582
  )
351
583
  throw new ContractError("invalid");
352
- return r.response.run;
584
+ return { run: r.response.run };
353
585
  };
586
+ const forget = (id: string) => {
587
+ if (state.runId !== id) return "";
588
+ state.runId = null;
589
+ persist();
590
+ return `Attempted run ${id} is not known to the owner and is not active, so it was never accepted. Cadence forgot it; nothing was replayed.\n`;
591
+ };
592
+ /** Returns a notice when an attempted run was proven absent and forgotten. */
354
593
  const requireSettledRun = async (ctx: ExtensionContext) => {
355
- if (!state.runId) return;
356
- const previous = await observe(ctx, state.runId);
357
- if (["running", "queued", "unknown"].includes(previous.status))
594
+ if (!state.runId) return "";
595
+ const seen = await observe(ctx, state.runId);
596
+ if ("absent" in seen) return forget(state.runId);
597
+ const previous = seen.run;
598
+ if (["running", "queued"].includes(previous.status))
599
+ throw new Error(
600
+ "The current workflow is still active. Keep discussing or use cadence_status/cadence_cancel; do not replace its identity with another goal.",
601
+ );
602
+ if (previous.status === "unknown" && acknowledgedUnknown !== previous.id)
358
603
  throw new Error(
359
- "The current workflow is still active or uncertain. Keep discussing or use cadence_status/cadence_cancel; do not replace its identity with another goal.",
604
+ `Workflow ${previous.id} has an unknown outcome (for example, its owner stopped while it ran); it is neither completed nor failed. Call cadence_status to observe it explicitly; after that research or a new plan may continue.`,
605
+ );
606
+ return "";
607
+ };
608
+ const deliver = (ctx: ExtensionContext, run: WorkflowRun) => {
609
+ ctx.ui.notify(
610
+ `Cadence workflow ${run.status}: ${run.goal.slice(0, 160)}`,
611
+ run.status === "completed" ? "info" : "warning",
612
+ );
613
+ // A message appended mid-turn would split a tool call from its result.
614
+ if (ctx.isIdle())
615
+ pi.sendMessage(
616
+ {
617
+ customType: "cadence-workflow-result",
618
+ content: summarize(run),
619
+ display: true,
620
+ },
621
+ { triggerTurn: false },
622
+ );
623
+ else pending.push({ generation, content: summarize(run) });
624
+ };
625
+ const flush = (ctx: ExtensionContext) => {
626
+ if (!pending.length || !ctx.isIdle()) return;
627
+ const ready = pending.filter((p) => p.generation === generation);
628
+ pending = [];
629
+ for (const p of ready)
630
+ pi.sendMessage(
631
+ {
632
+ customType: "cadence-workflow-result",
633
+ content: p.content,
634
+ display: true,
635
+ },
636
+ { triggerTurn: false },
360
637
  );
361
638
  };
362
639
  const watch = (ctx: ExtensionContext, id: string) => {
@@ -366,8 +643,14 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
366
643
  if (polling || generation !== expected || !state.enabled) return;
367
644
  polling = true;
368
645
  void observe(ctx, id)
369
- .then((run) => {
646
+ .then((seen) => {
370
647
  if (generation !== expected || state.runId !== id) return;
648
+ if ("absent" in seen) {
649
+ stopPolling();
650
+ status("ready");
651
+ return;
652
+ }
653
+ const run = seen.run;
371
654
  status(
372
655
  run.status === "running" || run.status === "queued"
373
656
  ? run.phase
@@ -375,14 +658,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
375
658
  );
376
659
  if (!["running", "queued"].includes(run.status)) {
377
660
  stopPolling();
378
- pi.sendMessage(
379
- {
380
- customType: "cadence-workflow-result",
381
- content: summarize(run),
382
- display: true,
383
- },
384
- { triggerTurn: false },
385
- );
661
+ deliver(ctx, run);
386
662
  }
387
663
  })
388
664
  .catch(() => {
@@ -395,24 +671,81 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
395
671
  }, 2000);
396
672
  poll.unref?.();
397
673
  };
674
+ /** A guarded dialog: the safe choice comes first (a stray Enter picks it),
675
+ * and the other needs a typed, non-paste Enter after the dialog settled. */
676
+ /** A model-opened selection counts only with a typed, non-paste Enter
677
+ * after the dialog settled; anything else reads as no selection. */
678
+ const pick = async (
679
+ ctx: ExtensionContext,
680
+ title: string,
681
+ options: string[],
682
+ ) => {
683
+ raw.openDialog();
684
+ let choice: string | undefined;
685
+ try {
686
+ choice = await ctx.ui.select(title, options);
687
+ } finally {
688
+ if (!raw.closeDialog()) choice = undefined;
689
+ }
690
+ return choice;
691
+ };
692
+ const confirm = async (
693
+ ctx: ExtensionContext,
694
+ title: string,
695
+ message: string,
696
+ safe: string,
697
+ act: string,
698
+ ) => (await pick(ctx, `${title}\n${message}`, [safe, act])) === act;
398
699
  const leave = async () => {
399
700
  ++generation;
400
701
  raw.clear();
401
702
  permission = undefined;
402
703
  allowStart = false;
704
+ pending = [];
403
705
  stopPolling();
404
- if (state.enabled) pi.setActiveTools(state.previousTools);
405
706
  return connection.detach();
406
707
  };
407
- pi.on("session_start", (_event, ctx) => {
708
+ const exit = (ctx: ExtensionContext) => {
709
+ context = ctx;
710
+ if (!state.enabled) {
711
+ ctx.ui.notify(
712
+ "Cadence mode is not enabled in this conversation.",
713
+ "info",
714
+ );
715
+ return;
716
+ }
717
+ release();
718
+ hide();
719
+ state = { ...state, enabled: false, proposal: null };
720
+ persist();
721
+ status();
408
722
  void leave().catch(() => {});
409
- unsubscribe?.();
723
+ ctx.ui.notify(
724
+ "Cadence mode disabled. Accepted work, if any, continues; exit is not Cancel.",
725
+ "info",
726
+ );
727
+ };
728
+ const rebind = (ctx: ExtensionContext) => {
410
729
  context = ctx;
411
730
  state = restoreCadenceMode(ctx.sessionManager.getBranch(), ctx.cwd);
412
- const normal = pi.getActiveTools().filter((n) => !TOOLS.includes(n));
413
- normalTools = normal;
414
- if (!state.previousTools.length) state.previousTools = normal;
415
- pi.setActiveTools(state.enabled ? TOOLS : normal);
731
+ acknowledgedUnknown = undefined;
732
+ if (engaged(ctx)) engage();
733
+ else {
734
+ // Only a session that showed Cadence tools changes the active set.
735
+ release();
736
+ hide();
737
+ }
738
+ };
739
+ pi.on("session_start", (_event, ctx) => {
740
+ void leave().catch(() => {});
741
+ unsubscribe?.();
742
+ unsubscribe = undefined;
743
+ rebind(ctx);
744
+ if (state.enabled && !engaged(ctx) && ctx.hasUI)
745
+ ctx.ui.notify(
746
+ `Cadence mode is saved for this conversation but inactive here: it needs a trusted interactive Pi terminal. Ordinary tools remain available; to leave the mode, ${EXIT_HINT}.`,
747
+ "info",
748
+ );
416
749
  status(state.runId ? "retained work; ask for status" : "ready");
417
750
  if (ctx.mode === "tui")
418
751
  unsubscribe = ctx.ui.onTerminalInput((data) => {
@@ -427,8 +760,11 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
427
760
  pi.on("session_shutdown", () => {
428
761
  unsubscribe?.();
429
762
  unsubscribe = undefined;
763
+ release();
430
764
  return departure(leave());
431
765
  });
766
+ // Navigation only detaches; tools change when the new branch is bound, so
767
+ // a canceled switch or navigation keeps the current mode intact.
432
768
  pi.on("session_before_switch", () => {
433
769
  void leave().catch(() => {});
434
770
  });
@@ -439,36 +775,23 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
439
775
  void leave().catch(() => {});
440
776
  });
441
777
  pi.on("session_tree", (_event, ctx) => {
442
- state = restoreCadenceMode(ctx.sessionManager.getBranch(), ctx.cwd);
443
- context = ctx;
444
- pi.setActiveTools(
445
- state.enabled
446
- ? TOOLS
447
- : state.previousTools.length
448
- ? state.previousTools
449
- : normalTools,
450
- );
778
+ rebind(ctx);
451
779
  status();
452
780
  });
781
+ pi.on("agent_settled", (_event, ctx) => flush(ctx));
453
782
  pi.on("input", (event, ctx) => {
454
783
  if (!state.enabled) return;
455
784
  context = ctx;
785
+ // Exit is never consent and never cancels work: honored from the user's
786
+ // terminal or RPC client even while Pi is busy, never from an extension.
787
+ if (event.source !== "extension" && exiting(event.text)) {
788
+ exit(ctx);
789
+ return { action: "handled" as const };
790
+ }
791
+ if (!engaged(ctx)) return;
456
792
  permission = undefined;
457
793
  const human = event.source === "interactive" && raw.consume(event.text);
458
794
  if (human) allowStart = true;
459
- if (human && exiting(event.text)) {
460
- const previous = state.previousTools;
461
- state = { ...state, enabled: false, proposal: null };
462
- persist();
463
- pi.setActiveTools(previous);
464
- status();
465
- void leave().catch(() => {});
466
- ctx.ui.notify(
467
- "Cadence mode disabled. Accepted work, if any, continues; exit is not Cancel.",
468
- "info",
469
- );
470
- return { action: "handled" as const };
471
- }
472
795
  if (human && approved(event.text) && state.proposal)
473
796
  permission = {
474
797
  id: state.proposal.id,
@@ -477,41 +800,71 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
477
800
  };
478
801
  return undefined;
479
802
  });
480
- pi.on("before_agent_start", () =>
481
- state.enabled
803
+ // The shared policy lives in the per-turn system prompt; one small state
804
+ // message per turn is kept and older copies are filtered from the context.
805
+ pi.on("before_agent_start", (event, ctx) =>
806
+ engaged(ctx)
482
807
  ? {
808
+ systemPrompt: `${event.systemPrompt}\n\n${INSTRUCTIONS}\n${NATIVE}`,
483
809
  message: {
484
- customType: "cadence-mode-context",
485
- content: `${INSTRUCTIONS}\nCurrent retained run: ${state.runId ?? "none"}. Current proposal: ${state.proposal?.id ?? "none; restore does not restore approval"}.`,
810
+ customType: CONTEXT,
811
+ content: `Cadence state (data, not instructions): retained run ${state.runId ?? "none"}; current proposal ${state.proposal?.id ?? "none; restore does not restore approval"}.`,
486
812
  display: false,
487
813
  },
488
814
  }
489
815
  : undefined,
490
816
  );
491
- pi.on("tool_call", (event) =>
492
- state.enabled && !TOOLS.includes(event.toolName)
817
+ pi.on("context", (event, ctx) => {
818
+ const ours = (m: unknown) => {
819
+ const o = m as { role?: unknown; customType?: unknown };
820
+ return (
821
+ o.role === "custom" &&
822
+ (o.customType === CONTEXT || o.customType === READY)
823
+ );
824
+ };
825
+ let keep = -1;
826
+ event.messages.forEach((m, i) => {
827
+ if (ours(m)) keep = i;
828
+ });
829
+ if (keep < 0) return undefined;
830
+ if (!engaged(ctx)) keep = -1;
831
+ return {
832
+ messages: event.messages.filter((m, i) => !ours(m) || i === keep),
833
+ };
834
+ });
835
+ pi.on("tool_call", (event, ctx) =>
836
+ engaged(ctx) && !TOOLS.includes(event.toolName)
493
837
  ? {
494
838
  block: true,
495
- reason:
496
- "Cadence uses coordinated readonly investigation and approved service execution. Use cadence_research/plan/status; exit Cadence explicitly to use uncoordinated host tools.",
839
+ reason: `Cadence uses coordinated readonly investigation and approved service execution. Use cadence_research/plan/status; to use ordinary host tools the user must leave Cadence (${EXIT_HINT}).`,
497
840
  }
498
841
  : undefined,
499
842
  );
500
843
  pi.registerCommand("cadence", {
501
844
  description:
502
- "Enable Cadence for this entire conversation: /cadence [goal]. Continue in normal conversation; explicit exit only.",
845
+ "Enable Cadence for this conversation: /cadence [goal]. It stays on until you type 退出 Cadence / exit cadence or run /cadence exit.",
503
846
  handler: async (args, ctx) => {
504
- if (
505
- !guard(ctx) ||
506
- !ctx.isIdle() ||
507
- ctx.hasPendingMessages() ||
508
- !raw.consumeCommand(args)
509
- )
847
+ if (EXIT_ARGS.has(args.trim().toLowerCase())) {
848
+ exit(ctx);
849
+ return;
850
+ }
851
+ if (!guard(ctx) || !ctx.isIdle() || ctx.hasPendingMessages()) {
852
+ raw.clear();
853
+ if (ctx.hasUI)
854
+ ctx.ui.notify(
855
+ guard(ctx)
856
+ ? "Cadence: wait until Pi is idle, then enter /cadence again."
857
+ : "Cadence mode needs a trusted interactive Pi terminal.",
858
+ "info",
859
+ );
510
860
  return;
861
+ }
862
+ if (!raw.consumeCommand(args)) return;
511
863
  context = ctx;
512
864
  permission = undefined;
513
865
  allowStart = true;
514
- if (!state.enabled) {
866
+ if (state.enabled) reattach = true;
867
+ else {
515
868
  state = {
516
869
  ...idle(),
517
870
  enabled: true,
@@ -520,25 +873,24 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
520
873
  };
521
874
  persist();
522
875
  }
523
- pi.setActiveTools(TOOLS);
876
+ engage();
524
877
  status();
525
878
  pi.sendMessage(
526
879
  {
527
880
  customType: "cadence-mode",
528
- content:
529
- "Cadence mode is ON for this conversation, until you explicitly exit. I will investigate and clarify first; implementation requires approval of the final plan. No task-manager menu or repeated /cadence is needed.",
881
+ content: `Cadence mode is ON for this conversation until you explicitly leave it (${EXIT_HINT}). I will investigate and clarify first; implementation requires approval of the final plan. No task-manager menu or repeated /cadence is needed.`,
530
882
  display: true,
531
883
  },
532
884
  { triggerTurn: false },
533
885
  );
534
886
  if (args.trim())
535
- pi.sendUserMessage(args, { expandPromptTemplates: false });
887
+ pi.sendUserMessage(args.trim(), { expandPromptTemplates: false });
888
+ // This turn starts without a prompt, so it carries the policy itself.
536
889
  else
537
890
  pi.sendMessage(
538
891
  {
539
- customType: "cadence-mode-ready",
540
- content:
541
- "Cadence mode is enabled. Continue the current goal if clear; otherwise ask what the user wants to accomplish. Do not create or execute a plan merely because mode was enabled.",
892
+ customType: READY,
893
+ content: `${INSTRUCTIONS}\n${NATIVE}\nCadence mode is enabled. Continue the current goal if clear; otherwise ask what the user wants to accomplish. Do not create or execute a plan merely because mode was enabled.`,
542
894
  display: false,
543
895
  },
544
896
  { triggerTurn: true },
@@ -557,33 +909,49 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
557
909
  async execute(_id, input, signal, update, ctx) {
558
910
  active(ctx);
559
911
  await connect(ctx);
560
- await requireSettledRun(ctx);
912
+ const notice = await requireSettledRun(ctx);
561
913
  const model = value(await client().models()).version;
562
- const commandId = randomUUID();
563
- state.runId = commandId;
564
- persist();
565
- const response = await request(
566
- ctx,
567
- { action: "research", ...input, model },
568
- commandId,
569
- );
914
+ const commandId = randomUUID(),
915
+ before = state.runId;
916
+ let sent = false,
917
+ response: WorkflowResponse;
918
+ try {
919
+ response = await request(
920
+ ctx,
921
+ { action: "research", ...input, model },
922
+ commandId,
923
+ () => {
924
+ // Retain the attempted identity before transport: a lost reply is
925
+ // observed, never replaced with another research request.
926
+ state.runId = commandId;
927
+ persist();
928
+ sent = true;
929
+ },
930
+ );
931
+ } catch (error) {
932
+ if ((!sent || definite(error)) && state.runId === commandId) {
933
+ state.runId = before;
934
+ persist();
935
+ }
936
+ throw error;
937
+ }
570
938
  if (response.type !== "run") throw new ContractError("invalid");
571
- state.runId = response.run.id;
572
- persist();
573
939
  status("research");
574
940
  let run = response.run;
575
941
  while (["queued", "running"].includes(run.status) && !signal?.aborted) {
576
942
  update?.(
577
943
  result(
578
- `Investigating: ${run.goal}\n${run.steps.map((s) => `${s.id}: ${s.status}`).join("\n")}`,
944
+ `Investigating: ${run.goal}\n${run.steps.map((s) => `${s.kind} ${s.id}: ${s.status}`).join("\n")}\nSubagents are listed in Pi's agent panel.`,
579
945
  ),
580
946
  );
581
947
  await new Promise((resolve) => setTimeout(resolve, 1000));
582
- run = await observe(ctx, run.id);
948
+ const seen = await observe(ctx, run.id);
949
+ if ("absent" in seen) throw new ContractError("unavailable");
950
+ run = seen.run;
583
951
  }
584
952
  status("ready");
585
953
  if (signal?.aborted) watch(ctx, run.id);
586
- return result(summarize(run));
954
+ return result(`${notice}${summarize(run)}`);
587
955
  },
588
956
  });
589
957
  pi.registerTool({
@@ -596,7 +964,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
596
964
  active(ctx);
597
965
  await connect(ctx);
598
966
  permission = undefined;
599
- await requireSettledRun(ctx);
967
+ const notice = await requireSettledRun(ctx);
600
968
  const plan = decodeWorkflowPlan(input);
601
969
  const response = await request(ctx, {
602
970
  action: "propose",
@@ -607,16 +975,42 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
607
975
  state.proposal = response.proposal;
608
976
  persist();
609
977
  status("awaiting plan approval");
610
- pi.sendMessage(
611
- {
612
- customType: "cadence-proposed-plan",
613
- content: readableWorkflowPlan(plan),
614
- display: true,
978
+ const shown = readableWorkflowPlan(response.proposal.plan);
979
+ const redacted =
980
+ canonicalJson(response.proposal.plan) !== canonicalJson(plan);
981
+ // The plan is displayed by this tool's own result: a message sent now
982
+ // would land between this tool call and its result.
983
+ return {
984
+ content: [
985
+ {
986
+ type: "text" as const,
987
+ text: `${notice}${shown}\nPlan identity: ${response.proposal.digest}\n${redacted ? "The owner redacted credential-like text; the plan above is exactly what would run.\n" : ""}The user sees this complete plan. They can type 按计划实施 to approve these exact bytes; vague agreement is not execution consent. Existing unrelated working-copy changes are not imported into isolated candidates.`,
988
+ },
989
+ ],
990
+ details: {
991
+ plan: shown,
992
+ digest: response.proposal.digest,
993
+ redacted,
615
994
  },
616
- { triggerTurn: false },
617
- );
618
- return result(
619
- `${readableWorkflowPlan(plan)}\nPlan identity: ${response.proposal.digest}\nPlease show this plan to the user. They can type 按计划实施 to approve these exact bytes; vague agreement is not execution consent. Existing unrelated working-copy changes are not imported into isolated candidates.`,
995
+ };
996
+ },
997
+ renderResult(output) {
998
+ const d = output.details as
999
+ | { plan?: unknown; digest?: unknown; redacted?: unknown }
1000
+ | undefined;
1001
+ if (typeof d?.plan === "string" && typeof d.digest === "string")
1002
+ return planComponent(
1003
+ `${d.plan}\nPlan identity: ${d.digest}\n${d.redacted === true ? "Credential-like text was redacted by the owner; this is exactly what would run.\n" : ""}Type 按计划实施 to approve these exact bytes, or keep discussing.`,
1004
+ );
1005
+ return new Text(
1006
+ diagnosticText(
1007
+ output.content
1008
+ .map((c) => (c.type === "text" ? c.text : ""))
1009
+ .join("\n"),
1010
+ Number.MAX_SAFE_INTEGER,
1011
+ ),
1012
+ 0,
1013
+ 0,
620
1014
  );
621
1015
  },
622
1016
  });
@@ -632,12 +1026,6 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
632
1026
  if (!proposal)
633
1027
  throw new Error("No current plan. Clarify and propose it first.");
634
1028
  const expected = generation;
635
- const prepared = await request(ctx, {
636
- action: "prepare",
637
- proposalId: proposal.id,
638
- digest: proposal.digest,
639
- });
640
- if (prepared.type !== "grant") throw new ContractError("invalid");
641
1029
  const fromInput =
642
1030
  permission?.id === proposal.id &&
643
1031
  permission.digest === proposal.digest &&
@@ -646,9 +1034,12 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
646
1034
  permission = undefined;
647
1035
  if (
648
1036
  !fromInput &&
649
- !(await ctx.ui.confirm(
1037
+ !(await confirm(
1038
+ ctx,
650
1039
  "Implement this plan automatically?",
651
- `${readableWorkflowPlan(prepared.proposal.plan)}\nProject: ${prepared.proposal.cwd}\nNo push or deployment. Canceling this dialog changes nothing.`,
1040
+ `${readableWorkflowPlan(proposal.plan)}\nProject: ${proposal.cwd}\nNo push or deployment. Keeping the discussion changes nothing.`,
1041
+ "Keep discussing (do not start)",
1042
+ "Start this exact plan",
652
1043
  ))
653
1044
  )
654
1045
  return result(
@@ -660,22 +1051,52 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
660
1051
  state.proposal?.digest !== proposal.digest
661
1052
  )
662
1053
  throw new ContractError("stale");
663
- const commandId = randomUUID();
664
- // Retain the exact attempted identity before transport; a lost reply is
665
- // observed, never replaced with another Start or a revived approval.
666
- state.runId = commandId;
667
- state.proposal = null;
668
- persist();
669
- const started = await request(
670
- ctx,
671
- {
672
- action: "execute",
673
- proposalId: proposal.id,
674
- digest: proposal.digest,
675
- grant: prepared.grant,
676
- },
677
- commandId,
678
- );
1054
+ // The grant is fresh after consent, so reading the plan never expires it.
1055
+ const prepared = await request(ctx, {
1056
+ action: "prepare",
1057
+ proposalId: proposal.id,
1058
+ digest: proposal.digest,
1059
+ });
1060
+ if (
1061
+ prepared.type !== "grant" ||
1062
+ canonicalJson(prepared.proposal.plan) !==
1063
+ canonicalJson(proposal.plan) ||
1064
+ prepared.proposal.cwd !== proposal.cwd
1065
+ )
1066
+ throw new ContractError("stale");
1067
+ const commandId = randomUUID(),
1068
+ before = { runId: state.runId, proposal };
1069
+ let sent = false,
1070
+ started: WorkflowResponse;
1071
+ try {
1072
+ started = await request(
1073
+ ctx,
1074
+ {
1075
+ action: "execute",
1076
+ proposalId: proposal.id,
1077
+ digest: proposal.digest,
1078
+ grant: prepared.grant,
1079
+ },
1080
+ commandId,
1081
+ () => {
1082
+ // Retain the exact attempted identity before transport; a lost
1083
+ // reply is observed, never replaced with another Start or a
1084
+ // revived approval.
1085
+ state.runId = commandId;
1086
+ state.proposal = null;
1087
+ persist();
1088
+ sent = true;
1089
+ },
1090
+ );
1091
+ } catch (error) {
1092
+ // A proven refusal had no effect: keep the plan for a fresh approval.
1093
+ if ((!sent || definite(error)) && state.runId === commandId) {
1094
+ state.runId = before.runId;
1095
+ state.proposal = before.proposal;
1096
+ persist();
1097
+ }
1098
+ throw error;
1099
+ }
679
1100
  if (started.type !== "run") throw new ContractError("invalid");
680
1101
  state.runId = started.run.id;
681
1102
  state.proposal = null;
@@ -691,33 +1112,61 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
691
1112
  name: "cadence_status",
692
1113
  label: "Observe workflow",
693
1114
  description:
694
- "Read the current retained workflow outcome without replaying any action.",
695
- parameters: Type.Object({ stepId: Type.Optional(Type.String()) }),
1115
+ "Read the current retained workflow outcome without replaying any action. With stepId, read that step's retained result, or its subagent transcript with transcript: true.",
1116
+ parameters: Type.Object({
1117
+ stepId: Type.Optional(Type.String()),
1118
+ transcript: Type.Optional(Type.Boolean()),
1119
+ }),
696
1120
  async execute(_id, input, _signal, _update, ctx) {
697
1121
  active(ctx);
698
1122
  if (!state.runId)
699
1123
  return result(
700
1124
  "Cadence is enabled; no run yet. Continue clarifying the goal.",
701
1125
  );
1126
+ const id = state.runId;
702
1127
  if (input.stepId) {
703
1128
  await connect(ctx, false);
1129
+ if (input.transcript) {
1130
+ const t = value(
1131
+ await client().workbenchRead({
1132
+ kind: "workflow-transcript",
1133
+ id,
1134
+ stepId: input.stepId,
1135
+ }),
1136
+ );
1137
+ if (
1138
+ t.kind !== "workflow-transcript" ||
1139
+ t.runId !== id ||
1140
+ t.stepId !== input.stepId
1141
+ )
1142
+ throw new ContractError("invalid");
1143
+ return result(transcriptText(t.turn));
1144
+ }
704
1145
  const detail = value(
705
1146
  await client().workbenchRead({
706
1147
  kind: "workflow-detail",
707
- id: state.runId,
1148
+ id,
708
1149
  stepId: input.stepId,
709
1150
  }),
710
1151
  );
711
1152
  if (
712
1153
  detail.kind !== "file" ||
713
- detail.path !== `workflow/${state.runId}/${input.stepId}`
1154
+ detail.path !== `workflow/${id}/${input.stepId}`
714
1155
  )
715
1156
  throw new ContractError("invalid");
716
1157
  return result(detail.text);
717
1158
  }
718
- const run = await observe(ctx, state.runId);
1159
+ const seen = await observe(ctx, id);
1160
+ if ("absent" in seen) {
1161
+ status("ready");
1162
+ return result(`${forget(id)}Continue normally.`);
1163
+ }
1164
+ const run = seen.run;
719
1165
  if (["running", "queued"].includes(run.status)) watch(ctx, run.id);
720
- return result(summarize(run));
1166
+ if (run.status === "unknown") acknowledgedUnknown = run.id;
1167
+ return result(
1168
+ `${summarize(run)}${run.status === "unknown" ? "\nThis explicit observation is recorded: research or a new plan may now continue. A new plan observes the current files; nothing about this run is assumed." : ""}`,
1169
+ );
721
1170
  },
722
1171
  });
723
1172
  pi.registerTool({
@@ -730,9 +1179,12 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
730
1179
  active(ctx);
731
1180
  if (!state.runId) return result("No active workflow.");
732
1181
  if (
733
- !(await ctx.ui.confirm(
1182
+ !(await confirm(
1183
+ ctx,
734
1184
  "Cancel current workflow?",
735
1185
  "Request Stop and retain actual files/results. This does not reset or undo edits. Cadence mode remains enabled.",
1186
+ "Keep running",
1187
+ "Request cancellation",
736
1188
  ))
737
1189
  )
738
1190
  return result("Cancellation not requested.");
@@ -759,13 +1211,15 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
759
1211
  (m) => m.eligibility === "candidate" && m.api,
760
1212
  );
761
1213
  const labels = models.map((m) => `${m.provider}/${m.model} (${m.api})`);
762
- const selected = await ctx.ui.select(
1214
+ const selected = await pick(
1215
+ ctx,
763
1216
  "Cadence model (remembered across projects)",
764
1217
  labels,
765
1218
  );
766
1219
  if (!selected) return result("Model unchanged.");
767
1220
  const model = models[labels.indexOf(selected)];
768
- const thinking = await ctx.ui.select(
1221
+ const thinking = await pick(
1222
+ ctx,
769
1223
  "Thinking",
770
1224
  model.thinking.filter((t) => t.selectable).map((t) => t.level),
771
1225
  );
@@ -782,7 +1236,9 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
782
1236
  choice,
783
1237
  }),
784
1238
  );
785
- new CadencePreferences(agentDir()).save(choice);
1239
+ // An explicit selection may atomically rewrite a corrupt preference.
1240
+ new CadencePreferences(agentDir()).choose(choice);
1241
+ warnedPreferences = false;
786
1242
  state.proposal = null;
787
1243
  permission = undefined;
788
1244
  persist();