@abelxiaoxing/cadence 2.0.21 → 2.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  /** User-owned model preference, never auth, approval or a reusable source-selection ID. */
2
- import { join } from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
3
4
  import { closed } from "./service/contracts/core.ts";
4
5
  import { PrivateFiles } from "./service/private-files.ts";
5
6
  import {
@@ -9,12 +10,32 @@ import {
9
10
  parseWireJson,
10
11
  } from "./service-contract.ts";
11
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
+
12
32
  export class CadencePreferences {
13
33
  readonly path: string;
14
34
  private readonly files: PrivateFiles;
15
35
  constructor(agentDir: string) {
16
- this.path = join(agentDir, "cadence", "settings.json");
17
- this.files = new PrivateFiles(agentDir, false);
36
+ const namespace = agentNamespace(agentDir);
37
+ this.path = join(namespace, "cadence", "settings.json");
38
+ this.files = new PrivateFiles(namespace, false);
18
39
  }
19
40
  read(): ModelSelector | null {
20
41
  const saved = this.files.read(this.path);
@@ -27,16 +48,30 @@ export class CadencePreferences {
27
48
  throw new Error("Unsupported Cadence preferences");
28
49
  return decodeModelSelector(o.model);
29
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. */
30
59
  save(model: ModelSelector): void {
31
60
  const selected = decodeModelSelector(model);
32
61
  const previous = this.files.read(this.path);
33
- // Validate an existing user file, including its schema, before replacing it.
34
62
  if (previous && canonicalJson(this.read()) === canonicalJson(selected))
35
63
  return;
36
- const bytes = canonicalJson({
37
- schema: "cadence-preferences/1",
38
- model: selected,
39
- });
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;
40
75
  if (previous) this.files.replace(this.path, previous, bytes);
41
76
  else this.files.create(this.path, bytes);
42
77
  }
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "d19e63723270a27a4c00776d8301849e08480e054bc832ca455f889d061c65c9",
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;
@@ -1,6 +1,7 @@
1
1
  /** Finite, authenticated workbench API. Ordinary chat is not task admission. */
2
2
  import {
3
3
  bool,
4
+ ContractError,
4
5
  canonicalJson,
5
6
  closed,
6
7
  decodeHash,
@@ -31,8 +32,14 @@ export interface CadenceConversation {
31
32
  head: string | null;
32
33
  proposal: WorkflowProposal | null;
33
34
  runs: string[];
35
+ /** Present only in a read projection of an unusable retained record: every
36
+ * command for that conversation refuses; nothing is inferred or repaired.
37
+ * Never persisted. */
38
+ notice?: string;
34
39
  }
35
40
  export function decodeCadenceConversation(v: unknown): CadenceConversation {
41
+ const degraded =
42
+ v !== null && typeof v === "object" && Object.hasOwn(v, "notice");
36
43
  const o = closed(v, [
37
44
  "id",
38
45
  "revision",
@@ -40,6 +47,7 @@ export function decodeCadenceConversation(v: unknown): CadenceConversation {
40
47
  "head",
41
48
  "proposal",
42
49
  "runs",
50
+ ...(degraded ? ["notice"] : []),
43
51
  ]);
44
52
  return {
45
53
  id: decodeId(o.id),
@@ -48,8 +56,14 @@ export function decodeCadenceConversation(v: unknown): CadenceConversation {
48
56
  head: nullable(o.head, decodeId),
49
57
  proposal: nullable(o.proposal, decodeWorkflowProposal),
50
58
  runs: list(o.runs, 200, decodeId),
59
+ ...(degraded ? { notice: text(o.notice, 1024, true) } : {}),
51
60
  };
52
61
  }
62
+ /** Browser conversation that owns an active workflow; native runs have none. */
63
+ export interface WorkflowLink {
64
+ runId: string;
65
+ conversationId: string;
66
+ }
53
67
  export type WorkbenchRead =
54
68
  | { kind: "cadence-conversation"; id: string }
55
69
  | { kind: "workflow-active" }
@@ -176,7 +190,12 @@ export type WorkbenchResult =
176
190
  turn: ChatTurn | null;
177
191
  }
178
192
  | { kind: "cadence-conversation"; state: CadenceConversation }
179
- | { kind: "workflow-active"; runs: WorkflowRun[] }
193
+ | {
194
+ kind: "workflow-active";
195
+ runs: WorkflowRun[];
196
+ /** At most one link per listed run; set by the workbench composition. */
197
+ links?: WorkflowLink[];
198
+ }
180
199
  | {
181
200
  kind: "cadence-grant";
182
201
  commandId: string;
@@ -474,8 +493,25 @@ export function decodeWorkbenchResult(v: unknown): WorkbenchResult {
474
493
  return { kind: k, state: decodeCadenceConversation(o.state) };
475
494
  }
476
495
  if (k === "workflow-active") {
477
- const o = closed(v, ["kind", "runs"]);
478
- return { kind: k, runs: list(o.runs, 4, decodeWorkflowRun) };
496
+ const linked =
497
+ v !== null && typeof v === "object" && Object.hasOwn(v, "links");
498
+ const o = closed(v, ["kind", "runs", ...(linked ? ["links"] : [])]);
499
+ const runs = list(o.runs, 4, decodeWorkflowRun);
500
+ const links = linked
501
+ ? list(o.links, 4, (value) => {
502
+ const l = closed(value, ["runId", "conversationId"]);
503
+ return {
504
+ runId: decodeId(l.runId),
505
+ conversationId: decodeId(l.conversationId),
506
+ };
507
+ })
508
+ : [];
509
+ if (
510
+ new Set(links.map((l) => l.runId)).size !== links.length ||
511
+ links.some((l) => !runs.some((r) => r.id === l.runId))
512
+ )
513
+ throw new ContractError("invalid");
514
+ return { kind: k, runs, links };
479
515
  }
480
516
  if (k === "cadence-grant") {
481
517
  const o = closed(v, [
@@ -117,7 +117,22 @@ export type WorkflowResponse =
117
117
  }
118
118
  | { type: "run"; run: WorkflowRun };
119
119
 
120
- export function workflowPath(v: unknown): string {
120
+ /** Clip by UTF-16 units without leaving a lone surrogate (unencodable on the wire). */
121
+ export function clipUnits(value: string, units: number): string {
122
+ if (value.length <= units) return value;
123
+ const last = value.charCodeAt(units - 1);
124
+ return value.slice(0, last >= 0xd800 && last <= 0xdbff ? units - 1 : units);
125
+ }
126
+ /** A declared write path owns itself and, as a directory, everything below it. */
127
+ export function workflowCovers(
128
+ scope: readonly string[],
129
+ name: string,
130
+ ): boolean {
131
+ return scope.some((p) => name === p || name.startsWith(`${p}/`));
132
+ }
133
+ /** Read decoding accepts every path 2.0.21 accepted; `strict` (new plans only)
134
+ * additionally refuses invisible format characters. */
135
+ export function workflowPath(v: unknown, strict = false): string {
121
136
  const p = text(v, 1024, true);
122
137
  if (
123
138
  p.startsWith("/") ||
@@ -125,6 +140,9 @@ export function workflowPath(v: unknown): string {
125
140
  [...p].some(
126
141
  (c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127 || c === ":",
127
142
  ) ||
143
+ // Bidi overrides/isolates/marks, zero-width and other format characters
144
+ // make a displayed scope differ from the enforced one.
145
+ (strict && /[\p{Cf}\p{Zl}\p{Zp}]/u.test(p)) ||
128
146
  p
129
147
  .split("/")
130
148
  .some(
@@ -135,9 +153,12 @@ export function workflowPath(v: unknown): string {
135
153
  throw new Error("Invalid workflow file path");
136
154
  return p;
137
155
  }
138
- const taskId = (v: unknown) => {
156
+ // Task IDs are worker assignment IDs and worktree names. New plans use the
157
+ // assignmentId bound (48); reads still accept retained 2.0.21 IDs (64).
158
+ const taskId = (v: unknown, strict = false) => {
139
159
  const s = text(v, 64, true);
140
- if (!/^[a-z][a-z0-9-]*$/u.test(s)) throw new Error("Invalid task id");
160
+ if (!/^[a-z][a-z0-9-]*$/u.test(s) || (strict && s.length > 48))
161
+ throw new Error("Invalid task id");
141
162
  return s;
142
163
  };
143
164
  export function decodeWorkflowCheck(v: unknown): WorkflowCheck {
@@ -180,7 +201,13 @@ export function workflowAncestors(
180
201
  visit(id);
181
202
  return workflowOrder(tasks).filter((t) => needed.has(t.id));
182
203
  }
183
- export function decodeWorkflowPlan(v: unknown): WorkflowPlan {
204
+ /** Retained plans decode with the rules they were accepted under; `strict` is
205
+ * for validating a new plan before publication or execution. */
206
+ export function decodeWorkflowPlan(
207
+ v: unknown,
208
+ options: { strict?: boolean } = {},
209
+ ): WorkflowPlan {
210
+ const strict = options.strict === true;
184
211
  canonicalJson(v, WORKFLOW_LIMITS.bytes);
185
212
  const o = closed(v, [
186
213
  "goal",
@@ -198,11 +225,13 @@ export function decodeWorkflowPlan(v: unknown): WorkflowPlan {
198
225
  const tasks = list(o.tasks, WORKFLOW_LIMITS.tasks, (value) => {
199
226
  const t = closed(value, ["id", "title", "instructions", "writes", "after"]);
200
227
  return {
201
- id: taskId(t.id),
228
+ id: taskId(t.id, strict),
202
229
  title: text(t.title, 256, true),
203
230
  instructions: text(t.instructions, 8192, true),
204
- writes: list(t.writes, 128, workflowPath),
205
- after: list(t.after, WORKFLOW_LIMITS.tasks, taskId),
231
+ writes: list(t.writes, 128, (p: unknown) => workflowPath(p, strict)),
232
+ after: list(t.after, WORKFLOW_LIMITS.tasks, (id: unknown) =>
233
+ taskId(id, strict),
234
+ ),
206
235
  };
207
236
  });
208
237
  if (
@@ -225,11 +254,8 @@ export function decodeWorkflowPlan(v: unknown): WorkflowPlan {
225
254
  )
226
255
  continue;
227
256
  if (
228
- a.writes.some((p) =>
229
- b.writes.some(
230
- (q) => p === q || p.startsWith(`${q}/`) || q.startsWith(`${p}/`),
231
- ),
232
- )
257
+ a.writes.some((p) => workflowCovers(b.writes, p)) ||
258
+ b.writes.some((q) => workflowCovers(a.writes, q))
233
259
  )
234
260
  throw new Error(
235
261
  "Independent tasks share write paths; assign an owner and dependency",