@abelxiaoxing/cadence 2.0.38 → 2.0.40

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.
@@ -34,12 +34,55 @@ const array = (value, maximum) => {
34
34
  throw new Error("Invalid investigation batch");
35
35
  return value;
36
36
  };
37
+ // Bound expansion work, not ordinary glob syntax. Native matchesGlob supports
38
+ // brace alternatives/extglobs; huge ranges/products must not allocate unboundedly.
39
+ const GLOB_EXPANSIONS = 4096;
37
40
  const glob = (value) => {
38
41
  string(value, 256);
39
- if (/[{}()]/u.test(value))
40
- throw new Error("Use a simple glob without braces or extglobs");
42
+ const stack = [{ alternatives: 0, product: 1, start: 0 }];
43
+ for (let i = 0; i < value.length; i++) {
44
+ if (value[i] === "\\") {
45
+ i++;
46
+ continue;
47
+ }
48
+ const current = stack.at(-1);
49
+ if (value[i] === "{")
50
+ stack.push({ alternatives: 0, product: 1, start: i + 1 });
51
+ else if (value[i] === "," && stack.length > 1) {
52
+ current.alternatives += current.product;
53
+ current.product = 1;
54
+ } else if (value[i] === "}" && stack.length > 1) {
55
+ stack.pop();
56
+ let size = current.alternatives + current.product;
57
+ const range =
58
+ /^(-?\d+|[a-zA-Z])\.\.(-?\d+|[a-zA-Z])(?:\.\.(-?\d+))?$/.exec(
59
+ value.slice(current.start, i),
60
+ );
61
+ if (range) {
62
+ const number = (part) =>
63
+ /^-?\d+$/.test(part) ? Number(part) : part.charCodeAt(0);
64
+ const step = Math.abs(Number(range[3] ?? 1)) || 1;
65
+ size =
66
+ Math.floor(Math.abs(number(range[2]) - number(range[1])) / step) + 1;
67
+ }
68
+ stack.at(-1).product *= size;
69
+ }
70
+ if (
71
+ stack.some(
72
+ (entry) =>
73
+ !Number.isFinite(entry.product) ||
74
+ entry.product + entry.alternatives > GLOB_EXPANSIONS,
75
+ )
76
+ )
77
+ throw new Error(
78
+ "Glob expansion is too large; use * or a smaller set of alternatives",
79
+ );
80
+ }
41
81
  return value;
42
82
  };
83
+ export const RESEARCH_INSTRUCTIONS =
84
+ "Readonly investigation: use read, grep, find/glob and ls directly, not shell command strings. Explicit absolute paths (including installed packages outside the checkout) and symlinks are readable; roots only choose the default search location. grep accepts regular expressions by default; use literal:true for exact text. find/glob accept brace alternatives and extglobs. There is no bash, write or edit tool in this readonly role: use ls for listing, read for file contents, grep for matching and find/glob for file discovery. Keep credentials and private session content out of reports. A returned cursor continues the same query; an empty page with a cursor is not absence.";
85
+
43
86
  function query(kind, args) {
44
87
  const common = ["pageSize", "path"];
45
88
  object(args, [
@@ -48,7 +91,7 @@ function query(kind, args) {
48
91
  ? ["files", "offset", "limit"]
49
92
  : kind === "grep"
50
93
  ? ["pattern", "patterns", "glob", "depth", "ignoreCase", "literal"]
51
- : kind === "find"
94
+ : ["find", "glob"].includes(kind)
52
95
  ? ["pattern", "depth"]
53
96
  : []),
54
97
  ]);
@@ -93,11 +136,12 @@ function query(kind, args) {
93
136
  });
