@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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/CHANGELOG.md +827 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1079 -2
- package/SECURITY.md +97 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/active-agents-prompt.d.ts +18 -0
- package/dist/active-agents-prompt.js +34 -0
- package/dist/advisor-status.d.ts +16 -0
- package/dist/advisor-status.js +74 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +123 -0
- package/dist/agent-file-toggle.d.ts +125 -0
- package/dist/agent-file-toggle.js +264 -0
- package/dist/agent-manager.d.ts +485 -0
- package/dist/agent-manager.js +1380 -0
- package/dist/agent-runner.d.ts +319 -0
- package/dist/agent-runner.js +1128 -0
- package/dist/agent-types.d.ts +119 -0
- package/dist/agent-types.js +286 -0
- package/dist/child-context.d.ts +15 -0
- package/dist/child-context.js +181 -0
- package/dist/child-session-shutdown.d.ts +3 -0
- package/dist/child-session-shutdown.js +48 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +66 -0
- package/dist/cross-extension-rpc.js +138 -0
- package/dist/custom-agents.d.ts +54 -0
- package/dist/custom-agents.js +386 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +125 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/error-log.d.ts +58 -0
- package/dist/error-log.js +168 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +3896 -0
- package/dist/invocation-config.d.ts +137 -0
- package/dist/invocation-config.js +129 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +87 -0
- package/dist/mention-clone.js +178 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +55 -0
- package/dist/nested-tools.js +299 -0
- package/dist/output-diagnostics.d.ts +11 -0
- package/dist/output-diagnostics.js +64 -0
- package/dist/output-file.d.ts +53 -0
- package/dist/output-file.js +248 -0
- package/dist/prompts.d.ts +61 -0
- package/dist/prompts.js +94 -0
- package/dist/recovery.d.ts +56 -0
- package/dist/recovery.js +341 -0
- package/dist/schedule-store.d.ts +44 -0
- package/dist/schedule-store.js +210 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +359 -0
- package/dist/settings.d.ts +360 -0
- package/dist/settings.js +251 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/standalone-fallback.d.ts +30 -0
- package/dist/standalone-fallback.js +239 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/terminal-progress.d.ts +115 -0
- package/dist/terminal-progress.js +206 -0
- package/dist/types.d.ts +382 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +235 -0
- package/dist/ui/agent-widget.js +652 -0
- package/dist/ui/conversation-viewer.d.ts +105 -0
- package/dist/ui/conversation-viewer.js +540 -0
- package/dist/ui/fleet-list.d.ts +183 -0
- package/dist/ui/fleet-list.js +494 -0
- package/dist/ui/fleet-overlay.d.ts +172 -0
- package/dist/ui/fleet-overlay.js +691 -0
- package/dist/ui/native-transcript.d.ts +33 -0
- package/dist/ui/native-transcript.js +230 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/tool-progress.d.ts +22 -0
- package/dist/ui/tool-progress.js +56 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +843 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +135 -0
- package/dist/usage.js +120 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +62 -0
- package/dist/workflow/host.js +363 -0
- package/dist/workflow/journal.d.ts +97 -0
- package/dist/workflow/journal.js +120 -0
- package/dist/workflow/json-schema.d.ts +51 -0
- package/dist/workflow/json-schema.js +111 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +334 -0
- package/dist/workflow/runtime.js +830 -0
- package/dist/workflow/saved.d.ts +90 -0
- package/dist/workflow/saved.js +203 -0
- package/dist/workflow/task.d.ts +136 -0
- package/dist/workflow/task.js +207 -0
- package/dist/workflow/tool-description.d.ts +38 -0
- package/dist/workflow/tool-description.js +199 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/FORK.md +40 -0
- package/docs/recovery.md +62 -0
- package/docs/rpc.md +189 -0
- package/docs/workflows.md +437 -0
- package/examples/agent-tool-description.md +43 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +63 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +75 -6
- package/src/abortable.ts +43 -0
- package/src/active-agents-prompt.ts +39 -0
- package/src/advisor-status.ts +74 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +273 -0
- package/src/agent-manager.ts +1601 -0
- package/src/agent-runner.ts +1372 -0
- package/src/agent-types.ts +345 -0
- package/src/child-context.ts +173 -0
- package/src/child-session-shutdown.ts +46 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +198 -0
- package/src/custom-agents.ts +417 -0
- package/src/default-agents.ts +129 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/error-log.ts +193 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +4218 -0
- package/src/invocation-config.ts +230 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +221 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +422 -0
- package/src/output-diagnostics.ts +68 -0
- package/src/output-file.ts +258 -0
- package/src/prompts.ts +151 -0
- package/src/recovery.ts +320 -0
- package/src/schedule-store.ts +201 -0
- package/src/schedule.ts +386 -0
- package/src/settings.ts +587 -0
- package/src/skill-loader.ts +102 -0
- package/src/standalone-fallback.ts +195 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/terminal-progress.ts +215 -0
- package/src/types.ts +394 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +732 -0
- package/src/ui/conversation-viewer.ts +523 -0
- package/src/ui/fleet-list.ts +563 -0
- package/src/ui/fleet-overlay.ts +847 -0
- package/src/ui/native-transcript.ts +220 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/tool-progress.ts +67 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +470 -0
- package/src/ui/workflow-dialog.ts +1115 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +404 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +128 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +550 -0
- package/src/workflow/runtime.ts +1219 -0
- package/src/workflow/saved.ts +217 -0
- package/src/workflow/task.ts +302 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +205 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* worktree.ts — Git worktree isolation for agents.
|
|
3
|
+
*
|
|
4
|
+
* Creates a temporary git worktree so the agent works on an isolated copy of the repo.
|
|
5
|
+
* On completion, if no changes were made, the worktree is cleaned up.
|
|
6
|
+
* If changes exist, a branch is created and returned in the result.
|
|
7
|
+
*
|
|
8
|
+
* Every git call goes through `pi.exec` (async) rather than `execFileSync`: a
|
|
9
|
+
* worktree copy can take seconds, and a session that spawns several isolated
|
|
10
|
+
* agents at once would otherwise serialize them all on the TUI's event loop.
|
|
11
|
+
*/
|
|
12
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
export interface WorktreeInfo {
|
|
14
|
+
/** Absolute path to the worktree directory (the copied repo's root). */
|
|
15
|
+
path: string;
|
|
16
|
+
/** Branch name created for this worktree (if changes exist). */
|
|
17
|
+
branch: string;
|
|
18
|
+
/** Commit SHA that the worktree was created from. */
|
|
19
|
+
baseSha: string;
|
|
20
|
+
/**
|
|
21
|
+
* Where the agent should work inside the worktree: the equivalent of the
|
|
22
|
+
* cwd the worktree was created from. Equals `path` when that cwd was the
|
|
23
|
+
* repo root; points at the copied subdirectory when it was deeper (e.g. a
|
|
24
|
+
* monorepo package), so the requested scoping survives isolation.
|
|
25
|
+
*/
|
|
26
|
+
workPath: string;
|
|
27
|
+
}
|
|
28
|
+
export declare function setWorktreeIsolationEnabled(enabled: boolean): void;
|
|
29
|
+
export declare function isWorktreeIsolationEnabled(): boolean;
|
|
30
|
+
export interface WorktreeCleanupResult {
|
|
31
|
+
/** Whether changes were found in the worktree. */
|
|
32
|
+
hasChanges: boolean;
|
|
33
|
+
/** Branch name if changes were committed. */
|
|
34
|
+
branch?: string;
|
|
35
|
+
/** Worktree path if it was kept. */
|
|
36
|
+
path?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Create a temporary git worktree for an agent.
|
|
40
|
+
* Returns the worktree path, or undefined if not in a git repo.
|
|
41
|
+
*/
|
|
42
|
+
export declare function createWorktree(pi: ExtensionAPI, cwd: string, agentId: string): Promise<WorktreeInfo | undefined>;
|
|
43
|
+
/**
|
|
44
|
+
* Clean up a worktree after agent completion.
|
|
45
|
+
* - If no changes: remove worktree entirely.
|
|
46
|
+
* - If changes exist: create a branch, commit changes, return branch info.
|
|
47
|
+
*/
|
|
48
|
+
export declare function cleanupWorktree(pi: ExtensionAPI, cwd: string, worktree: WorktreeInfo, agentDescription: string): Promise<WorktreeCleanupResult>;
|
|
49
|
+
/**
|
|
50
|
+
* Prune any orphaned worktrees (crash recovery).
|
|
51
|
+
*/
|
|
52
|
+
export declare function pruneWorktrees(pi: ExtensionAPI, cwd: string): Promise<void>;
|
package/dist/worktree.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* worktree.ts — Git worktree isolation for agents.
|
|
3
|
+
*
|
|
4
|
+
* Creates a temporary git worktree so the agent works on an isolated copy of the repo.
|
|
5
|
+
* On completion, if no changes were made, the worktree is cleaned up.
|
|
6
|
+
* If changes exist, a branch is created and returned in the result.
|
|
7
|
+
*
|
|
8
|
+
* Every git call goes through `pi.exec` (async) rather than `execFileSync`: a
|
|
9
|
+
* worktree copy can take seconds, and a session that spawns several isolated
|
|
10
|
+
* agents at once would otherwise serialize them all on the TUI's event loop.
|
|
11
|
+
*/
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { join, relative } from "node:path";
|
|
16
|
+
/**
|
|
17
|
+
* Project-wide switch for worktree isolation (`worktreeIsolation` in
|
|
18
|
+
* subagents.json). Default `true` — unchanged behaviour.
|
|
19
|
+
*
|
|
20
|
+
* The `"off"` isolation value gives a model a legal way to decline a worktree,
|
|
21
|
+
* but it still depends on the model choosing it. This is the deterministic half
|
|
22
|
+
* of the same fix: on a large repo where every worktree costs real time and
|
|
23
|
+
* disk (#184), turning it off means no caller can create one, whatever it
|
|
24
|
+
* passes.
|
|
25
|
+
*/
|
|
26
|
+
let worktreeIsolationEnabled = true;
|
|
27
|
+
export function setWorktreeIsolationEnabled(enabled) {
|
|
28
|
+
worktreeIsolationEnabled = enabled;
|
|
29
|
+
}
|
|
30
|
+
export function isWorktreeIsolationEnabled() {
|
|
31
|
+
return worktreeIsolationEnabled;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Run git and return its trimmed stdout, throwing on failure so callers keep
|
|
35
|
+
* the try/catch control flow `execFileSync` gave them.
|
|
36
|
+
*
|
|
37
|
+
* `pi.exec` never rejects — it reports failure in the result — and a command
|
|
38
|
+
* killed by its timeout comes back as `killed` with an exit code of 0, so both
|
|
39
|
+
* have to be checked to reproduce `execFileSync`'s "throws on anything but a
|
|
40
|
+
* clean exit".
|
|
41
|
+
*/
|
|
42
|
+
async function git(pi, cwd, args, timeout) {
|
|
43
|
+
const result = await pi.exec("git", args, { cwd, timeout });
|
|
44
|
+
if (result.killed || result.code !== 0) {
|
|
45
|
+
throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed (exit ${result.code})`);
|
|
46
|
+
}
|
|
47
|
+
return result.stdout.trim();
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Create a temporary git worktree for an agent.
|
|
51
|
+
* Returns the worktree path, or undefined if not in a git repo.
|
|
52
|
+
*/
|
|
53
|
+
export async function createWorktree(pi, cwd, agentId) {
|
|
54
|
+
// Verify we're in a git repo with at least one commit (HEAD must exist)
|
|
55
|
+
let baseSha;
|
|
56
|
+
let subdir;
|
|
57
|
+
try {
|
|
58
|
+
await git(pi, cwd, ["rev-parse", "--is-inside-work-tree"], 5000);
|
|
59
|
+
baseSha = await git(pi, cwd, ["rev-parse", "HEAD"], 5000);
|
|
60
|
+
// Where cwd sits inside the repo ("" at the root): the agent must work at
|
|
61
|
+
// the same subdirectory inside the copy, or a monorepo-package cwd would
|
|
62
|
+
// silently widen to the whole repo. realpath both sides — git emits
|
|
63
|
+
// resolved paths while cwd may arrive through a symlink (macOS /tmp).
|
|
64
|
+
const topLevel = await git(pi, cwd, ["rev-parse", "--show-toplevel"], 5000);
|
|
65
|
+
subdir = relative(realpathSync(topLevel), realpathSync(cwd));
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
const branch = `pi-agent-${agentId}`;
|
|
71
|
+
const suffix = randomUUID().slice(0, 8);
|
|
72
|
+
const worktreePath = join(tmpdir(), `pi-agent-${agentId}-${suffix}`);
|
|
73
|
+
try {
|
|
74
|
+
// Create detached worktree at HEAD
|
|
75
|
+
await git(pi, cwd, ["worktree", "add", "--detach", worktreePath, "HEAD"], 30000);
|
|
76
|
+
return { path: worktreePath, branch, baseSha, workPath: subdir ? join(worktreePath, subdir) : worktreePath };
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// If worktree creation fails, return undefined (agent runs in normal cwd)
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Clean up a worktree after agent completion.
|
|
85
|
+
* - If no changes: remove worktree entirely.
|
|
86
|
+
* - If changes exist: create a branch, commit changes, return branch info.
|
|
87
|
+
*/
|
|
88
|
+
export async function cleanupWorktree(pi, cwd, worktree, agentDescription) {
|
|
89
|
+
if (!existsSync(worktree.path)) {
|
|
90
|
+
return { hasChanges: false };
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
// Check for uncommitted changes in the worktree
|
|
94
|
+
const status = await git(pi, worktree.path, ["status", "--porcelain"], 10000);
|
|
95
|
+
if (status) {
|
|
96
|
+
// Changes exist — stage, commit, and create a branch
|
|
97
|
+
await git(pi, worktree.path, ["add", "-A"], 10000);
|
|
98
|
+
// Truncate description for commit message (no shell sanitization needed — pi.exec uses argv)
|
|
99
|
+
const safeDesc = agentDescription.slice(0, 200);
|
|
100
|
+
const commitMsg = `pi-agent: ${safeDesc}`;
|
|
101
|
+
await git(pi, worktree.path, ["commit", "--no-verify", "-m", commitMsg], 10000);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
const currentSha = await git(pi, worktree.path, ["rev-parse", "HEAD"], 5000);
|
|
105
|
+
if (currentSha === worktree.baseSha) {
|
|
106
|
+
// No changes — remove worktree
|
|
107
|
+
await removeWorktree(pi, cwd, worktree.path);
|
|
108
|
+
return { hasChanges: false };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// Create a branch pointing to the worktree's HEAD.
|
|
112
|
+
// If the branch already exists, append a suffix to avoid overwriting previous work.
|
|
113
|
+
let branchName = worktree.branch;
|
|
114
|
+
try {
|
|
115
|
+
await git(pi, worktree.path, ["branch", branchName], 5000);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
// Branch already exists — use a unique suffix
|
|
119
|
+
branchName = `${worktree.branch}-${Date.now()}`;
|
|
120
|
+
await git(pi, worktree.path, ["branch", branchName], 5000);
|
|
121
|
+
}
|
|
122
|
+
// Update branch name in worktree info for the caller
|
|
123
|
+
worktree.branch = branchName;
|
|
124
|
+
// Remove the worktree (branch persists in main repo)
|
|
125
|
+
await removeWorktree(pi, cwd, worktree.path);
|
|
126
|
+
return {
|
|
127
|
+
hasChanges: true,
|
|
128
|
+
branch: worktree.branch,
|
|
129
|
+
path: worktree.path,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Best effort cleanup on error
|
|
134
|
+
try {
|
|
135
|
+
await removeWorktree(pi, cwd, worktree.path);
|
|
136
|
+
}
|
|
137
|
+
catch { /* ignore */ }
|
|
138
|
+
return { hasChanges: false };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Force-remove a worktree.
|
|
143
|
+
*/
|
|
144
|
+
async function removeWorktree(pi, cwd, worktreePath) {
|
|
145
|
+
try {
|
|
146
|
+
await git(pi, cwd, ["worktree", "remove", "--force", worktreePath], 10000);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// If git worktree remove fails, try pruning
|
|
150
|
+
try {
|
|
151
|
+
await git(pi, cwd, ["worktree", "prune"], 5000);
|
|
152
|
+
}
|
|
153
|
+
catch { /* ignore */ }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Prune any orphaned worktrees (crash recovery).
|
|
158
|
+
*/
|
|
159
|
+
export async function pruneWorktrees(pi, cwd) {
|
|
160
|
+
try {
|
|
161
|
+
await git(pi, cwd, ["worktree", "prune"], 5000);
|
|
162
|
+
}
|
|
163
|
+
catch { /* ignore */ }
|
|
164
|
+
}
|
package/dist/xml.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xml.ts — escaping for the `<task-notification>` payloads.
|
|
3
|
+
*
|
|
4
|
+
* A module of its own because both notification builders need it and they sit
|
|
5
|
+
* on opposite sides of a dependency edge: the agent one lives in `index.ts`,
|
|
6
|
+
* which imports `workflow/task.ts`, so the workflow one cannot reach back for
|
|
7
|
+
* it without a cycle.
|
|
8
|
+
*/
|
|
9
|
+
/** Escape XML special characters to prevent injection in structured notifications. */
|
|
10
|
+
export declare function escapeXml(s: string): string;
|
package/dist/xml.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xml.ts — escaping for the `<task-notification>` payloads.
|
|
3
|
+
*
|
|
4
|
+
* A module of its own because both notification builders need it and they sit
|
|
5
|
+
* on opposite sides of a dependency edge: the agent one lives in `index.ts`,
|
|
6
|
+
* which imports `workflow/task.ts`, so the workflow one cannot reach back for
|
|
7
|
+
* it without a cycle.
|
|
8
|
+
*/
|
|
9
|
+
/** Escape XML special characters to prevent injection in structured notifications. */
|
|
10
|
+
export function escapeXml(s) {
|
|
11
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
12
|
+
}
|
package/docs/FORK.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Local fork provenance and development
|
|
2
|
+
|
|
3
|
+
Audience: developers maintaining `@timmyjl12/pi-subagents` alongside custom Pi extensions.
|
|
4
|
+
|
|
5
|
+
## Provenance
|
|
6
|
+
|
|
7
|
+
- Upstream: https://github.com/tintinweb/pi-subagents
|
|
8
|
+
- Initial baseline: `e955e29` (upstream package 0.19.0).
|
|
9
|
+
- Package: `@timmyjl12/pi-subagents` on npm, first released as `0.20.0`.
|
|
10
|
+
- Repository: `github.com/timmyjl12/pi-subagents` (`origin`). Upstream is kept as the `upstream` remote, and upstream Git history, license and attribution are retained.
|
|
11
|
+
- Local fork maintainer: Tim L / timmyjl12.
|
|
12
|
+
- oh-my-pi is a design reference, not a vendored dependency. Its core focus controller cannot be dropped into stock Pi, which does not expose that private session-focus API.
|
|
13
|
+
|
|
14
|
+
## Intended integration
|
|
15
|
+
|
|
16
|
+
`pi-fallback-chains` owns model recovery. Subagent execution must remain tracked through the whole recovery sequence, including delayed model selection, compaction and replacement turns. Do not add a competing provider retry loop to the subagent manager.
|
|
17
|
+
|
|
18
|
+
Keep public Agent tools, workflow contracts and sibling-extension event consumers intact. Changes to session ownership or event payloads require behavioral integration tests. The shared recovery contract and sibling-extension ownership rules live outside this package, in the workspace that holds the `@timmyjl12/pi-*` extensions.
|
|
19
|
+
|
|
20
|
+
## Development
|
|
21
|
+
|
|
22
|
+
Run in this directory:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
npm ci --ignore-scripts
|
|
26
|
+
npm run check
|
|
27
|
+
npm run test:e2e
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Development dependencies target Pi 1.1.0; the peer floor stays at 0.86.1. Scripted tests should use fake providers, not paid live requests. Report timeout/skipped suites separately. Do not interpret a passing renderer unit test as a visual test in a real terminal.
|
|
31
|
+
|
|
32
|
+
For an isolated manual test, use a fresh `PI_CODING_AGENT_DIR` and a scratch working directory. Explicitly load the local fork and local fallback extension; do not load upstream at the same time. Leave the ordinary global configuration untouched until activation is approved.
|
|
33
|
+
|
|
34
|
+
## Releasing
|
|
35
|
+
|
|
36
|
+
Publish with `npm publish` after `npm run check` passes (`prepublishOnly` also runs lint, typecheck, tests and the build). Use `--tag next` for a prerelease so it never replaces the stable build. Restart Pi rather than hot-replacing extensions while children are active.
|
|
37
|
+
|
|
38
|
+
## Upstream maintenance
|
|
39
|
+
|
|
40
|
+
Review incoming upstream changes against this fork's recovery and UI tests before merging. Avoid renaming established event namespaces merely to change package branding. Preserve original notices for any subsequently copied code; do not assume design inspiration grants permission to omit license attribution.
|
package/docs/recovery.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Child recovery lifecycle
|
|
2
|
+
|
|
3
|
+
`pi-fallback-chains` owns recovery policy whenever present. Subagents observe its optional version-1 lease and offer a bounded standalone target only when local inventory establishes absence. There is no production import of the sibling extension or global current-session pointer.
|
|
4
|
+
|
|
5
|
+
## Lifetime
|
|
6
|
+
|
|
7
|
+
- Each child gets a fresh `createEventBus()` passed to `DefaultResourceLoader`. `ChildRecovery` subscribes before extension loading and attaches the session identity before `bindExtensions()`.
|
|
8
|
+
- Initial prompts, structured-output retries, and resumes wait for both a terminal lease and `session.waitForIdle()`, rechecking the snapshot generation. A delay, model switch, compaction, or replacement prompt is still the same running invocation.
|
|
9
|
+
- Output, usage, turn-limit and abort subscriptions remain active until that wait ends. The manager retains its captured concurrency slot and finalizes output, cleanup, notification and slot release once.
|
|
10
|
+
- The final assistant message determines provider failure, even when recovery compaction changes the history boundary. Effective model/thinking metadata is refreshed from the live session.
|
|
11
|
+
- No provider reply means no observable lease, not absence. There is no recovery timeout, polling, or indefinite wait for a missing producer.
|
|
12
|
+
- Session-owned tool progress attaches before binding/execution, so a later-opened viewer sees ongoing partial results. This one subscription survives normal completion and resumes; session replacement, eviction and disposal release it. Viewer close does not own its cleanup.
|
|
13
|
+
|
|
14
|
+
## Version-1 event contract
|
|
15
|
+
|
|
16
|
+
The child-local bus carries these channels:
|
|
17
|
+
|
|
18
|
+
| Channel | Payload |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| `pi-fallback-chains:recovery` | `{version:1, sessionId, epoch, requestId, revision, phase, pending, model?, reason?}` |
|
|
21
|
+
| `pi-fallback-chains:recovery:query` | `{version:1, sessionId, reply(snapshot)}`; provider replies synchronously only for its session |
|
|
22
|
+
| `pi-fallback-chains:recovery:cancel` | `{version:1, sessionId, reason}` |
|
|
23
|
+
| `pi-fallback-chains:recovery:execution-error` | `{version:1, sessionId, event:"send_user_message", message}` |
|
|
24
|
+
|
|
25
|
+
Pending phases: `pending`, `switching`, `compacting`, `retrying`. Terminal/nonpending phases: `idle`, `settled`, `cancelled`, `failed`. Consumers reject malformed, stale, duplicate, foreign-session and inconsistent request snapshots. Revisions increase across the session; epochs invalidate superseded work.
|
|
26
|
+
|
|
27
|
+
Cancellation is emitted **before** SDK abort, including hard turn limits and already-aborted parent signals. Both compaction and branch-summary aborts are forwarded. Failed extension `send_user_message` submissions are forwarded from `bindExtensions.onError` with a fixed sanitized message, not raw provider errors. Session disposal removes the observer; manager teardown still emits extension `session_shutdown`.
|
|
28
|
+
|
|
29
|
+
The producer must claim its lease synchronously before scheduling recovery, keep it pending through replacement turns, and release it on success, exhaustion, cancellation or failed submission. A void `sendUserMessage()` return is not completion.
|
|
30
|
+
|
|
31
|
+
## Standalone agent fallback
|
|
32
|
+
|
|
33
|
+
Optional agent frontmatter `fallback_model` (alias `fallbackModel`) overrides the default standalone target: the exact parent/orchestrator provider and model identity captured before asynchronous child setup. Omission inherits that captured identity; there is no hardcoded provider or `inherited` sentinel. Managed resumes retain the original target even if the parent changes models. No parent model means no implicit target, and a target equal to the failed child model never causes a redundant retry. Initial execution and its structured-output correction share one attempt; a managed resume starts a new budget. A terminal assistant `stopReason: error` must positively identify a transient provider failure. Authentication, permissions, billing/quota, context, safety, cancellation, tool errors, unknown failures and thrown prompt exceptions do not qualify. Protected terminal failures never cause a structured-output correction either.
|
|
34
|
+
|
|
35
|
+
Ownership is independent of pending work: any valid session protocol snapshot suppresses local recovery even when idle, disabled, failed, cancelled or exhausted. Without a snapshot, the host inspects loaded and pre-filter extension identities, local manifests and entrypoints, global/project settings, additional loader paths and default discovery roots using the loader's `configCwd` and `agentDir`. Disabled/excluded resources and legacy configuration/commands remain evidence of presence. Inventory applies to both explicit and inherited targets; pre-filter evidence is captured for either. Without either target, no standalone inventory is configured. Inventory does not execute code, resolve remote packages, install dependencies, or contact providers.
|
|
36
|
+
|
|
37
|
+
This inventory deliberately fails closed: malformed/unreadable settings, loader errors, missing configured resources, opaque inline resources, unresolved packages and globs are ambiguous. Managed npm packages are inspected locally under the applicable config root's `npm/node_modules`; missing/mismatched manifests and legacy global installs fail closed. Git/URL sources remain ambiguous (no clone/cache resolver is invoked). Local inspection is bounded to 512 paths and 2 MiB per entrypoint; reaching either limit also suppresses fallback. This is not a general package resolver or a proof about arbitrary code renamed to hide its identity.
|
|
38
|
+
|
|
39
|
+
Exact `provider/modelId` targets require an authenticated exact match (including slash/colon model IDs); only shorthand uses the existing fuzzy resolver. An unavailable explicit target never falls back to the inherited default. There is no cross-provider rescue of exact targets, same-model retry, model restore, or implicit chain. Parent `scopedModels` entries, including thinking metadata, are copied into the child. The live child scope and enabled `scopeModels` policy both constrain fallback; the existing primary frontmatter-pin exception remains unchanged.
|
|
40
|
+
|
|
41
|
+
Unpinned children inherit the live parent's thinking level, independently of conversation-context inheritance; an explicit runner option wins over agent configuration, which wins over the parent. Frontmatter locking remains the invocation resolver's responsibility. `off` is an explicit SDK session level, not omission. SDK capability clamping still determines the effective level reported in model metadata.
|
|
42
|
+
|
|
43
|
+
The attempt is consumed before switching. `session.setModel(target, {persist:false})` refreshes effective model metadata and never widens scope or persists defaults. Cancellation, disposal, ownership, live scope and model changes are checked again after switching. One fixed continuation runs in the existing conversation via `session.prompt(..., {source:'extension', expandPromptTemplates:false})`; the original request is never replayed. Unfinished tool calls and failed tool results block this continuation. Existing slot, tracking, usage, output and turn-limit observers remain active through the attempt.
|
|
44
|
+
|
|
45
|
+
## Interactive steering
|
|
46
|
+
|
|
47
|
+
`AgentManager.steerAcknowledged(id, message)` returns a promise resolving true only when SDK steering succeeds or pre-session steering is queued; unavailable/stopped children and SDK rejections return false. It never starts a concurrent prompt. The existing synchronous `steer()` tool contract is unchanged.
|
|
48
|
+
|
|
49
|
+
## Verification
|
|
50
|
+
|
|
51
|
+
From this package directory:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
npm run test -- test/standalone-fallback.test.ts test/recovery-lifecycle.test.ts test/agent-runner.test.ts --maxWorkers=1
|
|
55
|
+
npm run test -- test/foreground-concurrency.test.ts test/background-resume-wiring.test.ts --maxWorkers=1
|
|
56
|
+
npm run typecheck
|
|
57
|
+
npm run lint
|
|
58
|
+
npx tsc --ignoreConfig --noEmit --target ES2022 --module ES2022 --moduleResolution bundler --strict --esModuleInterop --skipLibCheck --allowImportingTsExtensions test/recovery-lifecycle.test.ts test/recovery-producer.integration.ts
|
|
59
|
+
node --experimental-transform-types --test test/recovery-producer.integration.ts
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The lifecycle suite executes the real runner and manager against scripted SDK sessions in isolated temporary working directories. The native integration test requires a sibling `../pi-fallback-chains` checkout and loads its actual factory alongside the actual consumer. It runs separately from Vitest because importing the sibling's SDK tree into the mocked Vitest SDK stalled on Windows. These tests do not contact providers or prove live provider behavior. The standalone/lifecycle tests also exercise installed SDK thinking clamping via a narrow module import, avoiding the provider-catalog bootstrap under the mocked SDK. The additional foreground-concurrency/background-resume command timed out before test results in this Windows checkout (90 seconds, normal configuration, one worker); it is not a pass. Package-wide `npm run check` remains a separate gate.
|
package/docs/rpc.md
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# Driving subagents from another extension
|
|
2
|
+
|
|
3
|
+
Another pi extension can spawn a subagent, listen for subagent completion, read the result and stop the run — all over the `pi.events` bus, without importing this package directly. Four request/reply channels (`subagents:rpc:ping`, `subagents:rpc:spawn`, `subagents:rpc:stop`, `subagents:rpc:consume`), eleven lifecycle events, and one in-process registry at `Symbol.for("pi-subagents:manager")`.
|
|
4
|
+
|
|
5
|
+
The thing worth understanding up front is that **the bus is in-process.** Every "RPC" call here is a synchronous `pi.events.emit` into the same event loop, and every reply comes back the same way. That single fact explains most of what follows: why `signal` and the `on*` callbacks work on a spawn payload at all, why a `consume` fired inside a `subagents:completed` handler lands *before* the notification decision has been made, and why none of this survives a real process boundary.
|
|
6
|
+
|
|
7
|
+
For the channel list, the reply envelope, the per-channel snippets and the event table, see [`README.md`](../README.md#cross-extension-rpc). This document is the reference README does not have room for: the complete spawn-option surface, every error string, the notification race, the registry, and what protocol version `2` does and does not promise.
|
|
8
|
+
|
|
9
|
+
## Child advisor telemetry
|
|
10
|
+
|
|
11
|
+
Updated pi-advisor emits `pi-advisor:status` on each **child-local** event bus, not on the main extension's bus. The runner subscribes before extension binding and stores the latest validated `{ state, models, reviews, lastReviewAt? }` snapshot on `AgentRecord.advisorStatus`; `lastReviewAt` is epoch milliseconds of a successful review. The listener survives primary settlement/resume and is released during child shutdown. This is an observational integration, not a new `subagents:rpc:*` request or top-level lifecycle broadcast. Missing snapshots mean unavailable; explicit `advisor: false` supplies an OFF snapshot even though the advisor extension is excluded.
|
|
12
|
+
|
|
13
|
+
## Spawn options
|
|
14
|
+
|
|
15
|
+
`subagents:rpc:spawn` forwards `options` to `AgentManager.spawn` — but not verbatim. The manager's `spawn` behind the RPC is `spawnTopLevel` (`src/index.ts:698-721`), which deletes internal-only fields first, and then `spawnResolved` (`src/index.ts:666-696`) overwrites the activity-tracker callbacks with its own. The full interface is `SpawnOptions` at `src/agent-manager.ts:169-303`; what a bus caller actually gets is three different things.
|
|
16
|
+
|
|
17
|
+
**Honoured** — set these and they take effect:
|
|
18
|
+
|
|
19
|
+
| Field | Type | Notes |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| `description` | string | What the agent is doing. Shown in the widget, FleetView and the completion notification |
|
|
22
|
+
| `name` | string | A memorable second handle (`@auth-audit`). Slugged, never validated — anything unusable degrades rather than failing the spawn |
|
|
23
|
+
| `model` | `Model` **or** `"provider/modelId"` | Strings are resolved at the RPC boundary against `ctx.modelRegistry`. `null` means inherit, not override. Resolution is fuzzy — see [Model Scope](../README.md#model-scope) |
|
|
24
|
+
| `maxTurns` | number | Turn ceiling for the run |
|
|
25
|
+
| `isolated` | boolean | Strips extensions, skills and nested tools. **Not** a git worktree — see the trap table below |
|
|
26
|
+
| `inheritContext` | boolean | Fork the parent conversation into the child |
|
|
27
|
+
| `thinkingLevel` | ThinkingLevel | Clamped to what the resolved model supports |
|
|
28
|
+
| `isBackground` | boolean | Occupies a `maxConcurrent` slot and queues behind them. Every RPC spawn runs detached regardless; this is what decides whether it is *pooled* |
|
|
29
|
+
| `bypassQueue` | boolean | Starts immediately even when the concurrency limit would queue it. The slot is still counted once running |
|
|
30
|
+
| `structuredOutput` | CompiledSchema | Makes the child report through a `StructuredOutput` tool |
|
|
31
|
+
| `isolation` | `"worktree"` | Temp git worktree, committed to a `pi-agent-*` branch on completion |
|
|
32
|
+
| `cwd` | absolute path | The agent's tools operate here; `.pi` config still loads from the parent session's project |
|
|
33
|
+
| `invocation` | AgentInvocation | Resolved snapshot used for UI display |
|
|
34
|
+
| `signal` | AbortSignal | Aborting it stops the subagent |
|
|
35
|
+
| `onSpawned` / `onQueued` / `onCompaction` / `onBeforeWorktreeCleanup` | functions | Fire as documented on `SpawnOptions` |
|
|
36
|
+
|
|
37
|
+
`onBeforeWorktreeCleanup(worktreePath, terminalStatus)` receives the computed child outcome while its worktree still exists; the live record remains `running` until cleanup finishes.
|
|
38
|
+
|
|
39
|
+
**Silently stripped** — set these and nothing happens, with no error and no note. Each deletion is a deliberate guard, and the reasons are worth knowing because they say what the surface refuses to let a caller forge:
|
|
40
|
+
|
|
41
|
+
| Field | Why it is taken away |
|
|
42
|
+
|---|---|
|
|
43
|
+
| `parentAgentId` | Ownership. A forged parent hides your agent under someone else's nested tools |
|
|
44
|
+
| `workflowId` | A forged value would hide an RPC-spawned agent inside someone else's workflow — and take it out of the concurrency pool with it |
|
|
45
|
+
| `depth`, `maxSubagentDepth` | The nesting cap is inherited, not declared |
|
|
46
|
+
| `configCwd` | Config-discovery root; only nested launches may set it |
|
|
47
|
+
| `rootSessionId` | Names a transcript directory, so a forged value is a path-traversal primitive |
|
|
48
|
+
| `resumeSessionFile` | Worse: it names a file to **open and replay** as a conversation. Dispatcher only, and only from a path this extension itself recorded |
|
|
49
|
+
| `reclaim` | Bypasses handle allocation, so a forged value would duplicate a live agent's name and make `@handle` ambiguous |
|
|
50
|
+
| `blocking` | Every spawn through here is detached. A forged `blocking` would charge it to the foreground pool and defer it behind a queue whose gate nobody is holding |
|
|
51
|
+
|
|
52
|
+
**Silently overwritten** — `onToolActivity`, `onTextDelta`, `onTurnEnd`, `onSessionCreated` and `onAssistantUsage` are replaced by the activity tracker's own (`src/index.ts:693`). Every programmatic spawn passes through one funnel so none can supply half-wired callbacks; a half-wired tracker renders worse than none, which is the bug behind a row that reads `thinking…` for an agent's whole life ([#181](https://github.com/tintinweb/pi-subagents/pull/181)).
|
|
53
|
+
|
|
54
|
+
Four things that are not obvious from the tables:
|
|
55
|
+
|
|
56
|
+
- **Nothing is required at runtime.** `description` is non-optional in TypeScript and never validated. A spawn with no `options` at all is legal and is what `test/cross-extension-rpc.test.ts:81-94` pins.
|
|
57
|
+
- **`bypassQueue` is not stripped.** Its own doc comment scopes it to the scheduler and the `/agents` generator, but a bus caller can set it and skip the `maxConcurrent` check.
|
|
58
|
+
- **`structuredOutput` is documented "set only by the workflow host"** (`src/agent-manager.ts:231-234`) and is also not stripped.
|
|
59
|
+
- **`signal` and the `on*` callbacks are function values.** They work only because the bus is in-process. A caller that genuinely serializes its payload cannot use them, and they arrive as `undefined` rather than failing.
|
|
60
|
+
|
|
61
|
+
### Names that look right and are not
|
|
62
|
+
|
|
63
|
+
One of these already shipped as a bug in this project's own README example, so it is worth reading the table even if you are sure.
|
|
64
|
+
|
|
65
|
+
| You might write | What it does | What you meant |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `run_in_background` | Forwarded verbatim and ignored — it is the [`Agent`](../README.md#agent) *tool's* parameter name | `isBackground` |
|
|
68
|
+
| `isolated: true` | Disables extensions, skills and nested tools | `isolation: "worktree"` for a git worktree |
|
|
69
|
+
| `isolation: "worktree"` | Creates a git worktree | `isolated: true` to strip capabilities |
|
|
70
|
+
| `configCwd` | Stripped | `cwd` |
|
|
71
|
+
| `max_turns` / `thinking` / `inherit_context` | Ignored — tool and frontmatter spellings | `maxTurns` / `thinkingLevel` / `inheritContext` |
|
|
72
|
+
| `memory` | Nothing. **There is no such option** | Memory scope comes only from the agent definition's frontmatter |
|
|
73
|
+
|
|
74
|
+
**None of these produce an error.** Option keys are not validated on this path at all — unknown ones are accepted and dropped. (Contrast `agent()` inside a [workflow](workflows.md), which rejects unknown keys by name.)
|
|
75
|
+
|
|
76
|
+
## Errors
|
|
77
|
+
|
|
78
|
+
Every failure reaches the caller as `{ success: false, error }`, where `error` is `err?.message ?? String(err)` (`src/cross-extension-rpc.ts:87`) — so these strings are what you will actually see.
|
|
79
|
+
|
|
80
|
+
| Error | Source |
|
|
81
|
+
|---|---|
|
|
82
|
+
| `No active session` | `src/cross-extension-rpc.ts:107` — called before the first bound `session_start`, or in a session that excludes pi-subagents |
|
|
83
|
+
| `Model override "<label>" provided but ctx.modelRegistry is unavailable` | `src/cross-extension-rpc.ts:126` |
|
|
84
|
+
| `Model not found: "<input>".` + available models | `src/model-resolver.ts:117` |
|
|
85
|
+
| `Model not in scope: "<input>".` + allowed models | `src/model-scope.ts:62` — only with `scopeModels` on, and checked against the *resolved* model |
|
|
86
|
+
| `Unknown or disabled agent type: "<raw>". Available: <list>.` | `src/agent-types.ts:187` — only under `fallbackSubagent: none` |
|
|
87
|
+
| `No agent type given. Available: <list>.` | `src/agent-types.ts:187-194` — same condition |
|
|
88
|
+
| `<reason> The configured fallbackSubagent "<x>" is itself unknown or disabled. Available: <list>.` | `src/agent-types.ts:205-207` |
|
|
89
|
+
| `SpawnOptions.cwd must be an absolute path: "<value>"` | `src/agent-manager.ts:85` |
|
|
90
|
+
| `SpawnOptions.cwd does not exist: "<cwd>"` | `src/agent-manager.ts:91` |
|
|
91
|
+
| `SpawnOptions.cwd is not a directory: "<cwd>"` | `src/agent-manager.ts:94` |
|
|
92
|
+
| `Cannot run with isolation: "worktree" — not a git repo, no commits yet, or 'git worktree add' failed.` | `src/agent-manager.ts:716-719`, surfaced through `awaitStartup` |
|
|
93
|
+
| git plumbing failures | `src/worktree.ts:76` |
|
|
94
|
+
| `Agent not found` | stop — `src/cross-extension-rpc.ts:170` |
|
|
95
|
+
| `Agent is owned by another agent or workflow` | stop — `:178` |
|
|
96
|
+
| `Agent is not running` | stop — `:182`. The record exists, so it has already settled |
|
|
97
|
+
| `Agent not found or still running` | consume — `:193` |
|
|
98
|
+
|
|
99
|
+
Three things the table cannot show:
|
|
100
|
+
|
|
101
|
+
- **The failure that is not an error.** With `worktreeIsolation` off project-wide, `isolation: "worktree"` is dropped at `src/agent-manager.ts:712` with no error, no note on the record, and a success envelope on the wire. Your agent runs in the main tree. If you asked for isolation because two agents were going to write the same files, they now collide and nothing told you.
|
|
102
|
+
- **`data` is omitted** when a handler returns nothing, so a successful stop or consume reply is a bare `{ success: true }` and `reply.data.anything` throws.
|
|
103
|
+
- **`requestId` is not validated.** It is interpolated straight into the reply channel, so a caller that omits it gets its reply on the literal channel `subagents:rpc:spawn:reply:undefined` — where every other caller that omitted it is also listening. Send one, and send a unique one.
|
|
104
|
+
|
|
105
|
+
## Ownership
|
|
106
|
+
|
|
107
|
+
`isTopLevelAgent(record)` is `parentAgentId === undefined && workflowId === undefined` (`src/agent-manager.ts:122-126`). `subagents:rpc:stop` enforces it (`src/cross-extension-rpc.ts:178`): a nested child or a workflow's agent is owned by something that is *waiting on it*, and aborting it out from under that owner turns another extension's stop into a failed step. It is defence in depth rather than a live hole — no RPC hands out agent ids, so a caller has no ordinary way to name one it does not own.
|
|
108
|
+
|
|
109
|
+
Two asymmetries to know about, stated as they are:
|
|
110
|
+
|
|
111
|
+
- **Stop takes an id only** (`src/index.ts:806`). Consume takes an id *or* an `@handle`, through `resolveAgentRef` (`src/index.ts:816` → `:731-736`).
|
|
112
|
+
- **Consume checks `parentAgentId` but not `workflowId`** (`src/index.ts:816`). A workflow-owned agent's result can be marked consumed over the bus even though the same agent cannot be stopped.
|
|
113
|
+
|
|
114
|
+
The same predicate silently scopes the events. **Every lifecycle event is top-level only** — `subagents:started`, `:completed`, `:failed` and `:compacted` all return early for nested and workflow-owned agents (`src/index.ts:573`, `:615`, `:631`). A workflow's children are invisible on the bus: you will see the workflow's own agents come and go without a single event.
|
|
115
|
+
|
|
116
|
+
## The notification race
|
|
117
|
+
|
|
118
|
+
When a background agent finishes, pi-subagents sends the user a completion notification. If you have already shown the model that result yourself, that notification arrives on top of an answer that was already given, and it costs the parent a turn to dismiss. `subagents:rpc:consume` is how you say you have handled it — the bus-side half of what `get_subagent_result` does when it returns a result.
|
|
119
|
+
|
|
120
|
+
**When you send it decides whether it works.** The timeline:
|
|
121
|
+
|
|
122
|
+
1. The agent settles and `subagents:completed` is emitted — `src/index.ts:581`.
|
|
123
|
+
2. Eleven lines later, at `src/index.ts:592`, the code checks `record.resultConsumed` and decides whether to notify at all.
|
|
124
|
+
3. `pi.events` dispatch is synchronous and in-process, so a handler that emits `subagents:rpc:consume` **without awaiting anything** has already set that flag before step 2 evaluates.
|
|
125
|
+
|
|
126
|
+
| When you consume | What happens |
|
|
127
|
+
|---|---|
|
|
128
|
+
| Synchronously, inside your `subagents:completed` handler | The notification is never scheduled. This is the clean path |
|
|
129
|
+
| After an `await`, within 200 ms | Still suppressed. The nudge is held for `NUDGE_HOLD_MS` (`src/index.ts:451`), `consume` cancels the pending timer (`:819`), and there is a re-check at send time (`:474`) |
|
|
130
|
+
| After 200 ms | Too late. The follow-up has fired with `triggerTurn: true` and cost the parent a turn |
|
|
131
|
+
|
|
132
|
+
Fire-and-forget is the intended use: the reply carries nothing to act on, and the channel sits outside the `subagents:rpc:ping` version handshake on purpose (`src/cross-extension-rpc.ts:190`), so you can send it unconditionally and an older pi-subagents with no handler simply keeps notifying.
|
|
133
|
+
|
|
134
|
+
Consumption is not terminal. An `@handle` steer un-consumes the record (`src/index.ts:920`) because the agent's reply to that message still needs relaying, and so does a background resume (`src/agent-manager.ts:1135`) because the record is starting a new run.
|
|
135
|
+
|
|
136
|
+
One related thing that lives nowhere else: on every top-level settle, pi-subagents writes a session entry — not an event — via `pi.appendEntry("subagents:record", …)` (`src/index.ts:585`), carrying `id`, `type`, `description`, `status`, `result`, `error`, `startedAt` and `completedAt`. It exists for cross-extension history reconstruction. It is append-only history, not something to react to.
|
|
137
|
+
|
|
138
|
+
## The manager registry
|
|
139
|
+
|
|
140
|
+
`globalThis[Symbol.for("pi-subagents:manager")]` (`src/index.ts:649-659`) is a second integration surface — the standard Node cross-package singleton pattern, no bus involved:
|
|
141
|
+
|
|
142
|
+
| Member | Signature | Notes |
|
|
143
|
+
|---|---|---|
|
|
144
|
+
| `waitForAll()` | `() => Promise<void>` | Resolves when nothing is running. **All** agents, including ones you did not spawn — a shutdown barrier, not a join |
|
|
145
|
+
| `hasRunning()` | `() => boolean` | |
|
|
146
|
+
| `spawn(pi, ctx, type, prompt, options)` | `=> string` | **Is** `spawnTopLevel`, so the strip list above applies identically |
|
|
147
|
+
| `getRecord(id)` | `=> AgentRecord \| undefined` | Filtered through `isTopLevelAgent`, so someone else's child comes back `undefined` rather than leaking |
|
|
148
|
+
|
|
149
|
+
The slot is claimed by the first activation only; subagent sessions re-activate this extension in the same process, and unconditionally overwriting would point the registry at a short-lived child manager whose shutdown would then delete the root session's entry ([#128](https://github.com/tintinweb/pi-subagents/pull/128)). Child activations leave it alone, and shutdown releases it only if this activation claimed it (`src/index.ts:747-750`, `:1105-1107`).
|
|
150
|
+
|
|
151
|
+
Prefer the bus. The registry has no reply envelope, no version, and no availability event — `globalThis[Symbol.for("pi-subagents:manager")] === undefined` is the only probe you get, and it is also `undefined` in a session that filtered pi-subagents out. Reach for it for the two things the bus has no verb for — *is anything still running*, and *give me a settled record back* — or for a headless host that wants to block on `waitForAll()` before exiting.
|
|
152
|
+
|
|
153
|
+
## Protocol versions
|
|
154
|
+
|
|
155
|
+
`subagents:rpc:ping` replies `{ version: PROTOCOL_VERSION }`, currently `2` (`src/cross-extension-rpc.ts:33`). The constant was introduced already equal to `2` in 0.5.0; "v1" is a retroactive name for the pre-envelope contract, where spawn replied with a bare `{ id }` or `{ error }`, stop replied `{ success: boolean }` with no message, and each handler caught its own errors.
|
|
156
|
+
|
|
157
|
+
Everything added since shipped **without a bump**, because all of it is additive: stop's ownership refusal, string-`model` resolution ([#59](https://github.com/tintinweb/pi-subagents/pull/59)/[#60](https://github.com/tintinweb/pi-subagents/issues/60)), `scopeModels` enforcement ([#240](https://github.com/tintinweb/pi-subagents/issues/240)), and the whole `consume` channel.
|
|
158
|
+
|
|
159
|
+
> A `ping` that answers `2` does not tell you whether `consume` exists, whether model scope is enforced, or whether stop checks ownership.
|
|
160
|
+
|
|
161
|
+
So: send `consume` unconditionally and ignore the outcome — an older build has no handler and simply keeps notifying, which is exactly why it was left outside the handshake. And treat every error envelope as authoritative rather than trying to predict which checks are in force.
|
|
162
|
+
|
|
163
|
+
## Availability
|
|
164
|
+
|
|
165
|
+
`subagents:ready` is the discovery signal, and both the RPC handlers and the event itself are wired on the first bound `session_start` (`src/index.ts:789`, `:799`, `:827`) — deliberately not at factory time. pi runs every extension factory *before* applying an agent's `extensions:` filter and only delivers lifecycle events to the survivors, so a factory-time broadcast made a filtered-out session advertise a spawn service it could never provide: `ping` succeeded and every `spawn` answered `No active session` ([#142](https://github.com/tintinweb/pi-subagents/issues/142)).
|
|
166
|
+
|
|
167
|
+
The consequence is worth stating plainly: **a session that excludes pi-subagents is indistinguishable from pi-subagents not being installed.** It emits no `subagents:ready` and answers nothing. Give discovery a timeout and treat expiry as "not available here" rather than waiting indefinitely. The payload is `{}` — read nothing off it. Handlers are torn down and the flag reset on `session_shutdown` (`src/index.ts:1100-1103`), so a later `session_start` re-registers and re-emits.
|
|
168
|
+
|
|
169
|
+
One more trap on the way in: an RPC-spawned agent emits **no `subagents:created`**. The only two emit sites are the `Agent` tool's background branch (`src/index.ts:2104`) and detached resume (`:1350`). Your first event for your own agent is `subagents:started` (`:625`), so key your bookkeeping off the id that `spawn` handed you, not off `subagents:created`.
|
|
170
|
+
|
|
171
|
+
## What the tests pin
|
|
172
|
+
|
|
173
|
+
This document has no test of its own, so it is worth knowing which claims are actually held in place:
|
|
174
|
+
|
|
175
|
+
| Test | Level | Pins |
|
|
176
|
+
|---|---|---|
|
|
177
|
+
| `test/cross-extension-rpc.test.ts` | Mocked `SpawnCapable` | Envelope shape, per-channel error strings, model resolution and scope enforcement |
|
|
178
|
+
| `test/rpc-lifecycle-gating.test.ts` | Real extension factory | Nothing wired at factory time, everything once at `session_start`, and live widget activity for RPC spawns ([#142](https://github.com/tintinweb/pi-subagents/issues/142)/[#181](https://github.com/tintinweb/pi-subagents/pull/181)) |
|
|
179
|
+
| `test/rpc-result-consumption.test.ts` | Real delivery path | The notification firing, and not firing, around `consume` |
|
|
180
|
+
|
|
181
|
+
Not pinned anywhere, so treat them as descriptions rather than contracts: the `SpawnOptions.cwd` error strings, `subagents:ready`'s `{}` payload, consume's handle resolution, and its missing `workflowId` check.
|
|
182
|
+
|
|
183
|
+
## Reference implementation
|
|
184
|
+
|
|
185
|
+
[**`tintinweb/pi-tasks`**](https://github.com/tintinweb/pi-tasks) is the working integration and the one this surface was shaped by. Its `TaskExecute` drives `subagents:rpc:spawn` — including the serialized `"provider/modelId"` string form that the boundary now resolves — and its `TaskOutput` drives `subagents:rpc:consume`, which exists because pi-tasks joins an agent on `subagents:completed` and reports the result itself ([pi-tasks#62](https://github.com/tintinweb/pi-tasks/issues/62)).
|
|
186
|
+
|
|
187
|
+
Read it for the shape of the whole loop: waiting on `subagents:ready`, keeping an id-keyed map of outstanding spawns, resolving each from the `subagents:completed` / `subagents:failed` handler, and consuming the result in the same synchronous handler that reports it.
|
|
188
|
+
|
|
189
|
+
If what you want is many coordinated agents rather than one, hand a script to [`SubagentWorkflow`](workflows.md) instead of fanning out over `subagents:rpc:spawn` — and note that a workflow's agents are not yours: they emit no lifecycle events, and `subagents:rpc:stop` refuses them.
|