@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
@@ -1,299 +0,0 @@
1
- /**
2
- * @pi-unipi/subagents — Conversation Viewer
3
- *
4
- * Live-scrolling overlay for viewing agent conversations.
5
- * Subscribes to session events for real-time streaming updates.
6
- * Supports keyboard navigation: ↑↓, PgUp/PgDn, Home/End, Esc/q to close.
7
- */
8
-
9
- import type { AgentSession } from "@earendil-works/pi-coding-agent";
10
- import {
11
- type Component,
12
- matchesKey,
13
- type TUI,
14
- truncateToWidth,
15
- visibleWidth,
16
- wrapTextWithAnsi,
17
- } from "@earendil-works/pi-tui";
18
- import type { AgentActivity } from "./types.js";
19
-
20
- /** Lines consumed by chrome: top border + header + header sep + footer sep + footer + bottom border. */
21
- const CHROME_LINES = 6;
22
- const MIN_VIEWPORT = 3;
23
-
24
- /** Extract text from content array. */
25
- function extractText(content: string | Array<{ type: string; text?: string }>): string {
26
- if (typeof content === "string") return content;
27
- return content
28
- .filter((p): p is { type: "text"; text: string } => p.type === "text" && typeof p.text === "string")
29
- .map((p) => p.text)
30
- .join("");
31
- }
32
-
33
- /** Format duration. */
34
- function formatMs(ms: number): string {
35
- if (ms >= 60_000) return `${(ms / 60_000).toFixed(1)}m`;
36
- if (ms >= 1_000) return `${(ms / 1_000).toFixed(1)}s`;
37
- return `${ms}ms`;
38
- }
39
-
40
- /** Format tokens compactly. */
41
- function formatTokens(count: number): string {
42
- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M token`;
43
- if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k token`;
44
- return `${count} token`;
45
- }
46
-
47
- /** Describe current activity from active tools. */
48
- function describeActivity(activeTools: Map<string, string>, responseText?: string): string {
49
- if (activeTools.size > 0) {
50
- const names = [...new Set(activeTools.values())];
51
- return names.join(", ") + "…";
52
- }
53
- if (responseText && responseText.trim().length > 0) {
54
- const lastLine = responseText.split("\n").find((l) => l.trim())?.trim() ?? "";
55
- if (lastLine.length > 60) return lastLine.slice(0, 60) + "…";
56
- if (lastLine.length > 0) return lastLine;
57
- }
58
- return "thinking…";
59
- }
60
-
61
- interface ViewerRecord {
62
- type: string;
63
- description: string;
64
- status: string;
65
- toolUses: number;
66
- startedAt: number;
67
- completedAt?: number;
68
- }
69
-
70
- export class ConversationViewer implements Component {
71
- private scrollOffset = 0;
72
- private autoScroll = true;
73
- private unsubscribe: (() => void) | undefined;
74
- private lastInnerW = 0;
75
- private closed = false;
76
-
77
- constructor(
78
- private tui: TUI,
79
- private session: AgentSession,
80
- private record: ViewerRecord,
81
- private activity: AgentActivity | undefined,
82
- private theme: any,
83
- private done: (result: undefined) => void,
84
- ) {
85
- this.unsubscribe = session.subscribe(() => {
86
- if (this.closed) return;
87
- this.tui.requestRender();
88
- });
89
- }
90
-
91
- handleInput(data: string): void {
92
- if (matchesKey(data, "escape") || matchesKey(data, "q")) {
93
- this.closed = true;
94
- this.done(undefined);
95
- return;
96
- }
97
-
98
- const totalLines = this.buildContentLines(this.lastInnerW).length;
99
- const viewportHeight = this.viewportHeight();
100
- const maxScroll = Math.max(0, totalLines - viewportHeight);
101
-
102
- if (matchesKey(data, "up") || matchesKey(data, "k")) {
103
- this.scrollOffset = Math.max(0, this.scrollOffset - 1);
104
- this.autoScroll = this.scrollOffset >= maxScroll;
105
- } else if (matchesKey(data, "down") || matchesKey(data, "j")) {
106
- this.scrollOffset = Math.min(maxScroll, this.scrollOffset + 1);
107
- this.autoScroll = this.scrollOffset >= maxScroll;
108
- } else if (matchesKey(data, "pageUp")) {
109
- this.scrollOffset = Math.max(0, this.scrollOffset - viewportHeight);
110
- this.autoScroll = false;
111
- } else if (matchesKey(data, "pageDown")) {
112
- this.scrollOffset = Math.min(maxScroll, this.scrollOffset + viewportHeight);
113
- this.autoScroll = this.scrollOffset >= maxScroll;
114
- } else if (matchesKey(data, "home")) {
115
- this.scrollOffset = 0;
116
- this.autoScroll = false;
117
- } else if (matchesKey(data, "end")) {
118
- this.scrollOffset = maxScroll;
119
- this.autoScroll = true;
120
- }
121
- }
122
-
123
- render(width: number): string[] {
124
- if (width < 6) return [];
125
- const th = this.theme;
126
- const innerW = width - 4; // border + padding
127
- this.lastInnerW = innerW;
128
- const lines: string[] = [];
129
-
130
- const pad = (s: string, len: number) => {
131
- const vis = visibleWidth(s);
132
- return s + " ".repeat(Math.max(0, len - vis));
133
- };
134
- const row = (content: string) =>
135
- th.fg("border", "│") + " " + truncateToWidth(pad(content, innerW), innerW) + " " + th.fg("border", "│");
136
- const hrTop = th.fg("border", `╭${"─".repeat(width - 2)}╮`);
137
- const hrBot = th.fg("border", `╰${"─".repeat(width - 2)}╯`);
138
- const hrMid = row(th.fg("dim", "─".repeat(innerW)));
139
-
140
- // Header
141
- lines.push(hrTop);
142
- const name = this.record.type;
143
- const statusIcon =
144
- this.record.status === "running"
145
- ? th.fg("accent", "●")
146
- : this.record.status === "completed"
147
- ? th.fg("success", "✓")
148
- : this.record.status === "error"
149
- ? th.fg("error", "✗")
150
- : th.fg("dim", "○");
151
-
152
- const duration = this.record.completedAt
153
- ? formatMs(this.record.completedAt - this.record.startedAt)
154
- : `${formatMs(Date.now() - this.record.startedAt)} (running)`;
155
-
156
- const headerParts: string[] = [duration];
157
- const toolUses = this.activity?.toolUses ?? this.record.toolUses;
158
- if (toolUses > 0) headerParts.unshift(`${toolUses} tool${toolUses === 1 ? "" : "s"}`);
159
- if (this.activity?.session) {
160
- try {
161
- const tokens = (this.activity.session as any).getSessionStats().tokens.total;
162
- if (tokens > 0) headerParts.push(formatTokens(tokens));
163
- } catch {
164
- /* */
165
- }
166
- }
167
-
168
- lines.push(
169
- row(
170
- `${statusIcon} ${th.bold(name)} ${th.fg("muted", this.record.description)} ${th.fg("dim", "·")} ${th.fg("dim", headerParts.join(" · "))}`,
171
- ),
172
- );
173
- lines.push(hrMid);
174
-
175
- // Content area
176
- const contentLines = this.buildContentLines(innerW);
177
- const viewportHeight = this.viewportHeight();
178
- const maxScroll = Math.max(0, contentLines.length - viewportHeight);
179
-
180
- if (this.autoScroll) {
181
- this.scrollOffset = maxScroll;
182
- }
183
-
184
- const visibleStart = Math.min(this.scrollOffset, maxScroll);
185
- const visible = contentLines.slice(visibleStart, visibleStart + viewportHeight);
186
-
187
- for (let i = 0; i < viewportHeight; i++) {
188
- lines.push(row(visible[i] ?? ""));
189
- }
190
-
191
- // Footer
192
- lines.push(hrMid);
193
- const scrollPct =
194
- contentLines.length <= viewportHeight
195
- ? "100%"
196
- : `${Math.round(((visibleStart + viewportHeight) / contentLines.length) * 100)}%`;
197
- const footerLeft = th.fg("dim", `${contentLines.length} lines · ${scrollPct}`);
198
- const footerRight = th.fg("dim", "↑↓ scroll · PgUp/PgDn · Esc close");
199
- const footerGap = Math.max(1, innerW - visibleWidth(footerLeft) - visibleWidth(footerRight));
200
- lines.push(row(footerLeft + " ".repeat(footerGap) + footerRight));
201
- lines.push(hrBot);
202
-
203
- return lines;
204
- }
205
-
206
- invalidate(): void {
207
- /* no cached state to clear */
208
- }
209
-
210
- dispose(): void {
211
- this.closed = true;
212
- if (this.unsubscribe) {
213
- this.unsubscribe();
214
- this.unsubscribe = undefined;
215
- }
216
- }
217
-
218
- // ---- Private ----
219
-
220
- private viewportHeight(): number {
221
- return Math.max(MIN_VIEWPORT, this.tui.terminal.rows - CHROME_LINES);
222
- }
223
-
224
- private buildContentLines(width: number): string[] {
225
- if (width <= 0) return [];
226
-
227
- const th = this.theme;
228
- const messages = (this.session as any).messages;
229
- const lines: string[] = [];
230
-
231
- if (!messages || messages.length === 0) {
232
- lines.push(th.fg("dim", "(waiting for first message...)"));
233
- return lines;
234
- }
235
-
236
- let needsSeparator = false;
237
- for (const msg of messages) {
238
- if (msg.role === "user") {
239
- const text = typeof msg.content === "string" ? msg.content : extractText(msg.content);
240
- if (!text.trim()) continue;
241
- if (needsSeparator) lines.push(th.fg("dim", "───"));
242
- lines.push(th.fg("accent", "[User]"));
243
- for (const line of wrapTextWithAnsi(text.trim(), width)) {
244
- lines.push(line);
245
- }
246
- } else if (msg.role === "assistant") {
247
- const textParts: string[] = [];
248
- const toolCalls: string[] = [];
249
- for (const c of msg.content) {
250
- if (c.type === "text" && c.text) textParts.push(c.text);
251
- else if (c.type === "tool_use" || c.type === "toolCall") {
252
- toolCalls.push((c as any).name ?? (c as any).toolName ?? "unknown");
253
- }
254
- }
255
- if (needsSeparator) lines.push(th.fg("dim", "───"));
256
- lines.push(th.bold("[Assistant]"));
257
- if (textParts.length > 0) {
258
- for (const line of wrapTextWithAnsi(textParts.join("\n").trim(), width)) {
259
- lines.push(line);
260
- }
261
- }
262
- for (const name of toolCalls) {
263
- lines.push(truncateToWidth(th.fg("muted", ` [Tool: ${name}]`), width));
264
- }
265
- } else if (msg.role === "toolResult") {
266
- const text = extractText(msg.content);
267
- const truncated = text.length > 500 ? text.slice(0, 500) + "... (truncated)" : text;
268
- if (!truncated.trim()) continue;
269
- if (needsSeparator) lines.push(th.fg("dim", "───"));
270
- lines.push(th.fg("dim", "[Result]"));
271
- for (const line of wrapTextWithAnsi(truncated.trim(), width)) {
272
- lines.push(th.fg("dim", line));
273
- }
274
- } else if ((msg as any).role === "bashExecution") {
275
- const bash = msg as any;
276
- if (needsSeparator) lines.push(th.fg("dim", "───"));
277
- lines.push(truncateToWidth(th.fg("muted", ` $ ${bash.command}`), width));
278
- if (bash.output?.trim()) {
279
- const out = bash.output.length > 500 ? bash.output.slice(0, 500) + "... (truncated)" : bash.output;
280
- for (const line of wrapTextWithAnsi(out.trim(), width)) {
281
- lines.push(th.fg("dim", line));
282
- }
283
- }
284
- } else {
285
- continue;
286
- }
287
- needsSeparator = true;
288
- }
289
-
290
- // Streaming indicator for running agents
291
- if (this.record.status === "running" && this.activity) {
292
- const act = describeActivity(this.activity.activeTools, this.activity.responseText);
293
- lines.push("");
294
- lines.push(truncateToWidth(th.fg("accent", "▍ ") + th.fg("dim", act), width));
295
- }
296
-
297
- return lines.map((l) => truncateToWidth(l, width));
298
- }
299
- }
@@ -1,118 +0,0 @@
1
- /**
2
- * @pi-unipi/subagents — Custom agent loader
3
- *
4
- * Discovers agent types from:
5
- * - <workspace>/.unipi/config/agents/*.md (project, highest priority)
6
- * - ~/.unipi/config/agents/*.md (global)
7
- */
8
-
9
- import { existsSync, readdirSync, readFileSync, renameSync } from "node:fs";
10
- import { join } from "node:path";
11
- import { homedir } from "node:os";
12
- import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
13
- import type { AgentConfig } from "./types.js";
14
-
15
- /** Backup a corrupted file by renaming to .bak */
16
- function backupCorrupted(filePath: string): void {
17
- const backupPath = filePath + ".bak";
18
- try {
19
- renameSync(filePath, backupPath);
20
- } catch {
21
- // If backup fails, just leave it
22
- }
23
- }
24
-
25
- /** Get project agents directory. */
26
- function getProjectAgentsDir(cwd: string): string {
27
- return join(cwd, ".unipi", "config", "agents");
28
- }
29
-
30
- /** Get global agents directory. */
31
- function getGlobalAgentsDir(): string {
32
- return join(homedir(), ".unipi", "config", "agents");
33
- }
34
-
35
- /** All known built-in tool names. */
36
- const BUILTIN_TOOL_NAMES = ["read", "bash", "edit", "write", "grep", "find", "ls"];
37
-
38
- /**
39
- * Load a single agent from a .md file.
40
- */
41
- function loadAgentFromFile(filePath: string, source: "project" | "global"): AgentConfig | null {
42
- try {
43
- const content = readFileSync(filePath, "utf-8");
44
- const { frontmatter, body } = parseFrontmatter(content);
45
-
46
- if (!frontmatter || typeof frontmatter !== "object") {
47
- return null;
48
- }
49
-
50
- const name = filePath.split("/").pop()?.replace(/\.md$/, "") ?? "unknown";
51
-
52
- // Parse tools from comma-separated string
53
- const toolsStr = (frontmatter as any).tools as string | undefined;
54
- const builtinToolNames = toolsStr
55
- ? toolsStr.split(",").map((t) => t.trim()).filter((t) => BUILTIN_TOOL_NAMES.includes(t))
56
- : [...BUILTIN_TOOL_NAMES];
57
-
58
- return {
59
- name,
60
- displayName: (frontmatter as any).display_name as string | undefined,
61
- description: ((frontmatter as any).description as string) ?? `${name} agent`,
62
- builtinToolNames,
63
- disallowedTools: ((frontmatter as any).disallowed_tools as string | undefined)
64
- ?.split(",")
65
- .map((t) => t.trim()),
66
- extensions: (frontmatter as any).extensions !== false,
67
- skills: (frontmatter as any).skills !== false,
68
- model: (frontmatter as any).model as string | undefined,
69
- thinking: (frontmatter as any).thinking as any,
70
- maxTurns: (frontmatter as any).max_turns as number | undefined,
71
- systemPrompt: body.trim(),
72
- promptMode: ((frontmatter as any).prompt_mode as "replace" | "append") ?? "replace",
73
- inheritContext: (frontmatter as any).inherit_context as boolean | undefined,
74
- runInBackground: (frontmatter as any).run_in_background as boolean | undefined,
75
- isolated: (frontmatter as any).isolated as boolean | undefined,
76
- enabled: (frontmatter as any).enabled !== false,
77
- source,
78
- };
79
- } catch {
80
- // Corrupted file — backup and skip
81
- backupCorrupted(filePath);
82
- return null;
83
- }
84
- }
85
-
86
- /**
87
- * Load all custom agents from project and global directories.
88
- * Project agents override global agents with the same name.
89
- */
90
- export function loadCustomAgents(cwd: string): Map<string, AgentConfig> {
91
- const agents = new Map<string, AgentConfig>();
92
-
93
- // Load global agents first
94
- const globalDir = getGlobalAgentsDir();
95
- if (existsSync(globalDir)) {
96
- const files = readdirSync(globalDir).filter((f) => f.endsWith(".md"));
97
- for (const file of files) {
98
- const agent = loadAgentFromFile(join(globalDir, file), "global");
99
- if (agent) {
100
- agents.set(agent.name, agent);
101
- }
102
- }
103
- }
104
-
105
- // Load project agents (overrides global)
106
- const projectDir = getProjectAgentsDir(cwd);
107
- if (existsSync(projectDir)) {
108
- const files = readdirSync(projectDir).filter((f) => f.endsWith(".md"));
109
- for (const file of files) {
110
- const agent = loadAgentFromFile(join(projectDir, file), "project");
111
- if (agent) {
112
- agents.set(agent.name, agent);
113
- }
114
- }
115
- }
116
-
117
- return agents;
118
- }
package/src/file-lock.ts DELETED
@@ -1,102 +0,0 @@
1
- /**
2
- * @pi-unipi/subagents — Per-file transparent locking
3
- *
4
- * Agents never see lock errors. Write tool queues internally.
5
- * Per-file granularity: locking src/auth.ts doesn't block src/login.ts.
6
- */
7
-
8
- import type { FileLockEntry } from "./types.js";
9
-
10
- export class FileLock {
11
- /** Active locks by file path. */
12
- private locks = new Map<string, FileLockEntry>();
13
- /** Queue of waiting acquires per file path. */
14
- private queues = new Map<string, Array<() => void>>();
15
-
16
- /**
17
- * Acquire a lock on a file. Blocks until available.
18
- * Returns a release function.
19
- *
20
- * @param filePath - Absolute path to the file
21
- * @param agentId - ID of the agent requesting the lock
22
- * @returns Release function — call when done writing
23
- */
24
- async acquire(filePath: string, agentId: string): Promise<() => void> {
25
- // Wait for existing lock
26
- while (this.locks.has(filePath)) {
27
- await new Promise<void>((resolve) => {
28
- const queue = this.queues.get(filePath) ?? [];
29
- queue.push(resolve);
30
- this.queues.set(filePath, queue);
31
- });
32
- }
33
-
34
- // Create lock entry
35
- let releaseFn: () => void;
36
- const promise = new Promise<void>((resolve) => {
37
- releaseFn = () => {
38
- this.locks.delete(filePath);
39
- resolve();
40
- // Wake next waiter
41
- const queue = this.queues.get(filePath);
42
- if (queue && queue.length > 0) {
43
- const next = queue.shift()!;
44
- next();
45
- }
46
- };
47
- });
48
-
49
- const entry: FileLockEntry = {
50
- agentId,
51
- filePath,
52
- promise,
53
- release: releaseFn!,
54
- };
55
-
56
- this.locks.set(filePath, entry);
57
- return releaseFn!;
58
- }
59
-
60
- /**
61
- * Check if a file is currently locked.
62
- */
63
- isLocked(filePath: string): boolean {
64
- return this.locks.has(filePath);
65
- }
66
-
67
- /**
68
- * Get the agent that holds a lock on a file.
69
- */
70
- getHolder(filePath: string): string | undefined {
71
- return this.locks.get(filePath)?.agentId;
72
- }
73
-
74
- /**
75
- * Get count of locked files.
76
- */
77
- get lockCount(): number {
78
- return this.locks.size;
79
- }
80
-
81
- /**
82
- * Release all locks held by an agent (on abort).
83
- */
84
- releaseAll(agentId: string): void {
85
- for (const [filePath, entry] of this.locks) {
86
- if (entry.agentId === agentId) {
87
- entry.release();
88
- }
89
- }
90
- }
91
-
92
- /**
93
- * Clear all locks (on shutdown).
94
- */
95
- clear(): void {
96
- for (const entry of this.locks.values()) {
97
- entry.release();
98
- }
99
- this.locks.clear();
100
- this.queues.clear();
101
- }
102
- }