94
137
  } else {
95
138
  result.path = args.path === undefined ? undefined : string(args.path);
96
- result.depth = integer(args.depth ?? L.depth, L.depth, 0);
97
- if (kind === "find") result.glob = glob(args.pattern);
139
+ result.depth = integer(args.depth ?? L.depth, Number.MAX_SAFE_INTEGER, 0);
140
+ if (["find", "glob"].includes(kind)) result.glob = glob(args.pattern);
98
141
  if (kind === "grep") {
99
- if (args.literal !== undefined && args.literal !== true)
100
- throw new Error("Research grep supports literal text only, not regex");
142
+ if (args.literal !== undefined && typeof args.literal !== "boolean")
143
+ throw new Error("Invalid literal selection");
144
+ result.literal = args.literal === true;
101
145
  if (args.ignoreCase !== undefined && typeof args.ignoreCase !== "boolean")
102
146
  throw new Error("Invalid case selection");
103
147
  if ((args.pattern === undefined) === (args.patterns === undefined))
@@ -106,9 +150,22 @@ function query(kind, args) {
106
150
  result.patterns = array(args.patterns ?? [args.pattern], L.patterns).map(
107
151
  (pattern) => {
108
152
  const text = string(pattern, 256);
109
- return result.ignoreCase ? text.toLowerCase() : text;
153
+ return result.literal && result.ignoreCase
154
+ ? text.toLowerCase()
155
+ : text;
110
156
  },
111
157
  );
158
+ if (!result.literal) {
159
+ try {
160
+ result.regex = result.patterns.map(
161
+ (pattern) => new RegExp(pattern, result.ignoreCase ? "iu" : "u"),
162
+ );
163
+ } catch {
164
+ throw new Error(
165
+ "Invalid regular expression; use literal:true for exact text",
166
+ );
167
+ }
168
+ }
112
169
  if (args.glob !== undefined) result.glob = glob(args.glob);
113
170
  }
114
171
  }
@@ -120,13 +177,15 @@ const path = Type.Optional(
120
177
  minLength: 1,
121
178
  maxLength: 4096,
122
179
  description:
123
- "Within the admitted roots; relative paths use the first root.",
180
+ "An explicit host path, including outside the checkout. Relative paths use the first search root; ~ uses this account's home.",
124
181
  }),
125
182
  );
126
183
  const pageSize = Type.Optional(
127
184
  Type.Integer({ minimum: 1, maximum: L.results }),
128
185
  );
129
- const depth = Type.Optional(Type.Integer({ minimum: 0, maximum: L.depth }));
186
+ const depth = Type.Optional(
187
+ Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),
188
+ );
130
189
  const pattern = Type.String({ minLength: 1, maxLength: 256 });
131
190
  // Provider function schemas require an object root, not a union of objects.
132
191
  // Initial-query versus continuation exclusivity is checked before admission;
