@rackrot/pi-agents 0.0.1 → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 rackrot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1 +1,71 @@
1
- Placeholder. See https://github.com/rackrot/pi-tools
1
+ # @rackrot/pi-agents
2
+
3
+ Curated [pi-subagents](https://github.com/tintinweb/pi-subagents) agents, plus settings-driven
4
+ overrides for `model`, `thinking` and `max_turns`.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pi install npm:@rackrot/pi-agents
10
+ ```
11
+
12
+ Requires `@tintinweb/pi-subagents`. The package declares `pi.subagents.agents`, so the agents
13
+ appear read-only in `/agents`. Any file in `.pi/agents/` or `~/.pi/agent/agents/` with the same
14
+ name overrides them.
15
+
16
+ ## Agents
17
+
18
+ | Name | Purpose |
19
+ | ------------- | ----------------------------------------------------------- |
20
+ | `reviewer` | Diff review against a spec; read-only |
21
+ | `test-runner` | Runs tests/typecheck/lint, returns only failures; read-only |
22
+ | `docs-lookup` | Current library docs with sources |
23
+
24
+ ## Overrides
25
+
26
+ Add `agentOverrides` to `~/.pi/agent/settings.json` or `.pi/settings.json`:
27
+
28
+ ```json
29
+ {
30
+ "agentOverrides": {
31
+ "reviewer": { "model": "claude-opus", "thinking": "high" },
32
+ "test-runner": { "model": "claude-haiku", "maxTurns": 10 },
33
+ "Explore": { "model": "claude-haiku" }
34
+ }
35
+ }
36
+ ```
37
+
38
+ - Fields: `model` (`provider/id` or fuzzy name), `thinking` (`off` to `max`), `maxTurns` (integer >= 1).
39
+ - Precedence per field, lowest first: package `defaults.json`, global settings, project settings.
40
+ - Names are case-insensitive and work for any agent type, including built-ins (`Explore`, `Plan`) and agents from other packages.
41
+ - `/subagent-config` opens a settings screen (below). `/subagent-config show` prints the effective values.
42
+
43
+ ### `/subagent-config` screen
44
+
45
+ Four rows per agent: `enabled`, `model`, `thinking`, `max turns`. Type to search, Enter or Space to
46
+ change a value, Esc to close.
47
+
48
+ - **Tab** switches the save target between global (`~/.pi/agent/settings.json`) and project
49
+ (`.pi/settings.json`). Changes write immediately.
50
+ - **model** opens a picker over your `enabledModels` (project list if set, else global), plus `inherit`.
51
+ For a model outside that list, edit `agentOverrides` in settings.json.
52
+ - **inherit** removes the value at the selected scope. A lower layer, such as the package default,
53
+ may still supply one; the row's description says which layer does.
54
+ - **enabled** has no pi-subagents setting behind it. Turning an agent off writes
55
+ `<scope>/agents/<name>.md` containing only `enabled: false`, which shadows built-in and package
56
+ agents, the same way pi-subagents' own `/agents` Disable does. Turning it on deletes that stub, or
57
+ removes the line from a file you wrote. The row shows the state at the selected scope only.
58
+ - Listed agents: the built-ins, this package's, files in the global, project and `.agents` agent dirs,
59
+ and any name already in `agentOverrides`. Agents shipped by other packages appear once they have an override entry.
60
+
61
+ ### How it works, and limits
62
+
63
+ pi-subagents treats an agent file's `model`, `thinking` and `max_turns` as authoritative over the
64
+ caller. The shipped files therefore leave those fields out. A `tool_call` hook rewrites the `Agent`
65
+ call's `model`, `thinking` and `max_turns` from settings, and settings win over what the orchestrator passed.
66
+
67
+ The hook only sees calls made through the `Agent` tool. Not covered: workflow `agent()` options,
68
+ scheduled spawns, cross-extension RPC, and possibly `@mention` starts in `direct` mode. Those run
69
+ with the agent file's own settings, which for these agents means the parent's model.
70
+
71
+ If `scopeModels` is on in pi-subagents, a model outside `enabledModels` is rejected.
@@ -0,0 +1,18 @@
1
+ ---
2
+
3
+ name: docs-lookup
4
+ description: Looks up current library or API documentation and returns the exact signature, option or snippet with its source URL. Use when training data may be stale. Caller must name the library and the specific question.
5
+ tools: read, grep, find
6
+ extensions: true
7
+ skills: false
8
+ color: cyan
9
+ ---
10
+
11
+ You answer one documentation question using current sources.
12
+
13
+ 1. Prefer official docs and the library's own source or types. Use search and fetch tools if available, otherwise installed package files under node_modules.
14
+ 2. Start with a short, broad query, then narrow.
15
+ 3. Return the minimal answer: signature or snippet, the version it applies to, and the source URL or file path.
16
+ 4. If sources disagree or you cannot confirm, say so. Do not guess.
17
+
18
+ Output (under 250 words): answer, version, source.
@@ -0,0 +1,27 @@
1
+ ---
2
+
3
+ name: reviewer
4
+ description: Reviews a diff against a spec or plan and reports correctness gaps. Use after implementing a change and before committing. Not for writing code or style review. Caller must pass the spec path (or requirement text) and the diff range.
5
+ tools: read, grep, find, bash
6
+ disallowed_tools: edit, write
7
+ extensions: false
8
+ skills: false
9
+ color: orange
10
+ ---
11
+
12
+ You review changes against a written spec. You cannot edit files.
13
+
14
+ 1. Read the spec you were given and list each requirement.
15
+ 2. Inspect the diff with `git diff <range>`, and read touched files for context.
16
+ 3. For each requirement, confirm it is implemented and that listed edge cases have tests.
17
+ 4. Run the project's test command in full and record the exact command and result.
18
+
19
+ Report only issues that affect correctness. Skip style and naming.
20
+ Try at least one input that should fail and confirm it does.
21
+ Do not report a pass after running only part of the tests.
22
+
23
+ Output (under 300 words):
24
+
25
+ - Verdict: pass | gaps
26
+ - Gaps: `path:line` - requirement - what is missing
27
+ - Evidence: command run and its result
@@ -0,0 +1,22 @@
1
+ ---
2
+
3
+ name: test-runner
4
+ description: Runs the project's tests, typecheck and lint, and returns only the failures. Use when full-suite output would be large. Caller should name the command, or say to find it from package.json. Does not fix anything.
5
+ tools: read, grep, find, bash
6
+ disallowed_tools: edit, write
7
+ extensions: false
8
+ skills: false
9
+ color: green
10
+ ---
11
+
12
+ You run checks and report failures. You cannot edit files.
13
+
14
+ 1. Run the command you were given. If none, read package.json scripts and run test, typecheck and lint.
15
+ 2. Run the full command, not a subset, unless told otherwise.
16
+ 3. For each failure, give `path:line`, the first error line, and a one-line likely cause.
17
+
18
+ Output (under 200 words):
19
+
20
+ - Result: pass | fail, with the exact commands run
21
+ - Failures: one bullet each
22
+ If everything passes, say so and stop. Do not paste raw logs.
package/defaults.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "reviewer": { "thinking": "medium", "maxTurns": 25 },
3
+ "test-runner": { "thinking": "low", "maxTurns": 15 },
4
+ "docs-lookup": { "thinking": "low", "maxTurns": 20 }
5
+ }
package/package.json CHANGED
@@ -1 +1,43 @@
1
- {"name":"@rackrot/pi-agents","version":"0.0.1","description":"Placeholder - real releases are published from github.com/rackrot/pi-tools","license":"MIT","repository":{"type":"git","url":"git+https://github.com/rackrot/pi-tools.git","directory":"packages/agents"}}
1
+ {
2
+ "name": "@rackrot/pi-agents",
3
+ "version": "0.1.0",
4
+ "description": "Curated pi-subagents agent definitions with settings-driven model/thinking overrides",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "pi-extension",
9
+ "pi-subagents"
10
+ ],
11
+ "license": "MIT",
12
+ "files": [
13
+ "src",
14
+ "agents",
15
+ "defaults.json",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test test/*.test.ts"
20
+ },
21
+ "pi": {
22
+ "extensions": [
23
+ "./src/index.ts"
24
+ ],
25
+ "subagents": {
26
+ "agents": [
27
+ "./agents"
28
+ ]
29
+ }
30
+ },
31
+ "peerDependencies": {
32
+ "@earendil-works/pi-coding-agent": "*",
33
+ "@tintinweb/pi-subagents": "*"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/rackrot/pi-tools.git",
41
+ "directory": "packages/agents"
42
+ }
43
+ }
package/src/config.ts ADDED
@@ -0,0 +1,76 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
5
+ export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
6
+
7
+ /** Per-agent tuning. Every field is optional; an unset field leaves pi-subagents' own behavior. */
8
+ export interface Tuning {
9
+ model?: string;
10
+ thinking?: ThinkingLevel;
11
+ maxTurns?: number;
12
+ }
13
+
14
+ export type Overrides = Record<string, Tuning>;
15
+
16
+ /** Agent types are matched case-insensitively, as pi-subagents does. */
17
+ const key = (name: string) => name.toLowerCase();
18
+
19
+ /** Keeps only well-formed fields; anything else is dropped rather than passed to the Agent tool. */
20
+ export function parseOverrides(raw: unknown): Overrides {
21
+ const out: Overrides = {};
22
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
23
+ for (const [name, value] of Object.entries(raw)) {
24
+ if (!value || typeof value !== "object") continue;
25
+ const v = value as Record<string, unknown>;
26
+ const t: Tuning = {};
27
+ if (typeof v.model === "string" && v.model.trim()) t.model = v.model.trim();
28
+ if (THINKING_LEVELS.includes(v.thinking as ThinkingLevel))
29
+ t.thinking = v.thinking as ThinkingLevel;
30
+ if (typeof v.maxTurns === "number" && Number.isInteger(v.maxTurns) && v.maxTurns >= 1) {
31
+ t.maxTurns = v.maxTurns;
32
+ }
33
+ if (Object.keys(t).length) out[key(name)] = t;
34
+ }
35
+ return out;
36
+ }
37
+
38
+ /** Field-by-field merge; later layers win. Layers: package defaults, global settings, project settings. */
39
+ export function resolveTuning(name: string, layers: Overrides[]): Tuning {
40
+ const merged: Tuning = {};
41
+ for (const layer of layers) Object.assign(merged, layer[key(name)]);
42
+ return merged;
43
+ }
44
+
45
+ /** Index of the highest layer that sets `field` for `name`, or -1. */
46
+ export function sourceLayer(name: string, field: keyof Tuning, layers: Overrides[]): number {
47
+ for (let i = layers.length - 1; i >= 0; i--) {
48
+ if (layers[i][key(name)]?.[field] !== undefined) return i;
49
+ }
50
+ return -1;
51
+ }
52
+
53
+ /** Names that have any tuning in any layer, for display. */
54
+ export function configuredNames(layers: Overrides[]): string[] {
55
+ return [...new Set(layers.flatMap((l) => Object.keys(l)))].sort();
56
+ }
57
+
58
+ function readJson(path: string): Record<string, unknown> {
59
+ if (!existsSync(path)) return {};
60
+ try {
61
+ return JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
62
+ } catch {
63
+ return {};
64
+ }
65
+ }
66
+
67
+ export const SETTINGS_KEY = "agentOverrides";
68
+
69
+ /** Layers in precedence order, lowest first. */
70
+ export function loadLayers(packageDir: string, agentDir: string, cwd: string): Overrides[] {
71
+ return [
72
+ parseOverrides(readJson(join(packageDir, "defaults.json"))),
73
+ parseOverrides(readJson(join(agentDir, "settings.json"))[SETTINGS_KEY]),
74
+ parseOverrides(readJson(join(cwd, ".pi", "settings.json"))[SETTINGS_KEY]),
75
+ ];
76
+ }
package/src/index.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { dirname, join } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import { configuredNames, loadLayers, resolveTuning, SETTINGS_KEY } from "./config.ts";
5
+ import { openSettings } from "./settings-ui.ts";
6
+
7
+ const PACKAGE_DIR = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+
9
+ /**
10
+ * Applies `agentOverrides` from pi settings to pi-subagents' `Agent` tool calls.
11
+ *
12
+ * pi-subagents treats an agent file's `model`, `thinking` and `max_turns` as authoritative over
13
+ * the caller's, so the shipped agent files leave those fields out and this hook supplies them.
14
+ * Settings win over whatever the orchestrator passed, matching that authority.
15
+ *
16
+ * Covers calls made through the `Agent` tool. Workflow `agent()` calls, scheduled spawns and
17
+ * cross-extension RPC do not go through it.
18
+ */
19
+ export default function (pi: ExtensionAPI) {
20
+ pi.on("tool_call", (event, ctx) => {
21
+ if (event.toolName !== "Agent") return;
22
+ const input = event.input as Record<string, unknown>;
23
+ if (typeof input.subagent_type !== "string") return;
24
+ const tuning = resolveTuning(
25
+ input.subagent_type,
26
+ loadLayers(PACKAGE_DIR, getAgentDir(), ctx.cwd),
27
+ );
28
+ if (tuning.model) input.model = tuning.model;
29
+ if (tuning.thinking) input.thinking = tuning.thinking;
30
+ if (tuning.maxTurns) input.max_turns = tuning.maxTurns;
31
+ });
32
+
33
+ pi.registerCommand("subagent-config", {
34
+ description:
35
+ "Edit subagent model, thinking, max turns and enabled state. `show` prints effective values.",
36
+ handler: async (args, ctx) => {
37
+ if (ctx.hasUI && args.trim() !== "show") {
38
+ await openSettings(ctx, PACKAGE_DIR);
39
+ return;
40
+ }
41
+ const layers = loadLayers(PACKAGE_DIR, getAgentDir(), ctx.cwd);
42
+ const names = configuredNames(layers);
43
+ const lines = names.map((n) => `${n}: ${JSON.stringify(resolveTuning(n, layers))}`);
44
+ ctx.ui.notify(
45
+ lines.length ? lines.join("\n") : `No overrides. Set "${SETTINGS_KEY}" in settings.json.`,
46
+ "info",
47
+ );
48
+ },
49
+ });
50
+ }
@@ -0,0 +1,222 @@
1
+ import {
2
+ type ExtensionCommandContext,
3
+ getAgentDir,
4
+ getSelectListTheme,
5
+ getSettingsListTheme,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import {
8
+ type Component,
9
+ Container,
10
+ SelectList,
11
+ type SettingItem,
12
+ SettingsList,
13
+ Text,
14
+ } from "@earendil-works/pi-tui";
15
+ import {
16
+ configuredNames,
17
+ loadLayers,
18
+ type Overrides,
19
+ resolveTuning,
20
+ sourceLayer,
21
+ THINKING_LEVELS,
22
+ type ThinkingLevel,
23
+ } from "./config.ts";
24
+ import {
25
+ agentsDir,
26
+ discoverAgents,
27
+ isAgentDisabled,
28
+ readEnabledModels,
29
+ type Scope,
30
+ saveOverride,
31
+ setAgentEnabled,
32
+ settingsPath,
33
+ } from "./store.ts";
34
+
35
+ const INHERIT = "inherit";
36
+ const TURN_PRESETS = ["5", "10", "15", "25", "40", "60", "100"];
37
+ const SOURCES = ["package default", "global settings", "project settings"];
38
+
39
+ type Row = "enabled" | "model" | "thinking" | "maxTurns";
40
+ const ROW_LABEL: Record<Row, string> = {
41
+ enabled: "enabled",
42
+ model: "model",
43
+ thinking: "thinking",
44
+ maxTurns: "max turns",
45
+ };
46
+
47
+ const rowId = (row: Row, name: string) => `${row}:${name}`;
48
+ const parseId = (id: string): { row: Row; name: string } => {
49
+ const i = id.indexOf(":");
50
+ return { row: id.slice(0, i) as Row, name: id.slice(i + 1) };
51
+ };
52
+
53
+ /** Opens the settings screen. Resolves when the user closes it. */
54
+ export async function openSettings(
55
+ ctx: ExtensionCommandContext,
56
+ packageDir: string,
57
+ ): Promise<void> {
58
+ const agentDir = getAgentDir();
59
+ const cwd = ctx.cwd;
60
+ let scope: Scope = "global";
61
+ let layers: Overrides[] = loadLayers(packageDir, agentDir, cwd);
62
+ const models = readEnabledModels(agentDir, cwd);
63
+
64
+ const agentNames = () => discoverAgents(packageDir, agentDir, cwd, configuredNames(layers));
65
+
66
+ function modelItems(current: string) {
67
+ const list = [INHERIT, ...models];
68
+ if (current !== INHERIT && !list.includes(current)) list.splice(1, 0, current);
69
+ return list.map((value) => ({
70
+ value,
71
+ label: value === INHERIT ? "inherit (use the parent's model)" : value,
72
+ }));
73
+ }
74
+
75
+ function describe(name: string, row: Row): string {
76
+ if (row === "enabled") {
77
+ return `Writes agents/${name}.md with enabled: false in ${scope} scope (shadows built-in and package agents). Applies to new Agent calls; the tool's type list updates next session.`;
78
+ }
79
+ const src = sourceLayer(name, row, layers);
80
+ const where = src === -1 ? "not set, inherits" : `set by ${SOURCES[src]}`;
81
+ return `${where}. Saving writes ${scope} settings; "${INHERIT}" clears the ${scope} value.`;
82
+ }
83
+
84
+ function value(name: string, row: Row): string {
85
+ if (row === "enabled")
86
+ return isAgentDisabled(agentsDir(scope, agentDir, cwd), name) ? "off" : "on";
87
+ const v = resolveTuning(name, layers)[row];
88
+ return v === undefined ? INHERIT : String(v);
89
+ }
90
+
91
+ function cycleValues(name: string, row: Row): string[] | undefined {
92
+ if (row === "enabled") return ["on", "off"];
93
+ if (row === "thinking") return [INHERIT, ...THINKING_LEVELS];
94
+ if (row === "maxTurns") {
95
+ const cur = value(name, row);
96
+ return [
97
+ INHERIT,
98
+ ...TURN_PRESETS,
99
+ ...(cur !== INHERIT && !TURN_PRESETS.includes(cur) ? [cur] : []),
100
+ ];
101
+ }
102
+ return undefined;
103
+ }
104
+
105
+ const buildItem = (name: string, row: Row): SettingItem => ({
106
+ id: rowId(row, name),
107
+ label: `${name} · ${ROW_LABEL[row]}`,
108
+ description: describe(name, row),
109
+ currentValue: value(name, row),
110
+ values: cycleValues(name, row),
111
+ submenu:
112
+ row === "model"
113
+ ? (current, done) => {
114
+ const items = modelItems(current);
115
+ const list = new SelectList(items, Math.min(12, items.length), getSelectListTheme());
116
+ list.setSelectedIndex(
117
+ Math.max(
118
+ 0,
119
+ items.findIndex((i) => i.value === current),
120
+ ),
121
+ );
122
+ list.onSelect = (item) => done(item.value);
123
+ list.onCancel = () => done();
124
+ return list;
125
+ }
126
+ : undefined,
127
+ });
128
+
129
+ const buildItems = () =>
130
+ agentNames().flatMap((n) =>
131
+ (["enabled", "model", "thinking", "maxTurns"] as Row[]).map((r) => buildItem(n, r)),
132
+ );
133
+
134
+ function apply(id: string, next: string) {
135
+ const { row, name } = parseId(id);
136
+ if (row === "enabled") {
137
+ setAgentEnabled(agentsDir(scope, agentDir, cwd), name, next === "on");
138
+ return;
139
+ }
140
+ const path = settingsPath(scope, agentDir, cwd);
141
+ if (next === INHERIT) return saveOverride(path, name, row, undefined);
142
+ if (row === "maxTurns") return saveOverride(path, name, row, Number(next));
143
+ if (row === "thinking") return saveOverride(path, name, row, next as ThinkingLevel);
144
+ saveOverride(path, name, row, next);
145
+ }
146
+
147
+ await ctx.ui.custom<void>((tui, theme, kb, done) => {
148
+ const items = buildItems();
149
+ const title = new Text("", 0, 0);
150
+ const file = new Text("", 0, 0);
151
+ const header = new Container();
152
+ header.addChild(title);
153
+ header.addChild(file);
154
+
155
+ const tabKey = kb.getKeys("tui.input.tab")[0];
156
+ const renderHeader = () => {
157
+ const hint = tabKey ? theme.fg("muted", ` · ${tabKey} to switch`) : "";
158
+ title.setText(
159
+ `⚙ Subagent Settings · Saving to: ${scope === "global" ? "Global" : "Project"}${hint}`,
160
+ );
161
+ file.setText(
162
+ theme.fg(
163
+ "muted",
164
+ ` ${settingsPath(scope, agentDir, cwd)} · agent files in ${agentsDir(scope, agentDir, cwd)}`,
165
+ ),
166
+ );
167
+ };
168
+
169
+ const refresh = () => {
170
+ layers = loadLayers(packageDir, agentDir, cwd);
171
+ const fresh = new Map(buildItems().map((i) => [i.id, i]));
172
+ for (const item of items) {
173
+ const next = fresh.get(item.id);
174
+ if (next)
175
+ Object.assign(item, {
176
+ currentValue: next.currentValue,
177
+ description: next.description,
178
+ values: next.values,
179
+ });
180
+ }
181
+ renderHeader();
182
+ list.invalidate();
183
+ };
184
+
185
+ const status = new Text("", 0, 0);
186
+ const rows = Math.max(5, tui.terminal.rows - 10);
187
+ const list = new SettingsList(
188
+ items,
189
+ Math.min(rows, items.length),
190
+ getSettingsListTheme(),
191
+ (id, next) => {
192
+ try {
193
+ apply(id, next);
194
+ status.setText("");
195
+ } catch (e) {
196
+ status.setText(theme.fg("error", ` ${e instanceof Error ? e.message : String(e)}`));
197
+ }
198
+ refresh();
199
+ },
200
+ () => done(),
201
+ { enableSearch: true },
202
+ );
203
+ renderHeader();
204
+
205
+ const component: Component = {
206
+ render: (w) => [...header.render(w), "", ...list.render(w), ...status.render(w)],
207
+ invalidate: () => {
208
+ header.invalidate();
209
+ list.invalidate();
210
+ },
211
+ handleInput: (data) => {
212
+ if (kb.matches(data, "tui.input.tab")) {
213
+ scope = scope === "global" ? "project" : "global";
214
+ refresh();
215
+ return;
216
+ }
217
+ list.handleInput(data);
218
+ },
219
+ };
220
+ return component;
221
+ });
222
+ }
package/src/store.ts ADDED
@@ -0,0 +1,198 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ unlinkSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { basename, dirname, join } from "node:path";
11
+ import { SETTINGS_KEY, type Tuning } from "./config.ts";
12
+
13
+ export type Scope = "global" | "project";
14
+ export type Field = keyof Tuning;
15
+
16
+ /** Agents pi-subagents registers itself. */
17
+ export const BUILTIN_AGENTS = ["general-purpose", "Explore", "Plan"];
18
+
19
+ export const settingsPath = (scope: Scope, agentDir: string, cwd: string) =>
20
+ scope === "global" ? join(agentDir, "settings.json") : join(cwd, ".pi", "settings.json");
21
+
22
+ export const agentsDir = (scope: Scope, agentDir: string, cwd: string) =>
23
+ scope === "global" ? join(agentDir, "agents") : join(cwd, ".pi", "agents");
24
+
25
+ type Json = Record<string, unknown>;
26
+
27
+ /** Reads a settings file. A missing file is empty; an unparseable one throws so it is never overwritten. */
28
+ export function readSettings(path: string): { data: Json; indent: string } {
29
+ if (!existsSync(path)) return { data: {}, indent: "\t" };
30
+ const text = readFileSync(path, "utf8");
31
+ if (!text.trim()) return { data: {}, indent: "\t" };
32
+ const data = JSON.parse(text) as unknown;
33
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
34
+ throw new Error(`${path} is not a JSON object`);
35
+ }
36
+ const indent = /^\{\r?\n(\t| +)/.exec(text)?.[1] ?? "\t";
37
+ return { data: data as Json, indent };
38
+ }
39
+
40
+ /** Returns a copy of `data` with one override field set, or removed when `value` is undefined. */
41
+ export function applyOverride(
42
+ data: Json,
43
+ name: string,
44
+ field: Field,
45
+ value: string | number | undefined,
46
+ ): Json {
47
+ const next: Json = { ...data };
48
+ const all: Record<string, Record<string, unknown>> = {
49
+ ...((next[SETTINGS_KEY] as Record<string, Record<string, unknown>> | undefined) ?? {}),
50
+ };
51
+ const existing = Object.keys(all).find((k) => k.toLowerCase() === name.toLowerCase()) ?? name;
52
+ const entry = { ...(all[existing] ?? {}) };
53
+ if (value === undefined) delete entry[field];
54
+ else entry[field] = value;
55
+ if (Object.keys(entry).length) all[existing] = entry;
56
+ else delete all[existing];
57
+ if (Object.keys(all).length) next[SETTINGS_KEY] = all;
58
+ else delete next[SETTINGS_KEY];
59
+ return next;
60
+ }
61
+
62
+ function writeAtomic(path: string, text: string) {
63
+ mkdirSync(dirname(path), { recursive: true });
64
+ const tmp = `${path}.tmp-${process.pid}`;
65
+ writeFileSync(tmp, text);
66
+ renameSync(tmp, path);
67
+ }
68
+
69
+ export function saveOverride(
70
+ path: string,
71
+ name: string,
72
+ field: Field,
73
+ value: string | number | undefined,
74
+ ) {
75
+ const { data, indent } = readSettings(path);
76
+ writeAtomic(path, `${JSON.stringify(applyOverride(data, name, field, value), null, indent)}\n`);
77
+ }
78
+
79
+ /** `enabledModels`: project value if it is a list, else global. */
80
+ export function readEnabledModels(agentDir: string, cwd: string): string[] {
81
+ for (const scope of ["project", "global"] as const) {
82
+ try {
83
+ const v = readSettings(settingsPath(scope, agentDir, cwd)).data.enabledModels;
84
+ if (Array.isArray(v)) return v.filter((m): m is string => typeof m === "string");
85
+ } catch {
86
+ // unreadable settings are skipped for listing purposes
87
+ }
88
+ }
89
+ return [];
90
+ }
91
+
92
+ // ---- enable / disable ----
93
+ //
94
+ // pi-subagents has no setting for this. Its own /agents Disable writes a local file with
95
+ // `enabled: false`, which shadows a built-in or package agent of the same name. Same mechanism here.
96
+
97
+ const FENCE = /^---[ \t]*$/;
98
+ const ENABLED_FALSE = /^enabled:[ \t]*false[ \t]*$/;
99
+ const STUB = "---\nenabled: false\n---\n";
100
+
101
+ function frontmatterBounds(lines: string[]): { open: number; close: number } | undefined {
102
+ if (!lines.length || !FENCE.test(lines[0].replace(/\r?\n$/, ""))) return undefined;
103
+ const close = lines.findIndex((l, i) => i > 0 && FENCE.test(l.replace(/\r?\n$/, "")));
104
+ return close === -1 ? undefined : { open: 0, close };
105
+ }
106
+
107
+ const splitLines = (s: string) => s.split(/(?<=\n)/);
108
+
109
+ export function isDisabledContent(content: string): boolean {
110
+ const lines = splitLines(content);
111
+ const b = frontmatterBounds(lines);
112
+ return !!b && lines.slice(1, b.close).some((l) => ENABLED_FALSE.test(l.replace(/\r?\n$/, "")));
113
+ }
114
+
115
+ export function disableContent(content: string): string {
116
+ if (isDisabledContent(content)) return content;
117
+ const lines = splitLines(content);
118
+ if (!frontmatterBounds(lines)) return `---\nenabled: false\n---\n${content}`;
119
+ const eol = lines[0].endsWith("\r\n") ? "\r\n" : "\n";
120
+ lines.splice(1, 0, `enabled: false${eol}`);
121
+ return lines.join("");
122
+ }
123
+
124
+ /** Removes `enabled: false`. `remove` is true when what remains is the empty stub, so the file can go. */
125
+ export function enableContent(content: string): { content: string; remove: boolean } {
126
+ const lines = splitLines(content);
127
+ const b = frontmatterBounds(lines);
128
+ if (!b) return { content, remove: false };
129
+ const kept = lines.filter(
130
+ (l, i) => !(i > 0 && i < b.close && ENABLED_FALSE.test(l.replace(/\r?\n$/, ""))),
131
+ );
132
+ const out = kept.join("");
133
+ return { content: out, remove: out.replace(/\r\n/g, "\n").trim() === "---\n---" };
134
+ }
135
+
136
+ export function isAgentDisabled(dir: string, name: string): boolean {
137
+ const file = join(dir, `${name}.md`);
138
+ return existsSync(file) && isDisabledContent(readFileSync(file, "utf8"));
139
+ }
140
+
141
+ export function setAgentEnabled(dir: string, name: string, enabled: boolean) {
142
+ const file = join(dir, `${name}.md`);
143
+ if (!enabled) {
144
+ writeAtomic(file, existsSync(file) ? disableContent(readFileSync(file, "utf8")) : STUB);
145
+ return;
146
+ }
147
+ if (!existsSync(file)) return;
148
+ const { content, remove } = enableContent(readFileSync(file, "utf8"));
149
+ if (remove) unlinkSync(file);
150
+ else writeAtomic(file, content);
151
+ }
152
+
153
+ // ---- discovery ----
154
+
155
+ function agentNamesIn(dir: string): string[] {
156
+ if (!existsSync(dir)) return [];
157
+ const names: string[] = [];
158
+ for (const f of readdirSync(dir)) {
159
+ if (!f.endsWith(".md")) continue;
160
+ const stem = basename(f, ".md");
161
+ let name = stem;
162
+ try {
163
+ const m = /^name:[ \t]*["']?([^"'\r\n]+?)["']?[ \t]*$/m.exec(
164
+ readFileSync(join(dir, f), "utf8").slice(0, 2000),
165
+ );
166
+ if (m) name = m[1];
167
+ } catch {
168
+ // fall back to the file stem
169
+ }
170
+ names.push(name);
171
+ }
172
+ return names;
173
+ }
174
+
175
+ /**
176
+ * Agents worth listing: built-ins, this package's, local ones in the global, project and
177
+ * workspace dirs, and any already named in overrides. Agents shipped by other packages appear
178
+ * only once they have an override; add one in settings.json to list a new one.
179
+ */
180
+ export function discoverAgents(
181
+ packageDir: string,
182
+ agentDir: string,
183
+ cwd: string,
184
+ extra: string[],
185
+ ): string[] {
186
+ const seen = new Map<string, string>();
187
+ for (const n of [
188
+ ...BUILTIN_AGENTS,
189
+ ...agentNamesIn(join(packageDir, "agents")),
190
+ ...agentNamesIn(join(agentDir, "agents")),
191
+ ...agentNamesIn(join(cwd, ".pi", "agents")),
192
+ ...agentNamesIn(join(cwd, ".agents", "agents")),
193
+ ...extra,
194
+ ]) {
195
+ if (!seen.has(n.toLowerCase())) seen.set(n.toLowerCase(), n);
196
+ }
197
+ return [...seen.values()].sort((a, b) => a.localeCompare(b));
198
+ }