@signalridge/pi-subagents 1.4.0 → 1.6.1

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.
@@ -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
+ }
@@ -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
- let writtenCount = 1; // initial user prompt already written
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;