@abelxiaoxing/cadence 2.0.20 → 2.0.21

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.
@@ -0,0 +1,794 @@
1
+ /** Persistent, branch-aware conversation mode. No execution owner lives in Pi. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import type {
7
+ ExtensionAPI,
8
+ ExtensionContext,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import { Key, matchesKey } from "@earendil-works/pi-tui";
11
+ import { Type } from "typebox";
12
+ import { CADENCE_INSTRUCTIONS as INSTRUCTIONS } from "./cadence-instructions.ts";
13
+ import { CadencePreferences } from "./cadence-preferences.ts";
14
+ import { departure, NativeConnection } from "./native-client.ts";
15
+ import {
16
+ decodeWorkflowPlan,
17
+ readableWorkflowPlan,
18
+ type WorkflowProposal,
19
+ type WorkflowRequest,
20
+ type WorkflowResponse,
21
+ type WorkflowRun,
22
+ } from "./service/contracts/workflow.ts";
23
+ import { ServiceCoordination } from "./service/coordination.ts";
24
+ import {
25
+ ContractError,
26
+ canonicalJson,
27
+ decodeModelSelector,
28
+ type ModelSelector,
29
+ type Reply,
30
+ } from "./service-contract.ts";
31
+ import { effectiveWorkspace } from "./task-store.ts";
32
+
33
+ export const CADENCE_MODE_ENTRY = "cadence-conversation-mode/1";
34
+ const TOOLS = [
35
+ "cadence_research",
36
+ "cadence_plan",
37
+ "cadence_start",
38
+ "cadence_status",
39
+ "cadence_cancel",
40
+ "cadence_model",
41
+ ];
42
+ export interface CadenceModeState {
43
+ enabled: boolean;
44
+ cwd: string;
45
+ runId: string | null;
46
+ proposal: WorkflowProposal | null;
47
+ previousTools: string[];
48
+ }
49
+ const idle = (): CadenceModeState => ({
50
+ enabled: false,
51
+ cwd: "",
52
+ runId: null,
53
+ proposal: null,
54
+ previousTools: [],
55
+ });
56
+ /** Session restoration restores mode/context, NEVER a grant, pending command or action replay. */
57
+ export function restoreCadenceMode(
58
+ entries: readonly { type: string; customType?: string; data?: unknown }[],
59
+ cwd: string,
60
+ ): CadenceModeState {
61
+ let state = idle();
62
+ for (const entry of entries) {
63
+ if (entry.type !== "custom" || entry.customType !== CADENCE_MODE_ENTRY)
64
+ continue;
65
+ const v = entry.data as Partial<CadenceModeState> | null;
66
+ if (
67
+ !v ||
68
+ typeof v.enabled !== "boolean" ||
69
+ v.cwd !== cwd ||
70
+ !Array.isArray(v.previousTools) ||
71
+ !v.previousTools.every((s) => typeof s === "string") ||
72
+ !(v.runId === null || typeof v.runId === "string")
73
+ ) {
74
+ state = idle();
75
+ continue;
76
+ }
77
+ state = {
78
+ enabled: v.enabled,
79
+ cwd,
80
+ runId: v.runId,
81
+ proposal: null,
82
+ previousTools: v.previousTools.filter((n) => !TOOLS.includes(n)),
83
+ };
84
+ }
85
+ return state;
86
+ }
87
+ /** Raw terminal evidence is ephemeral, never supplied by model/tool text or paste. */
88
+ export class CadenceUserInput {
89
+ private value: { text: string; at: number } | undefined;
90
+ private pasting = false;
91
+ clear() {
92
+ this.value = undefined;
93
+ }
94
+ input(data: string, text: string, eligible: boolean, at = Date.now()) {
95
+ this.clear();
96
+ if (data.includes("\x1b[200~")) this.pasting = true;
97
+ if (data.includes("\x1b[201~")) {
98
+ this.pasting = false;
99
+ return;
100
+ }
101
+ if (!this.pasting && eligible && matchesKey(data, Key.enter))
102
+ this.value = { text, at };
103
+ }
104
+ consumeCommand(args: string, at = Date.now()) {
105
+ const v = this.value;
106
+ if (
107
+ !v ||
108
+ !/^\/cadence(?:[ \t]+[^\r\n]*)?$/u.test(v.text) ||
109
+ v.text.replace(/^\/cadence[ \t]*/u, "") !== args
110
+ ) {
111
+ this.clear();
112
+ return false;
113
+ }
114
+ return this.consume(v.text, at);
115
+ }
116
+ consume(text: string, at = Date.now()) {
117
+ const v = this.value;
118
+ this.clear();
119
+ return !!v && v.text === text && at >= v.at && at - v.at < 1500;
120
+ }
121
+ }
122
+ const approved = (s: string) =>
123
+ /^(?:按(?:这个|本)?计划(?:开始)?(?:执行|实施)|确认(?:计划并)?(?:执行|实施)|approve and execute)[。.!!]?$/iu.test(
124
+ s.trim(),
125
+ );
126
+ const exiting = (s: string) =>
127
+ /^(?:退出\s*cadence|关闭\s*cadence(?:模式)?|exit cadence)$/iu.test(s.trim());
128
+ const result = (text: string) => ({
129
+ content: [{ type: "text" as const, text }],
130
+ details: undefined,
131
+ });
132
+ const value = <T>(reply: Reply<T>): T => {
133
+ if (reply.kind !== "ok") throw new ContractError(reply.error.code);
134
+ return reply.value;
135
+ };
136
+ const guard = (ctx: ExtensionContext) =>
137
+ ctx.mode === "tui" &&
138
+ ctx.hasUI &&
139
+ ctx.isProjectTrusted() &&
140
+ process.env.CADENCE_SUBAGENT_CHILD !== "1";
141
+ const CHECK = Type.Object({
142
+ name: Type.String(),
143
+ command: Type.String(),
144
+ timeoutMs: Type.Integer({ minimum: 100, maximum: 1200000 }),
145
+ });
146
+ const PLAN = Type.Object({
147
+ goal: Type.String(),
148
+ design: Type.String(),
149
+ decisions: Type.String(),
150
+ acceptance: Type.String(),
151
+ projectContext: Type.String(),
152
+ tasks: Type.Array(
153
+ Type.Object({
154
+ id: Type.String(),
155
+ title: Type.String(),
156
+ instructions: Type.String(),
157
+ writes: Type.Array(Type.String()),
158
+ after: Type.Array(Type.String()),
159
+ }),
160
+ { minItems: 1, maxItems: 16 },
161
+ ),
162
+ checks: Type.Array(CHECK, { minItems: 1, maxItems: 16 }),
163
+ setup: Type.Array(CHECK, { maxItems: 4 }),
164
+ baselineChecks: Type.Array(CHECK, { maxItems: 16 }),
165
+ repairAttempts: Type.Integer({ minimum: 0, maximum: 2 }),
166
+ delivery: Type.Union([
167
+ Type.Literal("local-merge"),
168
+ Type.Literal("working-copy"),
169
+ ]),
170
+ });
171
+
172
+ export function registerCadenceMode(pi: ExtensionAPI): void {
173
+ let state = idle(),
174
+ context: ExtensionContext | undefined,
175
+ generation = 0;
176
+ let permission: { id: string; digest: string; at: number } | undefined;
177
+ let allowStart = false,
178
+ connecting: Promise<void> | undefined;
179
+ let unsubscribe: (() => void) | undefined,
180
+ poll: ReturnType<typeof setInterval> | undefined;
181
+ let polling = false;
182
+ // Host action methods are unavailable during extension discovery/loading.
183
+ let normalTools: string[] = [];
184
+ const raw = new CadenceUserInput(),
185
+ connection = new NativeConnection();
186
+ const client = () => {
187
+ if (!connection.client) throw new ContractError("unavailable");
188
+ return connection.client;
189
+ };
190
+ const persist = () => pi.appendEntry(CADENCE_MODE_ENTRY, state);
191
+ const status = (text = "ready") =>
192
+ context?.ui.setStatus(
193
+ "cadence",
194
+ state.enabled ? `Cadence • ${text}` : undefined,
195
+ );
196
+ const stopPolling = () => {
197
+ clearInterval(poll);
198
+ poll = undefined;
199
+ };
200
+ const active = (ctx: ExtensionContext) => {
201
+ if (!state.enabled || !guard(ctx) || ctx.cwd !== state.cwd)
202
+ throw new ContractError("forbidden");
203
+ context = ctx;
204
+ };
205
+ 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;
212
+ const expected = generation;
213
+ const check = () => {
214
+ active(ctx);
215
+ if (generation !== expected) throw new ContractError("stale");
216
+ };
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);
251
+ check();
252
+ }
253
+ if (!connection.client || !connection.compatible())
254
+ throw new ContractError("unsupported-context");
255
+ if (!selectModel) return;
256
+ const catalog = value(await connection.client.models());
257
+ check();
258
+ const preferences = new CadencePreferences(agentDir());
259
+ const saved = preferences.read();
260
+ const selected =
261
+ saved ??
262
+ (ctx.model
263
+ ? decodeModelSelector({
264
+ provider: ctx.model.provider,
265
+ model: ctx.model.id,
266
+ api: ctx.model.api,
267
+ thinking: ctx.thinkingLevel,
268
+ })
269
+ : null);
270
+ if (!selected)
271
+ throw new Error("Choose a Pi model before entering Cadence.");
272
+ const same =
273
+ catalog.selected &&
274
+ canonicalJson({
275
+ provider: catalog.selected.provider,
276
+ model: catalog.selected.model,
277
+ api: catalog.selected.api,
278
+ thinking: catalog.selected.thinking,
279
+ }) === canonicalJson(selected);
280
+ if (!same) {
281
+ value(
282
+ await connection.client.chooseModel({
283
+ expected: catalog.version,
284
+ choice: selected,
285
+ }),
286
+ );
287
+ check();
288
+ }
289
+ if (!saved) preferences.save(selected);
290
+ };
291
+ connecting = operation();
292
+ try {
293
+ await connecting;
294
+ } finally {
295
+ connecting = undefined;
296
+ }
297
+ };
298
+ const request = async (
299
+ ctx: ExtensionContext,
300
+ input: WorkflowRequest,
301
+ commandId = randomUUID(),
302
+ ): Promise<WorkflowResponse> => {
303
+ await connect(
304
+ ctx,
305
+ input.action === "research" || input.action === "propose",
306
+ );
307
+ if (!connection.client || !connection.session)
308
+ 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
+ );
317
+ if (r.kind !== "workflow") throw new ContractError("invalid");
318
+ const response = r.response;
319
+ if (
320
+ ((input.action === "execute" || input.action === "research") &&
321
+ (response.type !== "run" || response.run.id !== commandId)) ||
322
+ (input.action === "cancel" &&
323
+ (response.type !== "run" || response.run.id !== input.runId)) ||
324
+ (input.action === "propose" &&
325
+ (response.type !== "proposal" ||
326
+ response.proposal.id !== commandId ||
327
+ canonicalJson(response.proposal.plan) !==
328
+ canonicalJson(input.plan))) ||
329
+ (input.action === "prepare" &&
330
+ (response.type !== "grant" ||
331
+ response.proposal.id !== input.proposalId ||
332
+ response.proposal.digest !== input.digest))
333
+ )
334
+ throw new ContractError("unavailable");
335
+ return response;
336
+ };
337
+ const observe = async (
338
+ ctx: ExtensionContext,
339
+ id: string,
340
+ ): Promise<WorkflowRun> => {
341
+ 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
+ );
346
+ if (
347
+ r.kind !== "workflow" ||
348
+ r.response.type !== "run" ||
349
+ r.response.run.id !== id
350
+ )
351
+ throw new ContractError("invalid");
352
+ return r.response.run;
353
+ };
354
+ 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))
358
+ 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.",
360
+ );
361
+ };
362
+ const watch = (ctx: ExtensionContext, id: string) => {
363
+ stopPolling();
364
+ const expected = generation;
365
+ poll = setInterval(() => {
366
+ if (polling || generation !== expected || !state.enabled) return;
367
+ polling = true;
368
+ void observe(ctx, id)
369
+ .then((run) => {
370
+ if (generation !== expected || state.runId !== id) return;
371
+ status(
372
+ run.status === "running" || run.status === "queued"
373
+ ? run.phase
374
+ : "ready",
375
+ );
376
+ if (!["running", "queued"].includes(run.status)) {
377
+ stopPolling();
378
+ pi.sendMessage(
379
+ {
380
+ customType: "cadence-workflow-result",
381
+ content: summarize(run),
382
+ display: true,
383
+ },
384
+ { triggerTurn: false },
385
+ );
386
+ }
387
+ })
388
+ .catch(() => {
389
+ stopPolling();
390
+ status("observation unavailable; work may continue");
391
+ })
392
+ .finally(() => {
393
+ polling = false;
394
+ });
395
+ }, 2000);
396
+ poll.unref?.();
397
+ };
398
+ const leave = async () => {
399
+ ++generation;
400
+ raw.clear();
401
+ permission = undefined;
402
+ allowStart = false;
403
+ stopPolling();
404
+ if (state.enabled) pi.setActiveTools(state.previousTools);
405
+ return connection.detach();
406
+ };
407
+ pi.on("session_start", (_event, ctx) => {
408
+ void leave().catch(() => {});
409
+ unsubscribe?.();
410
+ context = ctx;
411
+ 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);
416
+ status(state.runId ? "retained work; ask for status" : "ready");
417
+ if (ctx.mode === "tui")
418
+ unsubscribe = ctx.ui.onTerminalInput((data) => {
419
+ raw.input(
420
+ data,
421
+ ctx.ui.getEditorText(),
422
+ guard(ctx) && ctx.isIdle() && !ctx.hasPendingMessages(),
423
+ );
424
+ return undefined;
425
+ });
426
+ });
427
+ pi.on("session_shutdown", () => {
428
+ unsubscribe?.();
429
+ unsubscribe = undefined;
430
+ return departure(leave());
431
+ });
432
+ pi.on("session_before_switch", () => {
433
+ void leave().catch(() => {});
434
+ });
435
+ pi.on("session_before_fork", () => {
436
+ void leave().catch(() => {});
437
+ });
438
+ pi.on("session_before_tree", () => {
439
+ void leave().catch(() => {});
440
+ });
441
+ 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
+ );
451
+ status();
452
+ });
453
+ pi.on("input", (event, ctx) => {
454
+ if (!state.enabled) return;
455
+ context = ctx;
456
+ permission = undefined;
457
+ const human = event.source === "interactive" && raw.consume(event.text);
458
+ 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
+ if (human && approved(event.text) && state.proposal)
473
+ permission = {
474
+ id: state.proposal.id,
475
+ digest: state.proposal.digest,
476
+ at: Date.now(),
477
+ };
478
+ return undefined;
479
+ });
480
+ pi.on("before_agent_start", () =>
481
+ state.enabled
482
+ ? {
483
+ 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"}.`,
486
+ display: false,
487
+ },
488
+ }
489
+ : undefined,
490
+ );
491
+ pi.on("tool_call", (event) =>
492
+ state.enabled && !TOOLS.includes(event.toolName)
493
+ ? {
494
+ 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.",
497
+ }
498
+ : undefined,
499
+ );
500
+ pi.registerCommand("cadence", {
501
+ description:
502
+ "Enable Cadence for this entire conversation: /cadence [goal]. Continue in normal conversation; explicit exit only.",
503
+ handler: async (args, ctx) => {
504
+ if (
505
+ !guard(ctx) ||
506
+ !ctx.isIdle() ||
507
+ ctx.hasPendingMessages() ||
508
+ !raw.consumeCommand(args)
509
+ )
510
+ return;
511
+ context = ctx;
512
+ permission = undefined;
513
+ allowStart = true;
514
+ if (!state.enabled) {
515
+ state = {
516
+ ...idle(),
517
+ enabled: true,
518
+ cwd: ctx.cwd,
519
+ previousTools: pi.getActiveTools().filter((n) => !TOOLS.includes(n)),
520
+ };
521
+ persist();
522
+ }
523
+ pi.setActiveTools(TOOLS);
524
+ status();
525
+ pi.sendMessage(
526
+ {
527
+ 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.",
530
+ display: true,
531
+ },
532
+ { triggerTurn: false },
533
+ );
534
+ if (args.trim())
535
+ pi.sendUserMessage(args, { expandPromptTemplates: false });
536
+ else
537
+ pi.sendMessage(
538
+ {
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.",
542
+ display: false,
543
+ },
544
+ { triggerTurn: true },
545
+ );
546
+ },
547
+ });
548
+ pi.registerTool({
549
+ name: "cadence_research",
550
+ label: "Investigate project",
551
+ description:
552
+ "Delegate one or two focused readonly investigations. Cite project evidence and consolidate questions in the main conversation. No code editing or task UI.",
553
+ parameters: Type.Object({
554
+ goal: Type.String(),
555
+ questions: Type.Array(Type.String(), { minItems: 1, maxItems: 2 }),
556
+ }),
557
+ async execute(_id, input, signal, update, ctx) {
558
+ active(ctx);
559
+ await connect(ctx);
560
+ await requireSettledRun(ctx);
561
+ 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
+ );
570
+ if (response.type !== "run") throw new ContractError("invalid");
571
+ state.runId = response.run.id;
572
+ persist();
573
+ status("research");
574
+ let run = response.run;
575
+ while (["queued", "running"].includes(run.status) && !signal?.aborted) {
576
+ update?.(
577
+ result(
578
+ `Investigating: ${run.goal}\n${run.steps.map((s) => `${s.id}: ${s.status}`).join("\n")}`,
579
+ ),
580
+ );
581
+ await new Promise((resolve) => setTimeout(resolve, 1000));
582
+ run = await observe(ctx, run.id);
583
+ }
584
+ status("ready");
585
+ if (signal?.aborted) watch(ctx, run.id);
586
+ return result(summarize(run));
587
+ },
588
+ });
589
+ pi.registerTool({
590
+ name: "cadence_plan",
591
+ label: "Propose implementation plan",
592
+ description:
593
+ "After interactive clarification, publish the exact readable plan, dependency graph, checks, setup commands, repair budget and delivery policy for user approval. Does not execute.",
594
+ parameters: PLAN,
595
+ async execute(_id, input, _signal, _update, ctx) {
596
+ active(ctx);
597
+ await connect(ctx);
598
+ permission = undefined;
599
+ await requireSettledRun(ctx);
600
+ const plan = decodeWorkflowPlan(input);
601
+ const response = await request(ctx, {
602
+ action: "propose",
603
+ plan,
604
+ model: value(await client().models()).version,
605
+ });
606
+ if (response.type !== "proposal") throw new ContractError("invalid");
607
+ state.proposal = response.proposal;
608
+ persist();
609
+ status("awaiting plan approval");
610
+ pi.sendMessage(
611
+ {
612
+ customType: "cadence-proposed-plan",
613
+ content: readableWorkflowPlan(plan),
614
+ display: true,
615
+ },
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.`,
620
+ );
621
+ },
622
+ });
623
+ pi.registerTool({
624
+ name: "cadence_start",
625
+ label: "Execute approved plan",
626
+ description:
627
+ "Start the current exact plan after fresh user approval. The service automatically implements, reviews, verifies, performs bounded repairs and delivers; client departure only detaches.",
628
+ parameters: Type.Object({}),
629
+ async execute(_id, _input, signal, _update, ctx) {
630
+ active(ctx);
631
+ const proposal = state.proposal;
632
+ if (!proposal)
633
+ throw new Error("No current plan. Clarify and propose it first.");
634
+ 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
+ const fromInput =
642
+ permission?.id === proposal.id &&
643
+ permission.digest === proposal.digest &&
644
+ Date.now() >= permission.at &&
645
+ Date.now() - permission.at < 120000;
646
+ permission = undefined;
647
+ if (
648
+ !fromInput &&
649
+ !(await ctx.ui.confirm(
650
+ "Implement this plan automatically?",
651
+ `${readableWorkflowPlan(prepared.proposal.plan)}\nProject: ${prepared.proposal.cwd}\nNo push or deployment. Canceling this dialog changes nothing.`,
652
+ ))
653
+ )
654
+ return result(
655
+ "Not started. Cadence remains enabled for further discussion.",
656
+ );
657
+ if (
658
+ signal?.aborted ||
659
+ expected !== generation ||
660
+ state.proposal?.digest !== proposal.digest
661
+ )
662
+ 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
+ );
679
+ if (started.type !== "run") throw new ContractError("invalid");
680
+ state.runId = started.run.id;
681
+ state.proposal = null;
682
+ persist();
683
+ status("executing");
684
+ watch(ctx, started.run.id);
685
+ return result(
686
+ `Accepted. Implementation, verification and agreed delivery now run under the persistent owner. No further routine approval is needed. ${started.run.id}\nCadence remains enabled. Closing/switching the conversation does not cancel this work.`,
687
+ );
688
+ },
689
+ });
690
+ pi.registerTool({
691
+ name: "cadence_status",
692
+ label: "Observe workflow",
693
+ description:
694
+ "Read the current retained workflow outcome without replaying any action.",
695
+ parameters: Type.Object({ stepId: Type.Optional(Type.String()) }),
696
+ async execute(_id, input, _signal, _update, ctx) {
697
+ active(ctx);
698
+ if (!state.runId)
699
+ return result(
700
+ "Cadence is enabled; no run yet. Continue clarifying the goal.",
701
+ );
702
+ if (input.stepId) {
703
+ await connect(ctx, false);
704
+ const detail = value(
705
+ await client().workbenchRead({
706
+ kind: "workflow-detail",
707
+ id: state.runId,
708
+ stepId: input.stepId,
709
+ }),
710
+ );
711
+ if (
712
+ detail.kind !== "file" ||
713
+ detail.path !== `workflow/${state.runId}/${input.stepId}`
714
+ )
715
+ throw new ContractError("invalid");
716
+ return result(detail.text);
717
+ }
718
+ const run = await observe(ctx, state.runId);
719
+ if (["running", "queued"].includes(run.status)) watch(ctx, run.id);
720
+ return result(summarize(run));
721
+ },
722
+ });
723
+ pi.registerTool({
724
+ name: "cadence_cancel",
725
+ label: "Cancel workflow",
726
+ description:
727
+ "Only on an explicit user request, request cancellation of the current workflow. No rollback, cleanup or inferred closure.",
728
+ parameters: Type.Object({}),
729
+ async execute(_id, _input, _signal, _update, ctx) {
730
+ active(ctx);
731
+ if (!state.runId) return result("No active workflow.");
732
+ if (
733
+ !(await ctx.ui.confirm(
734
+ "Cancel current workflow?",
735
+ "Request Stop and retain actual files/results. This does not reset or undo edits. Cadence mode remains enabled.",
736
+ ))
737
+ )
738
+ return result("Cancellation not requested.");
739
+ const r = await request(ctx, { action: "cancel", runId: state.runId });
740
+ if (r.type !== "run") throw new ContractError("invalid");
741
+ watch(ctx, r.run.id);
742
+ return result(
743
+ `Cancellation requested; closure is not yet implied.\n${summarize(r.run)}`,
744
+ );
745
+ },
746
+ });
747
+ pi.registerTool({
748
+ name: "cadence_model",
749
+ label: "Remember Cadence model",
750
+ description:
751
+ "Change the global Cadence model preference through a real user selection. Ordinary usage reuses the remembered model.",
752
+ parameters: Type.Object({}),
753
+ async execute(_id, _input, _signal, _update, ctx) {
754
+ active(ctx);
755
+ // Preference selection must never block observation/cancellation or the picker.
756
+ await connect(ctx, false);
757
+ const catalog = value(await client().models());
758
+ const models = catalog.entries.filter(
759
+ (m) => m.eligibility === "candidate" && m.api,
760
+ );
761
+ const labels = models.map((m) => `${m.provider}/${m.model} (${m.api})`);
762
+ const selected = await ctx.ui.select(
763
+ "Cadence model (remembered across projects)",
764
+ labels,
765
+ );
766
+ if (!selected) return result("Model unchanged.");
767
+ const model = models[labels.indexOf(selected)];
768
+ const thinking = await ctx.ui.select(
769
+ "Thinking",
770
+ model.thinking.filter((t) => t.selectable).map((t) => t.level),
771
+ );
772
+ if (!thinking) return result("Model unchanged.");
773
+ const choice: ModelSelector = decodeModelSelector({
774
+ provider: model.provider,
775
+ model: model.model,
776
+ api: model.api,
777
+ thinking,
778
+ });
779
+ value(
780
+ await client().chooseModel({
781
+ expected: catalog.version,
782
+ choice,
783
+ }),
784
+ );
785
+ new CadencePreferences(agentDir()).save(choice);
786
+ state.proposal = null;
787
+ permission = undefined;
788
+ persist();
789
+ return result(
790
+ "Cadence model preference saved. It does not copy credentials or change an already accepted run.",
791
+ );
792
+ },
793
+ });
794
+ }