pi-durable-subagents 1.4.2 → 1.4.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.4.3
4
+
5
+ - Startup: agent discovery no longer starts `npm root -g` every time (issue #5). Each pi start, run admission and CLI
6
+ request discovered agents, and npm took 100-300 ms to answer (seconds on a busy machine) before the TUI appeared.
7
+ The global root is now asked once and kept in this process and in `DSA_HOME/cache/npm-root.json`, keyed on the
8
+ `npm` and `node` executables found on `PATH`, the prefix environment and the user, global and builtin npmrc files;
9
+ a change asks npm again. A failed answer is not cached and is retried after a minute. When `npm` on `PATH` is a
10
+ version manager's shim (asdf, mise, Volta), which picks node per directory, its answer is kept only ten seconds in
11
+ the process. With a warm cache discovery takes about 10 ms; it took 100-140 ms here, and the reporter measured
12
+ 170-225 ms inside the extension's 250-300 ms factory.
13
+
3
14
  ## 1.4.2
4
15
 
5
16
  - Memory: a main session's polling no longer keeps every earlier pass alive. Each workflow entry's lazy `entries`
package/README.md CHANGED
@@ -614,7 +614,12 @@ ends with work still counted.
614
614
  Agent files, discovery and precedence follow `pi-subagents` 0.75.0. That
615
615
  covers user, project and package agents, `model:thinking`, `tools` and
616
616
  `skills`. The same builtin agents are included; an agent file of the same name
617
- in your user or project agents overrides one.
617
+ in your user or project agents overrides one. Packages in npm's global root are
618
+ searched as well. Its location is asked from `npm root -g` once and kept in
619
+ `DSA_HOME/cache/npm-root.json`, until the `npm` or `node` found on `PATH`, the
620
+ `npm_config_prefix`/`PREFIX` environment or an npmrc file changes (a version
621
+ manager's `npm` shim is asked again after ten seconds); with `PI_OFFLINE=1` npm
622
+ is not asked.
618
623
 
619
624
  | Agent | Use it when you want... |
620
625
  |---|---|
@@ -23,7 +23,7 @@ let noteSink;
23
23
  /** P16: Queue a UI note for the next boundary without waking the model. */
24
24
  export function presentNote(text) { noteSink?.(text); }
25
25
  /** P1, P15, P16, P25, P38: Register durable submission and serialized main-session presentation. */
26
- /** v12 §6: Agent discovery per cwd, reused for a few seconds (discovery may shell out to `npm root -g`). */
26
+ /** v12 §6: Agent discovery per cwd, reused for a few seconds (it reads every package's manifest). */
27
27
  const discovered = new Map();
28
28
  function agentsAt(cwd) {
29
29
  const hit = discovered.get(cwd);
@@ -4,6 +4,95 @@ import { homedir } from "node:os";
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.js";
7
+ import { cacheDir, dsaHome } from "../paths.js";
8
+ const stamp = (p) => { if (!p)
9
+ return null; try {
10
+ const s = fs.statSync(p);
11
+ return `${p}@${s.mtimeMs}:${s.size}`;
12
+ }
13
+ catch {
14
+ return `${p}@-`;
15
+ } };
16
+ /** The first `name` on PATH, resolved, with its stamp: what execFileSync would start. */
17
+ function onPath(name, env) {
18
+ const exts = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean).concat("") : [""];
19
+ for (const dir of (env.PATH ?? env.Path ?? "").split(path.delimiter)) {
20
+ if (!dir)
21
+ continue;
22
+ for (const ext of exts) {
23
+ try {
24
+ const p = fs.realpathSync(path.join(dir, name + ext));
25
+ if (fs.statSync(p).isFile())
26
+ return p;
27
+ }
28
+ catch { /* next */ }
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+ /** Everything `npm root -g` reads to decide its answer, except npm's own code: which npm and node PATH selects, the
34
+ * prefix environment, and the user, global and builtin npmrc files. -g ignores the project's .npmrc, so cwd is not
35
+ * part of it, unless `npm` is a version manager's shim (asdf, mise, Volta) rather than npm itself: the shim picks a
36
+ * node per directory from files this key does not see, so its answer is only `fixed` for a few seconds. */
37
+ function npmRootKey(env) {
38
+ const npm = onPath("npm", env), node = onPath("node", env);
39
+ const vars = Object.keys(env).filter(k => /^(npm_config_(prefix|userconfig|globalconfig)|PREFIX|DESTDIR)$/i.test(k)).sort().map(k => `${k}=${env[k]}`);
40
+ const userconfig = Object.entries(env).find(([k]) => /^npm_config_userconfig$/i.test(k))?.[1] ?? path.join(env.HOME || env.USERPROFILE || homedir(), ".npmrc");
41
+ const prefix = env.PREFIX ?? (node ? (process.platform === "win32" ? path.dirname(node) : path.dirname(path.dirname(node))) : undefined);
42
+ const globalconfig = Object.entries(env).find(([k]) => /^npm_config_globalconfig$/i.test(k))?.[1] ?? (prefix && path.join(prefix, "etc", "npmrc"));
43
+ const builtin = npm ? path.join(path.dirname(path.dirname(npm)), "npmrc") : undefined;
44
+ const fixed = !!npm && /[\\/]npm[\\/]bin[\\/]npm(-cli\.js)?$/.test(npm);
45
+ return { npm, fixed, key: JSON.stringify([stamp(npm ?? undefined), stamp(node ?? undefined), vars, stamp(userconfig), stamp(globalconfig), stamp(builtin), process.platform === "win32" ? null : stamp("/etc/npmrc"), fixed ? null : process.cwd()]) };
46
+ }
47
+ const NPM_ROOT_ENTRIES = 8, NPM_ROOT_RETRY_MS = 60_000, NPM_ROOT_SHIM_MS = 10_000;
48
+ let npmRootMemo;
49
+ /** Issue #5: npm's global root without starting npm on every discovery. `npm root -g` takes 100-300 ms, and seconds on
50
+ * a busy machine, while every pi start, run admission and CLI request discovers agents. The answer is kept in this
51
+ * process and in a small rebuildable cache file, keyed on npmRootKey; a changed input asks npm again. A failed answer
52
+ * is null and is retried after a minute, never written to disk. A shim's answer stays in this process for ten seconds
53
+ * and is never written to disk. No npm on PATH is null without starting anything. */
54
+ export function globalNpmRoot(options = {}) {
55
+ const env = options.env ?? process.env;
56
+ const { key, npm, fixed } = npmRootKey(env);
57
+ if (!npm)
58
+ return null;
59
+ const now = Date.now();
60
+ if (npmRootMemo?.key === key && npmRootMemo.until > now)
61
+ return npmRootMemo.root;
62
+ const file = !fixed ? null : options.cacheFile === undefined ? path.join(cacheDir(dsaHome(env)), "npm-root.json") : options.cacheFile;
63
+ let entries = [];
64
+ if (file) {
65
+ try {
66
+ const v = JSON.parse(fs.readFileSync(file, "utf8"));
67
+ if (Array.isArray(v))
68
+ entries = v.filter(e => typeof e?.key === "string" && typeof e?.root === "string");
69
+ }
70
+ catch { /* none yet */ }
71
+ const hit = entries.find(e => e.key === key);
72
+ if (hit) {
73
+ npmRootMemo = { key, root: hit.root, until: Infinity };
74
+ return hit.root;
75
+ }
76
+ }
77
+ let root = null;
78
+ try {
79
+ root = (options.run ?? (() => execFileSync("npm", ["root", "-g"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"], env })))().trim() || null;
80
+ }
81
+ catch {
82
+ root = null;
83
+ }
84
+ npmRootMemo = { key, root, until: !fixed ? now + NPM_ROOT_SHIM_MS : root === null ? now + NPM_ROOT_RETRY_MS : Infinity };
85
+ if (file && root !== null) {
86
+ try {
87
+ fs.mkdirSync(path.dirname(file), { recursive: true });
88
+ const tmp = `${file}.${process.pid}.tmp`;
89
+ fs.writeFileSync(tmp, JSON.stringify([{ key, root }, ...entries.filter(e => e.key !== key)].slice(0, NPM_ROOT_ENTRIES)));
90
+ fs.renameSync(tmp, file);
91
+ }
92
+ catch { /* A cache failure only costs asking npm again. */ }
93
+ }
94
+ return root;
95
+ }
7
96
  const directory = (p) => { try {
8
97
  return fs.statSync(p).isDirectory();
9
98
  }
@@ -171,7 +260,8 @@ function scans(values, cwd, home) {
171
260
  return fs.readdirSync(base, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => path.join(base, e.name, ...parts.slice(i + 1)));
172
261
  });
173
262
  }
174
- /** P35, P11: Discover a fresh snapshot with upstream roots and scope precedence; never write. */
263
+ /** P35, P11: Discover a fresh snapshot with upstream roots and scope precedence; never write (beyond the rebuildable
264
+ * npm-root cache, globalNpmRoot). */
175
265
  export function discoverAgents(cwd, options = {}) {
176
266
  cwd = path.resolve(cwd);
177
267
  const home = path.resolve(options.home ?? homedir());
@@ -213,14 +303,8 @@ export function discoverAgents(cwd, options = {}) {
213
303
  }
214
304
  }
215
305
  let globalRoot = options.globalNpmRoot;
216
- if (globalRoot === undefined && scope !== "project" && !/^(1|true|yes)$/i.test(process.env.PI_OFFLINE ?? "")) {
217
- try {
218
- globalRoot = execFileSync("npm", ["root", "-g"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
219
- }
220
- catch {
221
- globalRoot = null;
222
- }
223
- }
306
+ if (globalRoot === undefined && scope !== "project" && !/^(1|true|yes)$/i.test(process.env.PI_OFFLINE ?? ""))
307
+ globalRoot = globalNpmRoot();
224
308
  if (globalRoot && scope !== "project")
225
309
  roots.push(...packageRoots(globalRoot));
226
310
  for (const packageRoot of new Set(roots)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",