@@ -175,7 +234,7 @@ const definitions = [
175
234
  {
176
235
  name: "grep",
177
236
  description:
178
- "Search literal text, not regex, in one file or a tree. Supply pattern or patterns (OR; matchedPatterns are zero-based input indexes). Each file is scanned once per query. Optional simple glob, ignoreCase and depth. No symlink traversal, .gitignore interpretation, or .git/node_modules scan. Empty pages with a cursor are progress, NOT absence. Resume with {cursor}, or release with {cursor,close:true}.",
237
+ "Search regular expressions in one file or a tree; literal:true selects exact text. Supply pattern or patterns (OR; matchedPatterns are zero-based input indexes). Each matching logical path is scanned without replaying its consumed prefix. Optional glob, ignoreCase and depth. Explicit host paths, dependencies and symlinks are supported; .git is skipped during tree traversal, and .gitignore is not interpreted. Empty pages with a cursor are progress, NOT absence. Resume with {cursor}, or release with {cursor,close:true}.",
179
238
  parameters: parameters({
180
239
  path,
181
240
  pattern: Type.Optional(pattern),
@@ -183,18 +242,18 @@ const definitions = [
183
242
  Type.Array(pattern, { minItems: 1, maxItems: L.patterns }),
184
243
  ),
185
244
  glob: Type.Optional(pattern),
186
- literal: Type.Optional(Type.Literal(true)),
245
+ literal: Type.Optional(Type.Boolean()),
187
246
  ignoreCase: Type.Optional(Type.Boolean()),
188
247
  depth,
189
248
  pageSize,
190
249
  }),
191
250
  },
192
- {
193
- name: "find",
251
+ ...["find", "glob"].map((name) => ({
252
+ name,
194
253
  description:
195
- "Find file paths with a simple glob (*, **, ?, brackets; no braces/extglobs). Bounded traversal in filesystem order, skipping tree symlinks and .git/node_modules, not backup trees; .gitignore is not interpreted. Resume actual directory positions with {cursor}; {cursor,close:true} releases them. Coverage/omissions are explicit.",
254
+ "Find file paths by glob (*, **, ?, brackets, brace alternatives and extglobs). Explicit host paths, dependencies and symlinks are supported. Traversal defaults to depth 8; set depth explicitly for deeper trees. Symlink cycles and .git traversal are omitted visibly; .gitignore is not interpreted. Resume with this tool's {cursor}; {cursor,close:true} releases it. Coverage/omissions are explicit.",
196
255
  parameters: parameters({ path, pattern, depth, pageSize }),
197
- },
256
+ })),
198
257
  {
199
258
  name: "ls",
200
259
  description:
@@ -429,7 +429,10 @@ try {
429
429
  getPrompts: () => ({ prompts: [], diagnostics: [] }),
430
430
  getThemes: () => ({ themes: [], diagnostics: [] }),
431
431
  getAgentsFiles: () => ({ agentsFiles: [] }),
432
- getSystemPrompt: () => instructions,
432
+ getSystemPrompt: () =>
433
+ toolkit?.instructions
434
+ ? `${instructions}\n\n${toolkit.instructions}`
435
+ : instructions,
433
436
  getSystemPromptSource: () => undefined,
434
437
  getAppendSystemPrompt: () => [],
435
438
  getAppendSystemPromptSources: () => [],
@@ -0,0 +1,190 @@
1
+ /** Short-lived, single-writer Pi activity metadata. Readers never repair or delete. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { opendirSync, renameSync } from "node:fs";
4
+ import { hostname } from "node:os";
5
+ import { join } from "node:path";
6
+ import { canonicalAmbientRoot, defaultStateHome } from "../workspace.ts";
7
+ import {
8
+ closed,
9
+ decodeHash,
10
+ decodeId,
11
+ integer,
12
+ literal,
13
+ text,
14
+ } from "./contracts/core.ts";
15
+ import { decodeSessionId } from "./contracts/models.ts";
16
+ import { holderState, type ProcessMark } from "./liveness.ts";
17
+ import {
18
+ encoded,
19
+ type FileSnapshot,
20
+ hash,
21
+ json,
22
+ PrivateFiles,
23
+ } from "./private-files.ts";
24
+
25
+ export const ACTIVITY_RENEW_MS = 5000;
26
+ export const ACTIVITY_FRESH_MS = 15000;
27
+ /** Lost observations leave the activity area after two minutes, never as success. */
28
+ export const ACTIVITY_RETAIN_MS = 120000;
29
+ /** Per configuration/host scan and response bound; overflow is explicitly partial. */
30
+ export const ACTIVITY_FILES = 256;
31
+ export interface NativeActivity {
32
+ schema: "cadence-pi-activity/1";
33
+ instance: string;
34
+ activity: string;
35
+ scope: string;
36
+ sessionScope: string;
37
+ process: ProcessMark;
38
+ cwd: string;
39
+ sessionId: string;
40
+ leaf: string | null;
41
+ startedAt: number;
42
+ renewedAt: number;
43
+ }
44
+ export function decodeNativeActivity(value: unknown): NativeActivity {
45
+ const o = closed(value, [
46
+ "schema",
47
+ "instance",
48
+ "activity",
49
+ "scope",
50
+ "sessionScope",
51
+ "process",
52
+ "cwd",
53
+ "sessionId",
54
+ "leaf",
55
+ "startedAt",
56
+ "renewedAt",
57
+ ]);
58
+ const p = closed(o.process, ["pid", "host", "boot", "started"]);
59
+ return {
60
+ schema: literal(o.schema, "cadence-pi-activity/1"),
61
+ instance: decodeId(o.instance),
62
+ activity: decodeId(o.activity),
63
+ scope: decodeHash(o.scope),
64
+ sessionScope: decodeHash(o.sessionScope),
65
+ process: {
66
+ pid: integer(p.pid, 1, 2147483647),
67
+ host: text(p.host, 255, true),
68
+ boot: p.boot === null ? null : text(p.boot, 128, true),
69
+ started: p.started === null ? null : text(p.started, 128, true),
70
+ },
71
+ cwd: text(o.cwd, 4096, true),
72
+ sessionId: decodeSessionId(o.sessionId),
73
+ leaf: o.leaf === null ? null : text(o.leaf, 128, true),
74
+ startedAt: integer(o.startedAt, 0),
75
+ renewedAt: integer(o.renewedAt, 0),
76
+ };
77
+ }
78
+ export const activityScope = (agentDir: string) =>
79
+ hash(canonicalAmbientRoot(agentDir));
80
+ /** Bind the existing reader's configuration without exposing any source path. */
81
+ export const activityReaderScope = (agentDir: string, sessionDir?: string) =>
82
+ hash(
83
+ encoded([
84
+ canonicalAmbientRoot(agentDir),
85
+ process.env.PI_CODING_AGENT_SESSION_DIR ?? null,
86
+ sessionDir ?? null,
87
+ ]),
88
+ );
89
+ export class ActivityFiles {
90
+ readonly files: PrivateFiles;
91
+ readonly directory: string;
92
+ readonly scope: string;
93
+ constructor(agentDir: string, stateHome = defaultStateHome()) {
94
+ this.files = new PrivateFiles(
95
+ join(canonicalAmbientRoot(stateHome), "cadence-assistant-v1"),
96
+ );
97
+ this.scope = activityScope(agentDir);
98
+ this.directory = join(
99
+ this.files.namespace,
100
+ "pi-activity-v1",
101
+ this.scope,
102
+ hash(hostname()),
103
+ );
104
+ }
105
+ scan(): { records: NativeActivity[]; unavailable: number } {
106
+ const records: NativeActivity[] = [];
107
+ let unavailable = 0;
108
+ if (!this.files.directory(this.directory)) return { records, unavailable };
109
+ const dir = opendirSync(this.directory);
110
+ try {
111
+ let count = 0;
112
+ for (let e = dir.readSync(); e; e = dir.readSync()) {
113
+ if (++count > ACTIVITY_FILES) {
114
+ unavailable++;
115
+ break;
116
+ }
117
+ try {
118
+ if (!e.isFile() || !/^[0-9a-f-]{36}\.json$/.test(e.name))
119
+ throw new Error();
120
+ const file = this.files.read(join(this.directory, e.name));
121
+ if (!file) continue; // A publisher settled between directory and file reads.
122
+ const record = decodeNativeActivity(json(file));
123
+ if (
124
+ `${record.instance}.json` !== e.name ||
125
+ record.scope !== this.scope ||
126
+ record.process.host !== hostname()
127
+ )
128
+ throw new Error();
129
+ records.push(record);
130
+ } catch {
131
+ unavailable++;
132
+ }
133
+ }
134
+ } finally {
135
+ dir.closeSync();
136
+ }
137
+ return { records, unavailable };
138
+ }
139
+ /** Only a writer starting real work retires provably dead reports. Unknown
140
+ * and corrupt bytes stay untouched. Archived metadata expires with the existing
141
+ * 30-day recovery archive; a readonly discovery never cleans consumer data. */
142
+ retireDead(now: number): void {
143
+ const { records } = this.scan();
144
+ for (const record of records) {
145
+ if (
146
+ now - record.renewedAt <= ACTIVITY_RETAIN_MS ||
147
+ holderState(record.process).state !== "dead"
148
+ )
149
+ continue;
150
+ const path = join(this.directory, `${record.instance}.json`);
151
+ const before = this.files.read(path);
152
+ if (
153
+ !before ||
154
+ encoded(decodeNativeActivity(json(before))) !== encoded(record)
155
+ )
156
+ continue;
157
+ const archive = join(
158
+ this.files.namespace,
159
+ "recovery-archive-v1",
160
+ `${Date.now()}-${randomUUID()}`,
161
+ );
162
+ this.files.directory(archive, true);
163
+ this.files.assert(path, before);
164
+ renameSync(path, join(archive, "pi-activity.json"));
165
+ }
166
+ }
167
+ publish(record: NativeActivity, previous?: FileSnapshot): FileSnapshot {
168
+ if (!previous) {
169
+ const scanned = this.scan();
170
+ if (scanned.records.length + scanned.unavailable >= ACTIVITY_FILES)
171
+ throw new Error("activity-capacity");
172
+ }
173
+ const path = join(this.directory, `${record.instance}.json`);
174
+ const bytes = encoded(decodeNativeActivity(record));
175
+ if (previous) return this.files.replace(path, previous, bytes);
176
+ // Publish the first report atomically too. A failed temporary is preserved,
177
+ // not interpreted as an idle terminal or silently deleted by a reader.
178
+ this.files.directory(this.directory, true);
179
+ const temporary = join(this.directory, `pending-${record.instance}.json`);
180
+ this.files.create(temporary, bytes);
181
+ this.files.assert(path, undefined);
182
+ renameSync(temporary, path);
183
+ const saved = this.files.read(path);
184
+ if (!saved) throw new Error("activity-unavailable");
185
+ return saved;
186
+ }
187
+ withdraw(instance: string, previous: FileSnapshot): void {
188
+ this.files.remove(join(this.directory, `${instance}.json`), previous);
189
+ }
190
+ }
@@ -227,12 +227,15 @@ export class ServiceCoordination {
227
227
  readonly files: PrivateFiles;
228
228
  readonly registryDirectory: string;
229
229
  readonly stateHome: string;
230
- /** null addresses only account-wide registry recovery, never an implicit cwd. */
231
- constructor(workspace: string | null, stateHome?: string) {
230
+ /** null addresses only the account registry. An already validated CheckoutStore
231
+ * lets registry observation retain the registered root without running Git. */
232
+ constructor(workspace: string | CheckoutStore | null, stateHome?: string) {
232
233
  this.project =
233
234
  workspace === null
234
235
  ? undefined
235
- : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
236
+ : workspace instanceof CheckoutStore
237
+ ? workspace
238
+ : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
236
239
  this.stateHome = this.project
237
240
  ? dirname(dirname(this.project.privateRoot))
238
241
  : canonicalAmbientRoot(stateHome ?? defaultStateHome());
@@ -1789,7 +1789,7 @@ function gitArguments(args) {
1789
1789
  }
1790
1790
 
1791
1791
  // src/workspace.ts
1792
- import { spawnSync } from "node:child_process";
1792
+ import { execFile, spawnSync } from "node:child_process";
1793
1793
  import { createHash } from "node:crypto";
1794
1794
  import {
1795
1795
  closeSync as closeSync2,
@@ -1918,6 +1918,9 @@ function resolveWorkspace(cwd) {
1918
1918
  maxBuffer: 8192,
1919
1919
  windowsHide: true
1920
1920
  });
1921
+ return workspaceResult(actual, result);
1922
+ }
1923
+ function workspaceResult(actual, result) {
1921
1924
  const topLevel = result.stdout?.replace(process.platform === "win32" ? /\r?\n$/ : /\n$/, "");
1922
1925
  if (result.status === 0 && topLevel)
1923
1926
  return { root: realpathSync(topLevel), cwd: actual };
@@ -3411,7 +3414,7 @@ class ServiceCoordination {
3411
3414
  registryDirectory;
3412
3415
  stateHome;
3413
3416
  constructor(workspace, stateHome) {
3414
- this.project = workspace === null ? undefined : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
3417
+ this.project = workspace === null ? undefined : workspace instanceof CheckoutStore ? workspace : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
3415
3418
  this.stateHome = this.project ? dirname6(dirname6(this.project.privateRoot)) : canonicalAmbientRoot(stateHome ?? defaultStateHome());
3416
3419
  const namespace = join6(this.stateHome, "cadence-assistant-v1");
3417
3420
  this.files = new PrivateFiles(namespace);
@@ -7098,15 +7101,20 @@ function systemServiceStatus(s) {
7098
7101
  }
7099
7102
 
7100
7103
  // src/service/cli.ts
7101
- function nativeCall(c, operation, reveal = false, controlBody) {
7104
+ function nativeCall(c, operation, reveal = false, controlBody, signal) {
7105
+ if (signal?.aborted)
7106
+ return Promise.reject(new ContractError("unavailable"));
7102
7107
  const access = c.localAccess();
7103
7108
  const url = new URL(`${access.endpoint}/local/v1/admin/${operation}`);
7104
- const write2 = !["status", "diagnose"].includes(operation);
7109
+ const write2 = !["status", "diagnose", "activity"].includes(operation);
7110
+ const maximum = operation === "activity" ? 256 * 1024 : 16384;
7105
7111
  const body = write2 ? JSON.stringify(controlBody ?? (reveal ? { reveal: true } : {})) : undefined;
7106
7112
  return new Promise((resolve8, reject) => {
7107
7113
  let timer;
7114
+ let removeAbort = () => {};
7108
7115
  const fail = () => {
7109
7116
  clearTimeout(timer);
7117
+ removeAbort();
7110
7118
  reject(new ContractError("unavailable"));
7111
7119
  };
7112
7120
  const req = request(url, {
@@ -7126,7 +7134,7 @@ function nativeCall(c, operation, reveal = false, controlBody) {
7126
7134
  res.on("error", fail);
7127
7135
  res.on("data", (chunk) => {
7128
7136
  bytes += chunk.length;
7129
- if (bytes > 16384) {
7137
+ if (bytes > maximum) {
7130
7138
  res.destroy();
7131
7139
  fail();
7132
7140
  } else
@@ -7136,14 +7144,15 @@ function nativeCall(c, operation, reveal = false, controlBody) {
7136
7144
  try {
7137
7145
  if (res.statusCode !== 200)
7138
7146
  throw new ContractError("unavailable");
7139
- const reply = closed(parseWireJson(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)), 16384), ["kind", "value"]);
7147
+ const reply = closed(parseWireJson(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)), maximum), ["kind", "value"]);
7140
7148
  if (reply.kind !== "ok")
7141
7149
  throw new ContractError("unavailable");
7142
- if (["status", "diagnose", "stop"].includes(operation)) {
7150
+ if (["status", "diagnose", "stop", "activity"].includes(operation)) {
7143
7151
  if (!reply.value || typeof reply.value !== "object" || !("epoch" in reply.value) || reply.value.epoch !== access.epoch)
7144
7152
  throw new ContractError("stale");
7145
7153
  }
7146
7154
  clearTimeout(timer);
7155
+ removeAbort();
7147
7156
  resolve8(reply.value);
7148
7157
  } catch {
7149
7158
  fail();
@@ -7154,9 +7163,18 @@ function nativeCall(c, operation, reveal = false, controlBody) {
7154
7163
  fail();
7155
7164
  req.destroy();
7156
7165
  }, 2000);
7166
+ const cancel = () => {
7167
+ fail();
7168
+ req.destroy();
7169
+ };
7170
+ signal?.addEventListener("abort", cancel, { once: true });
7171
+ removeAbort = () => signal?.removeEventListener("abort", cancel);
7157
7172
  req.on("error", fail);
7158
7173
  req.on("close", fail);
7159
- req.end(body);
7174
+ if (signal?.aborted)
7175
+ cancel();
7176
+ else
7177
+ req.end(body);
7160
7178
  });
7161
7179
  }
7162
7180
  var pause = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));