@lune_99/pi-subagent 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +240 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +186 -0
  12. package/src/auto-model.ts +592 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +112 -0
  15. package/src/definitions.ts +324 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +318 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +168 -0
  20. package/src/inspector/details.ts +113 -0
  21. package/src/inspector/inspector.ts +653 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +54 -0
  27. package/src/notify/notification-box.ts +381 -0
  28. package/src/notify/notifier.ts +569 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +26 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +193 -0
  35. package/src/run/run-manager.ts +838 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +681 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +167 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +363 -0
  43. package/src/settings/panel.ts +179 -0
  44. package/src/settings/schema.ts +71 -0
  45. package/src/tools/format.ts +375 -0
  46. package/src/tools/subagent-tools.ts +467 -0
@@ -0,0 +1,112 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join } from "node:path";
4
+
5
+ import { parseDocument } from "yaml";
6
+
7
+ import { parseDefinition, type AgentDefinition } from "./definitions.ts";
8
+
9
+ /** The frontmatter fields the settings panel edits; the body stays as written. */
10
+ export type DefinitionField = "name" | "description" | "model" | "thinking" | "tools" | "isolation";
11
+
12
+ /**
13
+ * Set one frontmatter field of a definition file, or remove it with `undefined`, and return the
14
+ * definition the file then holds. The new text must parse as a definition before it replaces the
15
+ * file, and a file named after its agent is renamed with it. `siblings` are the other definitions
16
+ * of the same folder, which a new name must not reuse.
17
+ */
18
+ export function editDefinitionFile(
19
+ definition: AgentDefinition,
20
+ field: DefinitionField,
21
+ value: string | readonly string[] | undefined,
22
+ siblings: readonly AgentDefinition[],
23
+ ): AgentDefinition {
24
+ const content = setFrontmatterField(readFileSync(definition.file, "utf8"), field, value);
25
+ const renamed =
26
+ field === "name" &&
27
+ typeof value === "string" &&
28
+ value !== definition.name &&
29
+ basename(definition.file) === `${definition.name}.md`;
30
+ const file = renamed ? join(dirname(definition.file), `${value}.md`) : definition.file;
31
+ const edited = parseDefinition(content, file, definition.scope);
32
+ const clash = siblings.find(
33
+ (other) => other.file !== definition.file && other.name === edited.name,
34
+ );
35
+
36
+ if (clash) {
37
+ throw new Error(`The agent ${clash.file} already uses the name "${edited.name}".`);
38
+ }
39
+
40
+ if (renamed && existsSync(file)) {
41
+ throw new Error(`The file ${file} already exists; rename or remove it first.`);
42
+ }
43
+
44
+ // A temporary file in the same folder makes the replacement one rename; it is not a `.md`
45
+ // file, so the definition loader never reads it.
46
+ const temporary = join(
47
+ dirname(definition.file),
48
+ `.${basename(file)}.${randomBytes(4).toString("hex")}.tmp`,
49
+ );
50
+
51
+ writeFileSync(temporary, content, { flag: "wx" });
52
+
53
+ try {
54
+ renameSync(temporary, file);
55
+ } catch (error) {
56
+ rmSync(temporary, { force: true });
57
+
58
+ throw error;
59
+ }
60
+
61
+ if (renamed) {
62
+ try {
63
+ rmSync(definition.file);
64
+ } catch (error) {
65
+ throw new Error(
66
+ `The agent was written to ${file}, but ${definition.file} could not be removed, ` +
67
+ `so both files now use the name "${edited.name}": ${message(error)}`,
68
+ { cause: error },
69
+ );
70
+ }
71
+ }
72
+
73
+ return edited;
74
+ }
75
+
76
+ /** Edit the YAML document in place, so comments and the order of other fields stay. */
77
+ export function setFrontmatterField(
78
+ content: string,
79
+ field: DefinitionField,
80
+ value: string | readonly string[] | undefined,
81
+ ): string {
82
+ // The same split as Pi's parseFrontmatter, which reads the file afterwards.
83
+ const normalized = content
84
+ .replace(/^\uFEFF/, "")
85
+ .replace(/\r\n/g, "\n")
86
+ .replace(/\r/g, "\n");
87
+ const end = normalized.startsWith("---") ? normalized.indexOf("\n---", 3) : -1;
88
+
89
+ if (end === -1) {
90
+ throw new Error("The file has no frontmatter.");
91
+ }
92
+
93
+ const document = parseDocument(normalized.slice(4, end));
94
+
95
+ if (document.errors.length > 0) {
96
+ throw new Error(`Invalid frontmatter: ${document.errors[0]!.message}`);
97
+ }
98
+
99
+ if (value === undefined) {
100
+ document.delete(field);
101
+ } else if (typeof value === "string") {
102
+ document.set(field, value);
103
+ } else {
104
+ document.set(field, document.createNode([...value], { flow: true }));
105
+ }
106
+
107
+ return `---\n${document.toString({ flowCollectionPadding: false }).trimEnd()}${normalized.slice(end)}`;
108
+ }
109
+
110
+ function message(error: unknown): string {
111
+ return error instanceof Error ? error.message : String(error);
112
+ }
@@ -0,0 +1,324 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+
4
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
5
+ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
6
+
7
+ import { AUTO_MODEL, parseModelRef } from "./models.ts";
8
+ import { definitionsDir, projectDefinitionsDir } from "./paths.ts";
9
+ import { ISOLATION_MODES, THINKING_LEVELS, type Isolation } from "./run/types.ts";
10
+
11
+ /** `user`: Pi's agent directory. `project`: the project's `.pi` folder. */
12
+ export type DefinitionScope = "user" | "project";
13
+
14
+ export interface AgentDefinition {
15
+ name: string;
16
+ description: string;
17
+ tools?: string[];
18
+ /** `provider/id`, or `auto` to let the classifier choose per task. */
19
+ model?: string;
20
+ thinking?: ThinkingLevel;
21
+ isolation?: Isolation;
22
+ /** Appended to Pi's system prompt; empty when the file has only frontmatter. */
23
+ body: string;
24
+ file: string;
25
+ scope: DefinitionScope;
26
+ }
27
+
28
+ export interface DefinitionProblem {
29
+ file: string;
30
+ message: string;
31
+ }
32
+
33
+ export interface LoadedDefinitions {
34
+ /** In name order, the order of the roster and the `agent` enum. */
35
+ definitions: AgentDefinition[];
36
+ problems: DefinitionProblem[];
37
+ }
38
+
39
+ const FIELDS = new Set(["name", "description", "tools", "model", "thinking", "isolation"]);
40
+ export const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
41
+ export const INLINE_NAME_PATTERN = /^run-\d+$/;
42
+ const TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
43
+
44
+ /**
45
+ * User definitions and, in a trusted project, the project's own. A project definition replaces a
46
+ * user definition of the same name, and the replaced file is reported as not loaded.
47
+ */
48
+ export function loadAllDefinitions(options: {
49
+ agentDir: string;
50
+ cwd: string;
51
+ projectTrusted: boolean;
52
+ }): LoadedDefinitions {
53
+ const userDir = definitionsDir(options.agentDir);
54
+ const projectDir = projectDefinitionsDir(options.cwd);
55
+ const user = loadDefinitions(userDir, "user");
56
+
57
+ // An agent directory set to the project's `.pi` folder makes the two folders one.
58
+ if (!options.projectTrusted || resolve(projectDir) === resolve(userDir)) {
59
+ return user;
60
+ }
61
+
62
+ const project = loadDefinitions(projectDir, "project");
63
+ const definitions = [...project.definitions];
64
+ const problems = [...project.problems, ...user.problems];
65
+
66
+ for (const definition of user.definitions) {
67
+ const replacement = project.definitions.find(
68
+ (candidate) => candidate.name === definition.name,
69
+ );
70
+
71
+ if (replacement) {
72
+ problems.push({
73
+ file: definition.file,
74
+ message: `The project definition ${replacement.file} uses the name "${definition.name}" and replaces it.`,
75
+ });
76
+ } else {
77
+ definitions.push(definition);
78
+ }
79
+ }
80
+
81
+ definitions.sort(compareNames);
82
+
83
+ return { definitions, problems };
84
+ }
85
+
86
+ /**
87
+ * Read the `*.md` files directly in `dir`. A file that fails any check is skipped and reported,
88
+ * so a typo such as `tool:` cannot silently start runs with the default tools instead.
89
+ */
90
+ export function loadDefinitions(dir: string, scope: DefinitionScope): LoadedDefinitions {
91
+ if (!existsSync(dir)) {
92
+ return { definitions: [], problems: [] };
93
+ }
94
+
95
+ const problems: DefinitionProblem[] = [];
96
+ const parsed: AgentDefinition[] = [];
97
+
98
+ for (const entry of readdirSync(dir).sort()) {
99
+ if (!entry.endsWith(".md")) {
100
+ continue;
101
+ }
102
+
103
+ const file = join(dir, entry);
104
+
105
+ try {
106
+ if (!statSync(file).isFile()) {
107
+ continue;
108
+ }
109
+
110
+ parsed.push(parseDefinition(readFileSync(file, "utf8"), file, scope));
111
+ } catch (error) {
112
+ problems.push({
113
+ file,
114
+ message: error instanceof Error ? error.message : String(error),
115
+ });
116
+ }
117
+ }
118
+
119
+ const byName = new Map<string, AgentDefinition[]>();
120
+
121
+ for (const definition of parsed) {
122
+ byName.set(definition.name, [...(byName.get(definition.name) ?? []), definition]);
123
+ }
124
+
125
+ const definitions: AgentDefinition[] = [];
126
+
127
+ for (const [name, group] of byName) {
128
+ if (group.length === 1) {
129
+ definitions.push(group[0]!);
130
+ continue;
131
+ }
132
+
133
+ // No file wins: loading either one would depend on directory order.
134
+ for (const definition of group) {
135
+ problems.push({
136
+ file: definition.file,
137
+ message: `The name "${name}" is also used by ${group
138
+ .filter((other) => other !== definition)
139
+ .map((other) => other.file)
140
+ .join(", ")}.`,
141
+ });
142
+ }
143
+ }
144
+
145
+ definitions.sort(compareNames);
146
+
147
+ return { definitions, problems };
148
+ }
149
+
150
+ export function parseDefinition(
151
+ content: string,
152
+ file: string,
153
+ scope: DefinitionScope,
154
+ ): AgentDefinition {
155
+ let frontmatter: unknown;
156
+ let body: string;
157
+
158
+ try {
159
+ ({ frontmatter, body } = parseFrontmatter(content));
160
+ } catch (error) {
161
+ throw new Error(
162
+ `Invalid frontmatter: ${error instanceof Error ? error.message : String(error)}`,
163
+ { cause: error },
164
+ );
165
+ }
166
+
167
+ if (typeof frontmatter !== "object" || frontmatter === null || Array.isArray(frontmatter)) {
168
+ throw new Error("The frontmatter must be a YAML mapping.");
169
+ }
170
+
171
+ const fields = frontmatter as Record<string, unknown>;
172
+ const unknown = Object.keys(fields).filter((key) => !FIELDS.has(key));
173
+
174
+ if (unknown.length > 0) {
175
+ throw new Error(
176
+ `Unknown frontmatter field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}. ` +
177
+ `Allowed: ${[...FIELDS].join(", ")}.`,
178
+ );
179
+ }
180
+
181
+ const name = requiredString(fields, "name");
182
+
183
+ if (!NAME_PATTERN.test(name)) {
184
+ throw new Error(
185
+ `Invalid name "${name}": use letters, digits, ".", "_" and "-", at most 64 characters.`,
186
+ );
187
+ }
188
+
189
+ if (INLINE_NAME_PATTERN.test(name)) {
190
+ throw new Error(`The name "${name}" is reserved for inline runs.`);
191
+ }
192
+
193
+ const definition: AgentDefinition = {
194
+ name,
195
+ // The roster has one line per definition, so a folded YAML description must stay on one line.
196
+ description: requiredString(fields, "description").replace(/\s+/g, " "),
197
+ body,
198
+ file,
199
+ scope,
200
+ };
201
+
202
+ if (fields.tools !== undefined) {
203
+ definition.tools = parseTools(fields.tools);
204
+ }
205
+
206
+ if (fields.model !== undefined) {
207
+ const model = requiredString(fields, "model");
208
+
209
+ if (model !== AUTO_MODEL && !parseModelRef(model)) {
210
+ throw new Error(`Invalid model "${model}": use provider/id or ${AUTO_MODEL}.`);
211
+ }
212
+
213
+ definition.model = model;
214
+ }
215
+
216
+ if (fields.thinking !== undefined) {
217
+ definition.thinking = oneOf(fields, "thinking", THINKING_LEVELS);
218
+ }
219
+
220
+ if (fields.isolation !== undefined) {
221
+ definition.isolation = oneOf(fields, "isolation", ISOLATION_MODES);
222
+ }
223
+
224
+ return definition;
225
+ }
226
+
227
+ /**
228
+ * The `subagents` system prompt section: one line per definition, in name order, with project
229
+ * definitions marked.
230
+ */
231
+ export function renderRoster(definitions: readonly AgentDefinition[]): string | undefined {
232
+ if (definitions.length === 0) {
233
+ return undefined;
234
+ }
235
+
236
+ return definitions
237
+ .map(
238
+ (definition) =>
239
+ `- ${definition.name}${definition.scope === "project" ? " (project)" : ""}: ` +
240
+ definition.description,
241
+ )
242
+ .join("\n");
243
+ }
244
+
245
+ export function formatDefinitionProblems(problems: readonly DefinitionProblem[]): string {
246
+ return [
247
+ `Subagent definitions not loaded (${problems.length}):`,
248
+ ...problems.map((problem) => ` ${problem.file}: ${problem.message}`),
249
+ ].join("\n");
250
+ }
251
+
252
+ function compareNames(a: AgentDefinition, b: AgentDefinition): number {
253
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
254
+ }
255
+
256
+ function requiredString(fields: Record<string, unknown>, key: string): string {
257
+ const value = fields[key];
258
+
259
+ if (value === undefined || value === null) {
260
+ throw new Error(`Missing required field "${key}".`);
261
+ }
262
+
263
+ if (typeof value !== "string" || value.trim() === "") {
264
+ throw new Error(`The field "${key}" must be a non-empty string.`);
265
+ }
266
+
267
+ return value.trim();
268
+ }
269
+
270
+ function oneOf<const T extends readonly string[]>(
271
+ fields: Record<string, unknown>,
272
+ key: string,
273
+ values: T,
274
+ ): T[number] {
275
+ const value = fields[key];
276
+
277
+ if (typeof value !== "string" || !values.includes(value)) {
278
+ throw new Error(`The field "${key}" must be one of: ${values.join(", ")}.`);
279
+ }
280
+
281
+ return value as T[number];
282
+ }
283
+
284
+ /** `tools` takes a YAML list or a comma-separated string of exact names. */
285
+ function parseTools(value: unknown): string[] {
286
+ let names: unknown[];
287
+
288
+ if (typeof value === "string") {
289
+ names = value
290
+ .split(",")
291
+ .map((name) => name.trim())
292
+ .filter((name) => name !== "");
293
+ } else if (Array.isArray(value)) {
294
+ names = value;
295
+ } else {
296
+ throw new Error('The field "tools" must be a list or a comma-separated string.');
297
+ }
298
+
299
+ const tools: string[] = [];
300
+
301
+ for (const name of names) {
302
+ if (typeof name !== "string" || name.trim() === "") {
303
+ throw new Error('Every entry of "tools" must be a non-empty tool name.');
304
+ }
305
+
306
+ const trimmed = name.trim();
307
+
308
+ if (trimmed.startsWith("+") || trimmed.startsWith("-")) {
309
+ throw new Error(
310
+ `"tools" takes exact tool names, not +name or -name changes: ${trimmed}.`,
311
+ );
312
+ }
313
+
314
+ if (!TOOL_NAME_PATTERN.test(trimmed)) {
315
+ throw new Error(`Invalid tool name "${trimmed}".`);
316
+ }
317
+
318
+ if (!tools.includes(trimmed)) {
319
+ tools.push(trimmed);
320
+ }
321
+ }
322
+
323
+ return tools;
324
+ }
@@ -0,0 +1,78 @@
1
+ /** How long a failure keeps a Dock item's error marker when nobody opens the item's panel. */
2
+ export const ALERT_DURATION_MS = 10_000;
3
+
4
+ /**
5
+ * The lifetime of a Dock item's error marker. A failure shows from the time it happened until
6
+ * `ALERT_DURATION_MS` later, or until the user sees it in the item's panel. A check that finds a
7
+ * failure still showing also schedules the redraw that ends it, so a quiet screen does not keep
8
+ * the marker.
9
+ */
10
+ export class DockAlerts {
11
+ private readonly seen = new Set<string>();
12
+ /** A failure without a known time starts its window when it is first checked. */
13
+ private readonly firstChecked = new Map<string, number>();
14
+ private timer: ReturnType<typeof setTimeout> | undefined;
15
+ private dueAt = Infinity;
16
+ private readonly redraw: () => void;
17
+
18
+ constructor(redraw: () => void) {
19
+ this.redraw = redraw;
20
+ }
21
+
22
+ /** Whether the failure `key`, which happened at `at`, still shows the marker. */
23
+ shows(key: string, at: number | undefined): boolean {
24
+ if (this.seen.has(key)) {
25
+ return false;
26
+ }
27
+
28
+ const now = Date.now();
29
+ const since = at ?? this.firstChecked.get(key) ?? now;
30
+
31
+ if (at === undefined) {
32
+ this.firstChecked.set(key, since);
33
+ }
34
+
35
+ const endsAt = since + ALERT_DURATION_MS;
36
+
37
+ if (endsAt <= now) {
38
+ return false;
39
+ }
40
+
41
+ if (endsAt < this.dueAt) {
42
+ clearTimeout(this.timer);
43
+ this.dueAt = endsAt;
44
+ this.timer = setTimeout(() => {
45
+ this.timer = undefined;
46
+ this.dueAt = Infinity;
47
+ this.redraw();
48
+ }, endsAt - now);
49
+ }
50
+
51
+ return true;
52
+ }
53
+
54
+ /** The user saw the failure in the item's panel. False when it was seen before. */
55
+ acknowledge(key: string): boolean {
56
+ if (this.seen.has(key)) {
57
+ return false;
58
+ }
59
+
60
+ this.seen.add(key);
61
+
62
+ return true;
63
+ }
64
+
65
+ forget(key: string): void {
66
+ this.seen.delete(key);
67
+ this.firstChecked.delete(key);
68
+ }
69
+
70
+ /** Forgets every failure and stops the pending redraw, so a detached item draws nothing late. */
71
+ clear(): void {
72
+ clearTimeout(this.timer);
73
+ this.timer = undefined;
74
+ this.dueAt = Infinity;
75
+ this.seen.clear();
76
+ this.firstChecked.clear();
77
+ }
78
+ }