@lune_99/pi-subagent 0.1.0 → 0.2.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.
@@ -1,6 +1,5 @@
1
- import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
1
  import { defineTool, type Theme, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
- import { Text } from "@earendil-works/pi-tui";
2
+ import { stripTerminalSequences, Text } from "@earendil-works/pi-tui";
4
3
  import Type, { type TSchema } from "typebox";
5
4
 
6
5
  import type { ToolCatalog } from "../catalog.ts";
@@ -9,15 +8,9 @@ import { AUTO_MODEL } from "../models.ts";
9
8
  import { REPORT_TOOL_NAME } from "../run/report-tool.ts";
10
9
  import type { RunManager, StartParams } from "../run/run-manager.ts";
11
10
  import type { SendOutcome } from "../run/run.ts";
12
- import { ISOLATION_MODES, THINKING_LEVELS, type Isolation } from "../run/types.ts";
11
+ import { ISOLATION_MODES, THINKING_LEVELS } from "../run/types.ts";
13
12
  import { stringEnum } from "../schema.ts";
14
- import {
15
- formatRunList,
16
- formatRunStatus,
17
- formatStarted,
18
- formatStartedBatch,
19
- type StartOutcome,
20
- } from "./format.ts";
13
+ import { formatRunList, formatRunStatus, formatStarted } from "./format.ts";
21
14
 
22
15
  export const SUBAGENT_TOOL_NAMES = [
23
16
  "subagent_start",
@@ -29,23 +22,6 @@ export const SUBAGENT_TOOL_NAMES = [
29
22
  /** A catalog description keeps only the first sentence of each tool's own description. */
30
23
  const CATALOG_DESCRIPTION_CHARS = 100;
31
24
 
32
- /** One run's start values: the top level of `subagent_start`, or one entry of its `tasks`. */
33
- interface RunInput {
34
- task: string;
35
- agent?: string;
36
- model?: string;
37
- thinking?: ThinkingLevel;
38
- tools?: string[];
39
- isolation?: Isolation;
40
- }
41
-
42
- interface StartInput extends Partial<RunInput> {
43
- tasks?: RunInput[];
44
- }
45
-
46
- /** The start values that a `tasks` call takes in each entry, not at the top level. */
47
- const RUN_FIELDS = ["agent", "model", "thinking", "tools", "isolation"] as const;
48
-
49
25
  const TASK_DESCRIPTION =
50
26
  "The run's first message; it does not inherit your conversation. Give the goal, relevant " +
51
27
  "context and paths, expected output, acceptance checks and action limits. For edits, assign " +
@@ -56,12 +32,15 @@ export interface SubagentToolsOptions {
56
32
  definitions: readonly AgentDefinition[];
57
33
  /** `provider/id` references the `model` parameter allows. */
58
34
  models: readonly string[];
35
+ /** Auto mode only: the schema has no `model`, and inline runs use `model: auto`. */
36
+ autoOnly: boolean;
59
37
  catalog: ToolCatalog;
60
38
  }
61
39
 
62
40
  /**
63
- * The main agent's four tools. Their descriptions are fixed; only the `subagent_start` schema
64
- * depends on the session, and it is built once at `session_start` and kept for the session.
41
+ * The main agent's four tools. Only `subagent_start` depends on the session, through its schema
42
+ * and the inline settings it names; it is rebuilt only when the allowed models or Auto mode only
43
+ * change.
65
44
  */
66
45
  export function createSubagentTools(options: SubagentToolsOptions): ToolDefinition[] {
67
46
  const { manager } = options;
@@ -73,89 +52,45 @@ export function createSubagentTools(options: SubagentToolsOptions): ToolDefiniti
73
52
  "Start a separate Pi session for a bounded task in the background. Delegate when " +
74
53
  "independent execution, isolated context or a fresh verification pass improves speed " +
75
54
  "or quality. Handle quick tasks and tightly coupled steps directly. Use agent to " +
76
- 'reuse a listed role, or omit it for an inline task. Use isolation "shared" to work ' +
77
- 'in your current directory, including uncommitted changes; use "worktree" for a ' +
78
- "separate Git checkout at HEAD, without uncommitted or untracked files. Tool selection " +
79
- "and worktrees are not a security sandbox. Give task for one run or tasks for " +
80
- "independent runs started together. The call returns run IDs immediately; each turn's " +
81
- "report arrives as a message.",
55
+ "run a listed role with its own settings; give only task and title with it. Omit " +
56
+ `agent for an inline run that sets ${inlineSettings(options.autoOnly)} in the call` +
57
+ (options.autoOnly
58
+ ? "; the user's auto settings choose its model and thinking. "
59
+ : ". ") +
60
+ 'Use isolation "shared" to work in your current directory, including uncommitted ' +
61
+ 'changes; use "worktree" for a separate Git checkout at HEAD, without uncommitted or ' +
62
+ "untracked files. Tool selection and worktrees are not a security sandbox. Call once " +
63
+ "per run; independent starts can run in parallel. The call returns the run ID " +
64
+ "immediately; each turn's report arrives as a message.",
82
65
  promptSnippet: "Delegate bounded work to a background session and receive its report.",
83
66
  promptGuidelines: [
67
+ "Give a run a brief title so the user can identify it in the /agents inspector and Dock.",
84
68
  "Keep your work distinct from delegated work unless overlap is intentional verification. Coordinate shared-file edits so writers do not overlap.",
85
69
  "Reports arrive when turns end; do not poll subagent_status. Continue other useful work, or end your turn if none remains.",
86
70
  "When a run reports needs_input, answer with subagent_send if you can. Ask the user only when only the user can answer.",
71
+ "Pass a run's ID, never its name or title, to subagent_send, subagent_status and subagent_stop.",
87
72
  "Validate findings and changes you rely on. Worktree changes stay there until explicitly reviewed and integrated; nothing merges automatically.",
88
73
  ],
89
- parameters: Type.Object(startProperties(options)),
74
+ parameters: Type.Object(startProperties(options), { additionalProperties: false }),
90
75
 
91
76
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
92
77
  // The schema is built at runtime, so its static type is loose; Pi has validated the
93
78
  // arguments against it.
94
- const input = params as unknown as StartInput;
95
- const progress = (text: string): void =>
96
- onUpdate?.({ content: [{ type: "text", text }], details: undefined });
97
-
98
- if (input.tasks === undefined) {
99
- if (input.task === undefined) {
100
- throw new Error("Give task for one run, or tasks for several runs.");
101
- }
102
-
103
- const run = await manager.start(startParams(input.task, input), ctx, {
104
- signal,
105
- onProgress: progress,
106
- });
107
-
108
- return {
109
- content: [{ type: "text", text: formatStarted(run) }],
110
- details: undefined,
111
- };
112
- }
113
-
114
- const entries = input.tasks;
115
-
116
- checkBatch(input, entries);
117
-
118
- // Each entry starts on its own, as parallel calls would: a failed one undoes only its
119
- // own work, because a run that started cannot be taken back.
120
- const steps = entries.map(() => "Starting");
121
- const outcomes = await Promise.all(
122
- entries.map(async (entry, index): Promise<StartOutcome> => {
123
- try {
124
- const run = await manager.start(startParams(entry.task, entry), ctx, {
125
- signal,
126
- onProgress: (text) => {
127
- steps[index] = text;
128
- progress(batchProgress(steps));
129
- },
130
- });
131
-
132
- steps[index] = `Started run ${run.name} (${run.id})`;
133
-
134
- return { run };
135
- } catch (error) {
136
- steps[index] = "Failed";
137
-
138
- return { error: error instanceof Error ? error.message : String(error) };
139
- } finally {
140
- progress(batchProgress(steps));
141
- }
142
- }),
143
- );
144
- const text = formatStartedBatch(outcomes);
145
-
146
- if (outcomes.every((outcome) => "error" in outcome)) {
147
- throw new Error(text);
148
- }
79
+ const input = params as unknown as StartParams;
80
+ const run = await manager.start(input, ctx, {
81
+ signal,
82
+ onProgress: (text) =>
83
+ onUpdate?.({ content: [{ type: "text", text }], details: undefined }),
84
+ });
149
85
 
150
- return { content: [{ type: "text", text }], details: undefined };
86
+ return {
87
+ content: [{ type: "text", text: formatStarted(run) }],
88
+ details: undefined,
89
+ };
151
90
  },
152
91
 
153
92
  renderCall(args, theme) {
154
- const input = args as Partial<StartInput>;
155
-
156
- if (Array.isArray(input.tasks)) {
157
- return batchCall(theme, input.tasks);
158
- }
93
+ const input = args as Partial<StartParams>;
159
94
 
160
95
  return callLine(theme, "subagent_start", [
161
96
  input.agent ?? "inline",
@@ -177,7 +112,11 @@ export function createSubagentTools(options: SubagentToolsOptions): ToolDefiniti
177
112
  "accepted the message; a message arrives when the turn ends.",
178
113
  promptSnippet: "Answer, steer or continue a subagent run.",
179
114
  parameters: Type.Object({
180
- runId: Type.String({ description: "The run ID that subagent_start returned." }),
115
+ runId: Type.String({
116
+ description:
117
+ "The run ID that subagent_start returned, such as 8416992c. Pass the ID, not " +
118
+ "the run's name or title.",
119
+ }),
181
120
  message: Type.String({ description: "The message for the run." }),
182
121
  }),
183
122
 
@@ -190,7 +129,7 @@ export function createSubagentTools(options: SubagentToolsOptions): ToolDefiniti
190
129
  });
191
130
 
192
131
  return {
193
- content: [{ type: "text", text: sendText(run.name, run.id, outcome) }],
132
+ content: [{ type: "text", text: sendText(run.id, outcome) }],
194
133
  details: undefined,
195
134
  };
196
135
  },
@@ -211,7 +150,13 @@ export function createSubagentTools(options: SubagentToolsOptions): ToolDefiniti
211
150
  "with a preview of its report; with runId it returns that run's whole report.",
212
151
  promptSnippet: "Read the state and last report of subagent runs.",
213
152
  parameters: Type.Object({
214
- runId: Type.Optional(Type.String({ description: "One run ID. Default: every run." })),
153
+ runId: Type.Optional(
154
+ Type.String({
155
+ description:
156
+ "One run ID, such as 8416992c. Default: every run. Pass the ID, not the " +
157
+ "run's name or title.",
158
+ }),
159
+ ),
215
160
  }),
216
161
 
217
162
  async execute(_toolCallId, params) {
@@ -239,15 +184,19 @@ export function createSubagentTools(options: SubagentToolsOptions): ToolDefiniti
239
184
  "no turn-end message for a run you stop; this result holds its state.",
240
185
  promptSnippet: "Stop a running subagent run.",
241
186
  parameters: Type.Object({
242
- runId: Type.String({ description: "The run ID that subagent_start returned." }),
187
+ runId: Type.String({
188
+ description:
189
+ "The run ID that subagent_start returned, such as 8416992c. Pass the ID, not " +
190
+ "the run's name or title.",
191
+ }),
243
192
  }),
244
193
 
245
194
  async execute(_toolCallId, params) {
246
195
  const run = manager.branchRun(params.runId);
247
196
  const stopped = await manager.stop(run, "main-agent");
248
197
  const text = stopped
249
- ? `Stopped run ${run.name} (${run.id}).\n\n${formatRunStatus(run)}`
250
- : `Run ${run.name} (${run.id}) is not running; its state is ${run.state}.`;
198
+ ? `Stopped run ${run.id}.\n\n${formatRunStatus(run)}`
199
+ : `Run ${run.id} is not running; its state is ${run.state}.`;
251
200
 
252
201
  return { content: [{ type: "text", text }], details: undefined };
253
202
  },
@@ -262,37 +211,8 @@ export function createSubagentTools(options: SubagentToolsOptions): ToolDefiniti
262
211
  return [start, send, status, stop];
263
212
  }
264
213
 
214
+ /** The agent comes first, so a call names its role before writing the task and inline settings. */
265
215
  function startProperties(options: SubagentToolsOptions): Record<string, TSchema> {
266
- return {
267
- task: Type.Optional(
268
- Type.String({ description: `${TASK_DESCRIPTION} Leave it out when you give tasks.` }),
269
- ),
270
- ...runOptions(options, toolsDescription(options.catalog)),
271
- tasks: Type.Optional(
272
- Type.Array(
273
- Type.Object({
274
- task: Type.String({ description: TASK_DESCRIPTION }),
275
- // The catalog is long, so an entry points to it instead of repeating it.
276
- ...runOptions(
277
- options,
278
- "Exact names of the task tools the run gets, from the list of the " +
279
- "top-level tools parameter. Default: the agent's tools, then the " +
280
- "defaultTools setting.",
281
- ),
282
- }),
283
- {
284
- description:
285
- "Independent runs started together instead of task. Set agent, model, " +
286
- "thinking, tools and isolation per entry, not at the top level. A failed " +
287
- "start does not stop the other runs.",
288
- },
289
- ),
290
- ),
291
- };
292
- }
293
-
294
- /** The optional start values of one run, at the top level and in each `tasks` entry. */
295
- function runOptions(options: SubagentToolsOptions, toolsText: string): Record<string, TSchema> {
296
216
  const properties: Record<string, TSchema> = {};
297
217
  const agents = options.definitions.map((definition) => definition.name);
298
218
 
@@ -300,39 +220,60 @@ function runOptions(options: SubagentToolsOptions, toolsText: string): Record<st
300
220
  properties.agent = Type.Optional(
301
221
  stringEnum(agents, {
302
222
  description:
303
- "An agent from the subagents list. Leave it out to set up the run in this call.",
223
+ "An agent from the subagents list. It runs with its definition's model, " +
224
+ "thinking, tools and isolation, so give only task and title with it. Leave " +
225
+ `it out to set ${options.autoOnly ? inlineSettings(true) : "these"} in this call.`,
304
226
  }),
305
227
  );
306
228
  }
307
229
 
308
- if (options.models.length > 0) {
230
+ properties.title = Type.Optional(
231
+ Type.String({
232
+ description:
233
+ "A brief one-line title for this run, shown in the /agents inspector, Dock and " +
234
+ "run notifications. The subagent tools take a run's ID, never its title.",
235
+ }),
236
+ );
237
+ properties.task = Type.String({ description: TASK_DESCRIPTION });
238
+
239
+ const inlineOnly = agents.length > 0 ? "Only without agent. " : "";
240
+
241
+ if (!options.autoOnly && options.models.length > 0) {
309
242
  properties.model = Type.Optional(
310
243
  stringEnum([AUTO_MODEL, ...options.models], {
311
244
  description:
312
- `provider/id, or "${AUTO_MODEL}" to let a classifier rate the task and use ` +
313
- "the model set for its tier; it also sets thinking when the call and the " +
314
- "agent do not. Default: the agent's model, then your current model.",
245
+ `${inlineOnly}provider/id, or "${AUTO_MODEL}" to route both the model and ` +
246
+ "thinking for each task. Omit thinking with auto. Default: your current model.",
315
247
  }),
316
248
  );
317
249
  }
318
250
 
319
- properties.thinking = Type.Optional(
320
- stringEnum(THINKING_LEVELS, {
321
- description:
322
- "Default: the agent's thinking level, then the classifier's level for model " +
323
- "auto, then your current level.",
251
+ if (!options.autoOnly) {
252
+ properties.thinking = Type.Optional(
253
+ stringEnum(THINKING_LEVELS, {
254
+ description:
255
+ `${inlineOnly}Only for a fixed or inherited model; omit with model auto, ` +
256
+ "which chooses both model and thinking. Default: your current level.",
257
+ }),
258
+ );
259
+ }
260
+ properties.tools = Type.Optional(
261
+ Type.Array(Type.String(), {
262
+ description: `${inlineOnly}${toolsDescription(options.catalog)}`,
324
263
  }),
325
264
  );
326
- properties.tools = Type.Optional(Type.Array(Type.String(), { description: toolsText }));
327
265
  properties.isolation = Type.Optional(
328
- stringEnum(ISOLATION_MODES, {
329
- description: 'Default: the agent\'s isolation, then "shared".',
330
- }),
266
+ stringEnum(ISOLATION_MODES, { description: `${inlineOnly}Default: "shared".` }),
331
267
  );
332
268
 
333
269
  return properties;
334
270
  }
335
271
 
272
+ /** The settings an inline run takes from the call; under Auto mode only, the model is auto. */
273
+ function inlineSettings(autoOnly: boolean): string {
274
+ return autoOnly ? "tools and isolation" : "model, thinking, tools and isolation";
275
+ }
276
+
336
277
  function toolsDescription(catalog: ToolCatalog): string {
337
278
  const tools = catalog.tools
338
279
  .filter((tool) => tool.name !== REPORT_TOOL_NAME)
@@ -340,8 +281,8 @@ function toolsDescription(catalog: ToolCatalog): string {
340
281
 
341
282
  return [
342
283
  "Exact names of the task tools the run gets. Choose only tools needed for this task; " +
343
- "prefer read-only tools for investigation. Default: the agent's tools, then the " +
344
- "defaultTools setting. The run always gets report as well.",
284
+ "prefer read-only tools for investigation. Default: the defaultTools setting. The " +
285
+ "run always gets report as well.",
345
286
  "Available:",
346
287
  ...tools.map((line) => `- ${line}`),
347
288
  "- mcp__<server>__<tool>: a tool of an MCP server configured for the run's working directory.",
@@ -358,51 +299,14 @@ function firstSentence(text: string): string {
358
299
  : sentence;
359
300
  }
360
301
 
361
- function startParams(task: string, values: Omit<RunInput, "task">): StartParams {
362
- return {
363
- task,
364
- agent: values.agent,
365
- model: values.model,
366
- thinking: values.thinking,
367
- tools: values.tools,
368
- isolation: values.isolation,
369
- };
370
- }
371
-
372
- /** A `tasks` call takes start values only in its entries, so a mixed call starts nothing. */
373
- function checkBatch(input: StartInput, entries: readonly RunInput[]): void {
374
- if (input.task !== undefined) {
375
- throw new Error("Give task for one run or tasks for several runs, not both.");
376
- }
377
-
378
- const topLevel = RUN_FIELDS.filter((field) => input[field] !== undefined);
379
-
380
- if (topLevel.length > 0) {
381
- throw new Error(
382
- `With tasks, set ${topLevel.join(", ")} in each entry instead of at the top level.`,
383
- );
384
- }
385
-
386
- if (entries.length === 0) {
387
- throw new Error("tasks has no entries.");
388
- }
389
- }
390
-
391
- function batchProgress(steps: readonly string[]): string {
392
- return [
393
- `Starting ${steps.length} run${steps.length === 1 ? "" : "s"}`,
394
- ...steps.map((step, index) => `tasks[${index}]: ${step}`),
395
- ].join("\n");
396
- }
397
-
398
- function sendText(name: string, runId: string, outcome: SendOutcome): string {
302
+ function sendText(runId: string, outcome: SendOutcome): string {
399
303
  switch (outcome) {
400
304
  case "started":
401
- return `Run ${name} (${runId}) started a new turn with your message. A message arrives when the turn ends.`;
305
+ return `Run ${runId} started a new turn with your message. A message arrives when the turn ends.`;
402
306
  case "steered":
403
- return `Run ${name} (${runId}) is running; your message steers its current turn.`;
307
+ return `Run ${runId} is running; your message steers its current turn.`;
404
308
  case "deferred":
405
- return `Run ${name} (${runId}) is ending its turn; your message starts the next turn after it.`;
309
+ return `Run ${runId} is ending its turn; your message starts the next turn after it.`;
406
310
  }
407
311
  }
408
312
 
@@ -419,22 +323,6 @@ function callText(theme: Theme, tool: string, parts: readonly (string | undefine
419
323
  );
420
324
  }
421
325
 
422
- /** A `tasks` call: the run count, then one line per entry. An entry can still be streaming. */
423
- function batchCall(theme: Theme, entries: readonly unknown[]): Text {
424
- const lines = entries.map((entry) => {
425
- const run = (typeof entry === "object" && entry !== null ? entry : {}) as Partial<RunInput>;
426
- const parts = shownParts([
427
- typeof run.agent === "string" ? run.agent : "inline",
428
- preview(run.task),
429
- ]);
430
-
431
- return ` ${theme.fg("muted", parts.join(" · "))}`;
432
- });
433
- const count = `${entries.length} run${entries.length === 1 ? "" : "s"}`;
434
-
435
- return new Text([callText(theme, "subagent_start", [count]), ...lines].join("\n"), 0, 0);
436
- }
437
-
438
326
  function shownParts(parts: readonly (string | undefined)[]): string[] {
439
327
  return parts.filter((part): part is string => part !== undefined && part !== "");
440
328
  }
@@ -445,7 +333,7 @@ function preview(text: unknown): string | undefined {
445
333
  return undefined;
446
334
  }
447
335
 
448
- const line = text.replace(/\s+/g, " ").trim();
336
+ const line = stripTerminalSequences(text).replace(/\s+/g, " ").trim();
449
337
 
450
338
  return line.length > 60 ? `${line.slice(0, 59)}…` : line;
451
339
  }