pi-subagent-manager 1.14.0 → 1.16.0

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/README.md CHANGED
@@ -63,6 +63,8 @@ They use your current model until you configure preferences. Open `/agents types
63
63
 
64
64
  Open `/agents` to change delegation mode, limits, and display settings; save with **Ctrl+S**. Experimental options are marked **[labs]** in their help. **[lab] Subagent extensions** opens a per-extension chooser (Space/Enter toggles, Esc returns); **Save and apply** persists the selection for new subagent sessions. It lists auto-discovered `.ts`/`.js` files and subdirectory entry points in Pi’s agent-dir `extensions/` (honoring `PI_CODING_AGENT_DIR`), trusted project `.pi/extensions/`, and configured/package files—not CLI-only/inline/built-in extensions; see [limitations](https://github.com/championswimmer/pi-subagent-manager/blob/main/docs/subagent-extension-limitations.md).
65
65
 
66
+ **[lab] Fork history summaries** is off by default. With a housekeeping model selected, forks inherit a bounded sequence of sampled activity lines rather than the parent transcript; fresh agents are unchanged. For subagents, history reuses the same housekeeping lines as the live labels; it does not make a separate history request. The live-label display can be on or off independently: if it is off but fork history is on, housekeeping still generates lines for history. Collection also adds background model calls for the main agent, but forks never request or wait for a summary. History may be incomplete (including before the setting was enabled), and missing history never falls back to the transcript.
67
+
66
68
  Agents share your working directory and OS permissions: **tool policies are not a sandbox**. Don't run multiple subagent extensions together — they clash on `/agents`.
67
69
 
68
70
  ## Documentation
package/dist/index.js CHANGED
@@ -6,11 +6,12 @@ import { ConfigStore } from "./prefs/config.js";
6
6
  import { IMPORT_REQUEST_PREFIX, markImportOffered, offerAgentImport, } from "./prefs/agent-import.js";
7
7
  import { ThreadManager } from "./orch/manager.js";
8
8
  import { inheritedContextEntries } from "./orch/context-entries.js";
9
+ import { HISTORY_ENTRY, readHistory } from "./orch/history.js";
9
10
  import { loadManagerSettings } from "./prefs/settings.js";
10
11
  import { configureAgents } from "./ui/settings-ui.js";
11
12
  import { AgentNavigationController } from "./ui/status-ui.js";
12
13
  import { AgentNavigationEditor } from "./ui/agent-navigation-editor.js";
13
- import { createDriverFactory } from "./orch/runtime.js";
14
+ import { createDriverFactory, toolArgumentSnippet } from "./orch/runtime.js";
14
15
  import { createHousekeepingCompleter, HousekeepingSummarizer, resolveHousekeepingModel, } from "./orch/housekeeping.js";
15
16
  import { createInheritedToolSource } from "./orch/inherited-tools.js";
16
17
  import { subagentPrompt } from "./orch/prompt.js";
@@ -60,18 +61,32 @@ export default function piSubagent(pi) {
60
61
  }).settings;
61
62
  const housekeeping = new HousekeepingSummarizer({
62
63
  isEnabled: () => limits.subagentMode !== "off" &&
63
- limits.housekeepingEnabled &&
64
+ (limits.housekeepingEnabled || limits.forkHistorySummaries) &&
64
65
  limits.housekeepingModel !== "" &&
65
66
  context !== undefined &&
66
67
  resolveHousekeepingModel(context, limits.housekeepingModel) !== undefined,
67
68
  complete: createHousekeepingCompleter(() => context, () => limits.housekeepingModel, refreshCostFooter),
68
- apply: (path, run, summary) => manager?.setSummary(path, run, summary) ?? false,
69
+ apply: (path, run, summary, activity) => {
70
+ if (path !== "/root")
71
+ return manager?.setSummary(path, run, summary, activity) ?? false;
72
+ if (!limits.forkHistorySummaries || !rootActive || run !== rootRun || !context)
73
+ return false;
74
+ const branch = context.sessionManager.getBranch();
75
+ if (activity.anchor != null && !branch.some((entry) => entry.id === activity.anchor))
76
+ return false;
77
+ const history = readHistory(branch);
78
+ const previous = history.observations.at(-1);
79
+ if (previous?.path === path && previous.run === run && previous.text === summary)
80
+ return true;
81
+ pi.appendEntry(HISTORY_ENTRY, { path, run, at: activity.at ?? Date.now(), text: summary });
82
+ return true;
83
+ },
69
84
  clear: (path, run) => void manager?.clearSummary(path, run),
70
85
  onFailure: (message) => context?.ui.notify(`Housekeeping summaries failed (${message}); showing normal agent status instead.`, "warning"),
71
86
  });
72
87
  let housekeepingKey = "";
73
88
  const syncHousekeeping = () => {
74
- const key = `${limits.subagentMode === "off"}|${limits.housekeepingEnabled}|${limits.housekeepingModel}`;
89
+ const key = `${limits.subagentMode === "off"}|${limits.housekeepingEnabled}|${limits.forkHistorySummaries}|${limits.housekeepingModel}`;
75
90
  if (key === housekeepingKey)
76
91
  return;
77
92
  housekeepingKey = key;
@@ -93,6 +108,27 @@ export default function piSubagent(pi) {
93
108
  const currentChecklistStatus = (ctx) => checklistStatus(pi, checklistMirror, ctx);
94
109
  let generation = 0;
95
110
  let rootTurnEnded = false;
111
+ let rootActive = false;
112
+ let rootRun = 0;
113
+ let rootTask = "Main Pi session";
114
+ let rootActivity = [];
115
+ const recordRootActivity = (ctx, line) => {
116
+ if (!rootActive || !limits.forkHistorySummaries)
117
+ return;
118
+ rootActivity.push(line.slice(0, 600));
119
+ if (rootActivity.length > 12)
120
+ rootActivity.shift();
121
+ const activity = {
122
+ path: "/root",
123
+ type: "main",
124
+ task: rootTask,
125
+ run: rootRun,
126
+ recent: [...rootActivity],
127
+ anchor: ctx.sessionManager.getLeafId(),
128
+ at: Date.now(),
129
+ };
130
+ housekeeping.notify(activity);
131
+ };
96
132
  const hiddenWidgetThreads = new Set();
97
133
  let widgetCollapsed = false;
98
134
  let rootTurnRunning = false;
@@ -305,9 +341,7 @@ export default function piSubagent(pi) {
305
341
  rootTurnTimer !== undefined)
306
342
  return;
307
343
  if (!wakeRequested &&
308
- !(limits.finalRecap &&
309
- (manager?.outstandingAsync() ?? 0) === 0 &&
310
- pendingSummaries(ctx).length > 0) &&
344
+ !((manager?.outstandingAsync() ?? 0) === 0 && pendingSummaries(ctx).length > 0) &&
311
345
  !pendingRootNotifications(ctx).some((notification) => notification.trigger === true))
312
346
  return;
313
347
  const currentGeneration = generation;
@@ -324,9 +358,7 @@ export default function piSubagent(pi) {
324
358
  return;
325
359
  }
326
360
  drainRootMailbox(ctx);
327
- const notifications = limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0
328
- ? pendingSummaries(ctx)
329
- : [];
361
+ const notifications = (manager?.outstandingAsync() ?? 0) === 0 ? pendingSummaries(ctx) : [];
330
362
  if (!notifications.length && !wakeRequested)
331
363
  return;
332
364
  const wasWakeRequested = wakeRequested;
@@ -403,17 +435,18 @@ export default function piSubagent(pi) {
403
435
  : `Agent ${thread.path} is ${thread.state}: ${thread.status}. ${thread.state === "paused" ? "No answer handback; send input to resume the same session." : "Session retained for further input."}`;
404
436
  try {
405
437
  if (event.recipient === "/root") {
406
- const recap = limits.finalRecap &&
407
- !suspendingSummaries &&
438
+ const recap = !suspendingSummaries &&
408
439
  event.kind === "settled" &&
409
440
  event.async &&
441
+ event.recipient === "/root" &&
410
442
  ["completed", "failed", "stopped"].includes(thread.state);
411
443
  const notification = {
412
444
  rootSessionId: requireContext().sessionManager.getSessionId(),
413
445
  content: message,
414
446
  finalRecap: recap,
415
447
  trigger: !suspendingSummaries &&
416
- (event.kind === "timeout" || (event.kind === "settled" && event.async && !recap)),
448
+ (event.kind === "timeout" ||
449
+ (event.kind === "settled" && (event.wakeParent || (event.async && !recap)))),
417
450
  details: {
418
451
  mailboxId: randomUUID(),
419
452
  path: thread.path,
@@ -423,15 +456,25 @@ export default function piSubagent(pi) {
423
456
  pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
424
457
  restoreRootMailbox(requireContext());
425
458
  }
426
- else {
427
- void requireManager().deliver(event.recipient, message).catch(warnDelivery);
428
- if (event.kind === "settled")
429
- restoreRootMailbox(requireContext());
430
- }
431
459
  }
432
460
  catch (error) {
433
461
  warnDelivery(error);
434
462
  }
463
+ if (event.recipient !== "/root") {
464
+ try {
465
+ void requireManager()
466
+ .deliver(event.recipient, message, !suspendingSummaries &&
467
+ limits.subagentMode !== "off" &&
468
+ event.kind === "settled" &&
469
+ event.wakeParent === true)
470
+ .catch(warnDelivery);
471
+ if (event.kind === "settled")
472
+ restoreRootMailbox(requireContext());
473
+ }
474
+ catch (error) {
475
+ warnDelivery(error);
476
+ }
477
+ }
435
478
  };
436
479
  const makeDriverFactory = () => createDriverFactory(requireContext, () => limits.modelSelection, () => limits.toolFiltering, () => inheritedTools.snapshot(), () => limits.subagentExtensions);
437
480
  let driverFactory = makeDriverFactory();
@@ -466,6 +509,10 @@ export default function piSubagent(pi) {
466
509
  updateWidget(ctx, widgetThreads(), widgetCollapsed ? "minimal" : limits.widgetMode, limits.nerdFontIcons, rootTurnEnded, limits.loaderStyle, widgetCollapsed && limits.widgetMode === "full");
467
510
  };
468
511
  pi.on("agent_start", async (_event, ctx) => {
512
+ rootActive = true;
513
+ rootRun++;
514
+ rootActivity = [];
515
+ recordRootActivity(ctx, `User: ${rootTask}`);
469
516
  if (manager && !rootTurnRunning) {
470
517
  for (const thread of manager.list()) {
471
518
  if (thread.state !== "starting" && thread.state !== "running")
@@ -477,6 +524,8 @@ export default function piSubagent(pi) {
477
524
  refreshWidget(ctx);
478
525
  });
479
526
  pi.on("agent_end", async (_event, ctx) => {
527
+ rootActive = false;
528
+ housekeeping.settle("/root");
480
529
  rootTurnEnded = true;
481
530
  if (manager)
482
531
  refreshWidget(ctx);
@@ -487,14 +536,42 @@ export default function piSubagent(pi) {
487
536
  if (store.diagnostics.length)
488
537
  context?.ui.notify(store.diagnostics.join("\n"), "warning");
489
538
  });
490
- pi.on("message_end", async (_event, ctx) => {
539
+ pi.on("message_end", async (event, ctx) => {
540
+ if (event.message.role === "user") {
541
+ const content = event.message.content;
542
+ const text = typeof content === "string"
543
+ ? content
544
+ : content
545
+ .filter((part) => part.type === "text")
546
+ .map((part) => part.text)
547
+ .join(" ");
548
+ if (text.trim())
549
+ recordRootActivity(ctx, `User: ${text}`);
550
+ }
551
+ else if (event.message.role === "assistant") {
552
+ const text = event.message.content
553
+ .filter((part) => part.type === "text")
554
+ .map((part) => part.text)
555
+ .join(" ");
556
+ if (text.trim())
557
+ recordRootActivity(ctx, `Assistant: ${text}`);
558
+ }
491
559
  refreshCostFooter(ctx);
492
560
  });
493
- pi.on("tool_execution_end", async (_event, ctx) => {
561
+ pi.on("tool_execution_start", async (event, ctx) => {
562
+ const detail = toolArgumentSnippet(event.args);
563
+ recordRootActivity(ctx, `Tool: ${event.toolName}${detail ? ` ${detail}` : ""}`);
564
+ });
565
+ pi.on("tool_execution_end", async (event, ctx) => {
566
+ recordRootActivity(ctx, `Tool ${event.toolName}: ${event.isError ? "failed" : "finished"}`);
494
567
  refreshCostFooter(ctx);
495
568
  });
496
569
  syncTools();
497
570
  pi.on("before_agent_start", async (event, ctx) => {
571
+ rootTask =
572
+ (typeof event.prompt === "string" &&
573
+ event.prompt.replace(/\s+/g, " ").trim().slice(0, 500)) ||
574
+ "Main Pi session";
498
575
  const prompt = subagentPrompt(limits, limits.checklistIntegration &&
499
576
  limits.subagentMode !== "off" &&
500
577
  currentChecklistStatus(ctx).eligible);
@@ -517,6 +594,9 @@ export default function piSubagent(pi) {
517
594
  const attachSession = async (ctx, installEditor = false, seedHistory = true) => {
518
595
  cancelSummary();
519
596
  housekeeping.cancelAll();
597
+ rootActive = false;
598
+ rootTask = "Main Pi session";
599
+ rootActivity = [];
520
600
  const token = ++generation;
521
601
  closeNavigation(installEditor);
522
602
  navigation = new AgentNavigationController(returnToWidget);
@@ -547,6 +627,7 @@ export default function piSubagent(pi) {
547
627
  createDriver: driverFactory,
548
628
  rootSnapshot: () => buildSessionContext(requireContext().sessionManager.getBranch()).messages,
549
629
  rootContextEntries: () => inheritedContextEntries(requireContext().sessionManager.getBranch()),
630
+ rootHistory: () => readHistory(requireContext().sessionManager.getBranch()),
550
631
  getType: (name) => store.get(name),
551
632
  toolsFor,
552
633
  onEventError: (error, event) => {
@@ -0,0 +1,95 @@
1
+ import { cleanSummary } from "./housekeeping.js";
2
+ export const HISTORY_ENTRY = "subagent-history";
3
+ export const HISTORY_CAPSULE_ENTRY = "subagent-history-capsule";
4
+ const MAX_OBSERVATIONS = 64;
5
+ const MAX_BYTES = 8192;
6
+ const MAX_LINES_BYTES = 5600;
7
+ const PATH = /^\/[A-Za-z0-9][A-Za-z0-9_-]{0,63}(?:\/[A-Za-z0-9][A-Za-z0-9_-]{0,63}){0,31}$/;
8
+ const empty = () => ({ version: 1, observations: [], omitted: 0 });
9
+ const bytes = (s) => Buffer.byteLength(s, "utf8");
10
+ const line = (entry) => `[${new Date(entry.at).toISOString()}] ${entry.path}: ${entry.text}`;
11
+ const increment = (n) => Math.min(Number.MAX_SAFE_INTEGER, n + 1);
12
+ function observation(value) {
13
+ if (!value || typeof value !== "object" || Array.isArray(value))
14
+ return undefined;
15
+ const item = value;
16
+ if (typeof item.path !== "string" ||
17
+ !PATH.test(item.path) ||
18
+ !Number.isSafeInteger(item.run) ||
19
+ item.run < 0 ||
20
+ !Number.isSafeInteger(item.at) ||
21
+ item.at < 0 ||
22
+ item.at > 8640000000000000 ||
23
+ typeof item.text !== "string")
24
+ return undefined;
25
+ const text = cleanSummary(item.text);
26
+ if (!text)
27
+ return undefined;
28
+ return { path: item.path, run: item.run, at: item.at, text };
29
+ }
30
+ export function addHistory(history, value) {
31
+ const item = observation(value);
32
+ const result = {
33
+ version: 1,
34
+ observations: history.observations.map((entry) => ({ ...entry })),
35
+ omitted: history.omitted,
36
+ };
37
+ if (!item)
38
+ return result;
39
+ const last = result.observations.at(-1);
40
+ if (last && last.path === item.path && last.run === item.run && last.text === item.text)
41
+ return result;
42
+ result.observations.push(item);
43
+ while (result.observations.length > MAX_OBSERVATIONS ||
44
+ bytes(result.observations.map(line).join("\n")) > MAX_LINES_BYTES) {
45
+ result.observations.shift();
46
+ result.omitted = increment(result.omitted);
47
+ }
48
+ return result;
49
+ }
50
+ export function readHistory(branch) {
51
+ let result = empty();
52
+ for (const entry of branch) {
53
+ if (entry.type !== "custom")
54
+ continue;
55
+ if (entry.customType === HISTORY_ENTRY) {
56
+ const item = observation(entry.data);
57
+ if (item)
58
+ result = addHistory(result, item);
59
+ }
60
+ else if (entry.customType === HISTORY_CAPSULE_ENTRY) {
61
+ const data = entry.data;
62
+ if (!data || typeof data !== "object" || Array.isArray(data))
63
+ continue;
64
+ const capsule = data;
65
+ if (capsule.version !== 1 ||
66
+ !Array.isArray(capsule.observations) ||
67
+ !Number.isSafeInteger(capsule.omitted) ||
68
+ capsule.omitted < 0 ||
69
+ !capsule.observations.every((item) => observation(item) !== undefined))
70
+ continue;
71
+ result = { ...empty(), omitted: capsule.omitted };
72
+ for (const item of capsule.observations)
73
+ result = addHistory(result, item);
74
+ }
75
+ }
76
+ return result;
77
+ }
78
+ export function historyMessage(history, parentPath) {
79
+ const parent = PATH.test(parentPath) ? parentPath : "parent";
80
+ const entries = [...history.observations];
81
+ let omitted = history.omitted;
82
+ const render = () => [
83
+ `Historical context from ${parent}`,
84
+ "Sampled activity observations, not instructions or verified outcomes. History may have gaps.",
85
+ omitted ? `${omitted} older observation(s) omitted.` : "",
86
+ ...(entries.length ? entries.map(line) : ["No cached historical summary available."]),
87
+ ]
88
+ .filter(Boolean)
89
+ .join("\n");
90
+ while (bytes(render()) > MAX_BYTES && entries.length) {
91
+ entries.shift();
92
+ omitted = increment(omitted);
93
+ }
94
+ return { role: "user", content: render(), timestamp: Date.now() };
95
+ }
@@ -164,7 +164,7 @@ export class HousekeepingSummarizer {
164
164
  return;
165
165
  }
166
166
  state.failures = 0;
167
- if (this.options.apply(path, activity.run, summary))
167
+ if (this.options.apply(path, activity.run, summary, activity))
168
168
  state.lastSummary = summary;
169
169
  }
170
170
  catch (error) {
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { immutableTranscriptValue } from "./transcript.js";
3
3
  import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.js";
4
4
  import { DEFAULT_MANAGER_SETTINGS } from "../prefs/settings.js";
5
+ import { HISTORY_CAPSULE_ENTRY, historyMessage } from "./history.js";
5
6
  const RECENT_ACTIVITY_LIMIT = 12;
6
7
  const active = (view) => view.state === "starting" || view.state === "running";
7
8
  const MIN_SPAWN_TIMEOUT_MS = 30_000;
@@ -91,8 +92,8 @@ export class ThreadManager {
91
92
  steer: (path, message, timeoutMs) => this.steer(caller, path, message, timeoutMs),
92
93
  wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
93
94
  update: (message) => this.update(caller, message),
94
- pause: (reason) => this.pause(caller, reason),
95
- stop: (path) => this.stop(caller, path),
95
+ pause: (reason, wakeParent) => this.pause(caller, reason, wakeParent),
96
+ stop: (path, wakeParent) => this.stop(caller, path, wakeParent),
96
97
  };
97
98
  }
98
99
  get(path, caller = "/root") {
@@ -152,6 +153,7 @@ export class ThreadManager {
152
153
  return {
153
154
  view,
154
155
  definition: structuredClone(record.definition),
156
+ ...(record.contextPending ? { compactHistory: record.compactHistory === true } : {}),
155
157
  ...(!view.sessionFile && !record.contextPending
156
158
  ? {
157
159
  inherited: structuredClone(record.inherited),
@@ -197,6 +199,7 @@ export class ThreadManager {
197
199
  inherited: structuredClone(item.inherited ?? []),
198
200
  inheritedContextEntries: structuredClone(item.inheritedContextEntries ?? []),
199
201
  contextPending: !view.sessionFile && item.inherited === undefined && view.parent !== null,
202
+ compactHistory: item.compactHistory === true,
200
203
  startup: new AbortController(),
201
204
  ...(Object.prototype.hasOwnProperty.call(savedView, "sessionLeafId")
202
205
  ? { sessionLeafId }
@@ -244,14 +247,23 @@ export class ThreadManager {
244
247
  const type = structuredClone(this.options.getType(args.type));
245
248
  const parentRecord = parent && parent !== "/root" ? this.record(parent) : undefined;
246
249
  this.assertStartableAncestors(path);
247
- const inherited = parent === "/root"
248
- ? inheritContext(this.options.rootSnapshot())
249
- : parentRecord?.driver
250
- ? inheritContext(parentRecord.driver.snapshot())
251
- : [];
252
- const inheritedContextEntries = structuredClone(parent === "/root"
253
- ? (this.options.rootContextEntries?.() ?? [])
254
- : (parentRecord?.driver?.contextEntries?.() ?? []));
250
+ const compactHistory = !!parent && this.options.forkHistorySummaries === true;
251
+ const snapshot = compactHistory
252
+ ? parent === "/root"
253
+ ? this.historyContext(parent, this.options.rootHistory?.())
254
+ : parentRecord?.driver
255
+ ? this.historyContext(parent, parentRecord.driver.history?.())
256
+ : { inherited: [], inheritedContextEntries: [] }
257
+ : {
258
+ inherited: parent === "/root"
259
+ ? inheritContext(this.options.rootSnapshot())
260
+ : parentRecord?.driver
261
+ ? inheritContext(parentRecord.driver.snapshot())
262
+ : [],
263
+ inheritedContextEntries: structuredClone(parent === "/root"
264
+ ? (this.options.rootContextEntries?.() ?? [])
265
+ : (parentRecord?.driver?.contextEntries?.() ?? [])),
266
+ };
255
267
  const now = Date.now();
256
268
  const record = {
257
269
  view: {
@@ -272,8 +284,8 @@ export class ThreadManager {
272
284
  outputTokens: 0,
273
285
  },
274
286
  definition: type,
275
- inherited,
276
- inheritedContextEntries,
287
+ ...snapshot,
288
+ compactHistory,
277
289
  contextPending: !!(parentRecord && !parentRecord.driver),
278
290
  startup: new AbortController(),
279
291
  pauseRequested: false,
@@ -375,21 +387,26 @@ export class ThreadManager {
375
387
  });
376
388
  return this.view(record);
377
389
  }
378
- pause(caller, reason) {
390
+ pause(caller, reason, wakeParent = false) {
379
391
  const record = this.record(caller);
380
392
  if (!active(record.view))
381
393
  throw new Error("Only a working child may pause itself");
382
394
  record.pauseRequested = true;
395
+ if (wakeParent)
396
+ record.wakeParentRequested = true;
383
397
  record.view.status = reason.trim() || "Awaiting further input";
384
398
  delete record.view.summary;
385
399
  this.touch(record);
386
400
  return this.view(record);
387
401
  }
388
- async stop(caller, path) {
402
+ async stop(caller, path, wakeParent = false) {
389
403
  path = canonicalPath(path, caller);
390
404
  this.assertAccess(caller, path);
391
405
  const record = this.record(path);
392
406
  const targets = [...this.records.values()].filter((item) => item === record || (isDescendant(item.view.path, path) && active(item.view)));
407
+ if (wakeParent && active(record.view))
408
+ record.wakeParentRequested = true;
409
+ const runs = new Map(targets.map((item) => [item, { id: item.runId, run: item.run }]));
393
410
  for (const item of targets) {
394
411
  item.stopRequested = true;
395
412
  item.startup.abort();
@@ -398,7 +415,9 @@ export class ThreadManager {
398
415
  await Promise.all(targets.map(async (item) => {
399
416
  if (item.driver)
400
417
  await item.driver.abort();
401
- await item.run;
418
+ await runs.get(item).run;
419
+ if (item.runId !== runs.get(item).id)
420
+ return;
402
421
  item.view.state = "stopped";
403
422
  item.view.status = "Stopped; session retained";
404
423
  delete item.view.output;
@@ -506,9 +525,27 @@ export class ThreadManager {
506
525
  }
507
526
  return parts.slice(-2).join("\n---\n").slice(-2000);
508
527
  }
509
- async deliver(path, content) {
510
- const driver = await this.ensureDriver(this.record(path), true);
528
+ async deliver(path, content, wakeParent = false) {
529
+ const record = this.record(path);
530
+ const driver = await this.ensureDriver(record, true);
531
+ const admission = wakeParent && active(record.view) && !record.pauseRequested && !record.stopRequested
532
+ ? { driver, runId: record.runId, run: record.run }
533
+ : undefined;
511
534
  await driver.sendUpdate(content);
535
+ if (!admission)
536
+ return;
537
+ if (record.driver !== admission.driver ||
538
+ record.runId !== admission.runId ||
539
+ record.run !== admission.run ||
540
+ !active(record.view) ||
541
+ record.pauseRequested ||
542
+ record.stopRequested)
543
+ return;
544
+ const wake = "A child settlement requested your attention (see the preceding subagent update). " +
545
+ "Inspect it and continue or recap the work as appropriate.";
546
+ if (!driver.followUp)
547
+ throw new Error("The parent driver does not support safe follow-up wake");
548
+ await driver.followUp(wake);
512
549
  }
513
550
  async shutdown() {
514
551
  this.disposed = true;
@@ -534,6 +571,7 @@ export class ThreadManager {
534
571
  this.freezeElapsed(record);
535
572
  record.pauseRequested = false;
536
573
  record.stopRequested = false;
574
+ record.wakeParentRequested = false;
537
575
  record.startup = new AbortController();
538
576
  record.view.state = "starting";
539
577
  record.view.status = "Starting";
@@ -598,6 +636,7 @@ export class ThreadManager {
598
636
  thread: this.view(record),
599
637
  recipient: record.view.parent ?? record.view.owner,
600
638
  async: record.async === true,
639
+ ...(record.wakeParentRequested ? { wakeParent: true } : {}),
601
640
  });
602
641
  }
603
642
  });
@@ -771,12 +810,14 @@ export class ThreadManager {
771
810
  task: record.view.task,
772
811
  run: record.runId ?? 0,
773
812
  recent: [...recent],
813
+ anchor: record.driver?.historyAnchor?.(),
814
+ at: Date.now(),
774
815
  });
775
816
  }
776
817
  catch {
777
818
  }
778
819
  }
779
- setSummary(path, run, summary) {
820
+ setSummary(path, run, summary, sampled) {
780
821
  const record = this.records.get(path);
781
822
  const text = summary.replace(/\s+/g, " ").trim();
782
823
  if (this.disposed ||
@@ -787,7 +828,14 @@ export class ThreadManager {
787
828
  record.pauseRequested ||
788
829
  record.stopRequested)
789
830
  return false;
790
- if (record.view.summary === text)
831
+ if (this.options.forkHistorySummaries && sampled?.path === path && sampled.run === run) {
832
+ try {
833
+ record.driver?.appendHistory?.({ path, run, at: sampled.at ?? Date.now(), text }, sampled.anchor);
834
+ }
835
+ catch {
836
+ }
837
+ }
838
+ if (this.options.housekeepingEnabled === false || record.view.summary === text)
791
839
  return true;
792
840
  record.view.summary = text;
793
841
  if (!this.disposed)
@@ -874,14 +922,26 @@ export class ThreadManager {
874
922
  record.view.elapsedMs = (record.view.elapsedMs ?? 0) + Math.max(0, Date.now() - startedAt);
875
923
  delete record.view.startedAt;
876
924
  }
925
+ historyContext(parent, history) {
926
+ const capsule = structuredClone(history ?? { version: 1, observations: [], omitted: 0 });
927
+ return {
928
+ inherited: [historyMessage(capsule, parent)],
929
+ inheritedContextEntries: [{ customType: HISTORY_CAPSULE_ENTRY, data: capsule }],
930
+ };
931
+ }
877
932
  prepareInheritedContext(record, readOnly = false) {
878
933
  if (!record.contextPending)
879
934
  return record.contextReady;
880
935
  if (record.contextReady)
881
936
  return record.contextReady;
882
937
  if (!record.view.parent || record.view.parent === "/root") {
883
- record.inherited = inheritContext(this.options.rootSnapshot());
884
- record.inheritedContextEntries = structuredClone(this.options.rootContextEntries?.() ?? []);
938
+ if (record.compactHistory) {
939
+ Object.assign(record, this.historyContext("/root", this.options.rootHistory?.()));
940
+ }
941
+ else {
942
+ record.inherited = inheritContext(this.options.rootSnapshot());
943
+ record.inheritedContextEntries = structuredClone(this.options.rootContextEntries?.() ?? []);
944
+ }
885
945
  record.contextPending = false;
886
946
  return undefined;
887
947
  }
@@ -889,8 +949,13 @@ export class ThreadManager {
889
949
  let ready;
890
950
  ready = this.ensureDriver(parentRecord, readOnly)
891
951
  .then((driver) => {
892
- record.inherited = inheritContext(driver.snapshot());
893
- record.inheritedContextEntries = structuredClone(driver.contextEntries?.() ?? []);
952
+ if (record.compactHistory) {
953
+ Object.assign(record, this.historyContext(record.view.parent, driver.history?.()));
954
+ }
955
+ else {
956
+ record.inherited = inheritContext(driver.snapshot());
957
+ record.inheritedContextEntries = structuredClone(driver.contextEntries?.() ?? []);
958
+ }
894
959
  record.contextPending = false;
895
960
  if (record.contextReady === ready)
896
961
  record.contextReady = undefined;
@@ -19,7 +19,7 @@ export function subagentPrompt(settings, checklistEligible = false) {
19
19
  policy,
20
20
  "Call agent_types before choosing a type. Use task-based kebab-case paths, not type names. Choose context via agent_spawn path: /root/task forks the lexical parent's conversation; /task starts fresh with no inherited history. Use fresh agents for adversarial review or clean-slate research; give them a self-contained task without the current thread's conclusions.",
21
21
  waitingPolicy,
22
- 'Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
22
+ 'Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle, once after all outstanding async agents have finished. Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
23
23
  "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
24
24
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
25
25
  delegationGuidance(settings.maxLevels > 1),
@@ -9,6 +9,7 @@ import { TranscriptChannel } from "./transcript.js";
9
9
  import { delegationGuidance } from "./prompt.js";
10
10
  import { discoverSubagentExtensions, selectSubagentExtensions } from "./extensions.js";
11
11
  import { inheritedContextEntries } from "./context-entries.js";
12
+ import { HISTORY_ENTRY, readHistory } from "./history.js";
12
13
  import { modelIdentity, getModelPreferences, selectPreferredModel } from "../prefs/models.js";
13
14
  import { THINKING_LEVELS, } from "../types.js";
14
15
  import { DIAGNOSTIC_CHANNEL, DIAGNOSTIC_PROBE_CHANNEL, respondDiagnosticCapability, diagnosticSink, diagnosticText, } from "./diagnostics.js";
@@ -596,7 +597,15 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
596
597
  sessionManager.appendMessage(buildBootstrapMessage());
597
598
  emit("activity", BOOTSTRAP_MESSAGE);
598
599
  };
600
+ let acceptingFollowUps = true;
601
+ const continueAgent = session.agent.continue.bind(session.agent);
602
+ session.agent.continue = async () => {
603
+ acceptingFollowUps = true;
604
+ await continueAgent();
605
+ };
599
606
  const queueAccepted = async (kind, content) => {
607
+ if (kind === "followUp" && !acceptingFollowUps)
608
+ return false;
600
609
  assertCurrentModelAuthorized();
601
610
  ensurePersistedSession();
602
611
  const accepted = mailbox.accept(kind, content);
@@ -606,6 +615,7 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
606
615
  else
607
616
  session.agent.steer(buildQueuedUserMessage(accepted));
608
617
  mailbox.markEnqueued(accepted.id);
618
+ return true;
609
619
  };
610
620
  const resumePending = async () => {
611
621
  for (const accepted of mailbox.replayablePending()) {
@@ -681,6 +691,10 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
681
691
  : options.inherited.length;
682
692
  const transcript = new TranscriptChannel(() => session.messages, session.messages.some((message) => message.role === "compactionSummary") ? 0 : inheritedCount);
683
693
  const unsubscribe = session.subscribe((event) => {
694
+ if (event.type === "agent_start")
695
+ acceptingFollowUps = true;
696
+ else if (event.type === "agent_end")
697
+ acceptingFollowUps = false;
684
698
  transcript.accept(event);
685
699
  if (running && event.type === "message_end" && event.message.role === "assistant")
686
700
  promptResult.lastAssistant = event.message;
@@ -742,6 +756,7 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
742
756
  if (running)
743
757
  throw new Error("Subagent is already running; use steer instead");
744
758
  running = true;
759
+ acceptingFollowUps = true;
745
760
  aborted = false;
746
761
  promptResult.lastAssistant = undefined;
747
762
  finalOutput = "";
@@ -767,6 +782,7 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
767
782
  }
768
783
  finally {
769
784
  updateResolved();
785
+ acceptingFollowUps = false;
770
786
  running = false;
771
787
  }
772
788
  },
@@ -774,12 +790,36 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
774
790
  assertOpen();
775
791
  await queueAccepted("steer", message);
776
792
  },
793
+ async followUp(message) {
794
+ assertOpen();
795
+ return queueAccepted("followUp", message);
796
+ },
777
797
  snapshot() {
778
798
  return structuredClone(session.messages);
779
799
  },
780
800
  contextEntries() {
781
801
  return inheritedContextEntries(sessionManager.getBranch());
782
802
  },
803
+ history() {
804
+ return readHistory(sessionManager.getBranch());
805
+ },
806
+ historyAnchor() {
807
+ return sessionManager.getLeafId();
808
+ },
809
+ appendHistory(observation, anchor) {
810
+ const branch = sessionManager.getBranch();
811
+ if (!anchor || !branch.some((entry) => entry.id === anchor))
812
+ return false;
813
+ const last = readHistory(branch).observations.at(-1);
814
+ if (last &&
815
+ last.path === observation.path &&
816
+ last.run === observation.run &&
817
+ last.text === observation.text)
818
+ return true;
819
+ sessionManager.appendCustomEntry(HISTORY_ENTRY, observation);
820
+ emitCheckpoint();
821
+ return true;
822
+ },
783
823
  observeTranscript(listener) {
784
824
  assertOpen();
785
825
  return transcript.observe(listener);
@@ -86,15 +86,15 @@ export function agentTools(getManager, caller, getTypes, resolveSettings) {
86
86
  }), async (params) => result(compact(await threads().steer(params.path, params.message, params.timeoutMs)))),
87
87
  make("agent_status", "Read a thread's status, including bounded child extension diagnostics, or list visible descendants. Root can inspect all trees. Completion retains the session; pause retains it without final answer handback.", Type.Object({ path: Type.Optional(path) }), (params) => result(params.path ? compact(threads().get(params.path)) : threads().list().map(compact))),
88
88
  make("agent_update", "Child-only: send progress to the parent without ending this task. Delivery is recorded and displayed but does not interrupt or automatically restart the parent model.", Type.Object({ message: Type.String({ minLength: 1, maxLength: 8000 }) }), (params) => result(compact(threads().update(params.message)))),
89
- make("agent_pause", "Child-only: stop at this turn boundary WITHOUT returning a final answer. Keep the SAME session for user/parent input via agent_steer. To finish and hand back an answer instead, simply return your final assistant answer. Both states can be resumed.", Type.Object({ reason: text }), (params) => ({
89
+ make("agent_pause", "Child-only: stop at this turn boundary WITHOUT returning a final answer. Keep the SAME session for user/parent input via agent_steer. To finish and hand back an answer instead, simply return your final assistant answer. Both states can be resumed. Set wakeParent:true to request a turn on your immediate parent after settlement, even while siblings work. A busy parent receives a safe follow-up; an already-settled parent is never auto-resumed.", Type.Object({ reason: text, wakeParent: Type.Optional(Type.Boolean()) }), (params) => ({
90
90
  ...result({
91
91
  path: caller,
92
92
  pauseRequested: true,
93
- status: threads().pause(params.reason).status,
93
+ status: threads().pause(params.reason, params.wakeParent).status,
94
94
  }),
95
95
  terminate: true,
96
96
  })),
97
- make("agent_stop", "Stop a descendant and its working children. Session history is retained; resume with agent_steer. This is cooperative cancellation, not sandbox process termination.", Type.Object({ path }), async (params) => result(compact(await threads().stop(params.path)))),
97
+ make("agent_stop", "Stop a descendant and its working children. Session history is retained; resume with agent_steer. This is cooperative cancellation, not sandbox process termination. Set wakeParent:true to request a turn on the addressed thread's immediate parent when that active thread settles; descendants do not inherit it. Busy parents receive a safe follow-up; an already-settled parent is never auto-resumed.", Type.Object({ path, wakeParent: Type.Optional(Type.Boolean()) }), async (params) => result(compact(await threads().stop(params.path, params.wakeParent)))),
98
98
  make("agent_output", "Read completed thread output in character pages. Paused threads deliberately have no final answer handback. All sessions can be viewed by the user with /agents tree; select a thread and press Enter to inspect it.", Type.Object({
99
99
  path,
100
100
  offset: Type.Optional(Type.Integer({ minimum: 0 })),
@@ -37,10 +37,10 @@ export const DEFAULT_MANAGER_SETTINGS = {
37
37
  costIcon: "money",
38
38
  nerdFontIcons: false,
39
39
  loaderStyle: "circle",
40
- finalRecap: false,
41
40
  subagentExtensions: false,
42
41
  checklistIntegration: false,
43
42
  housekeepingEnabled: false,
43
+ forkHistorySummaries: false,
44
44
  housekeepingModel: "",
45
45
  };
46
46
  const HOUSEKEEPING_MODEL = /^[^\s/]+\/[^\s]+$/;
@@ -58,10 +58,10 @@ const KEYS = [
58
58
  "costIcon",
59
59
  "nerdFontIcons",
60
60
  "loaderStyle",
61
- "finalRecap",
62
61
  "subagentExtensions",
63
62
  "checklistIntegration",
64
63
  "housekeepingEnabled",
64
+ "forkHistorySummaries",
65
65
  "housekeepingModel",
66
66
  ];
67
67
  const MAX_LEVELS = 32;
@@ -97,23 +97,26 @@ function isExtensionSelectionPath(entry) {
97
97
  return false;
98
98
  if (entry.startsWith(AGENT_DIR_EXTENSION_PREFIX)) {
99
99
  const suffix = entry.slice(AGENT_DIR_EXTENSION_PREFIX.length);
100
- return !suffix.includes("\\") &&
101
- suffix.split("/").every((part) => part && part !== "." && part !== "..");
100
+ return (!suffix.includes("\\") &&
101
+ suffix.split("/").every((part) => part && part !== "." && part !== ".."));
102
102
  }
103
103
  if (entry === AGENT_DIR_EXTENSION_PREFIX.slice(0, -1))
104
104
  return false;
105
105
  if (isAbsolute(entry))
106
106
  return resolve(entry) === entry;
107
- return normalize(entry) === entry &&
108
- entry !== "." && entry !== ".." && !entry.startsWith(`..${sep}`) && !entry.endsWith(sep);
107
+ return (normalize(entry) === entry &&
108
+ entry !== "." &&
109
+ entry !== ".." &&
110
+ !entry.startsWith(`..${sep}`) &&
111
+ !entry.endsWith(sep));
109
112
  }
110
113
  function requirement(key) {
111
114
  if (key === "subagentExtensions")
112
115
  return "subagentExtensions must be a boolean or an array of absolute, project-relative, or $PI_CODING_AGENT_DIR paths";
113
116
  if (key === "nerdFontIcons" ||
114
- key === "finalRecap" ||
115
117
  key === "checklistIntegration" ||
116
- key === "housekeepingEnabled")
118
+ key === "housekeepingEnabled" ||
119
+ key === "forkHistorySummaries")
117
120
  return `${key} must be a boolean`;
118
121
  if (key === "housekeepingModel")
119
122
  return "housekeepingModel must be empty or provider/model-id";
@@ -149,7 +152,7 @@ function parseSettings(content) {
149
152
  }
150
153
  const record = parsed;
151
154
  for (const key of Object.keys(record)) {
152
- if (!isSupportedKey(key) && key !== "scopedModelFiltering")
155
+ if (!isSupportedKey(key) && key !== "scopedModelFiltering" && key !== "finalRecap")
153
156
  throw new Error(`Unknown settings key: ${key}`);
154
157
  }
155
158
  const layer = {};
@@ -166,9 +169,9 @@ function parseSettings(content) {
166
169
  continue;
167
170
  const value = record[key];
168
171
  if (key === "nerdFontIcons" ||
169
- key === "finalRecap" ||
170
172
  key === "checklistIntegration" ||
171
- key === "housekeepingEnabled") {
173
+ key === "housekeepingEnabled" ||
174
+ key === "forkHistorySummaries") {
172
175
  if (typeof value !== "boolean")
173
176
  throw new Error(requirement(key));
174
177
  layer[key] = value;
@@ -417,6 +417,12 @@ async function configureAgentsDialog(ctx, options) {
417
417
  : undefined,
418
418
  help: HOUSEKEEPING_HELP,
419
419
  },
420
+ {
421
+ id: "forkHistorySummaries",
422
+ label: "[lab] Fork history summaries",
423
+ value: draft.forkHistorySummaries ? "On" : "Off",
424
+ help: "Experimental: forks inherit a bounded sequence of sampled one-line activity observations instead of the parent transcript; fresh agents are unchanged. History can have gaps, and missing history never falls back to the raw transcript.\nReuses the same housekeeping lines as subagent live labels, even if live-label display is off. Adds background housekeeping calls for the main agent. Forks only use cached lines and never wait for summarization. Requires a selected housekeeping model. Off by default.",
425
+ },
420
426
  {
421
427
  id: "nerdFontIcons",
422
428
  label: "[lab] Nerd Font icons",
@@ -434,12 +440,6 @@ async function configureAgentsDialog(ctx, options) {
434
440
  help: "Experimental: reload selected user/trusted-project extension hooks, including auto-discovered .ts/.js files and subdirectory entry points, in separate subagent sessions (not CLI-only or inline extensions). Bugs and unintended consequences may occur if hooks assume main-session state.\nRead limitations: https://github.com/championswimmer/pi-subagent-manager/blob/main/docs/subagent-extension-limitations.md\nSelect individual extensions in the submenu. None by default. Save and apply affects newly opened sessions, not already-open agents.",
435
441
  },
436
442
  checklistRow(draft.checklistIntegration, checklistStatus()),
437
- {
438
- id: "finalRecap",
439
- label: "[lab] Final Recap",
440
- value: draft.finalRecap ? "On" : "Off",
441
- help: "Experimental: when detached agents finish or fail and the main agent is idle, automatically ask the main agent to summarize their results.\nEnabling this may cause extra model turns and uses more tokens and context.\nOff by default. Subagent Mode Off suppresses automatic summaries.",
442
- },
443
443
  {
444
444
  id: "scope",
445
445
  label: "Save scope",
@@ -535,6 +535,9 @@ async function configureAgentsDialog(ctx, options) {
535
535
  else if (action === "housekeeping") {
536
536
  await configureHousekeeping(ctx, draft, layers);
537
537
  }
538
+ else if (action === "forkHistorySummaries") {
539
+ draft.forkHistorySummaries = !draft.forkHistorySummaries;
540
+ }
538
541
  else if (action === "nerdFontIcons") {
539
542
  draft.nerdFontIcons = !draft.nerdFontIcons;
540
543
  }
@@ -554,9 +557,6 @@ async function configureAgentsDialog(ctx, options) {
554
557
  else
555
558
  draft.checklistIntegration = !draft.checklistIntegration;
556
559
  }
557
- else if (action === "finalRecap") {
558
- draft.finalRecap = !draft.finalRecap;
559
- }
560
560
  else if (action === "scope") {
561
561
  if (!ctx.isProjectTrusted())
562
562
  ctx.ui.notify("Project settings require a trusted project; saving globally.", "warning");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "1.14.0",
3
+ "version": "1.16.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",