@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.6

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "@nredd/pi-subagents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.22.0-nredd.6",
4
+ "description": "A pi extension that brings Claude Code-like sub-agents and workflow orchestration to pi — parallel execution, live widget, fleet view, custom agent types, mid-run steering, dynamic workflows, Claude Code compatibility, look and feel.",
5
+ "author": "tintinweb",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/nredd/pi-harness.git",
10
+ "directory": "packages/subagents"
11
+ },
12
+ "homepage": "https://github.com/nredd/pi-harness/tree/main/packages/subagents#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/nredd/pi-harness/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "keywords": [
20
+ "pi-package",
21
+ "pi",
22
+ "pi-extension",
23
+ "subagent",
24
+ "agent",
25
+ "autonomous"
26
+ ],
27
+ "peerDependencies": {
28
+ "@earendil-works/pi-ai": ">=1.1.0",
29
+ "@earendil-works/pi-coding-agent": ">=1.1.0",
30
+ "@earendil-works/pi-tui": ">=1.1.0",
31
+ "typebox": "*"
32
+ },
33
+ "dependencies": {
34
+ "croner": "^10.0.1",
35
+ "nanoid": "^5.1.16"
36
+ },
37
+ "files": [
38
+ "src",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "scripts": {
43
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc",
44
+ "prepublishOnly": "npm run lint && npm run typecheck && npm run test && npm run build",
45
+ "test": "vitest run",
46
+ "test:watch": "vitest",
47
+ "test:e2e": "vitest run e2e --reporter=verbose",
48
+ "typecheck": "tsc --noEmit",
49
+ "lint": "biome check src/ test/",
50
+ "lint:fix": "biome check --fix src/ test/",
51
+ "check": "npm run lint && npm run typecheck && npm run test && npm run test:bun",
52
+ "test:bun": "bun test test/session-scenarios.test.ts test/fleet-session.test.ts test/viewer-session.test.ts test/worktree-isolation-e2e.test.ts",
53
+ "test:coverage": "vitest run --coverage",
54
+ "bench": "vitest bench",
55
+ "bench:ab": "node test/perf/ab.mjs"
56
+ },
57
+ "devDependencies": {
58
+ "@biomejs/biome": "^2.4.14",
59
+ "@earendil-works/pi-ai": "https://github.com/nredd/pi/releases/download/v1.3.0-nredd.6/earendil-works-pi-ai-1.3.0.tgz",
60
+ "@earendil-works/pi-coding-agent": "https://github.com/nredd/pi/releases/download/v1.3.0-nredd.6/earendil-works-pi-coding-agent-1.3.0.tgz",
61
+ "@earendil-works/pi-tui": "https://github.com/nredd/pi/releases/download/v1.3.0-nredd.6/earendil-works-pi-tui-1.3.0.tgz",
62
+ "@xterm/headless": "5.5.0",
63
+ "@sinclair/typebox": "^0.34.49",
64
+ "@types/node": "^25.5.0",
65
+ "@vitest/coverage-istanbul": "^4.1.11",
66
+ "typebox": "^1.3.27",
67
+ "typescript": "^6.0.0",
68
+ "vitest": "^4.1.11"
69
+ },
70
+ "pi": {
71
+ "extensions": [
72
+ "./src/index.ts"
73
+ ],
74
+ "video": "https://github.com/tintinweb/pi-subagents/raw/master/media/demo.mp4",
75
+ "image": "https://github.com/tintinweb/pi-subagents/raw/master/media/screenshot.png"
76
+ }
77
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * abortable.ts — race a promise against an AbortSignal without cancelling the
3
+ * underlying work.
4
+ *
5
+ * Used by the `get_subagent_result` wait paths (top-level and nested): pressing
6
+ * Esc cancels only the caller's wait; the background child keeps running and its
7
+ * result stays unconsumed. The listener is removed on every settle path so the
8
+ * signal accumulates no handlers, and a late settlement of the wrapped promise
9
+ * after an abort is absorbed as a no-op (no unhandled rejection).
10
+ */
11
+
12
+ /** Await a promise until it settles or the caller cancels, without aborting the underlying work. */
13
+ export function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
14
+ if (!signal) return promise;
15
+ if (signal.aborted) return Promise.reject(signal.reason);
16
+
17
+ return new Promise<T>((resolve, reject) => {
18
+ let settled = false;
19
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
20
+ const onAbort = () => {
21
+ if (settled) return;
22
+ settled = true;
23
+ cleanup();
24
+ reject(signal.reason);
25
+ };
26
+
27
+ signal.addEventListener("abort", onAbort, { once: true });
28
+ promise.then(
29
+ (value) => {
30
+ if (settled) return;
31
+ settled = true;
32
+ cleanup();
33
+ resolve(value);
34
+ },
35
+ (error: unknown) => {
36
+ if (settled) return;
37
+ settled = true;
38
+ cleanup();
39
+ reject(error);
40
+ },
41
+ );
42
+ });
43
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * agent-color.ts — Claude Code-compatible agent name badges.
3
+ *
4
+ * Claude Code renders a subagent's name as a badge: the configured color is the
5
+ * background, the text an inverse foreground. Its eight named colors are
6
+ * reproduced here, along with six-digit hex and the extra palette names Agency
7
+ * Agents uses, so those definitions render as written.
8
+ */
9
+
10
+ import { getConfig } from "./agent-types.js";
11
+
12
+ const NAMED_AGENT_COLORS: Readonly<Record<string, string>> = {
13
+ // Claude Code's eight subagent colors, as its default theme renders them.
14
+ red: "#DC2626",
15
+ blue: "#6A9BCC",
16
+ green: "#16A34A",
17
+ yellow: "#CA8A04",
18
+ purple: "#827DBD",
19
+ orange: "#D97757",
20
+ pink: "#C46686",
21
+ cyan: "#0891B2",
22
+ // Agency Agents palette aliases.
23
+ amber: "#F59E0B",
24
+ teal: "#008080",
25
+ indigo: "#6366F1",
26
+ gold: "#EAB308",
27
+ "neon-green": "#10B981",
28
+ "neon-cyan": "#06B6D4",
29
+ "metallic-blue": "#3B82F6",
30
+ violet: "#8B5CF6",
31
+ rose: "#F43F5E",
32
+ lime: "#84CC16",
33
+ gray: "#6B7280",
34
+ grey: "#6B7280",
35
+ fuchsia: "#D946EF",
36
+ slate: "#64748B",
37
+ navy: "#1E3A8A",
38
+ };
39
+
40
+ const CUBE_VALUES = [0, 95, 135, 175, 215, 255];
41
+ const GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);
42
+ const BLACK = { r: 0, g: 0, b: 0 };
43
+ const WHITE = { r: 255, g: 255, b: 255 };
44
+
45
+ type Rgb = { r: number; g: number; b: number };
46
+ type ColorMode = "truecolor" | "256color";
47
+
48
+ export interface AgentNameTheme {
49
+ fg(color: string, text: string): string;
50
+ bold(text: string): string;
51
+ getColorMode?(): ColorMode;
52
+ }
53
+
54
+ export interface AgentNameStyle {
55
+ /** Existing theme foreground used when no valid agent color is configured. */
56
+ fallbackColor?: string;
57
+ /** Reapply an enclosing background after the badge instead of resetting it. */
58
+ restoreBackground?: string;
59
+ bold?: boolean;
60
+ }
61
+
62
+ /** Resolve Claude Code/Agency Agents color syntax to normalized #RRGGBB. */
63
+ export function resolveAgentColor(value: string | undefined): string | undefined {
64
+ if (!value) return undefined;
65
+ const normalized = value.trim().toLowerCase();
66
+ const resolved = NAMED_AGENT_COLORS[normalized] ?? normalized;
67
+ return /^#[0-9a-f]{6}$/i.test(resolved) ? resolved.toUpperCase() : undefined;
68
+ }
69
+
70
+ function parseHex(hex: string): Rgb {
71
+ return {
72
+ r: Number.parseInt(hex.slice(1, 3), 16),
73
+ g: Number.parseInt(hex.slice(3, 5), 16),
74
+ b: Number.parseInt(hex.slice(5, 7), 16),
75
+ };
76
+ }
77
+
78
+ /** Index of the entry in `values` closest to `value`. */
79
+ function nearest(values: readonly number[], value: number): number {
80
+ return values.reduce((best, v, i) => (Math.abs(value - v) < Math.abs(value - values[best]) ? i : best), 0);
81
+ }
82
+
83
+ /**
84
+ * Quantize to the xterm-256 palette the way pi's own theme does, returning both
85
+ * the index to emit and the color the terminal will actually show — badge
86
+ * contrast is judged against the latter.
87
+ */
88
+ function rgbTo256({ r, g, b }: Rgb): { index: number; rgb: Rgb } {
89
+ const [rIndex, gIndex, bIndex] = [r, g, b].map((channel) => nearest(CUBE_VALUES, channel));
90
+ const distance = ({ r: cr, g: cg, b: cb }: Rgb) => 0.299 * (r - cr) ** 2 + 0.587 * (g - cg) ** 2 + 0.114 * (b - cb) ** 2;
91
+ const grayIndex = nearest(GRAY_VALUES, Math.round(0.299 * r + 0.587 * g + 0.114 * b));
92
+ const gray = { r: GRAY_VALUES[grayIndex], g: GRAY_VALUES[grayIndex], b: GRAY_VALUES[grayIndex] };
93
+ const cube = { r: CUBE_VALUES[rIndex], g: CUBE_VALUES[gIndex], b: CUBE_VALUES[bIndex] };
94
+ // Only near-neutral colors may take the gray ramp; anything else keeps its tint.
95
+ if (Math.max(r, g, b) - Math.min(r, g, b) < 10 && distance(gray) < distance(cube)) {
96
+ return { index: 232 + grayIndex, rgb: gray };
97
+ }
98
+ return { index: 16 + 36 * rIndex + 6 * gIndex + bIndex, rgb: cube };
99
+ }
100
+
101
+ function ansiColor(layer: "foreground" | "background", color: Rgb | number): string {
102
+ const code = layer === "foreground" ? 38 : 48;
103
+ return typeof color === "number"
104
+ ? `\u001b[${code};5;${color}m`
105
+ : `\u001b[${code};2;${color.r};${color.g};${color.b}m`;
106
+ }
107
+
108
+ function relativeLuminance({ r, g, b }: Rgb): number {
109
+ const linear = (value: number) => {
110
+ const channel = value / 255;
111
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
112
+ };
113
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
114
+ }
115
+
116
+ /**
117
+ * Render one name as a padded background badge when `color` is valid. Claude
118
+ * Code uses one inverse color for every badge's text; black or white is picked
119
+ * by WCAG contrast here instead, so each palette entry stays readable. Invalid
120
+ * or omitted colors preserve the caller's existing theme styling.
121
+ */
122
+ export function renderAgentNameLabel(
123
+ name: string,
124
+ color: string | undefined,
125
+ theme: AgentNameTheme,
126
+ style: AgentNameStyle = {},
127
+ ): string {
128
+ const resolved = resolveAgentColor(color);
129
+ if (!resolved) {
130
+ const text = style.bold ? theme.bold(name) : name;
131
+ return style.fallbackColor ? theme.fg(style.fallbackColor, text) : text;
132
+ }
133
+
134
+ const rgb = parseHex(resolved);
135
+ const quantized = (theme.getColorMode?.() ?? "truecolor") === "256color" ? rgbTo256(rgb) : undefined;
136
+ const shown = quantized?.rgb ?? rgb;
137
+ const contrasting = relativeLuminance(shown) > 0.179 ? BLACK : WHITE;
138
+ const label = style.bold ? theme.bold(` ${name} `) : ` ${name} `;
139
+
140
+ return ansiColor("background", quantized?.index ?? rgb)
141
+ + ansiColor("foreground", quantized ? rgbTo256(contrasting).index : contrasting)
142
+ + label
143
+ + "\u001b[39m"
144
+ + (style.restoreBackground ?? "\u001b[49m");
145
+ }
146
+
147
+ /** Whether an agent renders as a badge — i.e. it has a valid configured color. */
148
+ export function hasAgentBadge(type: string | undefined): boolean {
149
+ return type !== undefined && resolveAgentColor(getConfig(type).color) !== undefined;
150
+ }
151
+
152
+ /** Render a registered agent's display name with its configured color. */
153
+ export function renderAgentName(
154
+ type: string | undefined,
155
+ theme: AgentNameTheme,
156
+ style: AgentNameStyle = {},
157
+ ): string {
158
+ if (!type) return renderAgentNameLabel("Agent", undefined, theme, style);
159
+ const config = getConfig(type);
160
+ return renderAgentNameLabel(config.displayName, config.color, theme, style);
161
+ }
@@ -0,0 +1,297 @@
1
+ /**
2
+ * agent-file-toggle.ts — Pure helpers for the `/agents` file-editing operations:
3
+ * locating an agent's .md file, toggling its `enabled:` frontmatter flag, and
4
+ * serializing an AgentConfig back to frontmatter for eject.
5
+ *
6
+ * These live outside src/index.ts so they can be tested directly: the `/agents`
7
+ * command handler is an ~890-line closure reached only through `registerCommand`,
8
+ * which every test mocks.
9
+ *
10
+ * The read side of this data (src/custom-agents.ts) parses frontmatter with a
11
+ * real YAML parser, so it honors `enabled: false` at any position in the block.
12
+ * This module must agree with it, and splits the work accordingly:
13
+ *
14
+ * - Deciding whether a file is disabled is a *read*, so it calls that same parser
15
+ * (`isDisabledContent`) instead of mirroring it. A mirror has to be right about
16
+ * YAML's boolean spellings and about pi's fence scan, and a regex was wrong
17
+ * about both.
18
+ * - *Editing* cannot go through the parser, because re-serializing a parsed
19
+ * document would reformat a file the README tells users to hand-author —
20
+ * discarding their comments, key order, and quoting. So the edits are line-wise
21
+ * and preserve everything they don't touch.
22
+ *
23
+ * That leaves removal best-effort: it recognizes a lowercase bare `false`, and
24
+ * reports `changed: false` for the spellings it cannot rewrite, so the caller
25
+ * refuses honestly rather than announcing a change it did not make.
26
+ */
27
+
28
+ import { existsSync } from "node:fs";
29
+ import { join, sep } from "node:path";
30
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
31
+ import { parseAgentFrontmatter } from "./custom-agents.js";
32
+ import type { AgentConfig } from "./types.js";
33
+
34
+ export type AgentFileLocation = "project" | "workspace" | "personal";
35
+
36
+ export const projectAgentsDir = (cwd: string = process.cwd()) => join(cwd, ".pi", "agents");
37
+ export const workspaceAgentsDir = (cwd: string = process.cwd()) => join(cwd, ".agents", "agents");
38
+ export const personalAgentsDir = () => join(getAgentDir(), "agents");
39
+
40
+ /**
41
+ * Find the file path of a custom agent by name, in discovery-precedence order
42
+ * (project, workspace, then global). Mirrors the load-side precedence in
43
+ * src/custom-agents.ts — if the two drift, `/agents` edits a file the loader
44
+ * isn't reading.
45
+ */
46
+ export function findAgentFile(
47
+ name: string,
48
+ cwd: string = process.cwd(),
49
+ ): { path: string; location: AgentFileLocation } | undefined {
50
+ const projectPath = join(projectAgentsDir(cwd), `${name}.md`);
51
+ if (existsSync(projectPath)) return { path: projectPath, location: "project" };
52
+ const workspacePath = join(workspaceAgentsDir(cwd), `${name}.md`);
53
+ if (existsSync(workspacePath)) return { path: workspacePath, location: "workspace" };
54
+ const personalPath = join(personalAgentsDir(), `${name}.md`);
55
+ if (existsSync(personalPath)) return { path: personalPath, location: "personal" };
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * Find the *editable* file behind a loaded agent, preferring the path the loader
61
+ * actually read (`AgentConfig.sourcePath`) over the `<type>.md` guess.
62
+ *
63
+ * An agent's type comes from its frontmatter `name:` now, so the two can
64
+ * disagree: `reviewer.md` declaring `name: code-reviewer` is loaded as
65
+ * `code-reviewer`, and probing for `code-reviewer.md` finds nothing. That is
66
+ * not a harmless miss — `/agents → Disable` would then take the no-file branch
67
+ * and write a NEW `code-reviewer.md` stub, which loses to `reviewer.md` on
68
+ * load, leaving the agent enabled while reporting success.
69
+ *
70
+ * The probe stays as the fallback: a built-in that was never ejected has no
71
+ * `sourcePath`, and a path can go stale between a load and this call.
72
+ *
73
+ * **A package agent has no editable file.** Its `sourcePath` points inside pi's
74
+ * install root, where an edit is lost on the next `pi update` and a delete is
75
+ * undone by the next `pi install`. Passing `source` lets that rule live here
76
+ * rather than at each `/agents` call site: the package path is ignored, and the
77
+ * name probe runs instead — which finds the local stub shadowing it, if one
78
+ * exists, and otherwise nothing. Callers then take their no-file branch, which
79
+ * is the Eject-or-shadow behaviour a not-yet-ejected builtin already gets.
80
+ */
81
+ export function locateAgentFile(
82
+ name: string,
83
+ sourcePath: string | undefined,
84
+ cwd: string = process.cwd(),
85
+ source?: AgentConfig["source"],
86
+ ): { path: string; location: AgentFileLocation } | undefined {
87
+ if (source !== "package" && sourcePath && existsSync(sourcePath)) {
88
+ return { path: sourcePath, location: classifyAgentDir(sourcePath, cwd) };
89
+ }
90
+ return findAgentFile(name, cwd);
91
+ }
92
+
93
+ /**
94
+ * Which discovery location a loaded agent's file came from. Only ever names
95
+ * a directory in a confirmation prompt, so an unrecognized parent reports as
96
+ * personal rather than widening the type for a case that has no better answer.
97
+ *
98
+ * Package-provided paths never reach here: `locateAgentFile` drops them above,
99
+ * because none of the three locations this classifies is where they live.
100
+ */
101
+ function classifyAgentDir(path: string, cwd: string): AgentFileLocation {
102
+ if (path.startsWith(projectAgentsDir(cwd) + sep)) return "project";
103
+ if (path.startsWith(workspaceAgentsDir(cwd) + sep)) return "workspace";
104
+ return "personal";
105
+ }
106
+
107
+ export type DisableOutcome = "disabled" | "already-disabled" | "no-frontmatter";
108
+
109
+ /** A line that sets `enabled: false`, ignoring trailing whitespace / CR. */
110
+ const ENABLED_FALSE = /^enabled:[ \t]*false[ \t]*$/;
111
+ /** An opening or closing `---` fence line. */
112
+ const FENCE = /^---[ \t]*$/;
113
+
114
+ /**
115
+ * Split a file into its frontmatter lines and everything else, agreeing with
116
+ * what `parseAgentFrontmatter` (the load side) considers a frontmatter block —
117
+ * including its BOM normalisation, which is why the fence test looks past one.
118
+ * The BOM itself stays in `lines[0]`: it belongs to the file's encoding, not to
119
+ * the block, and an edit must not strip it from the user's file.
120
+ *
121
+ * Lines keep their terminators, so an edit preserves the file's existing line
122
+ * endings instead of rewriting CRLF to LF. Returns undefined when there is no
123
+ * usable block.
124
+ */
125
+ function splitFrontmatter(content: string):
126
+ | { lines: string[]; openIdx: number; closeIdx: number; eol: string }
127
+ | undefined {
128
+ const lines = content.split(/(?<=\n)/);
129
+ if (lines.length === 0) return undefined;
130
+ // The BOM stays where it is — it belongs to the file, not the block — so the
131
+ // fence test looks past it and every index below is unaffected.
132
+ const bom = content.startsWith("\uFEFF");
133
+ const first = (bom ? lines[0].slice(1) : lines[0]).replace(/\r?\n$/, "");
134
+ if (!FENCE.test(first)) return undefined;
135
+ const closeIdx = lines.findIndex((l, i) => i > 0 && FENCE.test(l.replace(/\r?\n$/, "")));
136
+ if (closeIdx === -1) return undefined;
137
+ return { lines, openIdx: 0, closeIdx, eol: lines[0].endsWith("\r\n") ? "\r\n" : "\n" };
138
+ }
139
+
140
+ /**
141
+ * Does the loader consider this file disabled?
142
+ *
143
+ * Detection is a READ operation, so it asks the same parser the loader uses
144
+ * rather than mirroring it with a regex — that mirror has to be right about
145
+ * YAML's boolean spellings (`False`, `FALSE`, a trailing `# comment`, a quoted
146
+ * key) *and* about pi's fence scan, which closes the block on any line starting
147
+ * `---` and so ends it early on `----`. A throw means the file is already
148
+ * unparseable, which is what the loader sees too: it skips the agent, so there
149
+ * is no "disabled" state to report.
150
+ */
151
+ export function isDisabledContent(content: string): boolean {
152
+ try {
153
+ return parseAgentFrontmatter<Record<string, unknown>>(content).frontmatter.enabled === false;
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Add `enabled: false` to a file's frontmatter.
161
+ *
162
+ * `outcome` distinguishes a real edit from a no-op so the caller can report
163
+ * honestly instead of unconditionally claiming success.
164
+ */
165
+ export function disableInContent(content: string): { content: string; outcome: DisableOutcome } {
166
+ const block = splitFrontmatter(content);
167
+ if (!block) return { content, outcome: "no-frontmatter" };
168
+ if (isDisabledContent(content)) return { content, outcome: "already-disabled" };
169
+ const lines = [...block.lines];
170
+ lines.splice(1, 0, `enabled: false${block.eol}`);
171
+ return { content: lines.join(""), outcome: "disabled" };
172
+ }
173
+
174
+ /**
175
+ * Remove `enabled: false` from a file's frontmatter, wherever it appears in the
176
+ * block — the loader honors the key at any position, so the two must agree or a
177
+ * hand-authored agent can be disabled and never re-enabled.
178
+ *
179
+ * `changed` is false when the key wasn't found, so the caller can avoid
180
+ * reporting "Enabled <name>" for a write that did nothing.
181
+ */
182
+ export function enableInContent(content: string): { content: string; changed: boolean } {
183
+ const block = splitFrontmatter(content);
184
+ if (!block) return { content, changed: false };
185
+ const kept = block.lines.filter(
186
+ (l, i) => !(i > 0 && i < block.closeIdx && ENABLED_FALSE.test(l.replace(/\r?\n$/, ""))),
187
+ );
188
+ if (kept.length === block.lines.length) return { content, changed: false };
189
+ return { content: kept.join(""), changed: true };
190
+ }
191
+
192
+ /** Is this the empty stub `/agents` writes when disabling a built-in default? */
193
+ export function isEmptyStub(content: string): boolean {
194
+ return content.replace(/\r\n/g, "\n").trim() === "---\n---";
195
+ }
196
+
197
+ /** The answers `/agents → Create agent → Manual` collects, before serialization. */
198
+ export interface NewAgentInput {
199
+ description: string;
200
+ /** Already-resolved `tools:` value ("none", "all", or a CSV of tool names). */
201
+ tools: string;
202
+ /** `provider/modelId`, or undefined to inherit the parent's model. */
203
+ model?: string;
204
+ /** A pi thinking level, or undefined to inherit. */
205
+ thinking?: string;
206
+ systemPrompt: string;
207
+ }
208
+
209
+ /**
210
+ * Build the .md file the create wizard writes.
211
+ *
212
+ * `description` and `model` come straight from a free-text prompt, so they are
213
+ * quoted rather than interpolated — `serializeAgentFile` above quotes the
214
+ * description for the same reason. An unquoted YAML scalar mishandles ordinary
215
+ * input in two ways, and both are silent: a colon ("Scout: find things") makes
216
+ * the file unparseable, and since #212 an unparseable agent file is *skipped*,
217
+ * so the wizard reports success for an agent that does not exist; a `#`
218
+ * ("audit #security") opens a comment and truncates the value. `model` can
219
+ * carry a colon too — pi accepts a `provider/model:thinking` suffix.
220
+ *
221
+ * `tools` and `thinking` are not quoted: both are chosen from fixed menus, and
222
+ * `tools` is a CSV that must stay a bare scalar for the loader's parser.
223
+ */
224
+ export function buildNewAgentFile(input: NewAgentInput): string {
225
+ const modelLine = input.model ? `\nmodel: ${JSON.stringify(input.model)}` : "";
226
+ const thinkingLine = input.thinking ? `\nthinking: ${input.thinking}` : "";
227
+ return `---
228
+ description: ${JSON.stringify(input.description)}
229
+ tools: ${input.tools}${modelLine}${thinkingLine}
230
+ prompt_mode: replace
231
+ ---
232
+
233
+ ${input.systemPrompt}
234
+ `;
235
+ }
236
+
237
+ /**
238
+ * Rebuild the `tools:` CSV from the two halves the loader split it into.
239
+ *
240
+ * `extSelectors` has to come back with the built-ins: `parseToolsField` splits
241
+ * `tools: read, ext:mcp/github` into `["read"]` and `["ext:mcp/github"]`, so
242
+ * writing only the first half hands the ejected copy a *narrower* toolset than
243
+ * the file it came from. That was invisible while Eject only ever ran on
244
+ * built-in defaults, which carry no selectors; a package agent can.
245
+ *
246
+ * Zero built-ins with selectors present is not `none` — `none` means no tools at
247
+ * all, while `ext:` entries alone mean "extension tools only", which the loader
248
+ * reads back from a `tools:` line carrying just those entries.
249
+ */
250
+ function formatToolsField(tools: string[] | undefined, extSelectors?: string[]): string {
251
+ const selectors = extSelectors ?? [];
252
+ if (tools === undefined) return selectors.length > 0 ? ["*", ...selectors].join(", ") : "all";
253
+ if (tools.length === 0) return selectors.length > 0 ? selectors.join(", ") : "none";
254
+ return [...tools, ...selectors].join(", ");
255
+ }
256
+
257
+ /** Serialize an AgentConfig to a full .md file (frontmatter + system prompt) for eject. */
258
+ export function serializeAgentFile(cfg: AgentConfig): string {
259
+ const fmFields: string[] = [];
260
+ fmFields.push(`description: ${JSON.stringify(cfg.description)}`);
261
+ if (cfg.displayName) fmFields.push(`display_name: ${cfg.displayName}`);
262
+ if (cfg.color) fmFields.push(`color: ${JSON.stringify(cfg.color)}`);
263
+ // Absent means "all built-ins"; an EMPTY list means explicitly zero. Writing
264
+ // `all` for both would hand a deliberately tool-less agent the whole toolbox
265
+ // the first time it is ejected.
266
+ fmFields.push(`tools: ${formatToolsField(cfg.builtinToolNames, cfg.extSelectors)}`);
267
+ if (cfg.model) fmFields.push(`model: ${cfg.model}`);
268
+ if (cfg.thinking) fmFields.push(`thinking: ${cfg.thinking}`);
269
+ if (cfg.maxTurns) fmFields.push(`max_turns: ${cfg.maxTurns}`);
270
+ if (cfg.allowedSubagents !== undefined) {
271
+ fmFields.push(`allowed_subagents: ${cfg.allowedSubagents === "all" ? "all" : cfg.allowedSubagents.join(", ")}`);
272
+ }
273
+ fmFields.push(`prompt_mode: ${cfg.promptMode}`);
274
+ if (cfg.extensions === false) fmFields.push("extensions: false");
275
+ else if (Array.isArray(cfg.extensions)) fmFields.push(`extensions: ${cfg.extensions.join(", ")}`);
276
+ if (cfg.excludeExtensions?.length) fmFields.push(`exclude_extensions: ${cfg.excludeExtensions.join(", ")}`);
277
+ if (cfg.skills === false) fmFields.push("skills: false");
278
+ else if (Array.isArray(cfg.skills)) fmFields.push(`skills: ${cfg.skills.join(", ")}`);
279
+ if (cfg.disallowedTools?.length) fmFields.push(`disallowed_tools: ${cfg.disallowedTools.join(", ")}`);
280
+ if (cfg.inheritContext) fmFields.push("inherit_context: true");
281
+ // Both cases, not just `true`: with `backgroundByDefault` on, omitting the
282
+ // field means background, so `false` is the only way to pin an agent file to
283
+ // foreground and is no longer interchangeable with absence. Reachable since
284
+ // package agents became ejectable — a built-in default omits the field.
285
+ if (cfg.runInBackground !== undefined) fmFields.push(`run_in_background: ${cfg.runInBackground}`);
286
+ if (cfg.outputTranscript === false) fmFields.push("output_transcript: false");
287
+ if (cfg.isolated) fmFields.push("isolated: true");
288
+ if (cfg.memory) fmFields.push(`memory: ${cfg.memory}`);
289
+ if (cfg.isolation) fmFields.push(`isolation: ${cfg.isolation}`);
290
+ // Also only reachable through a package agent: no built-in default sets
291
+ // either. Omitting them would have the ejected copy silently stop persisting
292
+ // its session, or write it somewhere else.
293
+ if (cfg.persistSession !== undefined) fmFields.push(`persist_session: ${cfg.persistSession}`);
294
+ if (cfg.sessionDir) fmFields.push(`session_dir: ${JSON.stringify(cfg.sessionDir)}`);
295
+
296
+ return `---\n${fmFields.join("\n")}\n---\n\n${cfg.systemPrompt}\n`;
297
+ }