@luxass/pi-subagents 0.0.0-stage → 0.1.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.
@@ -0,0 +1,81 @@
1
+ import type { AutocompleteProviderFactory } from "@earendil-works/pi-coding-agent";
2
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
3
+
4
+ import type { SubagentDefinition } from "./agents.ts";
5
+
6
+ const LEADING_TYPE_MENTION = /^@([a-z0-9]+(?:-[a-z0-9]+)*)[ \t]+(\S[\s\S]*)$/;
7
+ const TYPING_LEADING_MENTION = /^@([a-z0-9-]*)$/;
8
+
9
+ /** Custom message type of the hidden instruction that follows a type mention. */
10
+ export const SUBAGENT_MENTION_MESSAGE = "subagents-mention";
11
+
12
+ /**
13
+ * For `@explorer review authentication`, returns a hidden instruction for the main model.
14
+ * Returns undefined when the prompt is not a leading mention of an available type.
15
+ */
16
+ export function subagentMentionInstruction(
17
+ prompt: string,
18
+ types: readonly SubagentDefinition[],
19
+ ): string | undefined {
20
+ const type = LEADING_TYPE_MENTION.exec(prompt)?.[1];
21
+ if (!type || !types.some((definition) => definition.name === type)) return undefined;
22
+ return `The user asked for a new "${type}" agent. Call Agent with subagent_type "${type}", a new task name, and a prompt you prepare from their message. Start a new agent even if other ${type} agents exist.`;
23
+ }
24
+
25
+ /** Adds agent types to `@` completion at the start of the prompt, keeping Pi's file suggestions. */
26
+ export function subagentMentionAutocomplete(
27
+ types: () => readonly SubagentDefinition[],
28
+ ): AutocompleteProviderFactory {
29
+ return (current) => {
30
+ const ours = new WeakSet<AutocompleteItem>();
31
+ return {
32
+ triggerCharacters: current.triggerCharacters,
33
+ shouldTriggerFileCompletion: current.shouldTriggerFileCompletion?.bind(current),
34
+ async getSuggestions(lines, cursorLine, cursorCol, options) {
35
+ const base = await current.getSuggestions(lines, cursorLine, cursorCol, options);
36
+ const typed =
37
+ cursorLine === 0
38
+ ? TYPING_LEADING_MENTION.exec((lines[0] ?? "").slice(0, cursorCol))
39
+ : null;
40
+ const query = typed?.[1];
41
+ if (query === undefined) return base;
42
+ const matches = types().filter((definition) => definition.name.startsWith(query));
43
+ if (!matches.length) return base;
44
+ const prefix = `@${query}`;
45
+ const names = new Set(matches.map((definition) => definition.name));
46
+ const typeItems = matches.map((definition) => {
47
+ const item: AutocompleteItem = {
48
+ value: `@${definition.name} `,
49
+ label: `@${definition.name}`,
50
+ description: `ask Pi to start ${definition.name} · ${definition.description}`,
51
+ };
52
+ ours.add(item);
53
+ return item;
54
+ });
55
+ // A file with a type's name stays reachable through an explicit path.
56
+ const fileItems =
57
+ base?.prefix === prefix
58
+ ? base.items.map((item) => {
59
+ const path = item.value.replace(/^@/, "").replace(/\/$/, "");
60
+ if (!names.has(path)) return item;
61
+ return {
62
+ value: `@./${item.value.replace(/^@/, "")}`,
63
+ label: item.label,
64
+ description: item.description,
65
+ };
66
+ })
67
+ : [];
68
+ return { prefix, items: [...typeItems, ...fileItems] };
69
+ },
70
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
71
+ if (!ours.has(item))
72
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
73
+ const line = lines[cursorLine] ?? "";
74
+ const start = cursorCol - prefix.length;
75
+ const next = [...lines];
76
+ next[cursorLine] = line.slice(0, start) + item.value + line.slice(cursorCol);
77
+ return { lines: next, cursorLine, cursorCol: start + item.value.length };
78
+ },
79
+ };
80
+ };
81
+ }
@@ -0,0 +1,16 @@
1
+ /** One part of a message's content. Only text parts have `text`. */
2
+ interface SubagentMessagePart {
3
+ type: string;
4
+ text?: string;
5
+ }
6
+
7
+ /**
8
+ * The text of a message's content: its text parts joined by line breaks. Other parts, such as
9
+ * images, thinking, and tool calls, are left out.
10
+ */
11
+ export function subagentMessageText(content: string | readonly SubagentMessagePart[]): string {
12
+ if (typeof content === "string") return content;
13
+ return content
14
+ .flatMap((part) => (part.type === "text" && part.text ? [part.text] : []))
15
+ .join("\n");
16
+ }
package/src/models.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** A model an agent can run on: one of Pi's available models. */
4
+ export type SubagentModel = NonNullable<ExtensionContext["model"]>;
5
+
6
+ function modelName(model: SubagentModel): string {
7
+ return `${model.provider}/${model.id}`;
8
+ }
9
+
10
+ /** Letters and digits only, so `Opus 5.5` and `claude-opus-5-5` agree on their shared part. */
11
+ function plainModelText(text: string): string {
12
+ return text.toLowerCase().replace(/[^a-z0-9]/g, "");
13
+ }
14
+
15
+ /** Up to five available models that share a word with the request, best first. */
16
+ function closestModels(available: readonly SubagentModel[], requested: string): string[] {
17
+ const words = requested.toLowerCase().match(/[a-z]{2,}/g) ?? [];
18
+ return available
19
+ .map((model) => {
20
+ const name = plainModelText(modelName(model));
21
+ return { model, score: words.filter((word) => name.includes(word)).length };
22
+ })
23
+ .filter((candidate) => candidate.score > 0)
24
+ .toSorted((first, second) => second.score - first.score)
25
+ .slice(0, 5)
26
+ .map((candidate) => modelName(candidate.model));
27
+ }
28
+
29
+ /**
30
+ * Finds the one available model a `model` value names. `provider/id` is used as written.
31
+ * Any other name ignores case, spaces, dots, and hyphens, so `opus 5.5` finds `claude-opus-5-5`.
32
+ *
33
+ * The closest kind of match decides: the whole name, then the end of the id, then any part of it.
34
+ * When that leaves models on several providers, the first provider in `preferredProviders` that
35
+ * has exactly one of them is used. Anything still unclear is rejected with the models it could be.
36
+ */
37
+ export function findSubagentModel(
38
+ available: readonly SubagentModel[],
39
+ requested: string,
40
+ preferredProviders: readonly string[],
41
+ ): SubagentModel {
42
+ const written = available.find((model) => modelName(model) === requested);
43
+ if (written) return written;
44
+
45
+ const wanted = plainModelText(requested);
46
+ const kindsOfMatch: ((model: SubagentModel) => boolean)[] = [
47
+ (model) => plainModelText(model.id) === wanted || plainModelText(modelName(model)) === wanted,
48
+ (model) => plainModelText(model.id).endsWith(wanted),
49
+ (model) => plainModelText(modelName(model)).includes(wanted),
50
+ ];
51
+ const matches = wanted
52
+ ? (kindsOfMatch
53
+ .map((matchesModel) => available.filter(matchesModel))
54
+ .find((found) => found.length) ?? [])
55
+ : [];
56
+
57
+ const [only] = matches;
58
+ if (matches.length === 1 && only) return only;
59
+ if (!matches.length) {
60
+ const closest = closestModels(available, requested);
61
+ const hint = closest.length ? ` Closest available models: ${closest.join(", ")}.` : "";
62
+ throw new Error(`No available model matches "${requested}".${hint}`);
63
+ }
64
+
65
+ for (const provider of preferredProviders) {
66
+ const fromProvider = matches.filter((model) => model.provider === provider);
67
+ const [preferred] = fromProvider;
68
+ if (fromProvider.length === 1 && preferred) return preferred;
69
+ // Several models on the preferred provider are still unclear.
70
+ if (fromProvider.length > 1) break;
71
+ }
72
+ const names = matches.slice(0, 8).map(modelName).join(", ");
73
+ throw new Error(
74
+ `Model "${requested}" matches ${matches.length} models: ${names}. Use provider/id, or list the provider to prefer in the subagents.preferredProviders setting.`,
75
+ );
76
+ }
package/src/results.ts ADDED
@@ -0,0 +1,237 @@
1
+ import type {
2
+ BoundaryResult,
3
+ CustomMessageEntryDraft,
4
+ ExtensionAPI,
5
+ ExtensionContext,
6
+ TurnEndEvent,
7
+ } from "@earendil-works/pi-coding-agent";
8
+
9
+ import { isSubagentFinished, type SubagentManager, type SubagentRecord } from "./manager.ts";
10
+
11
+ /** Custom message type of automatically delivered results. */
12
+ export const SUBAGENT_RESULT_MESSAGE = "subagents-result";
13
+
14
+ /** Longest result text the main model receives automatically. */
15
+ export const SUBAGENT_RESULT_LIMIT = 8000;
16
+
17
+ /** Longest wait for siblings in grouped delivery, from the first ready result. */
18
+ const GROUP_WAIT_MS = 60_000;
19
+
20
+ /** Time between checks while Pi compacts or summarizes a branch on the user's command. */
21
+ const IDLE_CHECK_MS = 1000;
22
+
23
+ /** Snapshots shown by the result block. They keep the full text for expansion. */
24
+ export interface SubagentResultDetails {
25
+ records: SubagentRecord[];
26
+ }
27
+
28
+ /** Cuts automatically delivered text at the limit and points to the full result. */
29
+ function cutSubagentResult(text: string, name: string): string {
30
+ if (text.length <= SUBAGENT_RESULT_LIMIT) return text;
31
+ return (
32
+ text.slice(0, SUBAGENT_RESULT_LIMIT) +
33
+ `\n\n[Result cut at ${SUBAGENT_RESULT_LIMIT} characters. Call get_subagent_result with name "${name}" for the full text.]`
34
+ );
35
+ }
36
+
37
+ function resultText(record: SubagentRecord): string {
38
+ const partial = record.partial ? " (partial: turn limit reached)" : "";
39
+ const header = `Agent ${record.name} (${record.agentType}) ${record.status}${partial}.`;
40
+ if (record.stoppedBy === "user") {
41
+ const result = cutSubagentResult(record.result, record.name);
42
+ return `${header} The user stopped it.${result ? `\n\n${result}` : ""}`;
43
+ }
44
+ let body = record.result || record.error || "(no answer)";
45
+ if (record.error && record.result) body += `\nError: ${record.error}`;
46
+ return `${header}\n\n${cutSubagentResult(body, record.name)}`;
47
+ }
48
+
49
+ /** Decides when and how finished background results reach the main model. */
50
+ export class SubagentDelivery {
51
+ private busy = false;
52
+ private disposed = false;
53
+ /** Ready results the model has not read yet, in completion order. */
54
+ private ready: SubagentRecord[] = [];
55
+ /** When each request's first unread result became ready, for the grouped deadline. */
56
+ private readyAt = new Map<number, number>();
57
+ private timers = new Map<number, ReturnType<typeof setTimeout>>();
58
+ private idleCheck: ReturnType<typeof setTimeout> | undefined;
59
+
60
+ constructor(
61
+ private readonly pi: ExtensionAPI,
62
+ private readonly ctx: ExtensionContext,
63
+ private readonly manager: SubagentManager,
64
+ ) {
65
+ manager.onRunSettled = (record) => this.settled(record);
66
+ }
67
+
68
+ private settled(record: SubagentRecord): void {
69
+ if (this.disposed) return;
70
+ if (record.receipt === "unread") {
71
+ // A continued agent can still wait here with its earlier result. Its newest result replaces
72
+ // that one, so the agent is reported once.
73
+ this.ready = this.ready.filter((waiting) => waiting !== record);
74
+ this.ready.push(record);
75
+ if (!this.readyAt.has(record.requestId)) this.readyAt.set(record.requestId, Date.now());
76
+ }
77
+ // A suppressed sibling can also complete a waiting group.
78
+ this.flushWhenIdle();
79
+ }
80
+
81
+ /**
82
+ * After a reload or a resumed session: delivers results that had finished before it but were
83
+ * still waiting, for example for a sibling in grouped mode.
84
+ */
85
+ deliverRestored(): void {
86
+ for (const record of this.manager.list()) {
87
+ if (record.receipt !== "unread") continue;
88
+ this.ready.push(record);
89
+ if (!this.readyAt.has(record.requestId)) this.readyAt.set(record.requestId, Date.now());
90
+ }
91
+ this.flushWhenIdle();
92
+ }
93
+
94
+ /** The main session started a run, so ready results wait for a boundary instead. */
95
+ agentStarted(): void {
96
+ this.busy = true;
97
+ for (const timer of this.timers.values()) clearTimeout(timer);
98
+ this.timers.clear();
99
+ clearTimeout(this.idleCheck);
100
+ this.idleCheck = undefined;
101
+ }
102
+
103
+ /** At a turn boundary that continues, add ready results to the next request without an extra one. */
104
+ turnEnded(event: TurnEndEvent): BoundaryResult | undefined {
105
+ if (this.disposed || event.toolResults.length === 0) return undefined;
106
+ const batch = this.take(this.ready);
107
+ if (!batch.length) return undefined;
108
+ const draft: CustomMessageEntryDraft = {
109
+ type: "custom_message",
110
+ customType: SUBAGENT_RESULT_MESSAGE,
111
+ content: batch.map(resultText).join("\n\n---\n\n"),
112
+ display: true,
113
+ details: { records: batch.map((record) => ({ ...record })) } satisfies SubagentResultDetails,
114
+ };
115
+ for (const record of batch) this.manager.markReceipt(record, "delivered");
116
+ return { entries: [...event.entries, draft] };
117
+ }
118
+
119
+ /** The main session stopped. Results it did not read are now idle deliveries. */
120
+ agentSettled(): void {
121
+ this.busy = false;
122
+ this.flushIdle();
123
+ }
124
+
125
+ /**
126
+ * Delivers ready results when no main-model run is active. Pi is also not idle while it compacts
127
+ * or summarizes a branch on the user's command, and no main-model run ends that. So delivery
128
+ * checks again until Pi is idle.
129
+ */
130
+ private flushWhenIdle(): void {
131
+ if (this.busy || this.disposed) return;
132
+ if (this.ctx.isIdle()) {
133
+ this.flushIdle();
134
+ return;
135
+ }
136
+ this.idleCheck ??= setTimeout(() => {
137
+ this.idleCheck = undefined;
138
+ this.flushWhenIdle();
139
+ }, IDLE_CHECK_MS);
140
+ }
141
+
142
+ private flushIdle(): void {
143
+ if (this.disposed) return;
144
+ this.forgetDelivered();
145
+ if (this.manager.settings.delivery.mode === "immediate") {
146
+ this.send(this.take(this.ready));
147
+ return;
148
+ }
149
+ const requests = new Set(this.ready.map((record) => record.requestId));
150
+ for (const requestId of requests) {
151
+ const group = this.ready.filter((record) => record.requestId === requestId);
152
+ const outstanding = this.manager
153
+ .list()
154
+ .some(
155
+ (record) =>
156
+ record.requestId === requestId &&
157
+ record.background &&
158
+ record.receipt === "pending" &&
159
+ !isSubagentFinished(record.status),
160
+ );
161
+ if (!outstanding) {
162
+ this.sendGroup(group);
163
+ continue;
164
+ }
165
+ if (this.timers.has(requestId)) continue;
166
+ const deadline = (this.readyAt.get(requestId) ?? Date.now()) + GROUP_WAIT_MS;
167
+ const timer = setTimeout(
168
+ () => {
169
+ this.timers.delete(requestId);
170
+ if (this.busy || this.disposed) return;
171
+ if (!this.ctx.isIdle()) {
172
+ // Pi is compacting. The idle check sets this timer again, and it then fires at once.
173
+ this.flushWhenIdle();
174
+ return;
175
+ }
176
+ // Report what finished. Stragglers form the next batch.
177
+ this.sendGroup(this.ready.filter((record) => record.requestId === requestId));
178
+ },
179
+ Math.max(0, deadline - Date.now()),
180
+ );
181
+ this.timers.set(requestId, timer);
182
+ }
183
+ }
184
+
185
+ private sendGroup(group: SubagentRecord[]): void {
186
+ this.send(this.take(group));
187
+ }
188
+
189
+ /** Removes the given records from the ready list and keeps only those still unread. */
190
+ private take(records: SubagentRecord[]): SubagentRecord[] {
191
+ const taken = new Set(records);
192
+ this.ready = this.ready.filter((record) => !taken.has(record));
193
+ this.forgetDelivered();
194
+ return records.filter((record) => record.receipt === "unread");
195
+ }
196
+
197
+ /**
198
+ * Drops results that no longer wait, such as one the model read with get_subagent_result. A
199
+ * request with no waiting result loses its 60-second clock, so its next result starts a new wait.
200
+ */
201
+ private forgetDelivered(): void {
202
+ this.ready = this.ready.filter((record) => record.receipt === "unread");
203
+ for (const requestId of this.readyAt.keys()) {
204
+ if (!this.ready.some((record) => record.requestId === requestId)) {
205
+ this.readyAt.delete(requestId);
206
+ }
207
+ }
208
+ }
209
+
210
+ private send(batch: SubagentRecord[]): void {
211
+ if (!batch.length) return;
212
+ // Agents the user stopped report without starting a main-model turn.
213
+ const triggerTurn = batch.some((record) => record.stoppedBy !== "user");
214
+ for (const record of batch) this.manager.markReceipt(record, "delivered");
215
+ this.pi.sendMessage(
216
+ {
217
+ customType: SUBAGENT_RESULT_MESSAGE,
218
+ content: batch.map(resultText).join("\n\n---\n\n"),
219
+ display: true,
220
+ details: {
221
+ records: batch.map((record) => ({ ...record })),
222
+ } satisfies SubagentResultDetails,
223
+ },
224
+ { triggerTurn },
225
+ );
226
+ }
227
+
228
+ /** Stops delivery before shutdown aborts any agent, so nothing arrives late. */
229
+ dispose(): void {
230
+ this.disposed = true;
231
+ for (const timer of this.timers.values()) clearTimeout(timer);
232
+ this.timers.clear();
233
+ clearTimeout(this.idleCheck);
234
+ this.idleCheck = undefined;
235
+ this.ready = [];
236
+ }
237
+ }