@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.
@@ -0,0 +1,78 @@
1
+ /** User-owned model preference, never auth, approval or a reusable source-selection ID. */
2
+ import { realpathSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { closed } from "./service/contracts/core.ts";
5
+ import { PrivateFiles } from "./service/private-files.ts";
6
+ import {
7
+ canonicalJson,
8
+ decodeModelSelector,
9
+ type ModelSelector,
10
+ parseWireJson,
11
+ } from "./service-contract.ts";
12
+
13
+ /** Pi follows links in its agent directory (dotfile setups link `~/.pi` or
14
+ * `~/.pi/agent`). Resolve the existing part of that directory as Pi does,
15
+ * then keep the no-follow private walk below it: a linked `cadence` directory
16
+ * or `settings.json`, another owner's directory or a hard link stay refused. */
17
+ function agentNamespace(agentDir: string): string {
18
+ let at = resolve(agentDir);
19
+ const missing: string[] = [];
20
+ for (;;) {
21
+ try {
22
+ return join(realpathSync(at), ...missing.reverse());
23
+ } catch {
24
+ const parent = dirname(at);
25
+ if (parent === at) return resolve(agentDir);
26
+ missing.push(basename(at));
27
+ at = parent;
28
+ }
29
+ }
30
+ }
31
+
32
+ export class CadencePreferences {
33
+ readonly path: string;
34
+ private readonly files: PrivateFiles;
35
+ constructor(agentDir: string) {
36
+ const namespace = agentNamespace(agentDir);
37
+ this.path = join(namespace, "cadence", "settings.json");
38
+ this.files = new PrivateFiles(namespace, false);
39
+ }
40
+ read(): ModelSelector | null {
41
+ const saved = this.files.read(this.path);
42
+ if (!saved) return null;
43
+ const o = closed(parseWireJson(saved.bytes.toString("utf8")), [
44
+ "schema",
45
+ "model",
46
+ ]);
47
+ if (o.schema !== "cadence-preferences/1")
48
+ throw new Error("Unsupported Cadence preferences");
49
+ return decodeModelSelector(o.model);
50
+ }
51
+ private encode(model: ModelSelector): string {
52
+ return canonicalJson({
53
+ schema: "cadence-preferences/1",
54
+ model: decodeModelSelector(model),
55
+ });
56
+ }
57
+ /** Implicit remembering: validate an existing user file, including its
58
+ * schema, before replacing it; never silently replace an unreadable one. */
59
+ save(model: ModelSelector): void {
60
+ const selected = decodeModelSelector(model);
61
+ const previous = this.files.read(this.path);
62
+ if (previous && canonicalJson(this.read()) === canonicalJson(selected))
63
+ return;
64
+ const bytes = this.encode(selected);
65
+ if (previous) this.files.replace(this.path, previous, bytes);
66
+ else this.files.create(this.path, bytes);
67
+ }
68
+ /** An explicit user model selection. It atomically replaces a regular file
69
+ * whose contents are corrupt or unsupported, since the user just chose the
70
+ * replacement; unsafe targets such as links are still refused. */
71
+ choose(model: ModelSelector): void {
72
+ const bytes = this.encode(model);
73
+ const previous = this.files.read(this.path);
74
+ if (previous?.bytes.toString("utf8") === bytes) return;
75
+ if (previous) this.files.replace(this.path, previous, bytes);
76
+ else this.files.create(this.path, bytes);
77
+ }
78
+ }
@@ -0,0 +1,109 @@
1
+ /** Finite private child/owner bridge. Never a browser API or shell executor. */
2
+ import { Type } from "typebox";
3
+
4
+ const CHECK = Type.Object({
5
+ name: Type.String(),
6
+ command: Type.String(),
7
+ timeoutMs: Type.Integer({ minimum: 100, maximum: 1200000 }),
8
+ });
9
+ const PLAN = Type.Object({
10
+ goal: Type.String(),
11
+ design: Type.String(),
12
+ decisions: Type.String(),
13
+ acceptance: Type.String(),
14
+ projectContext: Type.String(),
15
+ tasks: Type.Array(
16
+ Type.Object({
17
+ id: Type.String(),
18
+ title: Type.String(),
19
+ instructions: Type.String(),
20
+ writes: Type.Array(Type.String()),
21
+ after: Type.Array(Type.String()),
22
+ }),
23
+ { minItems: 1, maxItems: 16 },
24
+ ),
25
+ checks: Type.Array(CHECK, { minItems: 1, maxItems: 16 }),
26
+ setup: Type.Array(CHECK, { maxItems: 4 }),
27
+ baselineChecks: Type.Array(CHECK, { maxItems: 16 }),
28
+ repairAttempts: Type.Integer({ minimum: 0, maximum: 2 }),
29
+ delivery: Type.Union([
30
+ Type.Literal("local-merge"),
31
+ Type.Literal("working-copy"),
32
+ ]),
33
+ });
34
+ export function coordinatorTools() {
35
+ if (!process.send) throw new Error("Coordinator bridge unavailable");
36
+ const pending = new Map();
37
+ let counter = 0;
38
+ let chain = Promise.resolve();
39
+ const closed = () => {
40
+ for (const p of pending.values())
41
+ p.reject(new Error("Coordinator disconnected"));
42
+ pending.clear();
43
+ };
44
+ process.on("disconnect", closed);
45
+ process.on("message", (reply) => {
46
+ if (
47
+ !reply ||
48
+ typeof reply !== "object" ||
49
+ Buffer.byteLength(JSON.stringify(reply)) > 65536
50
+ )
51
+ return closed();
52
+ const p = pending.get(reply.id);
53
+ if (!p) return;
54
+ pending.delete(reply.id);
55
+ if (reply.ok === true && typeof reply.text === "string")
56
+ p.resolve({
57
+ content: [{ type: "text", text: reply.text }],
58
+ details: undefined,
59
+ });
60
+ else p.reject(new Error("Coordinator refused this request"));
61
+ });
62
+ return [
63
+ {
64
+ name: "cadence_research",
65
+ description:
66
+ "Investigate bounded project questions with readonly subagents; returns recorded evidence. Never edits.",
67
+ parameters: Type.Object({
68
+ goal: Type.String(),
69
+ questions: Type.Array(Type.String(), { minItems: 1, maxItems: 2 }),
70
+ }),
71
+ },
72
+ {
73
+ name: "cadence_plan",
74
+ description:
75
+ "Publish a complete proposal after decisions are aligned. This never authorizes execution. The user sees an exact plan card.",
76
+ parameters: PLAN,
77
+ },
78
+ {
79
+ name: "cadence_status",
80
+ description:
81
+ "Read actual workflow progress and outcomes, not inferred success.",
82
+ parameters: Type.Object({}),
83
+ },
84
+ ].map((tool) => ({
85
+ ...tool,
86
+ label: tool.name,
87
+ execute: async (_callId, args, signal) => {
88
+ if (signal?.aborted || ++counter > 16 || pending.size >= 4)
89
+ throw new Error("Coordinator budget exceeded");
90
+ const request = { id: counter, name: tool.name, args };
91
+ if (Buffer.byteLength(JSON.stringify(request)) > 65536)
92
+ throw new Error("Coordinator request exceeds bound");
93
+ const original = chain.then(
94
+ () =>
95
+ new Promise((resolve, reject) => {
96
+ pending.set(request.id, { resolve, reject });
97
+ process.send(request, (error) => {
98
+ if (error) {
99
+ pending.delete(request.id);
100
+ reject(new Error("Coordinator request unavailable"));
101
+ }
102
+ });
103
+ }),
104
+ );
105
+ chain = original.catch(() => {});
106
+ return original;
107
+ },
108
+ }));
109
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ import os from "node:os";
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import { registerAgentPanel } from "./agent-panel.ts";
4
4
  import { registerCadenceAgentFeed } from "./agent-panel-cadence.ts";
5
+ import { registerCadenceMode } from "./cadence-mode.ts";
5
6
  import { autostartNotice } from "./native-client.ts";
6
7
  import { CONFIG_MISSING, startupCardLines } from "./startup-card.ts";
7
8
  import { registerTaskShell } from "./task-shell.ts";
@@ -11,6 +12,7 @@ import { registerTaskShell } from "./task-shell.ts";
11
12
  export default function register(pi: ExtensionAPI): void {
12
13
  if (process.env.CADENCE_SUBAGENT_CHILD === "1") return;
13
14
  registerTaskShell(pi);
15
+ registerCadenceMode(pi);
14
16
  // Observes `subagent:*` bus events only; renders nothing until one arrives.
15
17
  registerAgentPanel(pi);
16
18
  // Publishes a running owner's child runs there; readonly, never starts one.
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "83a2720c0a5a61f9e18e4f67e9738f184dee61cf07e75d9b98b5728577daaa6d",
5
+ "02a8164a76a61a8c58a2858885dc3900628c07003313f10c5cb1cf68a930dc9b",
6
6
  } as const;
@@ -57,8 +57,19 @@ const bootStart = (o: AutostartObservation) =>
57
57
  o.platform === "linux" && (o.uid === 0 || o.env.CADENCE_LINGER !== "0");
58
58
  /** Pi's managed copy puts no `cadence` bin on PATH; CADENCE_LINGER=0 keeps
59
59
  * the suggested command login-only, too. */
60
+ const cliCommand = (o: AutostartObservation) =>
61
+ piUserCopy(o)
62
+ ? `node ${JSON.stringify(join(o.root, "src", "service-cli.mjs"))}`
63
+ : "cadence";
60
64
  const installCommand = (o: AutostartObservation) =>
61
- `${piUserCopy(o) ? `node ${JSON.stringify(join(o.root, "src", "service-cli.mjs"))}` : "cadence"} server install${o.platform === "linux" && o.uid === 0 ? " --system" : o.platform === "linux" && o.env.CADENCE_LINGER === "0" ? " --no-linger" : ""}`;
65
+ `${cliCommand(o)} server install${o.platform === "linux" && o.uid === 0 ? " --system" : o.platform === "linux" && o.env.CADENCE_LINGER === "0" ? " --no-linger" : ""}`;
66
+ /** The explicit command that stops one project owner. Text only. */
67
+ export function projectStopCommand(
68
+ workspace: string,
69
+ o: AutostartObservation = hostObservation(),
70
+ ): string {
71
+ return `${cliCommand(o)} stop --workspace ${JSON.stringify(workspace)}`;
72
+ }
62
73
 
63
74
  /** Name the explicit command while no background service is registered.
64
75
  * Reads paths only. */
@@ -241,6 +252,38 @@ export class NativeConnection {
241
252
  compatible(safety = false): boolean {
242
253
  return compatibleBuild(this.session?.build, nativeBuild, safety);
243
254
  }
255
+ /** Forget an attachment only when the registry proves its owner instance is
256
+ * gone: absent, stopped, or replaced by another epoch. Its slot ended with
257
+ * that process, so no detach request is sent and a later attach may proceed.
258
+ * A live or unobservable same-epoch owner keeps the exact attachment. */
259
+ forgetSuperseded(cwd: string): boolean {
260
+ if ((!this.transport && !this.network) || this.closing || this.allocating)
261
+ return false;
262
+ let observed: { status: string; epoch?: string | null };
263
+ try {
264
+ observed = new ServiceCoordination(
265
+ effectiveWorkspace(cwd).workspace,
266
+ ).inspect();
267
+ } catch {
268
+ return false;
269
+ }
270
+ const epoch = "epoch" in observed ? observed.epoch : undefined;
271
+ const gone =
272
+ observed.status === "absent" ||
273
+ (observed.status === "stopped" &&
274
+ (epoch === null || epoch === this.epoch)) ||
275
+ (typeof epoch === "string" && epoch !== this.epoch);
276
+ if (!gone) return false;
277
+ const network = this.network;
278
+ this.network = undefined;
279
+ this.networkClose = undefined;
280
+ this.transport = undefined;
281
+ this.client = undefined;
282
+ this.session = undefined;
283
+ this.epoch = undefined;
284
+ void network?.close().catch(() => {});
285
+ return true;
286
+ }
244
287
  detach(): Promise<void> {
245
288
  if (this.closing) return this.closing;
246
289
  const transport = this.transport;
@@ -19,6 +19,7 @@ import {
19
19
  readConversationContext,
20
20
  } from "./conversation-context.mjs";
21
21
  import { conversationResources } from "./conversation-resources.mjs";
22
+ import { coordinatorTools } from "./coordinator-tools.mjs";
22
23
  import { CaptureEmitter, SdkCapture } from "./worker-capture.mjs";
23
24
  import {
24
25
  closed,
@@ -46,6 +47,7 @@ const adapters = {
46
47
  import("@earendil-works/pi-ai/api/azure-openai-responses"),
47
48
  };
48
49
  let session;
50
+ let ownsCoordinatorChannel = false;
49
51
  let ownedAgent;
50
52
  let unsubscribe;
51
53
  let emitter;
@@ -205,7 +207,13 @@ try {
205
207
  const conversation =
206
208
  envelope.conversation === undefined
207
209
  ? null
208
- : closed(envelope.conversation, ["previous", "agentDir"]);
210
+ : closed(envelope.conversation, [
211
+ "previous",
212
+ "agentDir",
213
+ ...(Object.hasOwn(envelope.conversation, "coordinator")
214
+ ? ["coordinator"]
215
+ : []),
216
+ ]);
209
217
  if (
210
218
  conversation &&
211
219
  ((conversation.previous !== null &&
@@ -214,6 +222,12 @@ try {
214
222
  )
215
223
  refuse("parse", "invalid-conversation");
216
224
  const publicRequest = decodeWorkerPublicRequest(envelope.request);
225
+ const coordinator = conversation?.coordinator === true;
226
+ if (
227
+ conversation?.coordinator !== undefined &&
228
+ (!coordinator || !process.send || publicRequest.purpose !== "research")
229
+ )
230
+ refuse("parse", "invalid-coordinator");
217
231
  const request = {
218
232
  ...envelope,
219
233
  kind:
@@ -354,18 +368,22 @@ try {
354
368
  if (conversation)
355
369
  for (const message of readConversationContext(conversation.previous))
356
370
  manager.appendMessage(message);
371
+ const coordinationTools = coordinator ? coordinatorTools() : undefined;
372
+ ownsCoordinatorChannel = coordinator;
357
373
  const created = await createAgentSession({
358
374
  cwd,
359
375
  agentDir: cwd,
360
376
  model,
361
377
  modelRuntime: runtime,
362
378
  thinkingLevel: requestedThinkingLevel,
363
- tools:
364
- kind === "code"
379
+ tools: coordinator
380
+ ? ["cadence_research", "cadence_plan", "cadence_status"]
381
+ : kind === "code"
365
382
  ? ["read", "grep", "find", "ls", "write", "edit", "bash"]
366
383
  : ["read", "grep", "find", "ls"],
367
- customTools:
368
- kind === "code"
384
+ customTools: coordinator
385
+ ? coordinationTools
386
+ : kind === "code"
369
387
  ? [
370
388
  captureBash(
371
389
  cwd,
@@ -376,9 +394,10 @@ try {
376
394
  ),
377
395
  ]
378
396
  : [],
379
- resourceLoader: conversation
380
- ? conversationResources(resourceLoader, cwd, conversation.agentDir)
381
- : resourceLoader,
397
+ resourceLoader:
398
+ conversation && !coordinator
399
+ ? conversationResources(resourceLoader, cwd, conversation.agentDir)
400
+ : resourceLoader,
382
401
  sessionManager: manager,
383
402
  settingsManager: SettingsManager.inMemory({
384
403
  compaction: { enabled: false },
@@ -583,4 +602,5 @@ try {
583
602
  // A failed diagnostic write cannot print an arbitrary exception or repair failure.
584
603
  process.exitCode = 1;
585
604
  }
605
+ if (ownsCoordinatorChannel && process.connected) process.disconnect();
586
606
  }