@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,43 @@
1
+ /** User-owned model preference, never auth, approval or a reusable source-selection ID. */
2
+ import { join } from "node:path";
3
+ import { closed } from "./service/contracts/core.ts";
4
+ import { PrivateFiles } from "./service/private-files.ts";
5
+ import {
6
+ canonicalJson,
7
+ decodeModelSelector,
8
+ type ModelSelector,
9
+ parseWireJson,
10
+ } from "./service-contract.ts";
11
+
12
+ export class CadencePreferences {
13
+ readonly path: string;
14
+ private readonly files: PrivateFiles;
15
+ constructor(agentDir: string) {
16
+ this.path = join(agentDir, "cadence", "settings.json");
17
+ this.files = new PrivateFiles(agentDir, false);
18
+ }
19
+ read(): ModelSelector | null {
20
+ const saved = this.files.read(this.path);
21
+ if (!saved) return null;
22
+ const o = closed(parseWireJson(saved.bytes.toString("utf8")), [
23
+ "schema",
24
+ "model",
25
+ ]);
26
+ if (o.schema !== "cadence-preferences/1")
27
+ throw new Error("Unsupported Cadence preferences");
28
+ return decodeModelSelector(o.model);
29
+ }
30
+ save(model: ModelSelector): void {
31
+ const selected = decodeModelSelector(model);
32
+ const previous = this.files.read(this.path);
33
+ // Validate an existing user file, including its schema, before replacing it.
34
+ if (previous && canonicalJson(this.read()) === canonicalJson(selected))
35
+ return;
36
+ const bytes = canonicalJson({
37
+ schema: "cadence-preferences/1",
38
+ model: selected,
39
+ });
40
+ if (previous) this.files.replace(this.path, previous, bytes);
41
+ else this.files.create(this.path, bytes);
42
+ }
43
+ }
@@ -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
+ "d19e63723270a27a4c00776d8301849e08480e054bc832ca455f889d061c65c9",
6
6
  } as const;
@@ -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
  }
