@pi-unipi/subagents 2.3.0 → 2.4.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.
Files changed (66) hide show
  1. package/README.md +3 -1
  2. package/dist/agent-manager.d.ts +81 -0
  3. package/dist/agent-manager.d.ts.map +1 -0
  4. package/dist/agent-manager.js +292 -0
  5. package/dist/agent-manager.js.map +1 -0
  6. package/dist/agent-runner.d.ts +51 -0
  7. package/dist/agent-runner.d.ts.map +1 -0
  8. package/dist/agent-runner.js +262 -0
  9. package/dist/agent-runner.js.map +1 -0
  10. package/dist/config.d.ts +24 -0
  11. package/dist/config.d.ts.map +1 -0
  12. package/dist/config.js +132 -0
  13. package/dist/config.js.map +1 -0
  14. package/dist/conversation-viewer.d.ts +40 -0
  15. package/dist/conversation-viewer.d.ts.map +1 -0
  16. package/dist/conversation-viewer.js +276 -0
  17. package/dist/conversation-viewer.js.map +1 -0
  18. package/dist/core-compat.d.ts +14 -0
  19. package/dist/core-compat.d.ts.map +1 -0
  20. package/dist/core-compat.js +24 -0
  21. package/dist/core-compat.js.map +1 -0
  22. package/dist/custom-agents.d.ts +14 -0
  23. package/dist/custom-agents.d.ts.map +1 -0
  24. package/dist/custom-agents.js +106 -0
  25. package/dist/custom-agents.js.map +1 -0
  26. package/dist/file-lock.d.ts +42 -0
  27. package/dist/file-lock.d.ts.map +1 -0
  28. package/dist/file-lock.js +91 -0
  29. package/dist/file-lock.js.map +1 -0
  30. package/dist/index.d.ts +10 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +751 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/model-resolver.d.ts +19 -0
  35. package/dist/model-resolver.d.ts.map +1 -0
  36. package/dist/model-resolver.js +61 -0
  37. package/dist/model-resolver.js.map +1 -0
  38. package/dist/types.d.ts +96 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/types.js +47 -0
  41. package/dist/types.js.map +1 -0
  42. package/dist/widget.d.ts +56 -0
  43. package/dist/widget.d.ts.map +1 -0
  44. package/dist/widget.js +396 -0
  45. package/dist/widget.js.map +1 -0
  46. package/package.json +10 -6
  47. package/src/__tests__/badge-generation.test.ts +0 -315
  48. package/src/__tests__/config.test.ts +0 -240
  49. package/src/__tests__/esc-propagation.test.ts +0 -162
  50. package/src/__tests__/file-lock.test.ts +0 -244
  51. package/src/__tests__/shutdown-stale-ctx.test.ts +0 -185
  52. package/src/__tests__/workflow-integration.test.ts +0 -334
  53. package/src/agent-manager.ts +0 -334
  54. package/src/agent-runner.ts +0 -329
  55. package/src/config.ts +0 -147
  56. package/src/conversation-viewer.ts +0 -299
  57. package/src/custom-agents.ts +0 -118
  58. package/src/file-lock.ts +0 -102
  59. package/src/index.ts +0 -862
  60. package/src/model-resolver.ts +0 -79
  61. package/src/prompts.ts +0 -39
  62. package/src/skills/explore/SKILL.md +0 -32
  63. package/src/skills/work/SKILL.md +0 -40
  64. package/src/types.ts +0 -146
  65. package/src/widget.ts +0 -454
  66. package/tsconfig.json +0 -19
