@abelxiaoxing/cadence 2.0.20 → 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.
- package/README.de.md +24 -8
- package/README.es.md +24 -8
- package/README.fr.md +24 -8
- package/README.ja.md +27 -12
- package/README.ko.md +25 -12
- package/README.md +30 -13
- package/README.pt-BR.md +24 -8
- package/README.ru.md +24 -8
- package/README.zh-CN.md +33 -15
- package/docs/conversation-mode.md +114 -0
- package/docs/service-management.md +6 -4
- package/package.json +8 -3
- package/src/agent-panel-cadence.ts +302 -10
- package/src/cadence-instructions.ts +7 -0
- package/src/cadence-mode.ts +1250 -0
- package/src/cadence-preferences.ts +78 -0
- package/src/coordinator-tools.mjs +109 -0
- package/src/index.ts +2 -0
- package/src/native-build.ts +1 -1
- package/src/native-client.ts +44 -1
- package/src/sdk-worker.mjs +28 -8
- package/src/service/contracts/workbench.ts +296 -2
- package/src/service/contracts/workflow.ts +491 -0
- package/src/service/coordination.ts +2 -0
- package/src/service-cli.mjs +3 -1
- package/src/service-host.mjs +3713 -373
- package/src/startup-card.ts +1 -1
- package/src/task-shell.ts +6 -5
- package/web/dist/assets/cadence.css +1 -1
- package/web/dist/assets/cadence.js +18 -12
- package/web/dist/manifest.json +7 -7
|
@@ -0,0 +1,1250 @@
|
|
|
1
|
+
/** Persistent, branch-aware conversation mode. No execution owner lives in Pi. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import {
|
|
5
|
+
type ExtensionAPI,
|
|
6
|
+
type ExtensionContext,
|
|
7
|
+
getAgentDir,
|
|
8
|
+
getMarkdownTheme,
|
|
9
|
+
} from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import {
|
|
11
|
+
type Component,
|
|
12
|
+
Key,
|
|
13
|
+
Markdown,
|
|
14
|
+
matchesKey,
|
|
15
|
+
Text,
|
|
16
|
+
} from "@earendil-works/pi-tui";
|
|
17
|
+
import { Type } from "typebox";
|
|
18
|
+
import { CADENCE_INSTRUCTIONS as INSTRUCTIONS } from "./cadence-instructions.ts";
|
|
19
|
+
import { CadencePreferences } from "./cadence-preferences.ts";
|
|
20
|
+
import {
|
|
21
|
+
departure,
|
|
22
|
+
NativeConnection,
|
|
23
|
+
projectStopCommand,
|
|
24
|
+
} from "./native-client.ts";
|
|
25
|
+
import type { ChatTurn } from "./service/contracts/workbench.ts";
|
|
26
|
+
import {
|
|
27
|
+
decodeWorkflowPlan,
|
|
28
|
+
readableWorkflowPlan,
|
|
29
|
+
type WorkflowProposal,
|
|
30
|
+
type WorkflowRequest,
|
|
31
|
+
type WorkflowResponse,
|
|
32
|
+
type WorkflowRun,
|
|
33
|
+
} from "./service/contracts/workflow.ts";
|
|
34
|
+
import { ServiceCoordination } from "./service/coordination.ts";
|
|
35
|
+
import {
|
|
36
|
+
ContractError,
|
|
37
|
+
canonicalJson,
|
|
38
|
+
decodeModelSelector,
|
|
39
|
+
type ErrorCode,
|
|
40
|
+
type ModelSelector,
|
|
41
|
+
type PublicError,
|
|
42
|
+
type Reply,
|
|
43
|
+
} from "./service-contract.ts";
|
|
44
|
+
import { effectiveWorkspace } from "./task-store.ts";
|
|
45
|
+
import { diagnosticText } from "./verification-diagnostics.ts";
|
|
46
|
+
|
|
47
|
+
export const CADENCE_MODE_ENTRY = "cadence-conversation-mode/1";
|
|
48
|
+
const CONTEXT = "cadence-mode-context";
|
|
49
|
+
const READY = "cadence-mode-ready";
|
|
50
|
+
const TOOLS = [
|
|
51
|
+
"cadence_research",
|
|
52
|
+
"cadence_plan",
|
|
53
|
+
"cadence_start",
|
|
54
|
+
"cadence_status",
|
|
55
|
+
"cadence_cancel",
|
|
56
|
+
"cadence_model",
|
|
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
|
+
|
|
68
|
+
export interface CadenceModeState {
|
|
69
|
+
enabled: boolean;
|
|
70
|
+
cwd: string;
|
|
71
|
+
runId: string | null;
|
|
72
|
+
proposal: WorkflowProposal | null;
|
|
73
|
+
previousTools: string[];
|
|
74
|
+
}
|
|
75
|
+
const idle = (): CadenceModeState => ({
|
|
76
|
+
enabled: false,
|
|
77
|
+
cwd: "",
|
|
78
|
+
runId: null,
|
|
79
|
+
proposal: null,
|
|
80
|
+
previousTools: [],
|
|
81
|
+
});
|
|
82
|
+
/** Session restoration restores mode/context, NEVER a grant, pending command or action replay. */
|
|
83
|
+
export function restoreCadenceMode(
|
|
84
|
+
entries: readonly { type: string; customType?: string; data?: unknown }[],
|
|
85
|
+
cwd: string,
|
|
86
|
+
): CadenceModeState {
|
|
87
|
+
let state = idle();
|
|
88
|
+
for (const entry of entries) {
|
|
89
|
+
if (entry.type !== "custom" || entry.customType !== CADENCE_MODE_ENTRY)
|
|
90
|
+
continue;
|
|
91
|
+
const v = entry.data as Partial<CadenceModeState> | null;
|
|
92
|
+
if (
|
|
93
|
+
!v ||
|
|
94
|
+
typeof v.enabled !== "boolean" ||
|
|
95
|
+
v.cwd !== cwd ||
|
|
96
|
+
!Array.isArray(v.previousTools) ||
|
|
97
|
+
!v.previousTools.every((s) => typeof s === "string") ||
|
|
98
|
+
!(v.runId === null || typeof v.runId === "string")
|
|
99
|
+
) {
|
|
100
|
+
state = idle();
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
state = {
|
|
104
|
+
enabled: v.enabled,
|
|
105
|
+
cwd,
|
|
106
|
+
runId: v.runId,
|
|
107
|
+
proposal: null,
|
|
108
|
+
previousTools: v.previousTools.filter((n) => !TOOLS.includes(n)),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return state;
|
|
112
|
+
}
|
|
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. */
|
|
115
|
+
export class CadenceUserInput {
|
|
116
|
+
private value: { text: string; at: number } | undefined;
|
|
117
|
+
private pasting = false;
|
|
118
|
+
private dialog: { opened: number; fresh: boolean } | undefined;
|
|
119
|
+
clear() {
|
|
120
|
+
this.value = undefined;
|
|
121
|
+
}
|
|
122
|
+
input(data: string, text: string, eligible: boolean, at = Date.now()) {
|
|
123
|
+
this.clear();
|
|
124
|
+
if (data.includes("\x1b[200~")) this.pasting = true;
|
|
125
|
+
if (data.includes("\x1b[201~")) {
|
|
126
|
+
this.pasting = false;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
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;
|
|
147
|
+
}
|
|
148
|
+
consumeCommand(args: string, at = Date.now()) {
|
|
149
|
+
const typed = this.value?.text.trim();
|
|
150
|
+
if (
|
|
151
|
+
!typed ||
|
|
152
|
+
!/^\/cadence(?:[ \t]+[^\r\n]*)?$/u.test(typed) ||
|
|
153
|
+
typed.replace(/^\/cadence[ \t]*/u, "") !== args.trim()
|
|
154
|
+
) {
|
|
155
|
+
this.clear();
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
return this.consume(typed, at);
|
|
159
|
+
}
|
|
160
|
+
consume(text: string, at = Date.now()) {
|
|
161
|
+
const v = this.value;
|
|
162
|
+
this.clear();
|
|
163
|
+
return (
|
|
164
|
+
!!v && v.text.trim() === text.trim() && at >= v.at && at - v.at < 1500
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const approved = (s: string) =>
|
|
169
|
+
/^(?:按(?:这个|本)?计划(?:开始)?(?:执行|实施)|确认(?:计划并)?(?:执行|实施)|approve and execute)[。.!!]?$/iu.test(
|
|
170
|
+
s.trim(),
|
|
171
|
+
);
|
|
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", "退出", "关闭"]);
|
|
177
|
+
const result = (text: string) => ({
|
|
178
|
+
content: [{ type: "text" as const, text }],
|
|
179
|
+
details: undefined,
|
|
180
|
+
});
|
|
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
|
+
]);
|
|
202
|
+
const guard = (ctx: ExtensionContext) =>
|
|
203
|
+
ctx.mode === "tui" &&
|
|
204
|
+
ctx.hasUI &&
|
|
205
|
+
ctx.isProjectTrusted() &&
|
|
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
|
+
}
|
|
222
|
+
const CHECK = Type.Object({
|
|
223
|
+
name: Type.String(),
|
|
224
|
+
command: Type.String(),
|
|
225
|
+
timeoutMs: Type.Integer({ minimum: 100, maximum: 1200000 }),
|
|
226
|
+
});
|
|
227
|
+
const PLAN = Type.Object({
|
|
228
|
+
goal: Type.String(),
|
|
229
|
+
design: Type.String(),
|
|
230
|
+
decisions: Type.String(),
|
|
231
|
+
acceptance: Type.String(),
|
|
232
|
+
projectContext: Type.String(),
|
|
233
|
+
tasks: Type.Array(
|
|
234
|
+
Type.Object({
|
|
235
|
+
id: Type.String(),
|
|
236
|
+
title: Type.String(),
|
|
237
|
+
instructions: Type.String(),
|
|
238
|
+
writes: Type.Array(Type.String()),
|
|
239
|
+
after: Type.Array(Type.String()),
|
|
240
|
+
}),
|
|
241
|
+
{ minItems: 1, maxItems: 16 },
|
|
242
|
+
),
|
|
243
|
+
checks: Type.Array(CHECK, { minItems: 1, maxItems: 16 }),
|
|
244
|
+
setup: Type.Array(CHECK, { maxItems: 4 }),
|
|
245
|
+
baselineChecks: Type.Array(CHECK, { maxItems: 16 }),
|
|
246
|
+
repairAttempts: Type.Integer({ minimum: 0, maximum: 2 }),
|
|
247
|
+
delivery: Type.Union([
|
|
248
|
+
Type.Literal("local-merge"),
|
|
249
|
+
Type.Literal("working-copy"),
|
|
250
|
+
]),
|
|
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
|
+
}
|
|
278
|
+
|
|
279
|
+
export function registerCadenceMode(pi: ExtensionAPI): void {
|
|
280
|
+
let state = idle(),
|
|
281
|
+
context: ExtensionContext | undefined,
|
|
282
|
+
generation = 0;
|
|
283
|
+
let permission: { id: string; digest: string; at: number } | undefined;
|
|
284
|
+
let allowStart = false,
|
|
285
|
+
reattach = false;
|
|
286
|
+
let attaching: Promise<void> | undefined,
|
|
287
|
+
selecting: Promise<void> | undefined;
|
|
288
|
+
let unsubscribe: (() => void) | undefined,
|
|
289
|
+
poll: ReturnType<typeof setInterval> | undefined;
|
|
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 }[] = [];
|
|
298
|
+
const raw = new CadenceUserInput(),
|
|
299
|
+
connection = new NativeConnection();
|
|
300
|
+
const client = () => {
|
|
301
|
+
if (!connection.client) throw new ContractError("unavailable");
|
|
302
|
+
return connection.client;
|
|
303
|
+
};
|
|
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;
|
|
316
|
+
const status = (text = "ready") =>
|
|
317
|
+
context?.ui.setStatus(
|
|
318
|
+
"cadence",
|
|
319
|
+
!state.enabled
|
|
320
|
+
? undefined
|
|
321
|
+
: context && engaged(context)
|
|
322
|
+
? `Cadence • ${text}`
|
|
323
|
+
: "Cadence • inactive here",
|
|
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
|
+
};
|
|
343
|
+
const stopPolling = () => {
|
|
344
|
+
clearInterval(poll);
|
|
345
|
+
poll = undefined;
|
|
346
|
+
};
|
|
347
|
+
const active = (ctx: ExtensionContext) => {
|
|
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");
|
|
353
|
+
context = ctx;
|
|
354
|
+
};
|
|
355
|
+
const summarize = (run: WorkflowRun) =>
|
|
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;
|
|
404
|
+
const expected = generation;
|
|
405
|
+
const check = () => {
|
|
406
|
+
active(ctx);
|
|
407
|
+
if (generation !== expected) throw new ContractError("stale");
|
|
408
|
+
};
|
|
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);
|
|
424
|
+
check();
|
|
425
|
+
}
|
|
426
|
+
try {
|
|
427
|
+
await connection.attach(ctx.cwd);
|
|
428
|
+
} catch (error) {
|
|
429
|
+
reattach = true;
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
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");
|
|
447
|
+
const preferences = new CadencePreferences(agentDir());
|
|
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
|
+
}
|
|
462
|
+
const selected =
|
|
463
|
+
saved ??
|
|
464
|
+
(ctx.model
|
|
465
|
+
? decodeModelSelector({
|
|
466
|
+
provider: ctx.model.provider,
|
|
467
|
+
model: ctx.model.id,
|
|
468
|
+
api: ctx.model.api,
|
|
469
|
+
thinking: ctx.thinkingLevel,
|
|
470
|
+
})
|
|
471
|
+
: null);
|
|
472
|
+
if (!selected)
|
|
473
|
+
throw new Error("Choose a Pi model before entering Cadence.");
|
|
474
|
+
const same =
|
|
475
|
+
catalog.selected &&
|
|
476
|
+
canonicalJson({
|
|
477
|
+
provider: catalog.selected.provider,
|
|
478
|
+
model: catalog.selected.model,
|
|
479
|
+
api: catalog.selected.api,
|
|
480
|
+
thinking: catalog.selected.thinking,
|
|
481
|
+
}) === canonicalJson(selected);
|
|
482
|
+
if (!same) {
|
|
483
|
+
value(
|
|
484
|
+
await client().chooseModel({
|
|
485
|
+
expected: catalog.version,
|
|
486
|
+
choice: selected,
|
|
487
|
+
}),
|
|
488
|
+
);
|
|
489
|
+
if (generation !== expected) throw new ContractError("stale");
|
|
490
|
+
}
|
|
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
|
+
);
|
|
517
|
+
}
|
|
518
|
+
if (selectModel) await ensureModel(ctx);
|
|
519
|
+
};
|
|
520
|
+
const request = async (
|
|
521
|
+
ctx: ExtensionContext,
|
|
522
|
+
input: WorkflowRequest,
|
|
523
|
+
commandId = randomUUID(),
|
|
524
|
+
sending?: () => void,
|
|
525
|
+
): Promise<WorkflowResponse> => {
|
|
526
|
+
await connect(
|
|
527
|
+
ctx,
|
|
528
|
+
input.action === "research" || input.action === "propose",
|
|
529
|
+
);
|
|
530
|
+
if (!connection.client || !connection.session)
|
|
531
|
+
throw new ContractError("unavailable");
|
|
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));
|
|
541
|
+
if (r.kind !== "workflow") throw new ContractError("invalid");
|
|
542
|
+
const response = r.response;
|
|
543
|
+
if (
|
|
544
|
+
((input.action === "execute" || input.action === "research") &&
|
|
545
|
+
(response.type !== "run" || response.run.id !== commandId)) ||
|
|
546
|
+
(input.action === "cancel" &&
|
|
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.
|
|
550
|
+
(input.action === "propose" &&
|
|
551
|
+
(response.type !== "proposal" || response.proposal.id !== commandId)) ||
|
|
552
|
+
(input.action === "prepare" &&
|
|
553
|
+
(response.type !== "grant" ||
|
|
554
|
+
response.proposal.id !== input.proposalId ||
|
|
555
|
+
response.proposal.digest !== input.digest))
|
|
556
|
+
)
|
|
557
|
+
throw new ContractError("unavailable");
|
|
558
|
+
return response;
|
|
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. */
|
|
562
|
+
const observe = async (
|
|
563
|
+
ctx: ExtensionContext,
|
|
564
|
+
id: string,
|
|
565
|
+
): Promise<{ run: WorkflowRun } | { absent: true }> => {
|
|
566
|
+
await connect(ctx, false);
|
|
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);
|
|
578
|
+
if (
|
|
579
|
+
r.kind !== "workflow" ||
|
|
580
|
+
r.response.type !== "run" ||
|
|
581
|
+
r.response.run.id !== id
|
|
582
|
+
)
|
|
583
|
+
throw new ContractError("invalid");
|
|
584
|
+
return { run: r.response.run };
|
|
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. */
|
|
593
|
+
const requireSettledRun = async (ctx: ExtensionContext) => {
|
|
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)
|
|
603
|
+
throw new Error(
|
|
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 },
|
|
637
|
+
);
|
|
638
|
+
};
|
|
639
|
+
const watch = (ctx: ExtensionContext, id: string) => {
|
|
640
|
+
stopPolling();
|
|
641
|
+
const expected = generation;
|
|
642
|
+
poll = setInterval(() => {
|
|
643
|
+
if (polling || generation !== expected || !state.enabled) return;
|
|
644
|
+
polling = true;
|
|
645
|
+
void observe(ctx, id)
|
|
646
|
+
.then((seen) => {
|
|
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;
|
|
654
|
+
status(
|
|
655
|
+
run.status === "running" || run.status === "queued"
|
|
656
|
+
? run.phase
|
|
657
|
+
: "ready",
|
|
658
|
+
);
|
|
659
|
+
if (!["running", "queued"].includes(run.status)) {
|
|
660
|
+
stopPolling();
|
|
661
|
+
deliver(ctx, run);
|
|
662
|
+
}
|
|
663
|
+
})
|
|
664
|
+
.catch(() => {
|
|
665
|
+
stopPolling();
|
|
666
|
+
status("observation unavailable; work may continue");
|
|
667
|
+
})
|
|
668
|
+
.finally(() => {
|
|
669
|
+
polling = false;
|
|
670
|
+
});
|
|
671
|
+
}, 2000);
|
|
672
|
+
poll.unref?.();
|
|
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;
|
|
699
|
+
const leave = async () => {
|
|
700
|
+
++generation;
|
|
701
|
+
raw.clear();
|
|
702
|
+
permission = undefined;
|
|
703
|
+
allowStart = false;
|
|
704
|
+
pending = [];
|
|
705
|
+
stopPolling();
|
|
706
|
+
return connection.detach();
|
|
707
|
+
};
|
|
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();
|
|
722
|
+
void leave().catch(() => {});
|
|
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) => {
|
|
729
|
+
context = ctx;
|
|
730
|
+
state = restoreCadenceMode(ctx.sessionManager.getBranch(), ctx.cwd);
|
|
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
|
+
);
|
|
749
|
+
status(state.runId ? "retained work; ask for status" : "ready");
|
|
750
|
+
if (ctx.mode === "tui")
|
|
751
|
+
unsubscribe = ctx.ui.onTerminalInput((data) => {
|
|
752
|
+
raw.input(
|
|
753
|
+
data,
|
|
754
|
+
ctx.ui.getEditorText(),
|
|
755
|
+
guard(ctx) && ctx.isIdle() && !ctx.hasPendingMessages(),
|
|
756
|
+
);
|
|
757
|
+
return undefined;
|
|
758
|
+
});
|
|
759
|
+
});
|
|
760
|
+
pi.on("session_shutdown", () => {
|
|
761
|
+
unsubscribe?.();
|
|
762
|
+
unsubscribe = undefined;
|
|
763
|
+
release();
|
|
764
|
+
return departure(leave());
|
|
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.
|
|
768
|
+
pi.on("session_before_switch", () => {
|
|
769
|
+
void leave().catch(() => {});
|
|
770
|
+
});
|
|
771
|
+
pi.on("session_before_fork", () => {
|
|
772
|
+
void leave().catch(() => {});
|
|
773
|
+
});
|
|
774
|
+
pi.on("session_before_tree", () => {
|
|
775
|
+
void leave().catch(() => {});
|
|
776
|
+
});
|
|
777
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
778
|
+
rebind(ctx);
|
|
779
|
+
status();
|
|
780
|
+
});
|
|
781
|
+
pi.on("agent_settled", (_event, ctx) => flush(ctx));
|
|
782
|
+
pi.on("input", (event, ctx) => {
|
|
783
|
+
if (!state.enabled) return;
|
|
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;
|
|
792
|
+
permission = undefined;
|
|
793
|
+
const human = event.source === "interactive" && raw.consume(event.text);
|
|
794
|
+
if (human) allowStart = true;
|
|
795
|
+
if (human && approved(event.text) && state.proposal)
|
|
796
|
+
permission = {
|
|
797
|
+
id: state.proposal.id,
|
|
798
|
+
digest: state.proposal.digest,
|
|
799
|
+
at: Date.now(),
|
|
800
|
+
};
|
|
801
|
+
return undefined;
|
|
802
|
+
});
|
|
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)
|
|
807
|
+
? {
|
|
808
|
+
systemPrompt: `${event.systemPrompt}\n\n${INSTRUCTIONS}\n${NATIVE}`,
|
|
809
|
+
message: {
|
|
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"}.`,
|
|
812
|
+
display: false,
|
|
813
|
+
},
|
|
814
|
+
}
|
|
815
|
+
: undefined,
|
|
816
|
+
);
|
|
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)
|
|
837
|
+
? {
|
|
838
|
+
block: true,
|
|
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}).`,
|
|
840
|
+
}
|
|
841
|
+
: undefined,
|
|
842
|
+
);
|
|
843
|
+
pi.registerCommand("cadence", {
|
|
844
|
+
description:
|
|
845
|
+
"Enable Cadence for this conversation: /cadence [goal]. It stays on until you type 退出 Cadence / exit cadence or run /cadence exit.",
|
|
846
|
+
handler: async (args, ctx) => {
|
|
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
|
+
);
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
if (!raw.consumeCommand(args)) return;
|
|
863
|
+
context = ctx;
|
|
864
|
+
permission = undefined;
|
|
865
|
+
allowStart = true;
|
|
866
|
+
if (state.enabled) reattach = true;
|
|
867
|
+
else {
|
|
868
|
+
state = {
|
|
869
|
+
...idle(),
|
|
870
|
+
enabled: true,
|
|
871
|
+
cwd: ctx.cwd,
|
|
872
|
+
previousTools: pi.getActiveTools().filter((n) => !TOOLS.includes(n)),
|
|
873
|
+
};
|
|
874
|
+
persist();
|
|
875
|
+
}
|
|
876
|
+
engage();
|
|
877
|
+
status();
|
|
878
|
+
pi.sendMessage(
|
|
879
|
+
{
|
|
880
|
+
customType: "cadence-mode",
|
|
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.`,
|
|
882
|
+
display: true,
|
|
883
|
+
},
|
|
884
|
+
{ triggerTurn: false },
|
|
885
|
+
);
|
|
886
|
+
if (args.trim())
|
|
887
|
+
pi.sendUserMessage(args.trim(), { expandPromptTemplates: false });
|
|
888
|
+
// This turn starts without a prompt, so it carries the policy itself.
|
|
889
|
+
else
|
|
890
|
+
pi.sendMessage(
|
|
891
|
+
{
|
|
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.`,
|
|
894
|
+
display: false,
|
|
895
|
+
},
|
|
896
|
+
{ triggerTurn: true },
|
|
897
|
+
);
|
|
898
|
+
},
|
|
899
|
+
});
|
|
900
|
+
pi.registerTool({
|
|
901
|
+
name: "cadence_research",
|
|
902
|
+
label: "Investigate project",
|
|
903
|
+
description:
|
|
904
|
+
"Delegate one or two focused readonly investigations. Cite project evidence and consolidate questions in the main conversation. No code editing or task UI.",
|
|
905
|
+
parameters: Type.Object({
|
|
906
|
+
goal: Type.String(),
|
|
907
|
+
questions: Type.Array(Type.String(), { minItems: 1, maxItems: 2 }),
|
|
908
|
+
}),
|
|
909
|
+
async execute(_id, input, signal, update, ctx) {
|
|
910
|
+
active(ctx);
|
|
911
|
+
await connect(ctx);
|
|
912
|
+
const notice = await requireSettledRun(ctx);
|
|
913
|
+
const model = value(await client().models()).version;
|
|
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
|
+
}
|
|
938
|
+
if (response.type !== "run") throw new ContractError("invalid");
|
|
939
|
+
status("research");
|
|
940
|
+
let run = response.run;
|
|
941
|
+
while (["queued", "running"].includes(run.status) && !signal?.aborted) {
|
|
942
|
+
update?.(
|
|
943
|
+
result(
|
|
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.`,
|
|
945
|
+
),
|
|
946
|
+
);
|
|
947
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
948
|
+
const seen = await observe(ctx, run.id);
|
|
949
|
+
if ("absent" in seen) throw new ContractError("unavailable");
|
|
950
|
+
run = seen.run;
|
|
951
|
+
}
|
|
952
|
+
status("ready");
|
|
953
|
+
if (signal?.aborted) watch(ctx, run.id);
|
|
954
|
+
return result(`${notice}${summarize(run)}`);
|
|
955
|
+
},
|
|
956
|
+
});
|
|
957
|
+
pi.registerTool({
|
|
958
|
+
name: "cadence_plan",
|
|
959
|
+
label: "Propose implementation plan",
|
|
960
|
+
description:
|
|
961
|
+
"After interactive clarification, publish the exact readable plan, dependency graph, checks, setup commands, repair budget and delivery policy for user approval. Does not execute.",
|
|
962
|
+
parameters: PLAN,
|
|
963
|
+
async execute(_id, input, _signal, _update, ctx) {
|
|
964
|
+
active(ctx);
|
|
965
|
+
await connect(ctx);
|
|
966
|
+
permission = undefined;
|
|
967
|
+
const notice = await requireSettledRun(ctx);
|
|
968
|
+
const plan = decodeWorkflowPlan(input);
|
|
969
|
+
const response = await request(ctx, {
|
|
970
|
+
action: "propose",
|
|
971
|
+
plan,
|
|
972
|
+
model: value(await client().models()).version,
|
|
973
|
+
});
|
|
974
|
+
if (response.type !== "proposal") throw new ContractError("invalid");
|
|
975
|
+
state.proposal = response.proposal;
|
|
976
|
+
persist();
|
|
977
|
+
status("awaiting plan approval");
|
|
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,
|
|
994
|
+
},
|
|
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,
|
|
1014
|
+
);
|
|
1015
|
+
},
|
|
1016
|
+
});
|
|
1017
|
+
pi.registerTool({
|
|
1018
|
+
name: "cadence_start",
|
|
1019
|
+
label: "Execute approved plan",
|
|
1020
|
+
description:
|
|
1021
|
+
"Start the current exact plan after fresh user approval. The service automatically implements, reviews, verifies, performs bounded repairs and delivers; client departure only detaches.",
|
|
1022
|
+
parameters: Type.Object({}),
|
|
1023
|
+
async execute(_id, _input, signal, _update, ctx) {
|
|
1024
|
+
active(ctx);
|
|
1025
|
+
const proposal = state.proposal;
|
|
1026
|
+
if (!proposal)
|
|
1027
|
+
throw new Error("No current plan. Clarify and propose it first.");
|
|
1028
|
+
const expected = generation;
|
|
1029
|
+
const fromInput =
|
|
1030
|
+
permission?.id === proposal.id &&
|
|
1031
|
+
permission.digest === proposal.digest &&
|
|
1032
|
+
Date.now() >= permission.at &&
|
|
1033
|
+
Date.now() - permission.at < 120000;
|
|
1034
|
+
permission = undefined;
|
|
1035
|
+
if (
|
|
1036
|
+
!fromInput &&
|
|
1037
|
+
!(await confirm(
|
|
1038
|
+
ctx,
|
|
1039
|
+
"Implement this plan automatically?",
|
|
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",
|
|
1043
|
+
))
|
|
1044
|
+
)
|
|
1045
|
+
return result(
|
|
1046
|
+
"Not started. Cadence remains enabled for further discussion.",
|
|
1047
|
+
);
|
|
1048
|
+
if (
|
|
1049
|
+
signal?.aborted ||
|
|
1050
|
+
expected !== generation ||
|
|
1051
|
+
state.proposal?.digest !== proposal.digest
|
|
1052
|
+
)
|
|
1053
|
+
throw new ContractError("stale");
|
|
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
|
+
}
|
|
1100
|
+
if (started.type !== "run") throw new ContractError("invalid");
|
|
1101
|
+
state.runId = started.run.id;
|
|
1102
|
+
state.proposal = null;
|
|
1103
|
+
persist();
|
|
1104
|
+
status("executing");
|
|
1105
|
+
watch(ctx, started.run.id);
|
|
1106
|
+
return result(
|
|
1107
|
+
`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.`,
|
|
1108
|
+
);
|
|
1109
|
+
},
|
|
1110
|
+
});
|
|
1111
|
+
pi.registerTool({
|
|
1112
|
+
name: "cadence_status",
|
|
1113
|
+
label: "Observe workflow",
|
|
1114
|
+
description:
|
|
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
|
+
}),
|
|
1120
|
+
async execute(_id, input, _signal, _update, ctx) {
|
|
1121
|
+
active(ctx);
|
|
1122
|
+
if (!state.runId)
|
|
1123
|
+
return result(
|
|
1124
|
+
"Cadence is enabled; no run yet. Continue clarifying the goal.",
|
|
1125
|
+
);
|
|
1126
|
+
const id = state.runId;
|
|
1127
|
+
if (input.stepId) {
|
|
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
|
+
}
|
|
1145
|
+
const detail = value(
|
|
1146
|
+
await client().workbenchRead({
|
|
1147
|
+
kind: "workflow-detail",
|
|
1148
|
+
id,
|
|
1149
|
+
stepId: input.stepId,
|
|
1150
|
+
}),
|
|
1151
|
+
);
|
|
1152
|
+
if (
|
|
1153
|
+
detail.kind !== "file" ||
|
|
1154
|
+
detail.path !== `workflow/${id}/${input.stepId}`
|
|
1155
|
+
)
|
|
1156
|
+
throw new ContractError("invalid");
|
|
1157
|
+
return result(detail.text);
|
|
1158
|
+
}
|
|
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;
|
|
1165
|
+
if (["running", "queued"].includes(run.status)) watch(ctx, run.id);
|
|
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
|
+
);
|
|
1170
|
+
},
|
|
1171
|
+
});
|
|
1172
|
+
pi.registerTool({
|
|
1173
|
+
name: "cadence_cancel",
|
|
1174
|
+
label: "Cancel workflow",
|
|
1175
|
+
description:
|
|
1176
|
+
"Only on an explicit user request, request cancellation of the current workflow. No rollback, cleanup or inferred closure.",
|
|
1177
|
+
parameters: Type.Object({}),
|
|
1178
|
+
async execute(_id, _input, _signal, _update, ctx) {
|
|
1179
|
+
active(ctx);
|
|
1180
|
+
if (!state.runId) return result("No active workflow.");
|
|
1181
|
+
if (
|
|
1182
|
+
!(await confirm(
|
|
1183
|
+
ctx,
|
|
1184
|
+
"Cancel current workflow?",
|
|
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",
|
|
1188
|
+
))
|
|
1189
|
+
)
|
|
1190
|
+
return result("Cancellation not requested.");
|
|
1191
|
+
const r = await request(ctx, { action: "cancel", runId: state.runId });
|
|
1192
|
+
if (r.type !== "run") throw new ContractError("invalid");
|
|
1193
|
+
watch(ctx, r.run.id);
|
|
1194
|
+
return result(
|
|
1195
|
+
`Cancellation requested; closure is not yet implied.\n${summarize(r.run)}`,
|
|
1196
|
+
);
|
|
1197
|
+
},
|
|
1198
|
+
});
|
|
1199
|
+
pi.registerTool({
|
|
1200
|
+
name: "cadence_model",
|
|
1201
|
+
label: "Remember Cadence model",
|
|
1202
|
+
description:
|
|
1203
|
+
"Change the global Cadence model preference through a real user selection. Ordinary usage reuses the remembered model.",
|
|
1204
|
+
parameters: Type.Object({}),
|
|
1205
|
+
async execute(_id, _input, _signal, _update, ctx) {
|
|
1206
|
+
active(ctx);
|
|
1207
|
+
// Preference selection must never block observation/cancellation or the picker.
|
|
1208
|
+
await connect(ctx, false);
|
|
1209
|
+
const catalog = value(await client().models());
|
|
1210
|
+
const models = catalog.entries.filter(
|
|
1211
|
+
(m) => m.eligibility === "candidate" && m.api,
|
|
1212
|
+
);
|
|
1213
|
+
const labels = models.map((m) => `${m.provider}/${m.model} (${m.api})`);
|
|
1214
|
+
const selected = await pick(
|
|
1215
|
+
ctx,
|
|
1216
|
+
"Cadence model (remembered across projects)",
|
|
1217
|
+
labels,
|
|
1218
|
+
);
|
|
1219
|
+
if (!selected) return result("Model unchanged.");
|
|
1220
|
+
const model = models[labels.indexOf(selected)];
|
|
1221
|
+
const thinking = await pick(
|
|
1222
|
+
ctx,
|
|
1223
|
+
"Thinking",
|
|
1224
|
+
model.thinking.filter((t) => t.selectable).map((t) => t.level),
|
|
1225
|
+
);
|
|
1226
|
+
if (!thinking) return result("Model unchanged.");
|
|
1227
|
+
const choice: ModelSelector = decodeModelSelector({
|
|
1228
|
+
provider: model.provider,
|
|
1229
|
+
model: model.model,
|
|
1230
|
+
api: model.api,
|
|
1231
|
+
thinking,
|
|
1232
|
+
});
|
|
1233
|
+
value(
|
|
1234
|
+
await client().chooseModel({
|
|
1235
|
+
expected: catalog.version,
|
|
1236
|
+
choice,
|
|
1237
|
+
}),
|
|
1238
|
+
);
|
|
1239
|
+
// An explicit selection may atomically rewrite a corrupt preference.
|
|
1240
|
+
new CadencePreferences(agentDir()).choose(choice);
|
|
1241
|
+
warnedPreferences = false;
|
|
1242
|
+
state.proposal = null;
|
|
1243
|
+
permission = undefined;
|
|
1244
|
+
persist();
|
|
1245
|
+
return result(
|
|
1246
|
+
"Cadence model preference saved. It does not copy credentials or change an already accepted run.",
|
|
1247
|
+
);
|
|
1248
|
+
},
|
|
1249
|
+
});
|
|
1250
|
+
}
|