@timmyjl12/pi-subagents 0.21.2 → 0.21.6

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
@@ -7,6 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.21.6] - 2026-11-29
11
+
12
+ ### Fixed
13
+
14
+ - **Fix — an agent spawn or resume could be refused with "report store unavailable: cleanup-lock" while the store's own routine maintenance was finishing.** The availability check reads the cleanup lock; if maintenance ended while that read was in flight, the lock it had just read (this process, this maintenance's nonce) no longer matched an active exemption and was treated as someone else's cleanup. The check now honours the maintenance that was active when the read began. A lock that outlives a failed release is still refused.
15
+ - Tests: the workflow e2e tests wait for the run's journal file to exist instead of assuming the first asynchronous write has already created it.
16
+
17
+ ## [0.21.5] - 2026-11-29
18
+
19
+ ### Fixed
20
+
21
+ - **Fix — on Windows, agents could stop starting or resuming with "report store unavailable: cleanup-lock".** Reading the cleanup lock can briefly fail with EPERM/EBUSY while another handle (antivirus, the store's own unlink) has it open. One failed read made the store keep its own lock, which then refused every later spawn and resume in the session. Transient sharing errors are now retried; a lock that stays unreadable still fails closed.
22
+ - Tests: schedule, @mention, cleanup-command, interactive-await and schedule-e2e tests wait for the actual event instead of a fixed delay or a status that precedes it, so they pass on a loaded host. Windows test workers back to 6 (3 caused more timeouts, not fewer).
23
+
24
+ ## [0.21.4] - 2026-11-28
25
+
26
+ ### Fixed
27
+
28
+ - **Workflows no longer fail on a busy machine with "`meta` did not finish evaluating within 100ms".** The 100 ms limit is wall-clock, so a loaded host could miss it even for a plain literal. A first miss is now retried once with a 1 s limit; a genuinely non-terminating `meta` still fails.
29
+ - Tests: on Windows the suite runs 3 workers instead of 6 (real-timer and real-session tests missed their budgets on a busy desktop). `VITEST_MAX_WORKERS` still overrides.
30
+
31
+ ## [0.21.3] - 2026-11-28
32
+
33
+ ### Fixed
34
+
35
+ - Develop and test against pi 1.7.0 (read-only render arrays in the conversation viewer and cleanup preview).
36
+ - **Fix — a scheduled agent no longer starts after Scheduling is turned off** while its tick was saving; the job is not left recorded as running.
37
+ - **Fix — configured line-scroll bindings win over the built-in Alt+arrow defaults**, so a binding swapped onto the opposite arrow scrolls the configured way.
38
+ - **Fix — child extension errors are no longer counted as tool uses** (pi 1.6+ also forwards child `pi.events` handler errors).
39
+
10
40
  ## [0.21.2] - 2026-11-14
11
41
 
12
42
  ### Added
@@ -25,6 +25,15 @@ import { isChildRequestActive } from "./recovery.js";
25
25
  import { releaseToolProgress } from "./ui/tool-progress.js";
26
26
  import { addUsage } from "./usage.js";
27
27
  import { cleanupWorktree, createWorktree, isWorktreeIsolationEnabled, pruneWorktrees } from "./worktree.js";
28
+ /**
29
+ * True when a finished activity is a real tool use. `extension-error:` entries
30
+ * are diagnostics routed through the tool channel (pi >= 1.6 also forwards a
31
+ * child's pi.events handler errors to onError); they must not inflate the
32
+ * tool-use count shown in reports.
33
+ */
34
+ function countsAsToolUse(activity) {
35
+ return activity.type === "end" && !activity.toolName.startsWith("extension-error:");
36
+ }
28
37
  /**
29
38
  * Default max concurrent background agents.
30
39
  *
@@ -1398,7 +1407,7 @@ export class AgentManager {
1398
1407
  configCwd: options.configCwd ?? (customCwd !== undefined ? ctx.cwd : undefined),
1399
1408
  signal: record.abortController.signal,
1400
1409
  onToolActivity: (activity) => {
1401
- if (activity.type === "end")
1410
+ if (countsAsToolUse(activity))
1402
1411
  record.toolUses++;
1403
1412
  options.onToolActivity?.(activity);
1404
1413
  },
@@ -2291,7 +2300,7 @@ export class AgentManager {
2291
2300
  : `${prompt}\n\n[Messages received while this agent was queued]\n${queuedSteers.map(m => `- ${m}`).join("\n")}`;
2292
2301
  const promise = resumeAgent(record.session, resumePrompt, {
2293
2302
  onToolActivity: (activity) => {
2294
- if (activity.type === "end")
2303
+ if (countsAsToolUse(activity))
2295
2304
  record.toolUses++;
2296
2305
  options.onToolActivity?.(activity);
2297
2306
  },
@@ -470,6 +470,15 @@ export declare class ReportStore {
470
470
  * inherit the exemption.
471
471
  */
472
472
  private maintenanceExempt;
473
+ /**
474
+ * The exemption across an awaited lock read. `before` is this store's
475
+ * maintenance nonce taken before the read started. If that maintenance
476
+ * ended while the read was in flight, its row is gone by the time the caller
477
+ * checks, and the lock it just read (our PID, our nonce) would otherwise look
478
+ * foreign and refuse a spawn or resume. A lock that outlives a failed
479
+ * release is still refused by every later check, which starts with no row.
480
+ */
481
+ private maintenanceExemptAcross;
473
482
  /** Drop this store's in-memory ownership of exactly this handle. */
474
483
  private forgetLocalOwnership;
475
484
  /**
@@ -267,6 +267,27 @@ async function renameWithRetry(from, to, beforeCommit) {
267
267
  }
268
268
  }
269
269
  }
270
+ /**
271
+ * Read a lock file, retrying the transient sharing errors Windows reports
272
+ * while another handle (this process's own unlink, AV, an indexer) still has
273
+ * it open. Failing closed on one of those would be permanent, not cautious:
274
+ * a release that cannot read its own lock keeps the file, and a lock whose
275
+ * PID is this live process then refuses every later spawn and resume here.
276
+ */
277
+ async function readLockFileWithRetry(path) {
278
+ for (let attempt = 0;; attempt++) {
279
+ try {
280
+ return await readFile(path, "utf8");
281
+ }
282
+ catch (error) {
283
+ const code = errorCode(error);
284
+ const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
285
+ if (!transient || attempt >= RENAME_RETRIES)
286
+ throw error;
287
+ await new Promise((done) => setTimeout(done, RENAME_RETRY_MS * (attempt + 1)));
288
+ }
289
+ }
290
+ }
270
291
  async function chmodPrivate(path, mode) {
271
292
  try {
272
293
  await chmod(path, mode);
@@ -1014,6 +1035,19 @@ export class ReportStore {
1014
1035
  lock.pid === process.pid &&
1015
1036
  this.localMaintenanceExempt(rootSessionId, lock.nonce));
1016
1037
  }
1038
+ /**
1039
+ * The exemption across an awaited lock read. `before` is this store's
1040
+ * maintenance nonce taken before the read started. If that maintenance
1041
+ * ended while the read was in flight, its row is gone by the time the caller
1042
+ * checks, and the lock it just read (our PID, our nonce) would otherwise look
1043
+ * foreign and refuse a spawn or resume. A lock that outlives a failed
1044
+ * release is still refused by every later check, which starts with no row.
1045
+ */
1046
+ maintenanceExemptAcross(rootSessionId, lock, before) {
1047
+ if (this.maintenanceExempt(rootSessionId, lock))
1048
+ return true;
1049
+ return lock !== undefined && before !== undefined && lock.pid === process.pid && lock.nonce === before;
1050
+ }
1017
1051
  /** Drop this store's in-memory ownership of exactly this handle. */
1018
1052
  forgetLocalOwnership(handle) {
1019
1053
  const current = this.cleanupLocks.get(handle.rootSessionId);
@@ -1302,7 +1336,7 @@ export class ReportStore {
1302
1336
  async readCleanupLockRead(rootSessionId) {
1303
1337
  let raw;
1304
1338
  try {
1305
- raw = await readFile(this.lockPath(rootSessionId), "utf8");
1339
+ raw = await readLockFileWithRetry(this.lockPath(rootSessionId));
1306
1340
  }
1307
1341
  catch (error) {
1308
1342
  if (isNotFound(error))
@@ -1340,6 +1374,7 @@ export class ReportStore {
1340
1374
  * uncertain fails closed with an explicit reason (never silently active).
1341
1375
  */
1342
1376
  async writeBlockReason(rootSessionId) {
1377
+ const maintenanceBefore = this.maintenanceLocks.get(rootSessionId);
1343
1378
  const read = await this.readCleanupLockRead(rootSessionId);
1344
1379
  if (read.status === "uncertain") {
1345
1380
  this.diagnose(`cleanup lock uncertain (${read.reason ?? "unknown"}); refusing writes`);
@@ -1347,7 +1382,7 @@ export class ReportStore {
1347
1382
  }
1348
1383
  if (read.status !== "live")
1349
1384
  return undefined;
1350
- if (this.maintenanceExempt(rootSessionId, read.lock))
1385
+ if (this.maintenanceExemptAcross(rootSessionId, read.lock, maintenanceBefore))
1351
1386
  return undefined;
1352
1387
  return "cleanup-lock";
1353
1388
  }
@@ -1875,12 +1910,13 @@ export class ReportStore {
1875
1910
  this.diagnose(`unsafe root entry name: ${entry.name}`);
1876
1911
  return true;
1877
1912
  }
1913
+ const maintenanceBefore = this.maintenanceLocks.get(entry.name);
1878
1914
  const read = await this.readCleanupLockRead(entry.name);
1879
1915
  if (read.status === "uncertain")
1880
1916
  return true;
1881
1917
  if (read.status !== "live" || read.lock === undefined)
1882
1918
  continue;
1883
- if (this.maintenanceExempt(entry.name, read.lock))
1919
+ if (this.maintenanceExemptAcross(entry.name, read.lock, maintenanceBefore))
1884
1920
  continue;
1885
1921
  if (this.selectionMatches(read.lock, scope))
1886
1922
  return true;
@@ -1955,6 +1991,7 @@ export class ReportStore {
1955
1991
  const rootSessionId = this.context?.rootSessionId;
1956
1992
  if (!rootSessionId || !activation.persistence)
1957
1993
  return;
1994
+ const maintenanceBefore = this.maintenanceLocks.get(rootSessionId);
1958
1995
  const read = await this.readCleanupLockRead(rootSessionId);
1959
1996
  // The read awaited: only the activation that started it may be authorized.
1960
1997
  // A close, rebind or lost activation in that window makes this answer stale.
@@ -1966,7 +2003,7 @@ export class ReportStore {
1966
2003
  if (read.status === "uncertain") {
1967
2004
  throw new ReportUnavailableError("cleanup-lock-unreadable");
1968
2005
  }
1969
- if (read.status === "live" && !this.maintenanceExempt(rootSessionId, read.lock)) {
2006
+ if (read.status === "live" && !this.maintenanceExemptAcross(rootSessionId, read.lock, maintenanceBefore)) {
1970
2007
  throw new ReportUnavailableError("cleanup-lock");
1971
2008
  }
1972
2009
  }
@@ -37,7 +37,7 @@ export type ScheduleChangeEvent = {
37
37
  type: "skipped";
38
38
  jobId: string;
39
39
  name: string;
40
- reason: "overlap";
40
+ reason: "overlap" | "stopped";
41
41
  } | {
42
42
  type: "error";
43
43
  jobId: string;
@@ -60,6 +60,8 @@ export declare class SubagentScheduler {
60
60
  private jobs;
61
61
  private intervals;
62
62
  private activeRuns;
63
+ /** Bumped by start() and stop(); a tick from an older generation never spawns. */
64
+ private generation;
63
65
  private store;
64
66
  private pi;
65
67
  private ctx;
package/dist/schedule.js CHANGED
@@ -31,12 +31,15 @@ export class SubagentScheduler {
31
31
  jobs = new Map();
32
32
  intervals = new Map();
33
33
  activeRuns = new Set();
34
+ /** Bumped by start() and stop(); a tick from an older generation never spawns. */
35
+ generation = 0;
34
36
  store;
35
37
  pi;
36
38
  ctx;
37
39
  manager;
38
40
  /** Start the scheduler: bind to a session's store and arm enabled jobs. */
39
41
  start(pi, ctx, manager, store) {
42
+ this.generation += 1;
40
43
  this.pi = pi;
41
44
  this.ctx = ctx;
42
45
  this.manager = manager;
@@ -48,6 +51,8 @@ export class SubagentScheduler {
48
51
  }
49
52
  /** Stop all timers; drop refs. Safe to call repeatedly. */
50
53
  stop() {
54
+ // A tick suspended in an awaited store write must not spawn after this.
55
+ this.generation += 1;
51
56
  for (const cron of this.jobs.values())
52
57
  cron.stop();
53
58
  this.jobs.clear();
@@ -222,6 +227,7 @@ export class SubagentScheduler {
222
227
  const manager = this.manager;
223
228
  if (!store || !pi || !ctx || !manager)
224
229
  return;
230
+ const generation = this.generation;
225
231
  const job = store.get(id);
226
232
  if (!job?.enabled)
227
233
  return;
@@ -232,6 +238,15 @@ export class SubagentScheduler {
232
238
  this.activeRuns.add(id);
233
239
  try {
234
240
  await store.update(id, { lastStatus: "running" });
241
+ // Scheduling was turned off (or restarted) while the write was pending:
242
+ // do not launch, and do not leave the job recorded as running. (Only the
243
+ // scheduler generation is checked: a one-shot job is disabled right after
244
+ // its tick starts, by design, and must still run.)
245
+ if (generation !== this.generation) {
246
+ await store.update(id, { lastStatus: job.lastStatus }).catch(() => undefined);
247
+ this.emit({ type: "skipped", jobId: id, name: job.name, reason: "stopped" });
248
+ return;
249
+ }
235
250
  // Resolve model at fire time — registry contents may have changed since the
236
251
  // job was created (auth added/removed). Fall back silently to spawn-default
237
252
  // if resolution fails; the spawn path handles undefined model gracefully.
@@ -424,6 +424,7 @@ class CleanupPreview {
424
424
  const keys = this.keybindings?.getKeys(keybinding);
425
425
  return keys && keys.length > 0 ? keyLabel(keys[0]) : fallback;
426
426
  }
427
+ // Read-only: pi >= 1.6 components return (and may cache) readonly arrays.
427
428
  contentLines(width) {
428
429
  const styled = this.styledBody();
429
430
  if (styled !== this.lastStyledBody) {
@@ -218,10 +218,18 @@ export class ConversationViewer {
218
218
  this.markdownModeOverride = next;
219
219
  this.onMarkdownMode?.(next);
220
220
  }
221
- else if (matchesKey(data, "alt+up") || this.keybindings.matches(data, "tui.altScreen.lineUp")) {
221
+ else if (this.keybindings.matches(data, "tui.altScreen.lineUp")) {
222
+ // Configured bindings first: a key the user bound to one direction must
223
+ // win over the built-in Alt+arrow default for the other.
222
224
  this.scroll.scrollBy(-1);
223
225
  }
224
- else if (matchesKey(data, "alt+down") || this.keybindings.matches(data, "tui.altScreen.lineDown")) {
226
+ else if (this.keybindings.matches(data, "tui.altScreen.lineDown")) {
227
+ this.scroll.scrollBy(1);
228
+ }
229
+ else if (matchesKey(data, "alt+up")) {
230
+ this.scroll.scrollBy(-1);
231
+ }
232
+ else if (matchesKey(data, "alt+down")) {
225
233
  this.scroll.scrollBy(1);
226
234
  }
227
235
  else if (matchesKey(data, "pageUp") || matchesKey(data, "shift+up")) {
@@ -386,6 +394,7 @@ export class ConversationViewer {
386
394
  return dim ? lines.map(l => this.theme.fg("dim", l)) : lines;
387
395
  }
388
396
  /** Render `text` as Markdown, reusing this message's component instance. */
397
+ // Read-only: Markdown.render() returns (and may cache) a readonly array in pi >= 1.6.
389
398
  markdownLines(msg, text, width, dim) {
390
399
  let entry = this.markdownCache.get(msg);
391
400
  if (!entry) {
@@ -23,8 +23,14 @@ export class WorkflowMetaError extends Error {
23
23
  /**
24
24
  * Wall-clock bound on evaluating the `meta` fragment. Generous for a literal —
25
25
  * this exists only to stop a pathological one from hanging the host thread.
26
+ *
27
+ * It is wall-clock, so a loaded machine (a busy event loop, GC, many pi
28
+ * sessions) can make even `{ name: "x" }` miss it. A first miss is therefore
29
+ * retried once with a longer bound before the literal is called non-terminating;
30
+ * a real infinite loop still fails, within META_EVAL_RETRY_TIMEOUT_MS.
26
31
  */
27
32
  const META_EVAL_TIMEOUT_MS = 100;
33
+ const META_EVAL_RETRY_TIMEOUT_MS = 1_000;
28
34
  const PURE_LITERAL_HINT = "The `meta` object must be a PURE LITERAL — no variables, function calls, spreads, or template interpolation.";
29
35
  /** Matches `export const meta =` allowing arbitrary inner whitespace. */
30
36
  const META_DECLARATION = /(^|[\r\n])[ \t]*export[ \t\r\n]+const[ \t\r\n]+meta[ \t\r\n]*=/;
@@ -244,13 +250,24 @@ export function extractMeta(source) {
244
250
  // host thread, before the script ever reaches the worker. Without a bound it
245
251
  // would wedge pi itself. `timeout` only governs synchronous execution, which
246
252
  // is all a literal can contain.
247
- value = new Script(`(${fragment})`, { filename: "workflow-meta.js" })
248
- .runInContext(createContext({}), { timeout: META_EVAL_TIMEOUT_MS });
253
+ //
254
+ // Compile and create the context BEFORE the timed run: V8's first context
255
+ // setup can itself take longer than the bound under load.
256
+ const script = new Script(`(${fragment})`, { filename: "workflow-meta.js" });
257
+ const isTimeout = (error) => /timed out|Script execution/i.test(error instanceof Error ? error.message : String(error));
258
+ try {
259
+ value = script.runInContext(createContext({}), { timeout: META_EVAL_TIMEOUT_MS });
260
+ }
261
+ catch (first) {
262
+ if (!isTimeout(first))
263
+ throw first;
264
+ value = script.runInContext(createContext({}), { timeout: META_EVAL_RETRY_TIMEOUT_MS });
265
+ }
249
266
  }
250
267
  catch (error) {
251
268
  const detail = error instanceof Error ? error.message : String(error);
252
269
  if (/timed out|Script execution/i.test(detail)) {
253
- fail(`\`meta\` did not finish evaluating within ${META_EVAL_TIMEOUT_MS}ms — it must be a literal, not a computation.\n` +
270
+ fail(`\`meta\` did not finish evaluating within ${META_EVAL_RETRY_TIMEOUT_MS}ms — it must be a literal, not a computation.\n` +
254
271
  PURE_LITERAL_HINT);
255
272
  }
256
273
  fail(`\`meta\` could not be evaluated: ${detail}\n${PURE_LITERAL_HINT}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timmyjl12/pi-subagents",
3
- "version": "0.21.2",
3
+ "version": "0.21.6",
4
4
  "description": "Claude Code-style subagents and workflow orchestration for pi, with coordinated fallback recovery and an interactive child-session workspace.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -55,9 +55,9 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@biomejs/biome": "^2.4.14",
58
- "@earendil-works/pi-ai": "^1.5.2",
59
- "@earendil-works/pi-coding-agent": "^1.5.2",
60
- "@earendil-works/pi-tui": "^1.5.2",
58
+ "@earendil-works/pi-ai": "^1.7.0",
59
+ "@earendil-works/pi-coding-agent": "^1.7.0",
60
+ "@earendil-works/pi-tui": "^1.7.0",
61
61
  "@sinclair/typebox": "^0.34.49",
62
62
  "@types/node": "^25.5.0",
63
63
  "@vitest/coverage-istanbul": "^4.1.10",