package/src/index.ts DELETED
@@ -1,862 +0,0 @@
1
- /**
2
- * @pi-unipi/subagents — Extension entry
3
- *
4
- * Tools: spawn_helper, get_helper_result
5
- * Features: renderCall/renderResult, message renderer, conversation viewer
6
- * ESC propagation: all children abort on parent ESC
7
- */
8
-
9
- import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
- import { Text } from "@earendil-works/pi-tui";
11
- import { Type } from "typebox";
12
- import { existsSync, readdirSync } from "node:fs";
13
- import { join } from "node:path";
14
- import { homedir } from "node:os";
15
- import { emitEvent, MODULES, UNIPI_EVENTS, withHerdrBlocked, type UnipiBadgeGenerateRequestEvent } from "@pi-unipi/core";
16
- import { AgentManager } from "./agent-manager.js";
17
- import { initConfig } from "./config.js";
18
- import { type AgentActivity, type NotificationDetails, BUILTIN_TYPES } from "./types.js";
19
- import { ConversationViewer } from "./conversation-viewer.js";
20
- import { AgentWidget } from "./widget.js";
21
-
22
- /** Get info registry from global */
23
- function getInfoRegistry() {
24
- return globalThis.__unipi_info_registry;
25
- }
26
-
27
- // ---- Formatting helpers (shared between renderers and inline text) ----
28
-
29
- const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
30
-
31
- /** Tool name → human-readable action. */
32
- const TOOL_DISPLAY: Record<string, string> = {
33
- read: "reading",
34
- bash: "running command",
35
- edit: "editing",
36
- write: "writing",
37
- grep: "searching",
38
- find: "finding files",
39
- ls: "listing",
40
- };
41
-
42
- function formatTokens(count: number): string {
43
- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M token`;
44
- if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k token`;
45
- return `${count} token`;
46
- }
47
-
48
- function formatTurns(turn: number, max?: number | null): string {
49
- return max != null ? `⟳${turn}≤${max}` : `⟳${turn}`;
50
- }
51
-
52
- function formatMs(ms: number): string {
53
- if (ms >= 60_000) return `${(ms / 60_000).toFixed(1)}m`;
54
- if (ms >= 1_000) return `${(ms / 1_000).toFixed(1)}s`;
55
- return `${ms}ms`;
56
- }
57
-
58
- /** Build activity description from active tools. */
59
- function describeActivity(activeTools: Map<string, string>, responseText?: string): string {
60
- if (activeTools.size > 0) {
61
- const groups = new Map<string, number>();
62
- for (const toolName of activeTools.values()) {
63
- const action = TOOL_DISPLAY[toolName] ?? toolName;
64
- groups.set(action, (groups.get(action) ?? 0) + 1);
65
- }
66
- const parts: string[] = [];
67
- for (const [action, count] of groups) {
68
- if (count > 1) {
69
- parts.push(`${action} ${count} ${action === "searching" ? "patterns" : "files"}`);
70
- } else {
71
- parts.push(action);
72
- }
73
- }
74
- return parts.join(", ") + "…";
75
- }
76
- if (responseText && responseText.trim().length > 0) {
77
- const line = responseText.split("\n").find((l) => l.trim())?.trim() ?? "";
78
- if (line.length > 60) return line.slice(0, 60) + "…";
79
- if (line.length > 0) return line;
80
- }
81
- return "thinking…";
82
- }
83
-
84
- /** Format tokens safely from session. */
85
- function safeFormatTokens(session: any): string {
86
- if (!session) return "";
87
- try {
88
- const stats = session.getSessionStats();
89
- const total = stats.tokens?.total ?? 0;
90
- return formatTokens(total);
91
- } catch {
92
- return "";
93
- }
94
- }
95
-
96
- /** Get raw token count from session. */
97
- function safeTokenCount(session: any): number {
98
- if (!session) return 0;
99
- try {
100
- return session.getSessionStats().tokens?.total ?? 0;
101
- } catch {
102
- return 0;
103
- }
104
- }
105
-
106
- /** Build result text */
107
- function textResult(msg: string, details?: any) {
108
- return { content: [{ type: "text" as const, text: msg }], details };
109
- }
110
-
111
- /** Escape XML for structured notifications. */
112
- function escapeXml(s: string): string {
113
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
114
- }
115
-
116
- /** Human-readable status label. */
117
- function getStatusLabel(status: string, error?: string): string {
118
- switch (status) {
119
- case "error": return `Error: ${error ?? "unknown"}`;
120
- case "aborted": return "Aborted (max turns exceeded)";
121
- case "stopped": return "Stopped";
122
- default: return "Done";
123
- }
124
- }
125
-
126
- export default function (pi: ExtensionAPI) {
127
- // Initialize config
128
- const config = initConfig(process.cwd());
129
- if (!config.enabled) return;
130
-
131
- // Compute paths at factory time
132
- const homeDir = homedir();
133
- const cwd = process.cwd();
134
- const globalAgentsDir = join(homeDir, ".unipi", "config", "agents");
135
- const workspaceAgentsDir = join(cwd, ".unipi", "config", "agents");
136
-
137
- // Activity tracking for widget
138
- const agentActivity = new Map<string, AgentActivity>();
139
-
140
- /**
141
- * Set once `session_shutdown` fires — after which `pi` must not be touched.
142
- *
143
- * Pi disposes the session as soon as the shutdown handlers resolve, and
144
- * `AgentSession.dispose()` invalidates the extension runtime. Every
145
- * `assertActive`-gated method (`sendMessage`, `setSessionName`,
146
- * `appendEntry`, `setModel`, …) then throws "This extension ctx is stale
147
- * after session replacement or reload".
148
- *
149
- * Background agents outlive that moment: `abortAll()` only signals their
150
- * AbortController, so the in-flight promise settles a microtask *later* and
151
- * fires this completion callback against a dead runtime — an unhandled
152
- * throw that crashed the process on exit.
153
- *
154
- * Scoped to the extension factory rather than module scope on purpose:
155
- * `session_shutdown` also fires for `/new`, `/fork` and `/resume` (reasons
156
- * "new" / "fork" / "resume"), and pi re-invokes the extension factory for
157
- * the replacement session. A fresh closure therefore starts with
158
- * `sessionEnded = false`, so the guard can never latch permanently.
159
- * Verified: `/new` emits `shutdown reason=new` then re-runs the factory.
160
- *
161
- * `pi.events` is NOT gated, so cross-module events still fire.
162
- */
163
- let sessionEnded = false;
164
-
165
- // Create manager with completion callback
166
- const manager = new AgentManager(
167
- (record) => {
168
- agentActivity.delete(record.id);
169
-
170
- // After shutdown the UI is gone and the runtime is stale — nothing here
171
- // is deliverable, and touching `pi` would throw.
172
- if (sessionEnded) return;
173
-
174
- widget.markFinished(record.id);
175
- widget.update();
176
-
177
- // Build notification details
178
- const details = buildNotificationDetails(record, agentActivity.get(record.id));
179
-
180
- // Badge generation: extract name from agent result and set directly.
181
- // Mark resultConsumed BEFORE the notification check so the main agent
182
- // never sees this subagent.
183
- if (record.description === "Generate session name" && record.result && record.status === "completed") {
184
- const name = record.result.split("\n")[0]?.trim().slice(0, 50) ?? "";
185
- if (name && !name.startsWith("Error") && !name.includes("error")) {
186
- try {
187
- pi.setSessionName(name);
188
- } catch { /* best effort */ }
189
- }
190
- record.resultConsumed = true;
191
- }
192
-
193
-
194
- // Send styled notification via message renderer
195
- const status = getStatusLabel(record.status, record.error);
196
- const durationMs = record.completedAt ? record.completedAt - record.startedAt : 0;
197
- const resultPreview = record.result
198
- ? record.result.length > 500
199
- ? record.result.slice(0, 500) + "…"
200
- : record.result
201
- : "No output.";
202
-
203
- const notificationXml = [
204
- `<task-notification>`,
205
- `<task-id>${record.id}</task-id>`,
206
- `<status>${escapeXml(status)}</status>`,
207
- `<summary>Agent "${escapeXml(record.description)}" ${record.status}</summary>`,
208
- `<result>${escapeXml(resultPreview)}</result>`,
209
- `<usage><total_tokens>${details.totalTokens}</total_tokens><tool_uses>${record.toolUses}</tool_uses><duration_ms>${durationMs}</duration_ms></usage>`,
210
- `</task-notification>`,
211
- ].join("\n");
212
-
213
- if (!record.resultConsumed) {
214
- // Defence in depth: `sessionEnded` covers the ordinary shutdown path,
215
- // but a session can also be replaced mid-flight. Delivering a
216
- // notification is best-effort — it must never take the process down.
217
- try {
218
- pi.sendMessage<NotificationDetails>(
219
- {
220
- customType: "subagent-notification",
221
- content: notificationXml,
222
- display: true,
223
- details,
224
- },
225
- { deliverAs: "followUp", triggerTurn: true },
226
- );
227
- } catch {
228
- // Runtime went stale between the guard and here — nothing to notify.
229
- }
230
- }
231
-
232
- pi.events.emit("subagents:completed", {
233
- id: record.id,
234
- type: record.type,
235
- description: record.description,
236
- status: record.status,
237
- result: record.result,
238
- error: record.error,
239
- });
240
- },
241
- config.maxConcurrent,
242
- (record) => {
243
- pi.events.emit("subagents:started", {
244
- id: record.id,
245
- type: record.type,
246
- description: record.description,
247
- });
248
- },
249
- );
250
-
251
- // Build notification details for the message renderer
252
- function buildNotificationDetails(record: any, activity?: AgentActivity): NotificationDetails {
253
- return {
254
- id: record.id,
255
- description: record.description,
256
- status: record.status,
257
- toolUses: record.toolUses,
258
- turnCount: activity?.turnCount ?? 0,
259
- maxTurns: activity?.maxTurns,
260
- totalTokens: safeTokenCount(record.session),
261
- durationMs: record.completedAt ? record.completedAt - record.startedAt : 0,
262
- error: record.error,
263
- resultPreview: record.result
264
- ? record.result.length > 200
265
- ? record.result.slice(0, 200) + "…"
266
- : record.result
267
- : "No output.",
268
- };
269
- }
270
-
271
- // ---- Register custom notification renderer ----
272
- pi.registerMessageRenderer<NotificationDetails>(
273
- "subagent-notification",
274
- (message, { expanded }, theme) => {
275
- const d = message.details;
276
- if (!d) return undefined;
277
-
278
- function renderOne(d: NotificationDetails): string {
279
- const isError = d.status === "error" || d.status === "stopped" || d.status === "aborted";
280
- const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
281
- const statusText = isError
282
- ? d.status
283
- : d.status === "steered"
284
- ? "completed (steered)"
285
- : "completed";
286
-
287
- // Line 1: icon + agent description + status
288
- let line = `${icon} ${theme.bold(d.description)} ${theme.fg("dim", statusText)}`;
289
-
290
- // Line 2: stats
291
- const parts: string[] = [];
292
- if (d.turnCount > 0) parts.push(formatTurns(d.turnCount, d.maxTurns));
293
- if (d.toolUses > 0) parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
294
- if (d.totalTokens > 0) parts.push(formatTokens(d.totalTokens));
295
- if (d.durationMs > 0) parts.push(formatMs(d.durationMs));
296
- if (parts.length) {
297
- line += "\n " + parts.map((p) => theme.fg("dim", p)).join(" " + theme.fg("dim", "·") + " ");
298
- }
299
-
300
- // Line 3: result preview (collapsed) or full (expanded)
301
- if (expanded) {
302
- const lines = d.resultPreview.split("\n").slice(0, 30);
303
- for (const l of lines) line += "\n" + theme.fg("dim", ` ${l}`);
304
- } else {
305
- const preview = d.resultPreview.split("\n")[0]?.slice(0, 80) ?? "";
306
- line += "\n " + theme.fg("dim", `⎿ ${preview}`);
307
- }
308
-
309
- return line;
310
- }
311
-
312
- const all = [d, ...(d.others ?? [])];
313
- return new Text(all.map(renderOne).join("\n"), 0, 0);
314
- },
315
- );
316
-
317
- // Create widget
318
- const widget = new AgentWidget(manager, agentActivity);
319
-
320
- // Register info group at factory time (not session_start)
321
- const registry = getInfoRegistry();
322
- if (registry) {
323
- registry.registerGroup({
324
- id: "subagents",
325
- name: "Subagents",
326
- icon: "🤖",
327
- priority: 80,
328
- config: {
329
- showByDefault: true,
330
- stats: [
331
- { id: "maxConcurrent", label: "Max Concurrent", show: true },
332
- { id: "activeCount", label: "Active Agents", show: true },
333
- { id: "enabled", label: "Enabled", show: true },
334
- { id: "types", label: "Available Types", show: true },
335
- ],
336
- },
337
- dataProvider: async () => {
338
- const types = config.types || {};
339
- const builtinTypes = ["explore", "work"];
340
-
341
- const customTypes: string[] = [];
342
- for (const dir of [globalAgentsDir, workspaceAgentsDir]) {
343
- try {
344
- if (existsSync(dir)) {
345
- for (const file of readdirSync(dir)) {
346
- if (file.endsWith(".md") && !customTypes.includes(file.replace(".md", ""))) {
347
- customTypes.push(file.replace(".md", ""));
348
- }
349
- }
350
- }
351
- } catch { /* ignore */ }
352
- }
353
-
354
- const allTypes = [...new Set([...builtinTypes, ...Object.keys(types), ...customTypes])];
355
- const typeList = allTypes.map((t) => {
356
- const isEnabled = types[t]?.enabled !== false;
357
- const isBuiltin = builtinTypes.includes(t);
358
- const scope = customTypes.includes(t) ? "project" : "global";
359
- return `${t}(${scope})${isEnabled ? "" : " [disabled]"}`;
360
- }).join(", ");
361
-
362
- const activeAgents = manager.listAgents().filter((a) => a.status === "running").length;
363
-
364
- return {
365
- maxConcurrent: { value: String(manager.getMaxConcurrent()) },
366
- activeCount: { value: String(activeAgents) },
367
- enabled: { value: config.enabled ? "yes" : "no" },
368
- types: {
369
- value: allTypes.length > 0 ? allTypes[0] : "none",
370
- detail: allTypes.length > 1 ? typeList : undefined,
371
- },
372
- };
373
- },
374
- });
375
- }
376
-
377
- // Store session context for badge generation
378
- let sessionCtx: import("@earendil-works/pi-coding-agent").ExtensionContext | null = null;
379
-
380
- // Session start: emit MODULE_READY + capture context
381
- pi.on("session_start", async (_event, ctx) => {
382
- sessionCtx = ctx;
383
- emitEvent(pi, UNIPI_EVENTS.MODULE_READY, {
384
- name: MODULES.SUBAGENTS || "subagents",
385
- version: "0.2.0",
386
- commands: [],
387
- tools: ["spawn_helper", "get_helper_result"],
388
- });
389
- });
390
-
391
- // Listen for badge generation requests — spawn background agent
392
- pi.events.on(UNIPI_EVENTS.BADGE_GENERATE_REQUEST, async (data) => {
393
- const event = data as UnipiBadgeGenerateRequestEvent;
394
- if (!sessionCtx) return;
395
-
396
- const summary = event?.conversationSummary ?? "";
397
- const prompt = summary
398
- ? `Based on this conversation, generate a concise session title (MAX 5 WORDS). Reply with ONLY the title. No quotes, no explanation, no punctuation.\n\nConversation:\n${summary}`
399
- : `Generate a concise session title (MAX 5 WORDS) for this session. Reply with ONLY the title. No quotes, no explanation, no punctuation.`;
400
-
401
- // Try with configured model, fallback to inherit
402
- let modelInput: string | undefined = undefined;
403
- try {
404
- const fs = await import("node:fs");
405
- const path = await import("node:path");
406
- const configPath = path.resolve(process.cwd(), ".unipi/config/badge.json");
407
- if (fs.existsSync(configPath)) {
408
- const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8"));
409
- if (typeof parsed.generationModel === "string" && parsed.generationModel !== "inherit") {
410
- modelInput = parsed.generationModel;
411
- }
412
- }
413
- } catch { /* ignore — inherit parent model */ }
414
- let resolvedModel: any = undefined;
415
-
416
- // Check if model is available
417
- if (modelInput && sessionCtx.modelRegistry) {
418
- const { resolveModel } = await import("./model-resolver.js");
419
- const result = resolveModel(modelInput, sessionCtx.modelRegistry);
420
- if (typeof result !== "string") {
421
- resolvedModel = result;
422
- }
423
- // If result is a string (error), resolvedModel stays undefined → inherit parent
424
- }
425
-
426
- manager.spawn(pi, sessionCtx, "name-gen", prompt, {
427
- description: "Generate session name",
428
- model: resolvedModel,
429
- isBackground: true,
430
- isolated: true,
431
- maxTurns: 1,
432
- });
433
- });
434
-
435
- // ESC propagation: abort all agents on session shutdown.
436
- // Set the guard FIRST: abortAll() settles in-flight promises, whose
437
- // completion callbacks would otherwise reach a runtime that pi is about to
438
- // invalidate.
439
- pi.on("session_shutdown", async () => {
440
- sessionEnded = true;
441
- manager.abortAll();
442
- manager.dispose();
443
- });
444
-
445
- // Wire UI context for widget + age finished agents on new turn
446
- pi.on("tool_execution_start", async (_event, ctx) => {
447
- widget.setUICtx(ctx.ui);
448
- widget.onTurnStart();
449
- });
450
-
451
- // Create activity tracker
452
- function createActivityTracker(maxTurns?: number, onStreamUpdate?: () => void) {
453
- const state: AgentActivity = {
454
- activeTools: new Map(),
455
- toolUses: 0,
456
- turnCount: 1,
457
- maxTurns,
458
- tokens: "",
459
- responseText: "",
460
- };
461
-
462
- const callbacks = {
463
- onToolActivity: (activity: { type: "start" | "end"; toolName: string }) => {
464
- if (activity.type === "start") {
465
- state.activeTools.set(activity.toolName + "_" + Date.now(), activity.toolName);
466
- } else {
467
- for (const [key, name] of state.activeTools) {
468
- if (name === activity.toolName) {
469
- state.activeTools.delete(key);
470
- break;
471
- }
472
- }
473
- state.toolUses++;
474
- }
475
- state.tokens = safeFormatTokens(state.session);
476
- onStreamUpdate?.();
477
- },
478
- onTextDelta: (_delta: string, fullText: string) => {
479
- state.responseText = fullText;
480
- onStreamUpdate?.();
481
- },
482
- onTurnEnd: (turnCount: number) => {
483
- state.turnCount = turnCount;
484
- onStreamUpdate?.();
485
- },
486
- onSessionCreated: (session: any) => {
487
- state.session = session;
488
- },
489
- };
490
-
491
- return { state, callbacks };
492
- }
493
-
494
- // ---- Agent tool ----
495
-
496
- const builtinTypes = BUILTIN_TYPES.join(", ");
497
-
498
- pi.registerTool(
499
- defineTool({
500
- name: "spawn_helper",
501
- label: "Spawn Helper",
502
- description: `Launch a sub-agent for parallel work.
503
-
504
- Available agent types: ${builtinTypes}
505
- Custom types can be defined in:
506
- - ~/.unipi/config/agents/<name>.md (global)
507
- - <workspace>/.unipi/config/agents/<name>.md (project)
508
-
509
- Guidelines:
510
- - Use "explore" for parallel file reads
511
- - Use "work" for parallel file writes (transparent locking)
512
- - Use run_in_background for work you don't need immediately
513
- - ESC kills all running agents immediately
514
- - Agents inherit the parent model by default`,
515
- parameters: Type.Object({
516
- type: Type.String({
517
- description: `Agent type: ${builtinTypes}, or custom type from ~/.unipi/config/agents/*.md`,
518
- }),
519
- prompt: Type.String({
520
- description: "The task for the agent to perform.",
521
- }),
522
- description: Type.String({
523
- description: "A short (3-5 word) description of the task.",
524
- }),
525
- run_in_background: Type.Optional(
526
- Type.Boolean({
527
- description: "Run in background. Returns helper ID immediately.",
528
- }),
529
- ),
530
- max_turns: Type.Optional(
531
- Type.Number({
532
- description: "Max agentic turns before stopping.",
533
- minimum: 1,
534
- }),
535
- ),
536
- model: Type.Optional(
537
- Type.String({
538
- description: 'Model override. Accepts "provider/modelId" or fuzzy name (e.g. "haiku", "sonnet"). Omit to inherit parent model.',
539
- }),
540
- ),
541
- thinking: Type.Optional(
542
- Type.String({
543
- description: "Thinking level: off, minimal, low, medium, high, xhigh. Omit to inherit parent.",
544
- }),
545
- ),
546
- }),
547
-
548
- // ---- Rich inline rendering ----
549
-
550
- renderCall(args, theme) {
551
- const displayName = args.type ? args.type : "Agent";
552
- const desc = args.description ?? "";
553
- return new Text(
554
- "▸ " + theme.fg("toolTitle", theme.bold(displayName)) + (desc ? " " + theme.fg("muted", desc) : ""),
555
- 0,
556
- 0,
557
- );
558
- },
559
-
560
- renderResult(result, { expanded, isPartial }, theme) {
561
- const details = result.details as any;
562
- if (!details) {
563
- const text = result.content[0]?.type === "text" ? result.content[0].text : "";
564
- return new Text(text, 0, 0);
565
- }
566
-
567
- // Stats helper
568
- const stats = (d: any) => {
569
- const parts: string[] = [];
570
- if (d.turnCount != null && d.turnCount > 0) parts.push(formatTurns(d.turnCount, d.maxTurns));
571
- if (d.toolUses > 0) parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
572
- if (d.tokens) parts.push(d.tokens);
573
- return parts.map((p) => theme.fg("dim", p)).join(" " + theme.fg("dim", "·") + " ");
574
- };
575
-
576
- // Running
577
- if (isPartial || details.status === "running") {
578
- const frame = SPINNER[details.spinnerFrame ?? 0];
579
- const s = stats(details);
580
- let line = theme.fg("accent", frame) + (s ? " " + s : "");
581
- line += "\n" + theme.fg("dim", ` ⎿ ${details.activity ?? "thinking…"}`);
582
- return new Text(line, 0, 0);
583
- }
584
-
585
- // Background launched
586
- if (details.status === "background") {
587
- return new Text(theme.fg("dim", ` ⎿ Running in background (ID: ${details.agentId})`), 0, 0);
588
- }
589
-
590
- // Completed
591
- if (details.status === "completed") {
592
- const duration = formatMs(details.durationMs);
593
- const s = stats(details);
594
- let line = theme.fg("success", "✓") + (s ? " " + s : "");
595
- line += " " + theme.fg("dim", "·") + " " + theme.fg("dim", duration);
596
-
597
- if (expanded) {
598
- const resultText = result.content[0]?.type === "text" ? result.content[0].text : "";
599
- if (resultText) {
600
- const rlines = resultText.split("\n").slice(0, 50);
601
- for (const l of rlines) {
602
- line += "\n" + theme.fg("dim", ` ${l}`);
603
- }
604
- }
605
- } else {
606
- line += "\n" + theme.fg("dim", " ⎿ Done");
607
- }
608
- return new Text(line, 0, 0);
609
- }
610
-
611
- // Error / Aborted / Stopped
612
- const isError = details.status === "error";
613
- const isStopped = details.status === "stopped";
614
- const s = stats(details);
615
- let line = (isStopped ? theme.fg("dim", "■") : theme.fg("error", "✗")) + (s ? " " + s : "");
616
-
617
- if (isError) {
618
- line += "\n" + theme.fg("error", ` ⎿ Error: ${details.error ?? "unknown"}`);
619
- } else if (isStopped) {
620
- line += "\n" + theme.fg("dim", " ⎿ Stopped");
621
- } else {
622
- line += "\n" + theme.fg("warning", " ⎿ Aborted (max turns exceeded)");
623
- }
624
- return new Text(line, 0, 0);
625
- },
626
-
627
- // ---- Execute ----
628
-
629
- execute: async (toolCallId, params, signal, onUpdate, ctx) => {
630
- widget.setUICtx(ctx.ui);
631
-
632
- const type = params.type as string;
633
- const prompt = params.prompt as string;
634
- const description = params.description as string;
635
- const runInBackground = params.run_in_background as boolean | undefined;
636
- const maxTurns = params.max_turns as number | undefined;
637
- const modelInput = params.model as string | undefined;
638
- const thinkingLevel = params.thinking as any | undefined;
639
-
640
- if (runInBackground) {
641
- const { state: bgState, callbacks: bgCallbacks } = createActivityTracker(maxTurns);
642
-
643
- // Wrap onSessionCreated to sync tokens
644
- const origOnSession = bgCallbacks.onSessionCreated;
645
- bgCallbacks.onSessionCreated = (session: any) => {
646
- origOnSession(session);
647
- bgState.tokens = safeFormatTokens(session);
648
- widget.update();
649
- };
650
-
651
- const id = manager.spawn(pi, ctx, type, prompt, {
652
- description,
653
- maxTurns,
654
- modelInput,
655
- modelRegistry: ctx.modelRegistry,
656
- thinkingLevel,
657
- isBackground: true,
658
- ...bgCallbacks,
659
- });
660
-
661
- agentActivity.set(id, bgState);
662
- widget.ensureTimer();
663
- widget.update();
664
-
665
- const record = manager.getRecord(id);
666
- const isQueued = record?.status === "queued";
667
-
668
- return textResult(
669
- `Agent ${isQueued ? "queued" : "started"} in background.\n` +
670
- `ID: ${id}\n` +
671
- `Type: ${type}\n` +
672
- `Description: ${description}\n` +
673
- (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
674
- `\nYou will be notified when this agent completes.\n` +
675
- `Use get_result to retrieve full results.`,
676
- { status: "background", agentId: id },
677
- );
678
- }
679
-
680
- // Foreground execution — stream progress via onUpdate
681
- let spinnerFrame = 0;
682
- const startedAt = Date.now();
683
- let fgId: string | undefined;
684
-
685
- const { state: fgState, callbacks: fgCallbacks } = createActivityTracker(maxTurns);
686
-
687
- const streamUpdate = () => {
688
- onUpdate?.({
689
- content: [{ type: "text", text: `${fgState.toolUses} tool uses...` }],
690
- details: {
691
- status: "running",
692
- toolUses: fgState.toolUses,
693
- tokens: fgState.tokens,
694
- turnCount: fgState.turnCount,
695
- maxTurns: fgState.maxTurns,
696
- durationMs: Date.now() - startedAt,
697
- activity: describeActivity(fgState.activeTools, fgState.responseText),
698
- spinnerFrame: spinnerFrame % SPINNER.length,
699
- },
700
- });
701
- };
702
-
703
- // Wire session to register in widget
704
- const origOnSession = fgCallbacks.onSessionCreated;
705
- fgCallbacks.onSessionCreated = (session: any) => {
706
- origOnSession(session);
707
- fgState.tokens = safeFormatTokens(session);
708
- for (const a of manager.listAgents()) {
709
- if (a.session === session) {
710
- fgId = a.id;
711
- agentActivity.set(a.id, fgState);
712
- widget.ensureTimer();
713
- break;
714
- }
715
- }
716
- };
717
-
718
- const spinnerInterval = setInterval(() => {
719
- spinnerFrame++;
720
- streamUpdate();
721
- }, 80);
722
-
723
- streamUpdate();
724
-
725
- const record = await manager.spawnAndWait(pi, ctx, type, prompt, {
726
- description,
727
- maxTurns,
728
- modelInput,
729
- modelRegistry: ctx.modelRegistry,
730
- thinkingLevel,
731
- ...fgCallbacks,
732
- });
733
-
734
- clearInterval(spinnerInterval);
735
-
736
- // Clean up foreground agent from widget
737
- if (fgId) {
738
- agentActivity.delete(fgId);
739
- widget.markFinished(fgId);
740
- widget.update();
741
- }
742
-
743
- const tokenText = safeFormatTokens(fgState.session);
744
- const durationMs = (record.completedAt ?? Date.now()) - record.startedAt;
745
-
746
- if (record.status === "error") {
747
- return textResult(`Agent failed: ${record.error}`, {
748
- status: "error",
749
- toolUses: record.toolUses,
750
- tokens: tokenText,
751
- durationMs,
752
- error: record.error,
753
- });
754
- }
755
-
756
- return textResult(
757
- `Agent completed in ${(durationMs / 1000).toFixed(1)}s (${record.toolUses} tool uses${tokenText ? `, ${tokenText} tokens` : ""}).\n\n` +
758
- (record.result?.trim() || "No output."),
759
- {
760
- status: "completed",
761
- toolUses: record.toolUses,
762
- tokens: tokenText,
763
- durationMs,
764
- turnCount: fgState.turnCount,
765
- maxTurns: fgState.maxTurns,
766
- },
767
- );
768
- },
769
- }),
770
- );
771
-
772
- // ---- get_helper_result tool ----
773
-
774
- pi.registerTool(
775
- defineTool({
776
- name: "get_helper_result",
777
- label: "Get Helper Result",
778
- description: "Check status and retrieve results from a background agent. Use view: true to open a live conversation overlay.",
779
- parameters: Type.Object({
780
- agent_id: Type.String({
781
- description: "The helper ID to check.",
782
- }),
783
- wait: Type.Optional(
784
- Type.Boolean({
785
- description: "Wait for completion. Default: false.",
786
- }),
787
- ),
788
- view: Type.Optional(
789
- Type.Boolean({
790
- description: "Open a live conversation viewer overlay. Default: false.",
791
- }),
792
- ),
793
- }),
794
- execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
795
- const record = manager.getRecord(params.agent_id as string);
796
- if (!record) {
797
- return textResult(`Helper not found: "${params.agent_id}". It may have been cleaned up.`);
798
- }
799
-
800
- // Open conversation viewer overlay if requested
801
- if (params.view && record.session) {
802
- const activity = agentActivity.get(record.id);
803
- await withHerdrBlocked(
804
- pi,
805
- "helper viewer",
806
- () => ctx.ui.custom<undefined>(
807
- (tui, theme, _keybindings, done) => {
808
- return new ConversationViewer(
809
- tui,
810
- record.session!,
811
- {
812
- type: record.type,
813
- description: record.description,
814
- status: record.status,
815
- toolUses: record.toolUses,
816
- startedAt: record.startedAt,
817
- completedAt: record.completedAt,
818
- },
819
- activity,
820
- theme,
821
- done,
822
- );
823
- },
824
- {
825
- overlay: true,
826
- overlayOptions: { anchor: "center", width: "90%" },
827
- },
828
- ),
829
- );
830
- }
831
-
832
- if (params.wait && record.status === "running" && record.promise) {
833
- record.resultConsumed = true;
834
- await record.promise;
835
- }
836
-
837
- const duration = record.completedAt
838
- ? `${((record.completedAt - record.startedAt) / 1000).toFixed(1)}s`
839
- : "running";
840
-
841
- let output =
842
- `Agent: ${record.id}\n` +
843
- `Type: ${record.type} | Status: ${record.status} | Tool uses: ${record.toolUses} | Duration: ${duration}\n` +
844
- `Description: ${record.description}\n\n`;
845
-
846
- if (record.status === "running") {
847
- output += "Agent is still running. Use wait: true or check back later.";
848
- } else if (record.status === "error") {
849
- output += `Error: ${record.error}`;
850
- } else {
851
- output += record.result?.trim() || "No output.";
852
- }
853
-
854
- if (record.status !== "running" && record.status !== "queued") {
855
- record.resultConsumed = true;
856
- }
857
-
858
- return textResult(output);
859
- },
860
- }),
861
- );
862
- }