@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,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* output-file.ts — Streaming JSONL output file for agent transcripts.
|
|
3
|
+
*
|
|
4
|
+
* Creates a per-agent output file that streams conversation turns as JSONL,
|
|
5
|
+
* matching Claude Code's task output file format.
|
|
6
|
+
*/
|
|
7
|
+
import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { appendFile } from "node:fs/promises";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { logSubagentIssue } from "./error-log.js";
|
|
12
|
+
import { assistantDiagnosticContext, sanitizeDiagnosticText } from "./output-diagnostics.js";
|
|
13
|
+
/**
|
|
14
|
+
* Project/global default for writing a subagent's `.output` transcript; a custom
|
|
15
|
+
* agent's `output_transcript` overrides it per agent.
|
|
16
|
+
*
|
|
17
|
+
* State lives here rather than in an index.ts closure because both spawn paths
|
|
18
|
+
* need it — the top-level Agent tool and the nested delegation tools. Same
|
|
19
|
+
* reason `scopeModels` lives in model-scope.ts: a setting only one path can read
|
|
20
|
+
* is a setting the other path silently ignores.
|
|
21
|
+
*/
|
|
22
|
+
let outputTranscriptDefault = true;
|
|
23
|
+
export function getOutputTranscriptDefault() { return outputTranscriptDefault; }
|
|
24
|
+
export function setOutputTranscriptDefault(b) { outputTranscriptDefault = b; }
|
|
25
|
+
/**
|
|
26
|
+
* Encode a cwd path as a filesystem-safe directory name. Handles:
|
|
27
|
+
* - POSIX: "/home/user/project" → "home-user-project"
|
|
28
|
+
* - Windows: "C:\Users\foo\project" → "Users-foo-project"
|
|
29
|
+
* - UNC: "\\\\server\\share\\project" → "server-share-project"
|
|
30
|
+
*/
|
|
31
|
+
export function encodeCwd(cwd) {
|
|
32
|
+
return cwd
|
|
33
|
+
.replace(/[/\\]/g, "-") // both separators → dash
|
|
34
|
+
.replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
|
|
35
|
+
.replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The per-session scratch directory, created if missing.
|
|
39
|
+
* Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
|
|
40
|
+
*
|
|
41
|
+
* Shared with the workflow tool, which persists each invocation's script here so
|
|
42
|
+
* iterating on one is edit-file-then-rerun — the same convention, one directory.
|
|
43
|
+
*/
|
|
44
|
+
export function sessionTaskDir(cwd, sessionId) {
|
|
45
|
+
const encoded = encodeCwd(cwd);
|
|
46
|
+
const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
|
|
47
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
48
|
+
// chmod is a no-op on Windows and throws on some Windows filesystems.
|
|
49
|
+
// On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
|
|
50
|
+
try {
|
|
51
|
+
chmodSync(root, 0o700);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
if (process.platform !== "win32")
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
const dir = join(root, encoded, sessionId, "tasks");
|
|
58
|
+
mkdirSync(dir, { recursive: true });
|
|
59
|
+
return dir;
|
|
60
|
+
}
|
|
61
|
+
/** Create the output file path, ensuring the directory exists. */
|
|
62
|
+
export function createOutputFilePath(cwd, agentId, sessionId) {
|
|
63
|
+
return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Ensure a transcript file exists without disturbing what is already in it.
|
|
67
|
+
*
|
|
68
|
+
* A resume reuses the agent's existing transcript (same deterministic path), so
|
|
69
|
+
* it must never call `writeInitialEntry` — that truncates, discarding turns the
|
|
70
|
+
* completion notification still points the user at, and any history the session
|
|
71
|
+
* has since compacted away is gone for good. Appending nothing creates the file
|
|
72
|
+
* when this is the agent's first transcript and is a no-op when it is not.
|
|
73
|
+
*/
|
|
74
|
+
export function ensureOutputFile(path) {
|
|
75
|
+
try {
|
|
76
|
+
appendFileSync(path, "", "utf-8");
|
|
77
|
+
}
|
|
78
|
+
catch { /* ignore — streaming writes are best-effort too */ }
|
|
79
|
+
}
|
|
80
|
+
/** Write the initial user prompt entry. */
|
|
81
|
+
export function writeInitialEntry(path, agentId, prompt, cwd) {
|
|
82
|
+
const entry = {
|
|
83
|
+
isSidechain: true,
|
|
84
|
+
agentId,
|
|
85
|
+
type: "user",
|
|
86
|
+
message: { role: "user", content: prompt },
|
|
87
|
+
timestamp: new Date().toISOString(),
|
|
88
|
+
cwd,
|
|
89
|
+
};
|
|
90
|
+
writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Serialized write chains for transcript files: at most one in-flight append
|
|
94
|
+
* per file. A drain coalesces everything queued while it writes — a burst of
|
|
95
|
+
* finalized messages costs one append syscall per batch, not per message — and
|
|
96
|
+
* a resume subscribing a second stream to the same transcript chains after the
|
|
97
|
+
* previous stream's pending writes instead of interleaving with them.
|
|
98
|
+
*/
|
|
99
|
+
const writeChains = new Map();
|
|
100
|
+
function chainWrite(path, run) {
|
|
101
|
+
const chained = (writeChains.get(path) ?? Promise.resolve()).then(run);
|
|
102
|
+
writeChains.set(path, chained);
|
|
103
|
+
void chained.finally(() => {
|
|
104
|
+
if (writeChains.get(path) === chained)
|
|
105
|
+
writeChains.delete(path);
|
|
106
|
+
});
|
|
107
|
+
return chained;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Wait until every queued write to one transcript file has landed. Resolves
|
|
111
|
+
* immediately when the file is idle; the stream cleanup function returns it
|
|
112
|
+
* so a caller can await the final flush.
|
|
113
|
+
*/
|
|
114
|
+
export function drainOutputFile(path) {
|
|
115
|
+
return writeChains.get(path) ?? Promise.resolve();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Persist finalized events before retries can remove them from session.messages.
|
|
119
|
+
* Snapshot flushes also preserve eventless SDK additions (e.g. bashExecution).
|
|
120
|
+
* Lines are stringified at event time but written through an async per-file
|
|
121
|
+
* queue (see chainWrite), so message-sized JSON work never blocks the loop.
|
|
122
|
+
* Returns an idempotent final flush/unsubscribe that resolves once the flushed
|
|
123
|
+
* writes are on disk; never changes retry policy.
|
|
124
|
+
*/
|
|
125
|
+
export function streamToOutputFile(session, path, agentId, cwd, startIndex,
|
|
126
|
+
// Best-effort label for the central error log. Only call sites that know the
|
|
127
|
+
// agent type pass it (the index.ts spawn paths); nested-tools.ts does not,
|
|
128
|
+
// so central-log records from that path carry agentId/session names only.
|
|
129
|
+
agentType) {
|
|
130
|
+
const initial = session.messages;
|
|
131
|
+
// A resume supplies its pre-run boundary. Existing history on a reopened
|
|
132
|
+
// session is not new output either. Identity, not content/timestamp, keeps
|
|
133
|
+
// independent identical failures while deduplicating event + safety flush.
|
|
134
|
+
const seen = new WeakSet(initial.slice(0, startIndex ?? initial.length));
|
|
135
|
+
// writeInitialEntry already wrote the spawn prompt. New SDKs emit a system
|
|
136
|
+
// declaration first, so skipping array slot zero would duplicate the user.
|
|
137
|
+
let skipInitialUser = startIndex === undefined && !initial.some(msg => msg.role === "user");
|
|
138
|
+
let lastAssistant;
|
|
139
|
+
let closed = false;
|
|
140
|
+
// Queued lines are stringified at event time — messages are live SDK state,
|
|
141
|
+
// and a write must snapshot the finalized message, not a later mutation. The
|
|
142
|
+
// drain coalesces everything queued while a write is in flight.
|
|
143
|
+
let batch = [];
|
|
144
|
+
let draining = false;
|
|
145
|
+
const drain = async () => {
|
|
146
|
+
try {
|
|
147
|
+
while (batch.length > 0) {
|
|
148
|
+
const chunk = batch;
|
|
149
|
+
batch = [];
|
|
150
|
+
try {
|
|
151
|
+
await appendFile(path, chunk.join(""), "utf-8");
|
|
152
|
+
}
|
|
153
|
+
catch { /* best-effort file output; never write raw errors into the TUI */ }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
draining = false;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
const append = (fields) => {
|
|
161
|
+
let line;
|
|
162
|
+
try {
|
|
163
|
+
line = JSON.stringify({
|
|
164
|
+
isSidechain: true, agentId, ...fields, timestamp: new Date().toISOString(), cwd,
|
|
165
|
+
}) + "\n";
|
|
166
|
+
}
|
|
167
|
+
catch { /* best-effort file output; never write raw errors into the TUI */
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
batch.push(line);
|
|
171
|
+
if (!draining) {
|
|
172
|
+
draining = true;
|
|
173
|
+
void chainWrite(path, drain);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
const capture = (msg) => {
|
|
177
|
+
if (seen.has(msg) || (msg.role === "assistant" && msg.stopReason === "pending"))
|
|
178
|
+
return;
|
|
179
|
+
seen.add(msg);
|
|
180
|
+
if (msg.role === "user" && skipInitialUser) {
|
|
181
|
+
skipInitialUser = false;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
append({
|
|
185
|
+
type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
|
|
186
|
+
// Keep normal content/usage intact. Don't duplicate a credential-bearing
|
|
187
|
+
// error in the regular row beside its sanitized diagnostic, or mutate SDK state.
|
|
188
|
+
message: msg.role === "assistant" && msg.errorMessage !== undefined
|
|
189
|
+
? { ...msg, errorMessage: sanitizeDiagnosticText(msg.errorMessage) }
|
|
190
|
+
: msg,
|
|
191
|
+
});
|
|
192
|
+
if (msg.role === "assistant") {
|
|
193
|
+
lastAssistant = assistantDiagnosticContext(msg);
|
|
194
|
+
if (msg.stopReason === "error" || msg.stopReason === "aborted") {
|
|
195
|
+
const errorMessage = sanitizeDiagnosticText(msg.errorMessage);
|
|
196
|
+
append({ type: "diagnostic", diagnostic: {
|
|
197
|
+
event: msg.stopReason === "error" ? "assistant_error" : "assistant_aborted",
|
|
198
|
+
...lastAssistant, errorMessage, attempt: session.retryAttempt,
|
|
199
|
+
} });
|
|
200
|
+
// Same event in the persistent cross-session aggregate (see error-log.ts).
|
|
201
|
+
logSubagentIssue({ kind: "attempt_error", agentId, agentType, ...lastAssistant,
|
|
202
|
+
errorMessage, attempt: session.retryAttempt });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
const flush = () => { for (const msg of session.messages)
|
|
207
|
+
capture(msg); };
|
|
208
|
+
const unsubscribe = session.subscribe((event) => {
|
|
209
|
+
if (closed)
|
|
210
|
+
return;
|
|
211
|
+
if (event.type === "message_end")
|
|
212
|
+
capture(event.message);
|
|
213
|
+
if (event.type === "auto_retry_start") {
|
|
214
|
+
const errorMessage = sanitizeDiagnosticText(event.errorMessage);
|
|
215
|
+
append({ type: "diagnostic", diagnostic: {
|
|
216
|
+
event: event.type, ...lastAssistant, attempt: event.attempt, maxAttempts: event.maxAttempts,
|
|
217
|
+
delayMs: event.delayMs, errorMessage,
|
|
218
|
+
} });
|
|
219
|
+
logSubagentIssue({ kind: "retry_start", agentId, agentType, ...lastAssistant,
|
|
220
|
+
attempt: event.attempt, maxAttempts: event.maxAttempts, delayMs: event.delayMs, errorMessage });
|
|
221
|
+
}
|
|
222
|
+
if (event.type === "auto_retry_end") {
|
|
223
|
+
const finalError = sanitizeDiagnosticText(event.finalError);
|
|
224
|
+
append({ type: "diagnostic", diagnostic: {
|
|
225
|
+
event: event.type, ...lastAssistant, attempt: event.attempt, success: event.success,
|
|
226
|
+
finalError,
|
|
227
|
+
} });
|
|
228
|
+
logSubagentIssue({ kind: "retry_end", agentId, agentType, ...lastAssistant,
|
|
229
|
+
attempt: event.attempt, success: event.success, finalError });
|
|
230
|
+
}
|
|
231
|
+
if (event.type === "turn_end" || event.type === "compaction_start")
|
|
232
|
+
flush();
|
|
233
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
234
|
+
// Restored messages may be new objects. Mark the rebuilt history without
|
|
235
|
+
// writing it again; a subsequent overflow trim cannot strand this set.
|
|
236
|
+
for (const msg of session.messages)
|
|
237
|
+
seen.add(msg);
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
return () => {
|
|
241
|
+
if (closed)
|
|
242
|
+
return drainOutputFile(path);
|
|
243
|
+
closed = true;
|
|
244
|
+
unsubscribe();
|
|
245
|
+
flush();
|
|
246
|
+
return drainOutputFile(path);
|
|
247
|
+
};
|
|
248
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* prompts.ts — System prompt builder for agents.
|
|
3
|
+
*/
|
|
4
|
+
import type { AgentConfig, EnvInfo } from "./types.js";
|
|
5
|
+
/** Extra sections to inject into the system prompt (memory, skills, etc.). */
|
|
6
|
+
export interface PromptExtras {
|
|
7
|
+
/** Persistent memory content to inject (first 200 lines of MEMORY.md + instructions). */
|
|
8
|
+
memoryBlock?: string;
|
|
9
|
+
/**
|
|
10
|
+
* Built-in pin fallback notice (Explore/Plan pin named an unavailable
|
|
11
|
+
* provider, so the parent model is driving). Surfaced in the child's
|
|
12
|
+
* context so the substitution is visible, not silent.
|
|
13
|
+
*/
|
|
14
|
+
pinFallbackNotice?: string;
|
|
15
|
+
/** Preloaded skill contents to inject. */
|
|
16
|
+
skillBlocks?: {
|
|
17
|
+
name: string;
|
|
18
|
+
content: string;
|
|
19
|
+
}[];
|
|
20
|
+
/**
|
|
21
|
+
* Parent directory the worktree copy was created from. Set only for
|
|
22
|
+
* `isolation: "worktree"` spawns — triggers the block that tells the agent
|
|
23
|
+
* to stay in the copy.
|
|
24
|
+
*/
|
|
25
|
+
worktreeBase?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Set only for a workflow's own children, and only when they have no
|
|
28
|
+
* `StructuredOutput` tool to answer through.
|
|
29
|
+
*
|
|
30
|
+
* A workflow child's final text is not read by a human — it is the value
|
|
31
|
+
* `agent()` resolves to, and the script interpolates it straight into the
|
|
32
|
+
* next stage's prompt. Without this, children answer the way every other
|
|
33
|
+
* subagent does (a report addressed to a reader), and the padding becomes
|
|
34
|
+
* input tokens for the stage downstream. Claude Code's `Workflow` tool
|
|
35
|
+
* documents this contract to the script-writing model; this is the end of it
|
|
36
|
+
* that makes the documentation true.
|
|
37
|
+
*
|
|
38
|
+
* Deliberately NOT applied to every subagent. In pi an ordinary agent's
|
|
39
|
+
* output IS read by a human — through FleetView, the conversation viewer and
|
|
40
|
+
* `get_subagent_result` — so terse raw data would be the wrong answer there.
|
|
41
|
+
*/
|
|
42
|
+
workflowChild?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Build the system prompt for an agent from its config.
|
|
46
|
+
*
|
|
47
|
+
* - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
|
|
48
|
+
* - "append" mode: parent system prompt + sub-agent context + env header + config.systemPrompt
|
|
49
|
+
* - "append" with empty systemPrompt: pure parent clone
|
|
50
|
+
*
|
|
51
|
+
* Both modes include an `<active_agent name="${config.name}"/>` tag so downstream
|
|
52
|
+
* extensions (e.g. permission/policy systems) can resolve per-agent policy
|
|
53
|
+
* inside the child session by parsing the system prompt. In replace mode the tag
|
|
54
|
+
* is prepended; in append mode it follows the shared inherited content so the
|
|
55
|
+
* parent prompt forms an identical, cacheable byte prefix with the parent
|
|
56
|
+
* session (the LLM's KV cache can then reuse those tokens across every spawn).
|
|
57
|
+
*
|
|
58
|
+
* @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
|
|
59
|
+
* @param extras Optional extra sections to inject (memory, preloaded skills).
|
|
60
|
+
*/
|
|
61
|
+
export declare function buildAgentPrompt(config: AgentConfig, cwd: string, env: EnvInfo, parentSystemPrompt?: string, extras?: PromptExtras): string;
|
package/dist/prompts.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* prompts.ts — System prompt builder for agents.
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Build the system prompt for an agent from its config.
|
|
6
|
+
*
|
|
7
|
+
* - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
|
|
8
|
+
* - "append" mode: parent system prompt + sub-agent context + env header + config.systemPrompt
|
|
9
|
+
* - "append" with empty systemPrompt: pure parent clone
|
|
10
|
+
*
|
|
11
|
+
* Both modes include an `<active_agent name="${config.name}"/>` tag so downstream
|
|
12
|
+
* extensions (e.g. permission/policy systems) can resolve per-agent policy
|
|
13
|
+
* inside the child session by parsing the system prompt. In replace mode the tag
|
|
14
|
+
* is prepended; in append mode it follows the shared inherited content so the
|
|
15
|
+
* parent prompt forms an identical, cacheable byte prefix with the parent
|
|
16
|
+
* session (the LLM's KV cache can then reuse those tokens across every spawn).
|
|
17
|
+
*
|
|
18
|
+
* @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
|
|
19
|
+
* @param extras Optional extra sections to inject (memory, preloaded skills).
|
|
20
|
+
*/
|
|
21
|
+
export function buildAgentPrompt(config, cwd, env, parentSystemPrompt, extras) {
|
|
22
|
+
const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
|
|
23
|
+
const envBlock = `# Environment
|
|
24
|
+
Working directory: ${cwd}
|
|
25
|
+
${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
|
|
26
|
+
Platform: ${env.platform}`;
|
|
27
|
+
// A worktree agent is told its cwd twice: by the env block above (the copy)
|
|
28
|
+
// and by whatever names the main checkout — the inherited parent prompt in
|
|
29
|
+
// append mode, or the task prompt in either mode. It follows the latter and
|
|
30
|
+
// works in the shared tree (#187), so resolve the contradiction explicitly.
|
|
31
|
+
const worktreeBlock = extras?.worktreeBase
|
|
32
|
+
? `\n\n<worktree_isolation>
|
|
33
|
+
Your working directory is an isolated git worktree copy of ${extras.worktreeBase}.
|
|
34
|
+
Work only inside it — never in ${extras.worktreeBase}, even if other instructions name that path as your working directory.
|
|
35
|
+
</worktree_isolation>`
|
|
36
|
+
: "";
|
|
37
|
+
// The script, not a person, reads what this child returns — see
|
|
38
|
+
// `PromptExtras.workflowChild` for why only workflow children get this.
|
|
39
|
+
const workflowBlock = extras?.workflowChild
|
|
40
|
+
? `\n\n<workflow_child>
|
|
41
|
+
Your final message IS the return value of this task. A workflow script captures it and passes it to the next stage; no person reads it.
|
|
42
|
+
Return only the answer, in exactly the shape the prompt asks for — no preamble, no summary of what you did, no offer to continue.
|
|
43
|
+
</workflow_child>`
|
|
44
|
+
: "";
|
|
45
|
+
// Build optional extras suffix
|
|
46
|
+
const extraSections = [];
|
|
47
|
+
if (extras?.pinFallbackNotice) {
|
|
48
|
+
extraSections.push(`NOTE: ${extras.pinFallbackNotice}`);
|
|
49
|
+
}
|
|
50
|
+
if (extras?.memoryBlock) {
|
|
51
|
+
extraSections.push(extras.memoryBlock);
|
|
52
|
+
}
|
|
53
|
+
if (extras?.skillBlocks?.length) {
|
|
54
|
+
for (const skill of extras.skillBlocks) {
|
|
55
|
+
extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
|
|
59
|
+
if (config.promptMode === "append") {
|
|
60
|
+
const identity = parentSystemPrompt || genericBase;
|
|
61
|
+
const bridge = `<sub_agent_context>
|
|
62
|
+
You are operating as a sub-agent invoked to handle a specific task.
|
|
63
|
+
- Use the read tool instead of cat/head/tail
|
|
64
|
+
- Use the edit tool instead of sed/awk
|
|
65
|
+
- Use the write tool instead of echo/heredoc
|
|
66
|
+
- Use the find tool instead of bash find/ls for file search
|
|
67
|
+
- Use the grep tool instead of bash grep/rg for content search
|
|
68
|
+
- Make independent tool calls in parallel
|
|
69
|
+
- Use absolute file paths
|
|
70
|
+
- Do not use emojis
|
|
71
|
+
- Be concise but complete
|
|
72
|
+
</sub_agent_context>`;
|
|
73
|
+
const customSection = config.systemPrompt?.trim()
|
|
74
|
+
? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
|
|
75
|
+
: "";
|
|
76
|
+
// Place shared/stable content first so the LLM's KV cache can reuse the
|
|
77
|
+
// inherited prefix across all subagent invocations. The parent prompt is
|
|
78
|
+
// placed verbatim (no wrapper tag) so it forms an identical byte prefix
|
|
79
|
+
// with the parent session, maximising KV cache hits. The <active_agent>
|
|
80
|
+
// tag and env block vary per call and are placed after the cached prefix.
|
|
81
|
+
return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + worktreeBlock + workflowBlock + customSection + extrasSuffix;
|
|
82
|
+
}
|
|
83
|
+
// "replace" mode — env header + the config's full system prompt
|
|
84
|
+
const replaceHeader = `You are a pi coding agent sub-agent.
|
|
85
|
+
You have been invoked to handle a specific task autonomously.
|
|
86
|
+
|
|
87
|
+
${envBlock}`;
|
|
88
|
+
return activeAgentTag + replaceHeader + worktreeBlock + workflowBlock + "\n\n" + config.systemPrompt + extrasSuffix;
|
|
89
|
+
}
|
|
90
|
+
/** Fallback base prompt when parent system prompt is unavailable in append mode. */
|
|
91
|
+
const genericBase = `# Role
|
|
92
|
+
You are a general-purpose coding agent for complex, multi-step tasks.
|
|
93
|
+
You have full access to read, write, edit files, and execute commands.
|
|
94
|
+
Do what has been asked; nothing more, nothing less.`;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { AgentSession, EventBus, ExtensionError } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type StandalonePolicy } from "./standalone-fallback.js";
|
|
3
|
+
export declare const RECOVERY_CHANNEL = "pi-fallback-chains:recovery";
|
|
4
|
+
type RecoveryPhase = "idle" | "pending" | "switching" | "compacting" | "retrying" | "settled" | "cancelled" | "failed";
|
|
5
|
+
export interface RecoverySnapshot {
|
|
6
|
+
version: 1;
|
|
7
|
+
sessionId: string;
|
|
8
|
+
epoch: number;
|
|
9
|
+
requestId: string;
|
|
10
|
+
revision: number;
|
|
11
|
+
phase: RecoveryPhase;
|
|
12
|
+
pending: boolean;
|
|
13
|
+
model?: string;
|
|
14
|
+
reason?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare class ChildRecovery {
|
|
17
|
+
private bus;
|
|
18
|
+
private session?;
|
|
19
|
+
private snapshot?;
|
|
20
|
+
private cancelled;
|
|
21
|
+
private disposed;
|
|
22
|
+
private waiters;
|
|
23
|
+
private unsubscribe;
|
|
24
|
+
private onModelChange?;
|
|
25
|
+
private standalone?;
|
|
26
|
+
private ownerObserved;
|
|
27
|
+
private generation;
|
|
28
|
+
private attempted;
|
|
29
|
+
private prompting;
|
|
30
|
+
private unfinishedTools;
|
|
31
|
+
private unsafeTools;
|
|
32
|
+
configureStandalone(policy: StandalonePolicy): void;
|
|
33
|
+
/** A managed prompt — the run itself or its recovery continuation — is active. */
|
|
34
|
+
isPrompting(): boolean;
|
|
35
|
+
/** Only managed request boundaries reset cancellation and the one-attempt budget. */
|
|
36
|
+
beginRequest(): void;
|
|
37
|
+
/** Construct before loading extensions, attach before bindExtensions/session_start. */
|
|
38
|
+
constructor(bus: EventBus);
|
|
39
|
+
attach(session: AgentSession, onModelChange?: (session: AgentSession) => void): void;
|
|
40
|
+
private receive;
|
|
41
|
+
private query;
|
|
42
|
+
private wake;
|
|
43
|
+
cancel(reason: string): void;
|
|
44
|
+
executionError(error: ExtensionError): void;
|
|
45
|
+
prompt(text: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
46
|
+
private waitForSettlement;
|
|
47
|
+
dispose(): void;
|
|
48
|
+
}
|
|
49
|
+
/** True while a managed prompt (including fallback recovery) is still in flight. */
|
|
50
|
+
export declare function isChildRequestActive(session: AgentSession): boolean;
|
|
51
|
+
export declare function beginChildRequest(session: AgentSession): void;
|
|
52
|
+
export declare function promptWithRecovery(session: AgentSession, text: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
53
|
+
/** Invalidate extension timers/continuations synchronously BEFORE Pi aborts. */
|
|
54
|
+
export declare function abortChildSession(session: AgentSession, reason?: string): Promise<void>;
|
|
55
|
+
export declare function disposeChildRecovery(session: AgentSession): void;
|
|
56
|
+
export {};
|