@@ -3,6 +3,7 @@ import {
3
3
  bool,
4
4
  canonicalJson,
5
5
  closed,
6
+ decodeHash,
6
7
  decodeId,
7
8
  integer,
8
9
  list,
@@ -12,7 +13,49 @@ import {
12
13
  } from "./core.ts";
13
14
  import { type ChoiceVersion, decodeChoiceVersion } from "./models.ts";
14
15
 
16
+ import {
17
+ decodeWorkflowProposal,
18
+ decodeWorkflowRequest,
19
+ decodeWorkflowResponse,
20
+ decodeWorkflowRun,
21
+ type WorkflowProposal,
22
+ type WorkflowRequest,
23
+ type WorkflowResponse,
24
+ type WorkflowRun,
25
+ } from "./workflow.ts";
26
+
27
+ export interface CadenceConversation {
28
+ id: string;
29
+ revision: number;
30
+ enabled: boolean;
31
+ head: string | null;
32
+ proposal: WorkflowProposal | null;
33
+ runs: string[];
34
+ }
35
+ export function decodeCadenceConversation(v: unknown): CadenceConversation {
36
+ const o = closed(v, [
37
+ "id",
38
+ "revision",
39
+ "enabled",
40
+ "head",
41
+ "proposal",
42
+ "runs",
43
+ ]);
44
+ return {
45
+ id: decodeId(o.id),
46
+ revision: integer(o.revision, 0),
47
+ enabled: bool(o.enabled),
48
+ head: nullable(o.head, decodeId),
49
+ proposal: nullable(o.proposal, decodeWorkflowProposal),
50
+ runs: list(o.runs, 200, decodeId),
51
+ };
52
+ }
15
53
  export type WorkbenchRead =
54
+ | { kind: "cadence-conversation"; id: string }
55
+ | { kind: "workflow-active" }
56
+ | { kind: "workflow-detail"; id: string; stepId: string }
57
+ | { kind: "workflow-transcript"; id: string; stepId: string }
58
+ | { kind: "workflow"; id: string }
16
59
  | { kind: "conversations" }
17
60
  | { kind: "task-origin"; taskId: string }
18
61
  | { kind: "conversation"; id: string; before: string | null }
@@ -21,6 +64,48 @@ export type WorkbenchRead =
21
64
  | { kind: "directories"; path: string }
22
65
  | { kind: "projects" };
23
66
  export type WorkbenchCommand =
67
+ | {
68
+ kind: "cadence-exit";
69
+ commandId: string;
70
+ conversationId: string;
71
+ head: string | null;
72
+ revision: number;
73
+ }
74
+ | { kind: "restore-model"; commandId: string; epoch: string }
75
+ | {
76
+ kind: "cadence-send";
77
+ commandId: string;
78
+ conversationId: string;
79
+ head: string | null;
80
+ text: string;
81
+ model: ChoiceVersion;
82
+ revision: number;
83
+ intent: "message" | "enter" | "exit";
84
+ }
85
+ | {
86
+ kind: "cadence-prepare";
87
+ commandId: string;
88
+ conversationId: string;
89
+ revision: number;
90
+ proposalId: string;
91
+ digest: string;
92
+ }
93
+ | {
94
+ kind: "cadence-approve";
95
+ commandId: string;
96
+ conversationId: string;
97
+ revision: number;
98
+ proposalId: string;
99
+ digest: string;
100
+ grant: string;
101
+ }
102
+ | { kind: "workflow-cancel"; commandId: string; epoch: string; runId: string }
103
+ | {
104
+ kind: "workflow";
105
+ commandId: string;
106
+ epoch: string;
107
+ request: WorkflowRequest;
108
+ }
24
109
  | {
25
110
  kind: "link-task";
26
111
  commandId: string;
@@ -76,6 +161,7 @@ export interface ChatSummary {
76
161
  head: string;
77
162
  status: ChatStatus;
78
163
  updatedAt: number;
164
+ cadence?: boolean;
79
165
  }
80
166
  export interface FileEntry {
81
167
  name: string;
@@ -83,6 +169,23 @@ export interface FileEntry {
83
169
  directory: boolean;
84
170
  }
85
171
  export type WorkbenchResult =
172
+ | {
173
+ kind: "workflow-transcript";
174
+ runId: string;
175
+ stepId: string;
176
+ turn: ChatTurn | null;
177
+ }
178
+ | { kind: "cadence-conversation"; state: CadenceConversation }
179
+ | { kind: "workflow-active"; runs: WorkflowRun[] }
180
+ | {
181
+ kind: "cadence-grant";
182
+ commandId: string;
183
+ grant: string;
184
+ expiresAt: number;
185
+ revision: number;
186
+ proposal: WorkflowProposal;
187
+ }
188
+ | { kind: "workflow"; commandId: string | null; response: WorkflowResponse }
86
189
  | { kind: "task-origin"; taskId: string; conversationId: string | null }
87
190
  | { kind: "conversations"; entries: ChatSummary[] }
88
191
  | {
@@ -106,6 +209,11 @@ export interface WorkbenchPort {
106
209
  read(request: WorkbenchRead): WorkbenchResult;
107
210
  command(
108
211
  request: WorkbenchCommand,
212
+ caller?: {
213
+ attachmentId: string;
214
+ authority: "browser" | "local";
215
+ accessGeneration: number;
216
+ },
109
217
  ): WorkbenchResult | Promise<WorkbenchResult>;
110
218
  }
111
219
  const statuses = [
@@ -120,6 +228,22 @@ const statuses = [
120
228
  export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
121
229
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
122
230
  switch (kind) {
231
+ case "cadence-conversation": {
232
+ const o = closed(v, ["kind", "id"]);
233
+ return { kind, id: decodeId(o.id) };
234
+ }
235
+ case "workflow-active":
236
+ closed(v, ["kind"]);
237
+ return { kind };
238
+ case "workflow-transcript":
239
+ case "workflow-detail": {
240
+ const o = closed(v, ["kind", "id", "stepId"]);
241
+ return { kind, id: decodeId(o.id), stepId: text(o.stepId, 160, true) };
242
+ }
243
+ case "workflow": {
244
+ const o = closed(v, ["kind", "id"]);
245
+ return { kind, id: decodeId(o.id) };
246
+ }
123
247
  case "conversations":
124
248
  case "projects":
125
249
  closed(v, ["kind"]);
@@ -143,6 +267,86 @@ export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
143
267
  }
144
268
  export function decodeWorkbenchCommand(v: unknown): WorkbenchCommand {
145
269
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
270
+ if (kind === "restore-model" || kind === "workflow-cancel") {
271
+ const o = closed(
272
+ v,
273
+ kind === "restore-model"
274
+ ? ["kind", "commandId", "epoch"]
275
+ : ["kind", "commandId", "epoch", "runId"],
276
+ );
277
+ const base = { commandId: decodeId(o.commandId), epoch: decodeId(o.epoch) };
278
+ return kind === "restore-model"
279
+ ? { kind, ...base }
280
+ : { kind, ...base, runId: decodeId(o.runId) };
281
+ }
282
+ if (kind === "cadence-exit") {
283
+ const o = closed(v, [
284
+ "kind",
285
+ "commandId",
286
+ "conversationId",
287
+ "head",
288
+ "revision",
289
+ ]);
290
+ return {
291
+ kind,
292
+ commandId: decodeId(o.commandId),
293
+ conversationId: decodeId(o.conversationId),
294
+ head: nullable(o.head, decodeId),
295
+ revision: integer(o.revision, 0),
296
+ };
297
+ }
298
+ if (kind === "cadence-send") {
299
+ const o = closed(v, [
300
+ "kind",
301
+ "commandId",
302
+ "conversationId",
303
+ "head",
304
+ "text",
305
+ "model",
306
+ "revision",
307
+ "intent",
308
+ ]);
309
+ return {
310
+ kind,
311
+ commandId: decodeId(o.commandId),
312
+ conversationId: decodeId(o.conversationId),
313
+ head: nullable(o.head, decodeId),
314
+ text: text(o.text, 16384, true),
315
+ model: decodeChoiceVersion(o.model),
316
+ revision: integer(o.revision, 0),
317
+ intent: oneOf(o.intent, ["message", "enter", "exit"]),
318
+ };
319
+ }
320
+ if (kind === "cadence-prepare" || kind === "cadence-approve") {
321
+ const keys = [
322
+ "kind",
323
+ "commandId",
324
+ "conversationId",
325
+ "revision",
326
+ "proposalId",
327
+ "digest",
328
+ ];
329
+ const o = closed(v, kind === "cadence-approve" ? [...keys, "grant"] : keys);
330
+ const base = {
331
+ commandId: decodeId(o.commandId),
332
+ conversationId: decodeId(o.conversationId),
333
+ revision: integer(o.revision, 0),
334
+ proposalId: decodeId(o.proposalId),
335
+ digest: decodeHash(o.digest),
336
+ };
337
+ return kind === "cadence-prepare"
338
+ ? { kind, ...base }
339
+ : { kind, ...base, grant: decodeId(o.grant) };
340
+ }
341
+ if (kind === "workflow") {
342
+ const o = closed(v, ["kind", "commandId", "epoch", "request"]);
343
+ return {
344
+ kind,
345
+ commandId: decodeId(o.commandId),
346
+ epoch: decodeId(o.epoch),
347
+ request: decodeWorkflowRequest(o.request),
348
+ };
349
+ }
146
350
  if (kind === "link-task") {
147
351
  const o = closed(v, [
148
352
  "kind",
@@ -234,19 +438,73 @@ export function decodeChatTurn(v: unknown): ChatTurn {
234
438
  };
235
439
  }
236
440
  export function decodeChatSummary(v: unknown): ChatSummary {
237
- const o = closed(v, ["id", "title", "head", "status", "updatedAt"]);
441
+ const modern =
442
+ v !== null && typeof v === "object" && Object.hasOwn(v, "cadence");
443
+ const o = closed(v, [
444
+ "id",
445
+ "title",
446
+ "head",
447
+ "status",
448
+ "updatedAt",
449
+ ...(modern ? ["cadence"] : []),
450
+ ]);
238
451
  return {
239
452
  id: decodeId(o.id),
240
453
  title: text(o.title, 512, true),
241
454
  head: decodeId(o.head),
242
455
  status: oneOf(o.status, statuses),
243
456
  updatedAt: integer(o.updatedAt, 0),
457
+ ...(modern ? { cadence: bool(o.cadence) } : {}),
244
458
  };
245
459
  }
246
460
  export function decodeWorkbenchResult(v: unknown): WorkbenchResult {
247
- // A complete finite reply fits the existing page ceiling. No arbitrary file body.
248
461
  canonicalJson(v, 512 * 1024);
462
+ const k = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
463
+ if (k === "workflow-transcript") {
464
+ const o = closed(v, ["kind", "runId", "stepId", "turn"]);
465
+ return {
466
+ kind: k,
467
+ runId: decodeId(o.runId),
468
+ stepId: text(o.stepId, 160, true),
469
+ turn: nullable(o.turn, decodeChatTurn),
470
+ };
471
+ }
472
+ if (k === "cadence-conversation") {
473
+ const o = closed(v, ["kind", "state"]);
474
+ return { kind: k, state: decodeCadenceConversation(o.state) };
475
+ }
476
+ if (k === "workflow-active") {
477
+ const o = closed(v, ["kind", "runs"]);
478
+ return { kind: k, runs: list(o.runs, 4, decodeWorkflowRun) };
479
+ }
480
+ if (k === "cadence-grant") {
481
+ const o = closed(v, [
482
+ "kind",
483
+ "commandId",
484
+ "grant",
485
+ "expiresAt",
486
+ "revision",
487
+ "proposal",
488
+ ]);
489
+ return {
490
+ kind: k,
491
+ commandId: decodeId(o.commandId),
492
+ grant: decodeId(o.grant),
493
+ expiresAt: integer(o.expiresAt, 0),
494
+ revision: integer(o.revision, 0),
495
+ proposal: decodeWorkflowProposal(o.proposal),
496
+ };
497
+ }
498
+ // A complete finite reply fits the existing page ceiling. No arbitrary file body.
249
499
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
500
+ if (kind === "workflow") {
501
+ const o = closed(v, ["kind", "commandId", "response"]);
502
+ return {
503
+ kind,
504
+ commandId: nullable(o.commandId, decodeId),
505
+ response: decodeWorkflowResponse(o.response),
506
+ };
507
+ }
250
508
  if (kind === "task-origin") {
251
509
  const o = closed(v, ["kind", "taskId", "conversationId"]);
252
510
  return {