@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.5

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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
@@ -0,0 +1,75 @@
1
+ /**
2
+ * agent-source-badge.ts — How `/agents → Agent types` shows where an agent came
3
+ * from: the per-row badge, the legend that explains the badges actually on
4
+ * screen, and the description line under the highlighted row.
5
+ *
6
+ * These live outside src/index.ts for the same reason as agent-file-toggle.ts:
7
+ * the `/agents` handler is a large closure reached only through
8
+ * `registerCommand`, which every test mocks, so nothing inside it can be
9
+ * asserted on directly.
10
+ *
11
+ * The badges are deliberately terse — the list is one row per agent and the
12
+ * model already occupies the right-hand column. Anything wordier than a glyph
13
+ * (the package's name, in particular) goes on the description line, which
14
+ * `SettingsList` renders for the highlighted row only.
15
+ */
16
+
17
+ import type { AgentConfig } from "./types.js";
18
+
19
+ /**
20
+ * The badge column: a two-cell glyph plus a space, so every label starts at the
21
+ * same offset whether or not the agent is badged.
22
+ *
23
+ * Built-in defaults are unmarked. They are the majority of the list, and a
24
+ * badge on them would make the three that matter — the agents the user or a
25
+ * package put there — harder to pick out, not easier.
26
+ */
27
+ export function sourceIndicator(cfg: AgentConfig | undefined): string {
28
+ const disabled = cfg?.enabled === false;
29
+ if (cfg?.source === "project") return disabled ? "✕• " : "• ";
30
+ if (cfg?.source === "global") return disabled ? "✕◦ " : "◦ ";
31
+ if (cfg?.source === "package") return disabled ? "✕▪ " : "▪ ";
32
+ if (disabled) return "✕ ";
33
+ return " ";
34
+ }
35
+
36
+ /**
37
+ * The legend line, naming only the badges the given roster actually renders.
38
+ *
39
+ * Keyed on what `sourceIndicator` would emit, so the two cannot drift into a
40
+ * glyph with no key (which is what `▪` was) or a key for a glyph that is not on
41
+ * screen. A defaults-only roster returns "", and the caller omits the line.
42
+ *
43
+ * `source` is undefined for built-in defaults — the `"default"` member of the
44
+ * union is declared but never assigned, since default-agents.ts sets only
45
+ * `isDefault` — so they contribute no key, matching their blank badge.
46
+ */
47
+ export function sourceLegend(cfgs: readonly (AgentConfig | undefined)[]): string {
48
+ const parts: string[] = [];
49
+ if (cfgs.some(c => c?.source === "project")) parts.push("• = project");
50
+ if (cfgs.some(c => c?.source === "global")) parts.push("◦ = global");
51
+ if (cfgs.some(c => c?.source === "package")) parts.push("▪ = package");
52
+ if (cfgs.some(c => c?.enabled === false)) parts.push("✕ = disabled");
53
+ return parts.join(" ");
54
+ }
55
+
56
+ /**
57
+ * The description line under the highlighted row.
58
+ *
59
+ * `packageName` is the one piece of provenance a badge cannot carry: with two
60
+ * agent-providing packages installed, `▪` says only that *some* package won.
61
+ * It is prefixed rather than appended so it stays visible when a long
62
+ * description wraps, and it prefixes "(disabled)" too — a disabled package
63
+ * agent is exactly the case where you want to know whose it was.
64
+ *
65
+ * Falls back to the agent's own name when it has no description, which is what
66
+ * a hand-written agent file without one already showed.
67
+ */
68
+ export function rowDescription(
69
+ name: string,
70
+ cfg: AgentConfig | undefined,
71
+ packageName?: string,
72
+ ): string {
73
+ const base = cfg?.enabled === false ? "(disabled)" : (cfg?.description ?? name);
74
+ return packageName ? `${packageName} · ${base}` : base;
75
+ }
@@ -0,0 +1,346 @@
1
+ /**
2
+ * agent-types.ts — Unified agent type registry.
3
+ *
4
+ * Merges embedded default agents with user-defined agents from .pi/agents/*.md, .agents/agents/*.md, and global agents.
5
+ * User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
6
+ */
7
+
8
+ import { createCodingTools, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
9
+ import { DEFAULT_AGENTS } from "./default-agents.js";
10
+ import type { AgentConfig } from "./types.js";
11
+
12
+ /**
13
+ * All known built-in tool names, derived from pi's own tool factories rather
14
+ * than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
15
+ * `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
16
+ * read/grep/find/ls; their de-duplicated union is the 7 built-ins
17
+ * (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
18
+ * operations we never invoke here — we read each tool's `.name` and discard it.
19
+ */
20
+ export const BUILTIN_TOOL_NAMES: string[] = [
21
+ ...new Set([...createCodingTools("."), ...createReadOnlyTools(".")].map((t) => t.name)),
22
+ ];
23
+
24
+ /** Unified runtime registry of all agents (defaults + user-defined). */
25
+ const agents = new Map<string, AgentConfig>();
26
+
27
+ /** When true, DEFAULT_AGENTS are skipped during registration. */
28
+ let disableDefaults = false;
29
+
30
+ /** Check whether default agents are disabled. */
31
+ export function isDefaultsDisabled(): boolean { return disableDefaults; }
32
+
33
+ /** Set whether default agents are disabled. */
34
+ export function setDefaultsDisabled(b: boolean): void { disableDefaults = b; }
35
+
36
+ /** `fallbackSubagent` value that disables the fallback entirely (strict dispatch). */
37
+ export const NO_FALLBACK = "none";
38
+
39
+ /**
40
+ * Agent type substituted when a caller-supplied `subagent_type` doesn't resolve
41
+ * to exactly one enabled agent. `undefined` keeps the historical behavior
42
+ * (general-purpose); `NO_FALLBACK` makes dispatch fail closed. Set from
43
+ * `subagents.json` (`fallbackSubagent`).
44
+ *
45
+ * Module state rather than an index.ts closure because every caller-supplied
46
+ * spawn path needs it — the Agent tool, the scheduler, and cross-extension RPC.
47
+ */
48
+ let fallbackSubagent: string | undefined;
49
+
50
+ /** Get the configured fallback agent type. undefined = general-purpose. */
51
+ export function getFallbackSubagent(): string | undefined { return fallbackSubagent; }
52
+
53
+ /** Set the configured fallback agent type. undefined = general-purpose. */
54
+ export function setFallbackSubagent(v: string | undefined): void { fallbackSubagent = v; }
55
+
56
+ /**
57
+ * Build a registry map: DEFAULT_AGENTS first (unless disabled via settings),
58
+ * then user agents overlaid on top (same name overrides the default).
59
+ * Pure — callers that must not disturb the process-wide registry (nested
60
+ * delegation resolving agents from its own config root) build their own map.
61
+ */
62
+ export function buildAgentRegistry(userAgents: Map<string, AgentConfig>): Map<string, AgentConfig> {
63
+ const registry = new Map<string, AgentConfig>();
64
+ if (!disableDefaults) {
65
+ for (const [name, config] of DEFAULT_AGENTS) registry.set(name, config);
66
+ }
67
+ for (const [name, config] of userAgents) registry.set(name, config);
68
+ return registry;
69
+ }
70
+
71
+ /**
72
+ * Register agents into the unified registry.
73
+ * Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
74
+ * Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
75
+ */
76
+ export function registerAgents(userAgents: Map<string, AgentConfig>): void {
77
+ agents.clear();
78
+ for (const [name, config] of buildAgentRegistry(userAgents)) {
79
+ agents.set(name, config);
80
+ }
81
+ }
82
+
83
+ /** Case-insensitive key resolution within a registry. */
84
+ function resolveKeyIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
85
+ if (registry.has(name)) return name;
86
+ const lower = name.toLowerCase();
87
+ for (const key of registry.keys()) {
88
+ if (key.toLowerCase() === lower) return key;
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ /** Case-insensitive key resolution. */
94
+ function resolveKey(name: string): string | undefined {
95
+ return resolveKeyIn(agents, name);
96
+ }
97
+
98
+ /** Resolve a type name case-insensitively in a registry. Returns the canonical key or undefined. */
99
+ export function resolveTypeIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
100
+ return resolveKeyIn(registry, name);
101
+ }
102
+
103
+ /** Get the agent config for a type (case-insensitive) from a registry. */
104
+ export function getAgentConfigIn(registry: Map<string, AgentConfig>, name: string): AgentConfig | undefined {
105
+ const key = resolveKeyIn(registry, name);
106
+ return key ? registry.get(key) : undefined;
107
+ }
108
+
109
+ /** Check if a type is valid and enabled (case-insensitive) in a registry. */
110
+ export function isValidTypeIn(registry: Map<string, AgentConfig>, type: string): boolean {
111
+ const key = resolveKeyIn(registry, type);
112
+ if (!key) return false;
113
+ return registry.get(key)?.enabled !== false;
114
+ }
115
+
116
+ /** Get all enabled type names in a registry (for spawning and tool descriptions). */
117
+ export function getAvailableTypesIn(registry: Map<string, AgentConfig>): string[] {
118
+ return [...registry.entries()]
119
+ .filter(([_, config]) => config.enabled !== false)
120
+ .map(([name]) => name);
121
+ }
122
+
123
+ /**
124
+ * Case-insensitive resolution that refuses to guess. An exact match always wins;
125
+ * otherwise the name must match exactly one key. Two agents differing only in
126
+ * case are reachable (`loadCustomAgents` keys by filename across three
127
+ * directories), and picking whichever came first would silently dispatch a
128
+ * different agent, model and tool policy than the caller meant.
129
+ */
130
+ function resolveUnambiguousKeyIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
131
+ if (registry.has(name)) return name;
132
+ const lower = name.toLowerCase();
133
+ const matches = [...registry.keys()].filter(key => key.toLowerCase() === lower);
134
+ return matches.length === 1 ? matches[0] : undefined;
135
+ }
136
+
137
+ /**
138
+ * The canonical key for a caller-supplied name that identifies exactly one
139
+ * ENABLED agent, or undefined. Strict by construction: no fallback, no guessing
140
+ * between case-variants. Nested delegation resolves with this directly, since
141
+ * "unknown types are rejected rather than falling back" is its own contract.
142
+ */
143
+ export function resolveEnabledTypeIn(
144
+ registry: Map<string, AgentConfig>,
145
+ requested: unknown,
146
+ ): string | undefined {
147
+ const raw = typeof requested === "string" ? requested.trim() : "";
148
+ if (!raw) return undefined;
149
+ const key = resolveUnambiguousKeyIn(registry, raw);
150
+ return key !== undefined && registry.get(key)?.enabled !== false ? key : undefined;
151
+ }
152
+
153
+ /** Outcome of resolving a caller-supplied `subagent_type` into a spawnable type. */
154
+ export type SpawnTypeResolution =
155
+ /** Spawn this type. `fellBackFrom` is set when it isn't what the caller asked for. */
156
+ | { ok: true; type: string; fellBackFrom?: string }
157
+ /** Refuse the spawn and return this message to the caller. */
158
+ | { ok: false; message: string };
159
+
160
+ /**
161
+ * Resolve a caller-supplied agent type against a registry, applying the
162
+ * `fallbackSubagent` policy. The single decision point for every caller-supplied
163
+ * spawn — the Agent tool, the scheduler, cross-extension RPC, and the nested
164
+ * tools — so a type that fails here never reaches `runAgent`, where `getConfig`
165
+ * would silently substitute general-purpose.
166
+ *
167
+ * Unknown, disabled, and case-ambiguous names are all treated the same way:
168
+ * the caller named something that doesn't identify exactly one enabled agent.
169
+ *
170
+ * Pure over `registry` — callers that need fresh agent files reload before
171
+ * calling (the Agent tool already does, per spawn). Reloading here would mean
172
+ * importing custom-agents.ts, which imports this module.
173
+ */
174
+ export function resolveSpawnTypeIn(
175
+ registry: Map<string, AgentConfig>,
176
+ requested: unknown,
177
+ ): SpawnTypeResolution {
178
+ const raw = typeof requested === "string" ? requested.trim() : "";
179
+ const available = () => getAvailableTypesIn(registry).join(", ") || "(none)";
180
+
181
+ const key = resolveEnabledTypeIn(registry, raw);
182
+ if (key !== undefined) return { ok: true, type: key };
183
+
184
+ // A missing type follows the same policy as a wrong one rather than always
185
+ // erroring: before this setting existed an empty type fell back like any
186
+ // other unresolvable name, and only opting in should change that.
187
+ const reason = raw ? `Unknown or disabled agent type: "${raw}".` : "No agent type given.";
188
+
189
+ // Trimmed like `requested`: a padded value set programmatically would
190
+ // otherwise be reported as a missing agent.
191
+ const configured = typeof fallbackSubagent === "string" ? fallbackSubagent.trim() : undefined;
192
+
193
+ if (configured !== undefined && configured.toLowerCase() === NO_FALLBACK) {
194
+ return { ok: false, message: `${reason} Available: ${available()}.` };
195
+ }
196
+
197
+ if (configured !== undefined) {
198
+ // An explicitly configured fallback that is itself unusable is a
199
+ // misconfiguration, not a second chance to guess — say so rather than
200
+ // quietly dropping to general-purpose.
201
+ const fallbackKey = resolveUnambiguousKeyIn(registry, configured);
202
+ if (fallbackKey === undefined || registry.get(fallbackKey)?.enabled === false) {
203
+ return {
204
+ ok: false,
205
+ message:
206
+ `${reason} The configured fallbackSubagent "${configured}" is itself ` +
207
+ `unknown or disabled. Available: ${available()}.`,
208
+ };
209
+ }
210
+ return { ok: true, type: fallbackKey, fellBackFrom: raw };
211
+ }
212
+
213
+ // Unset: historical behavior, deliberately unchanged. #183 asks for the
214
+ // fallback to remain the default, so the pre-existing hole it leaves — an
215
+ // unregistered general-purpose resolving to `getConfig`'s all-tools hardcoded
216
+ // tier — is what `fallbackSubagent: none` is for, not something to close
217
+ // under everyone silently.
218
+ return { ok: true, type: "general-purpose", fellBackFrom: raw };
219
+ }
220
+
221
+ /** Resolve a caller-supplied agent type against the process-wide registry. */
222
+ export function resolveSpawnType(requested: unknown): SpawnTypeResolution {
223
+ return resolveSpawnTypeIn(agents, requested);
224
+ }
225
+
226
+ /** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
227
+ export function resolveType(name: string): string | undefined {
228
+ return resolveKey(name);
229
+ }
230
+
231
+ /** Get the agent config for a type (case-insensitive). */
232
+ export function getAgentConfig(name: string): AgentConfig | undefined {
233
+ return getAgentConfigIn(agents, name);
234
+ }
235
+
236
+ /** Get all enabled type names (for spawning and tool descriptions). */
237
+ export function getAvailableTypes(): string[] {
238
+ return getAvailableTypesIn(agents);
239
+ }
240
+
241
+ /** Get all type names including disabled (for UI listing). */
242
+ export function getAllTypes(): string[] {
243
+ return [...agents.keys()];
244
+ }
245
+
246
+ /** Get names of default agents currently in the registry. */
247
+ export function getDefaultAgentNames(): string[] {
248
+ return [...agents.entries()]
249
+ .filter(([_, config]) => config.isDefault === true)
250
+ .map(([name]) => name);
251
+ }
252
+
253
+ /** Get names of user-defined agents (non-defaults) currently in the registry. */
254
+ export function getUserAgentNames(): string[] {
255
+ return [...agents.entries()]
256
+ .filter(([_, config]) => config.isDefault !== true)
257
+ .map(([name]) => name);
258
+ }
259
+
260
+ /** Check if a type is valid and enabled (case-insensitive). */
261
+ export function isValidType(type: string): boolean {
262
+ return isValidTypeIn(agents, type);
263
+ }
264
+
265
+ /** Tool names required for memory management. */
266
+ const MEMORY_TOOL_NAMES = ["read", "write", "edit"];
267
+
268
+ /**
269
+ * Get memory tool names (read/write/edit) not already in the provided set.
270
+ */
271
+ export function getMemoryToolNames(existingToolNames: Set<string>): string[] {
272
+ return MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
273
+ }
274
+
275
+ /** Tool names needed for read-only memory access. */
276
+ const READONLY_MEMORY_TOOL_NAMES = ["read"];
277
+
278
+ /**
279
+ * Get read-only memory tool names not already in the provided set.
280
+ */
281
+ export function getReadOnlyMemoryToolNames(existingToolNames: Set<string>): string[] {
282
+ return READONLY_MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
283
+ }
284
+
285
+ /** Get built-in tool names for a type (case-insensitive). */
286
+ export function getToolNamesForType(type: string): string[] {
287
+ const key = resolveKey(type);
288
+ const raw = key ? agents.get(key) : undefined;
289
+ const config = raw?.enabled !== false ? raw : undefined;
290
+ // `undefined` (definition omitted the field) → all built-ins; an explicit `[]`
291
+ // (`tools: none` or a `tools:` with only `ext:` entries) → zero built-ins.
292
+ return config?.builtinToolNames ?? [...BUILTIN_TOOL_NAMES];
293
+ }
294
+
295
+ /** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to general-purpose. */
296
+ export function getConfig(type: string): {
297
+ displayName: string;
298
+ color?: string;
299
+ description: string;
300
+ builtinToolNames: string[];
301
+ extensions: true | string[] | false;
302
+ excludeExtensions?: string[];
303
+ skills: true | string[] | false;
304
+ promptMode: "replace" | "append";
305
+ } {
306
+ const key = resolveKey(type);
307
+ const config = key ? agents.get(key) : undefined;
308
+ if (config && config.enabled !== false) {
309
+ return {
310
+ displayName: config.displayName ?? config.name,
311
+ color: config.color,
312
+ description: config.description,
313
+ builtinToolNames: config.builtinToolNames ?? BUILTIN_TOOL_NAMES,
314
+ extensions: config.extensions,
315
+ excludeExtensions: config.excludeExtensions,
316
+ skills: config.skills,
317
+ promptMode: config.promptMode,
318
+ };
319
+ }
320
+
321
+ // Fallback for unknown/disabled types — general-purpose config
322
+ const gp = agents.get("general-purpose");
323
+ if (gp && gp.enabled !== false) {
324
+ return {
325
+ displayName: gp.displayName ?? gp.name,
326
+ color: gp.color,
327
+ description: gp.description,
328
+ builtinToolNames: gp.builtinToolNames ?? BUILTIN_TOOL_NAMES,
329
+ extensions: gp.extensions,
330
+ excludeExtensions: gp.excludeExtensions,
331
+ skills: gp.skills,
332
+ promptMode: gp.promptMode,
333
+ };
334
+ }
335
+
336
+ // Absolute fallback (should never happen)
337
+ return {
338
+ displayName: "Agent",
339
+ description: "General-purpose agent for complex, multi-step tasks",
340
+ builtinToolNames: BUILTIN_TOOL_NAMES,
341
+ extensions: true,
342
+ skills: true,
343
+ promptMode: "append",
344
+ };
345
+ }
346
+
@@ -0,0 +1,15 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ /**
4
+ * Marks resource loading/session construction performed for a subagent. This is
5
+ * async-context-local so concurrent top-level extension work is unaffected.
6
+ */
7
+ const childSessionContext = new AsyncLocalStorage<boolean>();
8
+
9
+ export function inChildSessionContext(): boolean {
10
+ return childSessionContext.getStore() === true;
11
+ }
12
+
13
+ export function runInChildSessionContext<T>(fn: () => Promise<T>): Promise<T> {
14
+ return childSessionContext.run(true, fn);
15
+ }
package/src/clock.ts ADDED
@@ -0,0 +1,25 @@
1
+ /** A timer owns cancellation, without requiring a Node-specific handle. */
2
+ export interface TimerHandle {
3
+ cancel(): void;
4
+ unref?(): void;
5
+ }
6
+
7
+ /** Scheduling boundary, structurally compatible with pi-session-kit's clock. */
8
+ export interface Clock {
9
+ now(): number;
10
+ setTimeout(callback: () => void, ms: number): TimerHandle;
11
+ setInterval(callback: () => void, ms: number): TimerHandle;
12
+ }
13
+
14
+ /** Native timers keep their original reference/unref behavior; cancellation uses the native clear functions. */
15
+ export const realClock: Clock = {
16
+ now: () => Date.now(),
17
+ setTimeout(callback, ms) {
18
+ const timer = setTimeout(callback, ms);
19
+ return { cancel: () => clearTimeout(timer) };
20
+ },
21
+ setInterval(callback, ms) {
22
+ const timer = setInterval(callback, ms);
23
+ return { cancel: () => clearInterval(timer), unref: () => { timer.unref(); } };
24
+ },
25
+ };
@@ -0,0 +1,125 @@
1
+ /**
2
+ * completion-outbox.ts — When background completions reach the parent.
3
+ *
4
+ * Claude Code queues each completion and, after every tool batch, hands the
5
+ * model everything that queued up in one go: a busy parent sees what finished
6
+ * during the batch before its next model call, and nothing waits for a sibling.
7
+ * pi's steering queue would split those into one model call each under its
8
+ * default `one-at-a-time` mode, so the outbox holds them and sends ONE message
9
+ * at the boundary instead.
10
+ *
11
+ * - Parent busy: held until `turn_end`, which pi emits after the tool batch and
12
+ * before it reads the steering queue.
13
+ * - Parent idle: sent after a short hold, so near-simultaneous completions
14
+ * share a turn and `get_subagent_result` still gets a moment to consume one.
15
+ * - Parent turn aborted (Esc) or failed: held through it — pi clears its own
16
+ * queues on Esc — and sent once the run has ended, starting a turn. Claude
17
+ * Code keeps an agent's completion queued through Esc the same way and runs
18
+ * it as soon as the interrupted turn stops.
19
+ */
20
+
21
+ import { type Clock, realClock, type TimerHandle } from "./clock.js";
22
+ import type { NotificationDetails } from "./types.js";
23
+
24
+ /** How long an idle parent's notification is held before it is sent. */
25
+ export const NOTIFICATION_HOLD_MS = 200;
26
+
27
+ export interface OutboxMessage {
28
+ content: string;
29
+ details: NotificationDetails;
30
+ }
31
+
32
+ /**
33
+ * A notification for one or more agents, built when they finished: a resume
34
+ * before the send must not rewrite it. Reading an agent's result cancels its
35
+ * id, and an item left with none is dropped; `build` gets the ids still pending.
36
+ */
37
+ export interface OutboxItem {
38
+ ids: string[];
39
+ build(ids: readonly string[]): OutboxMessage;
40
+ }
41
+
42
+ export class CompletionOutbox {
43
+ private items: OutboxItem[] = [];
44
+ private timer: TimerHandle | undefined;
45
+
46
+ constructor(
47
+ /** Delivers one message as a steer that triggers a turn when the parent is idle. */
48
+ private send: (message: OutboxMessage) => void,
49
+ /** Whether the parent has a run in flight, so a `turn_end` is coming. */
50
+ private parentRunning: () => boolean,
51
+ /** Shared with the scheduler by hosts that control time in-process. */
52
+ private clock: Clock = realClock,
53
+ ) {}
54
+
55
+ /** A newer completion of the same agent (a resume) replaces its pending one. */
56
+ add(item: OutboxItem): void {
57
+ for (const id of item.ids) this.cancel(id);
58
+ this.items.push(item);
59
+ if (!this.parentRunning()) this.arm();
60
+ }
61
+
62
+ /** The parent finished a turn: its tool batch is done, the next model call is not. */
63
+ onTurnEnd(stopReason: string | undefined): void {
64
+ // An aborted turn ends its run; a failed one may be retried. Either way
65
+ // what is held waits for the next boundary or the run's end — sent now,
66
+ // it would sit in a queue pi is about to clear.
67
+ if (stopReason !== "aborted" && stopReason !== "error") this.flush();
68
+ }
69
+
70
+ /** The agent's result was read: it must not also be notified. */
71
+ cancel(id: string): void {
72
+ for (const item of this.items) item.ids = item.ids.filter(i => i !== id);
73
+ this.items = this.items.filter(item => item.ids.length > 0);
74
+ }
75
+
76
+ /**
77
+ * Completions that landed after the run's last `turn_end` would otherwise wait for the next run.
78
+ * Called at `agent_end` and again at `agent_settled`: one can land while the ending run is still open.
79
+ */
80
+ onAgentEnd(): void {
81
+ if (this.items.length > 0) this.arm();
82
+ }
83
+
84
+ dispose(): void {
85
+ this.timer?.cancel();
86
+ this.timer = undefined;
87
+ this.items = [];
88
+ }
89
+
90
+ /** Not reset by later items: the first completion is never pushed back. */
91
+ private arm(): void {
92
+ this.timer ??= this.clock.setTimeout(() => {
93
+ this.timer = undefined;
94
+ this.flush();
95
+ }, NOTIFICATION_HOLD_MS);
96
+ }
97
+
98
+ /** Remove held completions for transfer to their session's detached spool. */
99
+ takePending(): OutboxMessage | undefined {
100
+ this.timer?.cancel();
101
+ this.timer = undefined;
102
+ const items = this.items;
103
+ this.items = [];
104
+ const messages = items.map(item => item.build(item.ids));
105
+ return messages.length > 0 ? combine(messages) : undefined;
106
+ }
107
+
108
+ private flush(): void {
109
+ const message = this.takePending();
110
+ if (!message) return;
111
+ // A send from a timer can outlive the session it was meant for (pi -p
112
+ // tearing down): pi throws on the stale context, and nothing is left to tell.
113
+ try { this.send(message); } catch { /* stale context */ }
114
+ }
115
+ }
116
+
117
+ /** One message stays as it was built; several become one message with every agent's details. */
118
+ function combine(messages: OutboxMessage[]): OutboxMessage {
119
+ if (messages.length === 1) return messages[0];
120
+ const [first, ...rest] = messages.flatMap(({ details: { others, ...own } }) => [own, ...(others ?? [])]);
121
+ return {
122
+ content: `${messages.length} background tasks finished.\n\n${messages.map(m => m.content).join("\n\n")}`,
123
+ details: { ...first, others: rest },
124
+ };
125
+ }
package/src/context.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * context.ts — Extract parent conversation context for subagent inheritance.
3
+ */
4
+
5
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+
7
+ /** Extract text from a message content block array. */
8
+ export function extractText(content: unknown[]): string {
9
+ return content
10
+ .filter((c: any) => c.type === "text")
11
+ .map((c: any) => c.text ?? "")
12
+ .join("\n");
13
+ }
14
+
15
+ /**
16
+ * Build a text representation of the parent conversation context.
17
+ * Used when inherit_context is true to give the subagent visibility
18
+ * into what has been discussed/done so far.
19
+ */
20
+ export function buildParentContext(ctx: ExtensionContext): string {
21
+ const entries = ctx.sessionManager.getBranch();
22
+ if (!entries || entries.length === 0) return "";
23
+
24
+ const parts: string[] = [];
25
+
26
+ for (const entry of entries) {
27
+ if (entry.type === "message") {
28
+ const msg = entry.message;
29
+ if (msg.role === "user") {
30
+ const text = typeof msg.content === "string"
31
+ ? msg.content
32
+ : extractText(msg.content);
33
+ if (text.trim()) parts.push(`[User]: ${text.trim()}`);
34
+ } else if (msg.role === "assistant") {
35
+ const text = extractText(msg.content);
36
+ if (text.trim()) parts.push(`[Assistant]: ${text.trim()}`);
37
+ }
38
+ // Skip toolResult messages — too verbose for context
39
+ } else if (entry.type === "compaction") {
40
+ // Include compaction summaries — they're already condensed
41
+ if (entry.summary) {
42
+ parts.push(`[Summary]: ${entry.summary}`);
43
+ }
44
+ }
45
+ }
46
+
47
+ if (parts.length === 0) return "";
48
+
49
+ return `# Parent Conversation Context
50
+ The following is the conversation history from the parent session that spawned you.
51
+ Use this context to understand what has been discussed and decided so far.
52
+
53
+ ${parts.join("\n\n")}
54
+
55
+ ---
56
+ # Your Task (below)
57
+ `;
58
+ }