@signalridge/pi-subagents 1.5.0 → 1.7.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 +44 -0
- package/README.md +7 -4
- package/package.json +7 -6
- package/src/agent-color.ts +188 -0
- package/src/agent-file-toggle.ts +8 -0
- package/src/agent-manager.ts +793 -62
- package/src/agent-runner.ts +313 -21
- package/src/agent-tiers.ts +82 -3
- package/src/agent-types.ts +3 -0
- package/src/ask-tools.ts +114 -0
- package/src/cross-extension-rpc.ts +16 -5
- package/src/custom-agents.ts +67 -2
- package/src/default-agents.ts +6 -5
- package/src/gate.ts +0 -0
- package/src/index.ts +3165 -1195
- package/src/mention-clone.ts +196 -0
- package/src/mention.ts +141 -0
- package/src/output-file.ts +23 -1
- package/src/settings.ts +159 -3
- package/src/supervisor.ts +115 -0
- package/src/types.ts +59 -2
- package/src/ui/agent-mention.ts +163 -0
- package/src/ui/conversation-viewer.ts +5 -4
- package/src/ui/fleet-list.ts +9 -7
- package/src/worktree.ts +128 -648
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mention-clone.ts — start a mentioned agent through a clone of this
|
|
3
|
+
* conversation, without putting anything in the chat.
|
|
4
|
+
*
|
|
5
|
+
* Claude Code routes `@agent-<type>` through the main model: the mention
|
|
6
|
+
* becomes a `<system-reminder>` appended to the prompt and the model makes the
|
|
7
|
+
* tool call (see `agentMentionReminder`). That buys the spawned agent a prompt
|
|
8
|
+
* written with conversation context, and costs a visible turn — the model's
|
|
9
|
+
* reasoning and its tool block land in the transcript, for a decision the user
|
|
10
|
+
* already made when they typed the handle.
|
|
11
|
+
*
|
|
12
|
+
* So the turn happens somewhere else. The conversation is cloned into a
|
|
13
|
+
* throwaway in-memory session — same messages, same system prompt, same model —
|
|
14
|
+
* and that copy takes the turn off-screen. A literal clone: the session's own
|
|
15
|
+
* entries, projected by pi's own `sessionEntryToContextMessages`, not
|
|
16
|
+
* `inherit_context`'s text rendering of them.
|
|
17
|
+
*
|
|
18
|
+
* Cloned from memory rather than from the session file, which cannot be relied
|
|
19
|
+
* on: `SessionManager._persist` withholds every write until the first assistant
|
|
20
|
+
* message lands, so a fork taken before then reads an empty file and throws.
|
|
21
|
+
* `buildSessionContext()` has no such timing, and is compaction-aware — it walks
|
|
22
|
+
* the leaf path and substitutes the summary for entries folded into it, so a
|
|
23
|
+
* long conversation clones as what the main model is actually working from. A
|
|
24
|
+
* conversation with nothing in it yet clones to nothing in it yet, which is the
|
|
25
|
+
* correct answer rather than a failure.
|
|
26
|
+
*
|
|
27
|
+
* It is also the oldest of the equivalent Pi APIs — `buildContextEntries` on
|
|
28
|
+
* ReadonlySessionManager and the `sessionEntryToContextMessages` export both
|
|
29
|
+
* arrived in 0.80.5 — where this one has been exported unchanged from before
|
|
30
|
+
* the declared peer floor, and is the same code path (`byId` is only an index
|
|
31
|
+
* cache, so passing it or not cannot change the result). Keeping the floor
|
|
32
|
+
* honest costs nothing here: see the `compat-floor-pi` job.
|
|
33
|
+
*
|
|
34
|
+
* Its `thinkingLevel` is NOT used, and is the one place the newer API would be
|
|
35
|
+
* better. `getSessionContextSettings` starts at "off" and moves only on an
|
|
36
|
+
* explicit `thinking_level_change` entry, so a session where nobody ran
|
|
37
|
+
* `/think` reports "off" rather than the level it is really using. Omitting the
|
|
38
|
+
* field instead lets `createAgentSession` resolve it from settings, which is
|
|
39
|
+
* that real level.
|
|
40
|
+
*
|
|
41
|
+
* Three details make the spawn belong to the real session rather than the
|
|
42
|
+
* clone:
|
|
43
|
+
*
|
|
44
|
+
* - the clone is handed the *registered* `Agent` tool, whose handler closes
|
|
45
|
+
* over the main activation, so it spawns top-level: widget, fleet row,
|
|
46
|
+
* handle, completion notification, all as if the main model had called it;
|
|
47
|
+
* - that tool is re-bound to the main `ExtensionContext`, because the handler
|
|
48
|
+
* reads `cwd`, `model` and `sessionManager.getSessionId()` off it to place
|
|
49
|
+
* the transcript and the `rootSessionId`. The clone's own context would
|
|
50
|
+
* file both under the throwaway fork;
|
|
51
|
+
* - it is called with no tool-call id. The clone's turn produces one, but the
|
|
52
|
+
* real session never issued it, and a `<tool-use-id>` pointing at nothing
|
|
53
|
+
* is exactly the bug the mention-resume path had to fix;
|
|
54
|
+
* - and it is forced into the background. A foreground agent returns its
|
|
55
|
+
* answer as the tool result and is marked `resultConsumed` so no completion
|
|
56
|
+
* notification is sent — correct when the caller is the real conversation,
|
|
57
|
+
* silent loss when the caller is a fork about to be discarded. Background
|
|
58
|
+
* delivery is the only route from a mention back to the main model.
|
|
59
|
+
*
|
|
60
|
+
* The clone gets one tool and one job. It cannot read, write or run anything —
|
|
61
|
+
* an invisible turn with the full toolset could do invisible work.
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
65
|
+
import {
|
|
66
|
+
buildSessionContext,
|
|
67
|
+
createAgentSession,
|
|
68
|
+
type ExtensionContext,
|
|
69
|
+
SessionManager,
|
|
70
|
+
type ToolDefinition,
|
|
71
|
+
} from "@earendil-works/pi-coding-agent";
|
|
72
|
+
import { runInChildSessionContext } from "./child-context.js";
|
|
73
|
+
import { agentMentionReminder } from "./mention.js";
|
|
74
|
+
import type { SubagentType, ThinkingLevel } from "./types.js";
|
|
75
|
+
|
|
76
|
+
export interface MentionCloneOptions {
|
|
77
|
+
/** The MAIN session's context — what the spawn is attributed to, and the
|
|
78
|
+
* source of both the conversation and the live system prompt. */
|
|
79
|
+
ctx: ExtensionContext;
|
|
80
|
+
/** Agent type the handle resolved to. */
|
|
81
|
+
type: SubagentType;
|
|
82
|
+
/** What the user typed after the handle. */
|
|
83
|
+
message: string;
|
|
84
|
+
/** The registered `Agent` tool, reused so the spawn is an ordinary one. */
|
|
85
|
+
agentTool: ToolDefinition;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface MentionCloneResult {
|
|
89
|
+
/** True once the clone actually called `Agent`. */
|
|
90
|
+
spawned: boolean;
|
|
91
|
+
/** Why not, when it didn't. Absent on success. */
|
|
92
|
+
error?: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Fork the conversation, let the copy make the tool call, throw the copy away.
|
|
97
|
+
* Never rejects: a clone that cannot run is reported so the caller can fall
|
|
98
|
+
* back to starting the agent directly.
|
|
99
|
+
*/
|
|
100
|
+
export async function runMentionClone(opts: MentionCloneOptions): Promise<MentionCloneResult> {
|
|
101
|
+
const { ctx, type, message, agentTool } = opts;
|
|
102
|
+
|
|
103
|
+
let spawned = false;
|
|
104
|
+
const cloneAgentTool: ToolDefinition = {
|
|
105
|
+
...agentTool,
|
|
106
|
+
execute: (_cloneToolCallId, params, signal, onUpdate, _cloneCtx) => {
|
|
107
|
+
// One spawn per mention. The clone has a single tool and every reason to
|
|
108
|
+
// stop after using it, but a model that decides to "also" launch a second
|
|
109
|
+
// agent would do it where nobody can see and nobody asked.
|
|
110
|
+
if (spawned) {
|
|
111
|
+
return Promise.resolve({
|
|
112
|
+
content: [{ type: "text" as const, text: "Already started an agent for this mention. Stop here." }],
|
|
113
|
+
details: undefined,
|
|
114
|
+
isError: true,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
spawned = true;
|
|
118
|
+
// undefined tool-call id + the main ctx: see the header. Background is
|
|
119
|
+
// forced rather than left to the clone: `run_in_background` defaults to
|
|
120
|
+
// false, and a foreground agent answers through its TOOL RESULT — which
|
|
121
|
+
// here is delivered into a session that is disposed moments later, so the
|
|
122
|
+
// agent would run, appear in the widget and the fleet, and reach nobody.
|
|
123
|
+
return agentTool.execute(
|
|
124
|
+
undefined as never,
|
|
125
|
+
{ ...(params as Record<string, unknown>), run_in_background: true } as typeof params,
|
|
126
|
+
signal,
|
|
127
|
+
onUpdate,
|
|
128
|
+
ctx,
|
|
129
|
+
);
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
let session: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
|
|
134
|
+
try {
|
|
135
|
+
// Pi 0.80.8 moved createAgentSession from modelRegistry to modelRuntime;
|
|
136
|
+
// agent-runner.ts carries the same shim for the same reason — pass both so
|
|
137
|
+
// the clone keeps the parent's providers across the supported range.
|
|
138
|
+
const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: unknown }).runtime;
|
|
139
|
+
// The conversation as the main session resolves it: compaction applied,
|
|
140
|
+
// branch summaries substituted.
|
|
141
|
+
const conversation = buildSessionContext(
|
|
142
|
+
ctx.sessionManager.getEntries(),
|
|
143
|
+
ctx.sessionManager.getLeafId(),
|
|
144
|
+
);
|
|
145
|
+
// Pi 0.82.0 added this; below it the field is absent and the clone takes
|
|
146
|
+
// the settings level instead, which is what a session that never ran
|
|
147
|
+
// `/think` is on anyway. Same shim shape as `modelRuntime` below.
|
|
148
|
+
const thinkingLevel = (ctx as { thinkingLevel?: ThinkingLevel }).thinkingLevel;
|
|
149
|
+
const created = await runInChildSessionContext(() =>
|
|
150
|
+
createAgentSession({
|
|
151
|
+
cwd: ctx.cwd,
|
|
152
|
+
// Nothing about the copy is worth persisting, and an in-memory manager
|
|
153
|
+
// is also what keeps the real session untouched.
|
|
154
|
+
sessionManager: SessionManager.inMemory(ctx.cwd),
|
|
155
|
+
model: ctx.model as Model<never> | undefined,
|
|
156
|
+
...(thinkingLevel && { thinkingLevel }),
|
|
157
|
+
modelRegistry: ctx.modelRegistry,
|
|
158
|
+
...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime as never }),
|
|
159
|
+
// An allowlist naming exactly the clone's own tool. NOT `noTools:
|
|
160
|
+
// "all"`, whose doc comment ("start with no tools enabled") reads like
|
|
161
|
+
// it spares custom tools and does not: it resolves to an EMPTY
|
|
162
|
+
// allowlist, and `isAllowedTool` then drops every tool from the
|
|
163
|
+
// registry — the custom one included. The clone would be prompted with
|
|
164
|
+
// nothing to call, answer in prose, and every mention would fall
|
|
165
|
+
// through to the direct start with a warning. Same idiom as
|
|
166
|
+
// agent-runner's `tools: sessionTools` beside its nested `customTools`.
|
|
167
|
+
tools: [cloneAgentTool.name],
|
|
168
|
+
customTools: [cloneAgentTool],
|
|
169
|
+
} as Parameters<typeof createAgentSession>[0]),
|
|
170
|
+
);
|
|
171
|
+
session = created.session;
|
|
172
|
+
|
|
173
|
+
// The clone rebuilds a system prompt from cwd and agentDir, which is close
|
|
174
|
+
// but not the live one — extensions contribute to it per turn. Copy the
|
|
175
|
+
// real thing, so the copy reasons under the instructions the user's model
|
|
176
|
+
// is actually working under.
|
|
177
|
+
const systemPrompt = ctx.getSystemPrompt?.();
|
|
178
|
+
if (systemPrompt) session.agent.state.systemPrompt = systemPrompt;
|
|
179
|
+
|
|
180
|
+
// The conversation itself. Pushed rather than assigned so the array the
|
|
181
|
+
// session was built around stays the one it goes on using.
|
|
182
|
+
session.agent.state.messages.push(...conversation.messages);
|
|
183
|
+
|
|
184
|
+
// User text first, reminder after — the order Claude Code's attachment
|
|
185
|
+
// renderer produces, where the reminder trails the message it is about.
|
|
186
|
+
await session.prompt(`${message}\n\n${agentMentionReminder(type)}`);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
return { spawned, error: err instanceof Error ? err.message : String(err) };
|
|
189
|
+
} finally {
|
|
190
|
+
session?.dispose?.();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return spawned
|
|
194
|
+
? { spawned: true }
|
|
195
|
+
: { spawned: false, error: "the conversation clone did not start it" };
|
|
196
|
+
}
|
package/src/mention.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mention.ts — the `@handle` grammar for messaging a subagent from the prompt.
|
|
3
|
+
*
|
|
4
|
+
* Claude Code lets you type `@code-review take another look` at the prompt and
|
|
5
|
+
* routes the message to that agent instead of the main model. Its grammar is
|
|
6
|
+
* reproduced here so the two behave identically:
|
|
7
|
+
*
|
|
8
|
+
* - suggestions fire on `@` at the start of the input or after whitespace,
|
|
9
|
+
* followed by `[\w-]*` (so `@src/foo.ts` is a file, never an agent);
|
|
10
|
+
* - a send is recognized only at the START of the input, and only with a
|
|
11
|
+
* non-empty message after the handle. That is why a bare `@code-review`
|
|
12
|
+
* goes to the main model rather than anywhere near the agent.
|
|
13
|
+
*
|
|
14
|
+
* A record's own identity is a UUID plus a deliberately non-unique description,
|
|
15
|
+
* neither of which is typeable, so the handle is derived from the agent type.
|
|
16
|
+
* Colliding handles are numbered (`explore`, `explore-2`), which is also what
|
|
17
|
+
* Claude Code's `allocateName` does — it recycles a name only once the task
|
|
18
|
+
* behind it is gone. Its SendMessage prompt describes the *registry* as
|
|
19
|
+
* latest-wins, which is a different thing and not how names are allocated.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Suggestion trigger: `@` at a token boundary plus the partial handle typed so
|
|
24
|
+
* far. Ported from Claude Code, including the CJK sentence-ending punctuation
|
|
25
|
+
* it accepts as a boundary.
|
|
26
|
+
*/
|
|
27
|
+
export const MENTION_TRIGGER = /(^|[\s。、?!])@([\w-]*)$/;
|
|
28
|
+
|
|
29
|
+
/** Send grammar: leading `@handle`, then a non-empty message. */
|
|
30
|
+
const MENTION_SEND = /^@([\w-]+)\s+([\s\S]+)$/;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Upper bound on a handle, matching Claude Code's `dSS`. Nothing here generates
|
|
34
|
+
* a name this long, but an agent type or a model-supplied name can be arbitrary
|
|
35
|
+
* text, and an unbounded handle would wrap the suggestion popup.
|
|
36
|
+
*/
|
|
37
|
+
const MAX_HANDLE_LENGTH = 64;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Handles that address something other than a subagent, and so can never be
|
|
41
|
+
* allocated to one. Claude Code reserves exactly this name (`Vq = "main"`),
|
|
42
|
+
* refusing it at spawn and routing it to the main conversation instead.
|
|
43
|
+
*/
|
|
44
|
+
const RESERVED_HANDLES: ReadonlySet<string> = new Set(["main"]);
|
|
45
|
+
|
|
46
|
+
/** Whether `@handle` names the main conversation rather than any subagent. */
|
|
47
|
+
export function isReservedHandle(handle: string): boolean {
|
|
48
|
+
return RESERVED_HANDLES.has(handle.toLowerCase());
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Slug of an agent type or name, restricted to the `[\w-]` the grammar allows. */
|
|
52
|
+
export function handleBase(type: string): string {
|
|
53
|
+
const slug = type.toLowerCase()
|
|
54
|
+
.replace(/[^a-z0-9_-]+/g, "-")
|
|
55
|
+
.replace(/^-+|-+$/g, "")
|
|
56
|
+
.slice(0, MAX_HANDLE_LENGTH)
|
|
57
|
+
// The slice can land mid-run and leave the trailing hyphen back.
|
|
58
|
+
.replace(/-+$/, "");
|
|
59
|
+
return slug || "agent";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* `base`, else `base-2`, `base-3`, … — the first form that is neither `taken`
|
|
64
|
+
* nor reserved. Callers pass one shared `taken` set covering type-derived
|
|
65
|
+
* handles and model-supplied aliases alike, so the two can never collide.
|
|
66
|
+
*/
|
|
67
|
+
export function assignHandle(base: string, taken: ReadonlySet<string>): string {
|
|
68
|
+
let candidate = base;
|
|
69
|
+
let n = 1;
|
|
70
|
+
while (taken.has(candidate) || RESERVED_HANDLES.has(candidate)) {
|
|
71
|
+
n++;
|
|
72
|
+
candidate = `${base}-${n}`;
|
|
73
|
+
}
|
|
74
|
+
return candidate;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Map a typed handle back to a registered agent type, so `@explore fix it`
|
|
79
|
+
* reaches the Explore agent even when no instance has ever run. `handleBase` is
|
|
80
|
+
* the single source of truth in both directions, so a type is addressable by
|
|
81
|
+
* exactly the handle its instances would be given.
|
|
82
|
+
*/
|
|
83
|
+
export function resolveHandleToType(handle: string, types: readonly string[]): string | undefined {
|
|
84
|
+
const wanted = handle.toLowerCase();
|
|
85
|
+
// A type slugging to a reserved name is unaddressable rather than shadowing
|
|
86
|
+
// it — `assignHandle` refuses that name too, so its instances never hold one.
|
|
87
|
+
if (RESERVED_HANDLES.has(wanted)) return undefined;
|
|
88
|
+
return types.find(type => handleBase(type) === wanted);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Claude Code documents `@agent-<name>` as the form you type by hand when the
|
|
93
|
+
* picker isn't involved. Accepted here as an exact synonym: the caller tries the
|
|
94
|
+
* handle as written first, so an agent genuinely called `agent-foo` still wins
|
|
95
|
+
* over `@agent-` + `foo`, and only falls back to this when that finds nothing.
|
|
96
|
+
* Returns undefined when the prefix is absent or is the whole handle.
|
|
97
|
+
*/
|
|
98
|
+
export function stripAgentPrefix(handle: string): string | undefined {
|
|
99
|
+
const rest = /^agent-(.+)$/i.exec(handle)?.[1];
|
|
100
|
+
return rest || undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A spawn needs the short description every agent surface renders. A mention
|
|
105
|
+
* carries no separate label, so the message itself becomes one: first line,
|
|
106
|
+
* whitespace collapsed, clipped to roughly the 3-5 words the Agent tool asks of
|
|
107
|
+
* the model.
|
|
108
|
+
*/
|
|
109
|
+
export function describeMention(message: string): string {
|
|
110
|
+
const oneLine = message.split("\n", 1)[0].replace(/\s+/g, " ").trim();
|
|
111
|
+
return oneLine.length > 40 ? `${oneLine.slice(0, 39).trimEnd()}…` : oneLine;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* What Claude Code sends the main model when a mention names an agent it could
|
|
116
|
+
* start. Its `@agent-<type>` mention is not a spawn at all: it becomes an
|
|
117
|
+
* `agent_mention` attachment, which renders to a synthetic `isMeta` user
|
|
118
|
+
* message placed after the user's own untouched text — no tool forcing, no
|
|
119
|
+
* allowed-tools narrowing, and the Task tool is not even named. The model reads
|
|
120
|
+
* this and calls the tool itself.
|
|
121
|
+
*
|
|
122
|
+
* Ported verbatim from the 2.1.233 bundle's attachment renderer, trailing space
|
|
123
|
+
* before the closing newline included, so the wording the model was trained
|
|
124
|
+
* against is the wording it gets. The one substitution is ours: pi's equivalent
|
|
125
|
+
* of Task is the `Agent` tool, and the agent listing that teaches valid
|
|
126
|
+
* `subagent_type` values is the tool spec rather than a separate attachment.
|
|
127
|
+
*/
|
|
128
|
+
export function agentMentionReminder(type: string): string {
|
|
129
|
+
return `<system-reminder>\nThe user has expressed a desire to invoke the agent "${type}". Please invoke the agent appropriately, passing in the required context to it. \n</system-reminder>`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Split `@handle message` into its parts, or null when the text isn't a send —
|
|
134
|
+
* a bare handle, a leading file path, or a mention that isn't at the start.
|
|
135
|
+
*/
|
|
136
|
+
export function parseMention(text: string): { handle: string; message: string } | null {
|
|
137
|
+
const match = MENTION_SEND.exec(text);
|
|
138
|
+
if (!match) return null;
|
|
139
|
+
const message = match[2].trim();
|
|
140
|
+
return message ? { handle: match[1], message } : null;
|
|
141
|
+
}
|
package/src/output-file.ts
CHANGED
|
@@ -68,6 +68,22 @@ export function writeInitialEntry(path: string, agentId: string, prompt: string,
|
|
|
68
68
|
writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Ensure a transcript file exists without disturbing what is already in it.
|
|
73
|
+
*
|
|
74
|
+
* A resume reuses the agent's existing transcript (same deterministic path), so
|
|
75
|
+
* it must never call `writeInitialEntry` — that truncates, discarding turns the
|
|
76
|
+
* completion notification still points the user at, and any history the session
|
|
77
|
+
* has since compacted away is gone for good (#145). Appending nothing creates
|
|
78
|
+
* the file when this is the agent's first transcript and is a no-op when it is
|
|
79
|
+
* not.
|
|
80
|
+
*/
|
|
81
|
+
export function ensureOutputFile(path: string): void {
|
|
82
|
+
try {
|
|
83
|
+
appendFileSync(path, "", "utf-8");
|
|
84
|
+
} catch { /* ignore — streaming writes are best-effort too */ }
|
|
85
|
+
}
|
|
86
|
+
|
|
71
87
|
/**
|
|
72
88
|
* Subscribe to session events and flush new messages to the output file on each turn_end.
|
|
73
89
|
* Returns a cleanup function that does a final flush and unsubscribes.
|
|
@@ -77,8 +93,14 @@ export function streamToOutputFile(
|
|
|
77
93
|
path: string,
|
|
78
94
|
agentId: string,
|
|
79
95
|
cwd: string,
|
|
96
|
+
startIndex?: number,
|
|
80
97
|
): () => void {
|
|
81
|
-
|
|
98
|
+
// Index of the first message this stream is responsible for. A spawn writes
|
|
99
|
+
// messages[0] as the initial prompt entry, so it starts at 1. A resume hands
|
|
100
|
+
// in the session's length as of just before the run: the session already
|
|
101
|
+
// holds every prior turn, and re-emitting those would duplicate history that
|
|
102
|
+
// is already in the file.
|
|
103
|
+
let writtenCount = startIndex ?? 1;
|
|
82
104
|
|
|
83
105
|
const flush = () => {
|
|
84
106
|
const messages = session.messages;
|
package/src/settings.ts
CHANGED
|
@@ -2,13 +2,23 @@
|
|
|
2
2
|
// - Global: ~/.pi/agent/subagents.json (via getAgentDir()) — manual defaults, never written here
|
|
3
3
|
// - Project: <cwd>/.pi/subagents.json — written by /agents → Settings; overrides global on load
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { basename, dirname, join } from "node:path";
|
|
7
8
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
8
9
|
import type { WorkflowTier } from "@signalridge/pi-subagents-protocol";
|
|
10
|
+
// Imported only for the applySettings fallback so a persisted defaultToolTimeoutMs
|
|
11
|
+
// takes effect even before the host wires the new applier — avoids needing to
|
|
12
|
+
// edit index.ts in the same change.
|
|
13
|
+
import { setDefaultToolTimeoutMs } from "./agent-runner.js";
|
|
9
14
|
import { NO_FALLBACK } from "./agent-types.js";
|
|
10
15
|
import type { JoinMode, ThinkingLevel } from "./types.js";
|
|
11
16
|
|
|
17
|
+
/** How a `@handle message` mention is dispatched. See `agentMentions`. */
|
|
18
|
+
export const AGENT_MENTION_MODES = ["model", "direct", "off"] as const;
|
|
19
|
+
export type AgentMentionMode = (typeof AGENT_MENTION_MODES)[number];
|
|
20
|
+
const VALID_AGENT_MENTION_MODES: ReadonlySet<string> = new Set(AGENT_MENTION_MODES);
|
|
21
|
+
|
|
12
22
|
/** A tier's thinking value: a level, or `inherit` to keep the parent's. */
|
|
13
23
|
export type TierThinking = ThinkingLevel | "inherit";
|
|
14
24
|
|
|
@@ -109,6 +119,19 @@ export interface SubagentsSettings {
|
|
|
109
119
|
*/
|
|
110
120
|
defaultMaxTurns?: number;
|
|
111
121
|
graceTurns?: number;
|
|
122
|
+
/**
|
|
123
|
+
* Token budget for one subagent run. `0` (default) = unlimited, matching
|
|
124
|
+
* `defaultMaxTurns`. A wrap-up steer is sent at 80% and the run is aborted at
|
|
125
|
+
* 100%. Bounds what one agent can spend, which a turn count cannot — a single
|
|
126
|
+
* turn can burn an arbitrary number of tokens. Frontmatter `max_tokens` wins.
|
|
127
|
+
*/
|
|
128
|
+
defaultMaxTokens?: number;
|
|
129
|
+
/**
|
|
130
|
+
* Tool-call budget for one subagent run. `0` (default) = unlimited, with the
|
|
131
|
+
* same 80%/100% shape as `defaultMaxTokens`. Frontmatter `max_tool_calls`
|
|
132
|
+
* wins.
|
|
133
|
+
*/
|
|
134
|
+
defaultMaxToolCalls?: number;
|
|
112
135
|
defaultJoinMode?: JoinMode;
|
|
113
136
|
/**
|
|
114
137
|
* Master switch for the schedule subagent feature. Defaults to `true`.
|
|
@@ -182,6 +205,32 @@ export interface SubagentsSettings {
|
|
|
182
205
|
* (`isolation: worktree`), or memory files.
|
|
183
206
|
*/
|
|
184
207
|
outputTranscript?: boolean;
|
|
208
|
+
/**
|
|
209
|
+
* Whether evicted agent records stay addressable as resumable entries
|
|
210
|
+
* (`@handle` reopen). Defaults to true. When false, a cleaned-up record is
|
|
211
|
+
* forgotten entirely.
|
|
212
|
+
*/
|
|
213
|
+
rememberAgents?: boolean;
|
|
214
|
+
/**
|
|
215
|
+
* How `@handle message` typed at the prompt is dispatched.
|
|
216
|
+
*
|
|
217
|
+
* - `"model"` (default) — a mention that names an agent TYPE takes its turn
|
|
218
|
+
* in an off-screen clone of the conversation, so the started agent gets a
|
|
219
|
+
* prompt written with context instead of only the words after the handle.
|
|
220
|
+
* Messaging and resuming an existing agent stay direct either way.
|
|
221
|
+
* - `"direct"` — start the agent straight from the typed text, no clone.
|
|
222
|
+
* - `"off"` — the text goes to the main model verbatim, exactly as it did
|
|
223
|
+
* before mentions existed.
|
|
224
|
+
*
|
|
225
|
+
* A boolean is still accepted and read as `"model"`/`"off"`.
|
|
226
|
+
*/
|
|
227
|
+
agentMentions?: AgentMentionMode;
|
|
228
|
+
/**
|
|
229
|
+
* Whether subagents may interrupt with `contact_supervisor` to ask their
|
|
230
|
+
* human a question. Defaults to true. The tool is only ever injected where
|
|
231
|
+
* there is a UI to ask through, so this turns it off where there is one.
|
|
232
|
+
*/
|
|
233
|
+
supervisorQuestions?: boolean;
|
|
185
234
|
/**
|
|
186
235
|
* Hard ceiling on nested subagent delegation, counted from the main session:
|
|
187
236
|
* main = 0, its subagents = 1, their children = 2. Defaults to `2`; `0` or `1`
|
|
@@ -189,6 +238,22 @@ export interface SubagentsSettings {
|
|
|
189
238
|
* change applies to agents started after it.
|
|
190
239
|
*/
|
|
191
240
|
maxSubagentDepth?: number;
|
|
241
|
+
/**
|
|
242
|
+
* Cumulative descendants any one top-level agent may start, over its whole
|
|
243
|
+
* life. Defaults to `64`. The depth cap bounds how DEEP nesting goes and
|
|
244
|
+
* nothing about how WIDE it gets — this is the horizontal bound. Minimum 1;
|
|
245
|
+
* turn nesting off with `maxSubagentDepth` instead.
|
|
246
|
+
*/
|
|
247
|
+
maxSubagentSpawnsPerBranch?: number;
|
|
248
|
+
/**
|
|
249
|
+
* Default per-tool timeout in milliseconds. `0` = disabled (no timeout). When
|
|
250
|
+
* set, any tool call that does not settle within this window is aborted with
|
|
251
|
+
* a timeout error, preventing a hung `bash` or MCP tool from stalling the
|
|
252
|
+
* subagent forever. `0` when unset, matching tintinweb (no per-tool timeout
|
|
253
|
+
* by default; hung tools are reclaimed via abort/quiescence). Frontmatter does
|
|
254
|
+
* not override.
|
|
255
|
+
*/
|
|
256
|
+
defaultToolTimeoutMs?: number;
|
|
192
257
|
/**
|
|
193
258
|
* Agent type substituted when a caller-supplied `subagent_type` doesn't
|
|
194
259
|
* resolve to exactly one enabled agent (unknown, disabled, or ambiguous by
|
|
@@ -204,15 +269,25 @@ export interface SubagentsSettings {
|
|
|
204
269
|
* meaning one thing here and another in the resolver.
|
|
205
270
|
*/
|
|
206
271
|
fallbackSubagent?: string;
|
|
272
|
+
/**
|
|
273
|
+
* Project-wide switch for worktree isolation (upstream #184). When false,
|
|
274
|
+
* no caller can create a worktree regardless of isolation param. Defaults to
|
|
275
|
+
* true (unchanged behaviour). Routed through worktree.ts singleton.
|
|
276
|
+
*/
|
|
277
|
+
worktreeIsolation?: boolean;
|
|
207
278
|
}
|
|
208
279
|
|
|
209
280
|
export type ToolDescriptionMode = "full" | "compact" | "custom";
|
|
210
281
|
|
|
211
282
|
/** Setter hooks used by applySettings to wire persisted values into in-memory state. */
|
|
212
283
|
export interface SettingsAppliers {
|
|
284
|
+
setWorktreeIsolation?: (enabled: boolean) => void;
|
|
213
285
|
setMaxConcurrent: (n: number) => void;
|
|
214
286
|
setDefaultMaxTurns: (n: number) => void;
|
|
215
287
|
setGraceTurns: (n: number) => void;
|
|
288
|
+
setDefaultMaxTokens: (n: number) => void;
|
|
289
|
+
setDefaultMaxToolCalls: (n: number) => void;
|
|
290
|
+
setDefaultToolTimeout?: (ms: number) => void;
|
|
216
291
|
setDefaultJoinMode: (mode: JoinMode) => void;
|
|
217
292
|
/** `undefined` and `"inherit"` both mean "follow the parent session". */
|
|
218
293
|
setDefaultModel: (ref: string | undefined) => void;
|
|
@@ -223,7 +298,11 @@ export interface SettingsAppliers {
|
|
|
223
298
|
setToolDescriptionMode: (mode: ToolDescriptionMode) => void;
|
|
224
299
|
setFleetView: (b: boolean) => void;
|
|
225
300
|
setOutputTranscript: (b: boolean) => void;
|
|
301
|
+
setRememberAgents: (b: boolean) => void;
|
|
302
|
+
setAgentMentions: (mode: AgentMentionMode) => void;
|
|
303
|
+
setSupervisorQuestions: (b: boolean) => void;
|
|
226
304
|
setMaxSubagentDepth: (n: number) => void;
|
|
305
|
+
setMaxSubagentSpawnsPerBranch: (n: number) => void;
|
|
227
306
|
setFallbackSubagent: (v: string | undefined) => void;
|
|
228
307
|
/** Optional because non-runtime settings tests and consumers need not apply workflow state. */
|
|
229
308
|
setWorkflow?: (settings: WorkflowSettings) => void;
|
|
@@ -268,6 +347,14 @@ const MAX_CONCURRENT_CEILING = 1024;
|
|
|
268
347
|
const MAX_TURNS_CEILING = 10_000;
|
|
269
348
|
const GRACE_TURNS_CEILING = 1_000;
|
|
270
349
|
const SUBAGENT_DEPTH_CEILING = 16;
|
|
350
|
+
/**
|
|
351
|
+
* Upper bound on the branch spawn budget. A configured value this high is
|
|
352
|
+
* already far past the point where a fan-out is intentional; the ceiling exists
|
|
353
|
+
* so a typo cannot turn the horizontal bound off by writing a huge number.
|
|
354
|
+
*/
|
|
355
|
+
const SUBAGENT_SPAWNS_PER_BRANCH_CEILING = 4_096;
|
|
356
|
+
/** Per-tool timeout ceiling: 10 minutes, matching gate timeout. */
|
|
357
|
+
const TOOL_TIMEOUT_CEILING_MS = 600_000;
|
|
271
358
|
|
|
272
359
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
273
360
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -427,6 +514,13 @@ function sanitize(raw: unknown): SubagentsSettings {
|
|
|
427
514
|
) {
|
|
428
515
|
out.graceTurns = r.graceTurns as number;
|
|
429
516
|
}
|
|
517
|
+
// `0` is accepted and means unlimited, matching `defaultMaxTurns`.
|
|
518
|
+
if (Number.isInteger(r.defaultMaxTokens) && (r.defaultMaxTokens as number) >= 0) {
|
|
519
|
+
out.defaultMaxTokens = r.defaultMaxTokens as number;
|
|
520
|
+
}
|
|
521
|
+
if (Number.isInteger(r.defaultMaxToolCalls) && (r.defaultMaxToolCalls as number) >= 0) {
|
|
522
|
+
out.defaultMaxToolCalls = r.defaultMaxToolCalls as number;
|
|
523
|
+
}
|
|
430
524
|
if (
|
|
431
525
|
Number.isInteger(r.maxSubagentDepth) &&
|
|
432
526
|
(r.maxSubagentDepth as number) >= 0 &&
|
|
@@ -434,6 +528,23 @@ function sanitize(raw: unknown): SubagentsSettings {
|
|
|
434
528
|
) {
|
|
435
529
|
out.maxSubagentDepth = r.maxSubagentDepth as number;
|
|
436
530
|
}
|
|
531
|
+
// Minimum 1, not 0: zero reads as a limit, and silently meaning "unlimited"
|
|
532
|
+
// is how a safety valve gets disabled by accident. Nesting is turned off with
|
|
533
|
+
// `maxSubagentDepth`, which says so.
|
|
534
|
+
if (
|
|
535
|
+
Number.isInteger(r.maxSubagentSpawnsPerBranch) &&
|
|
536
|
+
(r.maxSubagentSpawnsPerBranch as number) >= 1 &&
|
|
537
|
+
(r.maxSubagentSpawnsPerBranch as number) <= SUBAGENT_SPAWNS_PER_BRANCH_CEILING
|
|
538
|
+
) {
|
|
539
|
+
out.maxSubagentSpawnsPerBranch = r.maxSubagentSpawnsPerBranch as number;
|
|
540
|
+
}
|
|
541
|
+
if (
|
|
542
|
+
Number.isInteger(r.defaultToolTimeoutMs) &&
|
|
543
|
+
(r.defaultToolTimeoutMs as number) >= 0 &&
|
|
544
|
+
(r.defaultToolTimeoutMs as number) <= TOOL_TIMEOUT_CEILING_MS
|
|
545
|
+
) {
|
|
546
|
+
out.defaultToolTimeoutMs = r.defaultToolTimeoutMs as number;
|
|
547
|
+
}
|
|
437
548
|
if (isModelReference(r.defaultModel)) {
|
|
438
549
|
out.defaultModel = r.defaultModel.trim();
|
|
439
550
|
}
|
|
@@ -461,6 +572,17 @@ function sanitize(raw: unknown): SubagentsSettings {
|
|
|
461
572
|
if (typeof r.outputTranscript === "boolean") {
|
|
462
573
|
out.outputTranscript = r.outputTranscript;
|
|
463
574
|
}
|
|
575
|
+
if (typeof r.rememberAgents === "boolean") {
|
|
576
|
+
out.rememberAgents = r.rememberAgents;
|
|
577
|
+
}
|
|
578
|
+
if (typeof r.agentMentions === "boolean") {
|
|
579
|
+
out.agentMentions = r.agentMentions ? "model" : "off";
|
|
580
|
+
} else if (typeof r.agentMentions === "string" && VALID_AGENT_MENTION_MODES.has(r.agentMentions)) {
|
|
581
|
+
out.agentMentions = r.agentMentions as AgentMentionMode;
|
|
582
|
+
}
|
|
583
|
+
if (typeof r.supervisorQuestions === "boolean") {
|
|
584
|
+
out.supervisorQuestions = r.supervisorQuestions;
|
|
585
|
+
}
|
|
464
586
|
if (r.fallbackSubagent === false) {
|
|
465
587
|
// The only non-string spelling worth accepting: a boolean would otherwise be
|
|
466
588
|
// dropped, silently leaving the PERMISSIVE default in place. Every string is
|
|
@@ -471,6 +593,9 @@ function sanitize(raw: unknown): SubagentsSettings {
|
|
|
471
593
|
} else if (typeof r.fallbackSubagent === "string" && r.fallbackSubagent.trim()) {
|
|
472
594
|
out.fallbackSubagent = r.fallbackSubagent.trim();
|
|
473
595
|
}
|
|
596
|
+
if (typeof r.worktreeIsolation === "boolean") {
|
|
597
|
+
out.worktreeIsolation = r.worktreeIsolation;
|
|
598
|
+
}
|
|
474
599
|
|
|
475
600
|
const workflow = sanitizeWorkflow(r.workflow);
|
|
476
601
|
if (workflow) out.workflow = workflow;
|
|
@@ -799,7 +924,23 @@ export function saveSettings(s: SubagentsSettings, cwd: string = process.cwd()):
|
|
|
799
924
|
const path = projectPath(cwd);
|
|
800
925
|
try {
|
|
801
926
|
mkdirSync(dirname(path), { recursive: true });
|
|
802
|
-
|
|
927
|
+
// Atomic write: settings are written on every /agents mutation, and a torn
|
|
928
|
+
// write (crash, kill, disk full between truncate and flush) would silently
|
|
929
|
+
// discard the project's entire configuration. Write to a unique temp file
|
|
930
|
+
// in the same directory, then rename over the target — rename is atomic on
|
|
931
|
+
// POSIX and Windows. Same pattern as packages/pi-goal/src/settings.ts.
|
|
932
|
+
const document = `${JSON.stringify(sanitize(s), null, 2)}\n`;
|
|
933
|
+
const temporaryPath = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
934
|
+
try {
|
|
935
|
+
writeFileSync(temporaryPath, document, { encoding: "utf8", flag: "wx" });
|
|
936
|
+
renameSync(temporaryPath, path);
|
|
937
|
+
} finally {
|
|
938
|
+
try {
|
|
939
|
+
rmSync(temporaryPath, { force: true });
|
|
940
|
+
} catch {
|
|
941
|
+
// Best-effort cleanup must not replace the save result.
|
|
942
|
+
}
|
|
943
|
+
}
|
|
803
944
|
return true;
|
|
804
945
|
} catch {
|
|
805
946
|
return false;
|
|
@@ -811,8 +952,20 @@ export function applySettings(s: SubagentsSettings, appliers: SettingsAppliers):
|
|
|
811
952
|
if (typeof s.maxConcurrent === "number") appliers.setMaxConcurrent(s.maxConcurrent);
|
|
812
953
|
if (typeof s.defaultMaxTurns === "number") appliers.setDefaultMaxTurns(s.defaultMaxTurns);
|
|
813
954
|
if (typeof s.graceTurns === "number") appliers.setGraceTurns(s.graceTurns);
|
|
955
|
+
if (typeof s.defaultMaxTokens === "number") appliers.setDefaultMaxTokens(s.defaultMaxTokens);
|
|
956
|
+
if (typeof s.defaultMaxToolCalls === "number") appliers.setDefaultMaxToolCalls(s.defaultMaxToolCalls);
|
|
814
957
|
if (typeof s.maxSubagentDepth === "number") appliers.setMaxSubagentDepth(s.maxSubagentDepth);
|
|
958
|
+
if (typeof s.maxSubagentSpawnsPerBranch === "number")
|
|
959
|
+
appliers.setMaxSubagentSpawnsPerBranch(s.maxSubagentSpawnsPerBranch);
|
|
960
|
+
if (typeof s.defaultToolTimeoutMs === "number") {
|
|
961
|
+
appliers.setDefaultToolTimeout?.(s.defaultToolTimeoutMs);
|
|
962
|
+
// Fallback for hosts that have not yet wired the new applier (and for tests
|
|
963
|
+
// that call applySettings with a minimal appliers object): ensure the
|
|
964
|
+
// in-memory timeout still follows the persisted value.
|
|
965
|
+
setDefaultToolTimeoutMs(s.defaultToolTimeoutMs);
|
|
966
|
+
}
|
|
815
967
|
if (typeof s.fallbackSubagent === "string") appliers.setFallbackSubagent(s.fallbackSubagent);
|
|
968
|
+
if (typeof s.worktreeIsolation === "boolean") appliers.setWorktreeIsolation?.(s.worktreeIsolation);
|
|
816
969
|
// Applied whenever the key is present, `"inherit"` included: that spelling is
|
|
817
970
|
// how a project cancels a global default model, so it has to reach the setter.
|
|
818
971
|
if (typeof s.defaultModel === "string") appliers.setDefaultModel(s.defaultModel);
|
|
@@ -824,6 +977,9 @@ export function applySettings(s: SubagentsSettings, appliers: SettingsAppliers):
|
|
|
824
977
|
if (s.toolDescriptionMode) appliers.setToolDescriptionMode(s.toolDescriptionMode);
|
|
825
978
|
if (typeof s.fleetView === "boolean") appliers.setFleetView(s.fleetView);
|
|
826
979
|
if (typeof s.outputTranscript === "boolean") appliers.setOutputTranscript(s.outputTranscript);
|
|
980
|
+
if (typeof s.rememberAgents === "boolean") appliers.setRememberAgents(s.rememberAgents);
|
|
981
|
+
if (s.agentMentions) appliers.setAgentMentions(s.agentMentions);
|
|
982
|
+
if (typeof s.supervisorQuestions === "boolean") appliers.setSupervisorQuestions(s.supervisorQuestions);
|
|
827
983
|
if (s.workflow) appliers.setWorkflow?.(s.workflow);
|
|
828
984
|
// Applied unconditionally so a session that had tiers and no longer does gets
|
|
829
985
|
// the empty catalogue rather than keeping the previous one.
|