@astrofoundry/astrogate 0.0.0-stage → 0.1.2
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/README.md +13 -2
- package/agents/foreman.md +27 -0
- package/cli/astro-install.sh +242 -0
- package/cli/astro.sh +449 -0
- package/cli/astro.test.ts +65 -0
- package/cli/astrogate.sh +309 -0
- package/cli/astrogate.test.ts +113 -0
- package/cli/verify-release.sh +77 -0
- package/cli/verify-release.test.ts +140 -0
- package/dist/bridge.js +9950 -0
- package/dist/claude.js +7899 -0
- package/dist/extensions/bridge/index.js +9937 -0
- package/dist/extensions/gate/index.js +286 -0
- package/dist/extensions/guard/index.js +364 -0
- package/dist/extensions/subagents/index.js +8458 -0
- package/extensions/bridge/admin.ts +86 -0
- package/extensions/bridge/approvals.ts +147 -0
- package/extensions/bridge/attachments.ts +65 -0
- package/extensions/bridge/chunk.ts +50 -0
- package/extensions/bridge/claude-run.test.ts +62 -0
- package/extensions/bridge/claude-run.ts +301 -0
- package/extensions/bridge/commands.ts +89 -0
- package/extensions/bridge/config.ts +263 -0
- package/extensions/bridge/conversations.ts +144 -0
- package/extensions/bridge/daemon.ts +60 -0
- package/extensions/bridge/discord.test.ts +547 -0
- package/extensions/bridge/gateway.ts +222 -0
- package/extensions/bridge/index.ts +951 -0
- package/extensions/bridge/launcher.ts +36 -0
- package/extensions/bridge/lifecycle.test.ts +78 -0
- package/extensions/bridge/open-work.ts +74 -0
- package/extensions/bridge/plugin.ts +172 -0
- package/extensions/bridge/quote.ts +39 -0
- package/extensions/bridge/reports.ts +65 -0
- package/extensions/bridge/rest.ts +217 -0
- package/extensions/bridge/setup.ts +218 -0
- package/extensions/gate/approvals.test.ts +40 -0
- package/extensions/gate/config.ts +110 -0
- package/extensions/gate/core.ts +114 -0
- package/extensions/gate/index.test.ts +202 -0
- package/extensions/gate/index.ts +114 -0
- package/extensions/gate/risky.ts +14 -0
- package/extensions/gate/types.ts +19 -0
- package/extensions/guard/config.test.ts +107 -0
- package/extensions/guard/config.ts +120 -0
- package/extensions/guard/defaults.ts +40 -0
- package/extensions/guard/index.test.ts +313 -0
- package/extensions/guard/index.ts +183 -0
- package/extensions/guard/rules.test.ts +118 -0
- package/extensions/guard/rules.ts +101 -0
- package/extensions/guard/types.ts +12 -0
- package/extensions/subagents/agents.test.ts +137 -0
- package/extensions/subagents/agents.ts +207 -0
- package/extensions/subagents/bundled.test.ts +29 -0
- package/extensions/subagents/child.test.ts +202 -0
- package/extensions/subagents/child.ts +367 -0
- package/extensions/subagents/index.test.ts +123 -0
- package/extensions/subagents/index.ts +352 -0
- package/extensions/subagents/pi-paths.test.ts +39 -0
- package/extensions/subagents/pi-paths.ts +58 -0
- package/extensions/subagents/render.ts +221 -0
- package/extensions/subagents/sessions.test.ts +32 -0
- package/extensions/subagents/sessions.ts +34 -0
- package/extensions/subagents/ticker.test.ts +40 -0
- package/extensions/subagents/ticker.ts +36 -0
- package/harness/claude/agents.ts +93 -0
- package/harness/claude/claude.test.ts +171 -0
- package/harness/claude/hook.ts +77 -0
- package/harness/claude/main.ts +122 -0
- package/harness/claude/mcp.ts +174 -0
- package/harness/claude/settings.ts +63 -0
- package/package.json +71 -4
- package/release.sha256 +99 -0
- package/release.sha256.sig +6 -0
- package/specialists/AGENTS.md +67 -0
- package/specialists/README.md +81 -0
- package/specialists/entry/specialist-cli.sh +22 -0
- package/specialists/entry/specialist-install.sh +861 -0
- package/specialists/entry/specialist-install.test.ts +305 -0
- package/specialists/lib/argv.ts +19 -0
- package/specialists/lib/audit.ts +20 -0
- package/specialists/lib/config.ts +27 -0
- package/specialists/lib/errors.ts +8 -0
- package/specialists/lib/flush.test.ts +21 -0
- package/specialists/lib/lib.test.ts +87 -0
- package/specialists/lib/lock.test.ts +42 -0
- package/specialists/lib/lock.ts +67 -0
- package/specialists/lib/main.ts +40 -0
- package/specialists/lib/output.ts +11 -0
- package/specialists/lib/paths.ts +22 -0
- package/specialists/lib/pinned.test.ts +55 -0
- package/specialists/lib/pinned.ts +67 -0
- package/specialists/lib/proc.ts +49 -0
- package/specialists/lib/repo.ts +198 -0
- package/specialists/lib/runtime.test.ts +81 -0
- package/specialists/lib/sanitize.ts +43 -0
- package/specialists/lib/secrets.ts +28 -0
- package/specialists/lib/ssh.ts +38 -0
- package/specialists/lib/tunnel.test.ts +44 -0
- package/specialists/lib/tunnel.ts +76 -0
- package/specialists/provision/provision.sh +96 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import * as os from "node:os";
|
|
2
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
3
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
4
|
+
import { getMarkdownTheme, type Theme, type ThemeColor } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
|
|
6
|
+
import { finalOutput, isFailed, type RunResult, type UsageStats } from "./child.ts";
|
|
7
|
+
|
|
8
|
+
export type Mode = "single" | "parallel" | "chain";
|
|
9
|
+
|
|
10
|
+
export interface SubagentDetails {
|
|
11
|
+
mode: Mode;
|
|
12
|
+
results: RunResult[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const COLLAPSED_ITEM_COUNT = 10;
|
|
16
|
+
|
|
17
|
+
function formatTokens(count: number): string {
|
|
18
|
+
if (count < 1000) return count.toString();
|
|
19
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
20
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
21
|
+
return `${(count / 1000000).toFixed(1)}M`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function formatUsage(usage: UsageStats, model?: string): string {
|
|
25
|
+
const parts: string[] = [];
|
|
26
|
+
if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
|
|
27
|
+
if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
|
|
28
|
+
if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
|
|
29
|
+
if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
|
|
30
|
+
if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
|
|
31
|
+
if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
|
|
32
|
+
if (usage.contextTokens > 0) parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
|
|
33
|
+
if (model) parts.push(model);
|
|
34
|
+
return parts.join(" ");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function aggregateUsage(results: RunResult[]): UsageStats {
|
|
38
|
+
const total: UsageStats = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
|
|
39
|
+
for (const r of results) {
|
|
40
|
+
total.input += r.usage.input;
|
|
41
|
+
total.output += r.usage.output;
|
|
42
|
+
total.cacheRead += r.usage.cacheRead;
|
|
43
|
+
total.cacheWrite += r.usage.cacheWrite;
|
|
44
|
+
total.cost += r.usage.cost;
|
|
45
|
+
total.turns += r.usage.turns;
|
|
46
|
+
}
|
|
47
|
+
return total;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type Fg = (color: ThemeColor, text: string) => string;
|
|
51
|
+
|
|
52
|
+
function str(value: unknown, fallback: string): string {
|
|
53
|
+
return typeof value === "string" && value.length > 0 ? value : fallback;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function shortenPath(p: string): string {
|
|
57
|
+
const home = os.homedir();
|
|
58
|
+
return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function formatToolCall(toolName: string, args: Record<string, unknown>, fg: Fg): string {
|
|
62
|
+
switch (toolName) {
|
|
63
|
+
case "bash": {
|
|
64
|
+
const command = str(args.command, "...");
|
|
65
|
+
return fg("muted", "$ ") + fg("toolOutput", command.length > 60 ? `${command.slice(0, 60)}...` : command);
|
|
66
|
+
}
|
|
67
|
+
case "read":
|
|
68
|
+
case "write":
|
|
69
|
+
case "edit": {
|
|
70
|
+
const filePath = shortenPath(str(args.file_path, str(args.path, "...")));
|
|
71
|
+
return fg("muted", `${toolName} `) + fg("accent", filePath);
|
|
72
|
+
}
|
|
73
|
+
case "ls":
|
|
74
|
+
return fg("muted", "ls ") + fg("accent", shortenPath(str(args.path, ".")));
|
|
75
|
+
case "find":
|
|
76
|
+
return fg("muted", "find ") + fg("accent", str(args.pattern, "*")) + fg("dim", ` in ${shortenPath(str(args.path, "."))}`);
|
|
77
|
+
case "grep":
|
|
78
|
+
return fg("muted", "grep ") + fg("accent", `/${str(args.pattern, "")}/`) + fg("dim", ` in ${shortenPath(str(args.path, "."))}`);
|
|
79
|
+
default: {
|
|
80
|
+
const preview = JSON.stringify(args);
|
|
81
|
+
return fg("accent", toolName) + fg("dim", ` ${preview.length > 50 ? `${preview.slice(0, 50)}...` : preview}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, unknown> };
|
|
87
|
+
|
|
88
|
+
function displayItems(messages: Message[]): DisplayItem[] {
|
|
89
|
+
const items: DisplayItem[] = [];
|
|
90
|
+
for (const msg of messages) {
|
|
91
|
+
if (msg.role !== "assistant") continue;
|
|
92
|
+
for (const part of msg.content) {
|
|
93
|
+
if (part.type === "text") items.push({ type: "text", text: part.text });
|
|
94
|
+
else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments as Record<string, unknown> });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return items;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function statusIcon(r: RunResult, theme: Theme): string {
|
|
101
|
+
if (r.exitCode === -1) return theme.fg("warning", "⏳");
|
|
102
|
+
return isFailed(r) ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function renderItems(items: DisplayItem[], theme: Theme, expanded: boolean, limit?: number): string {
|
|
106
|
+
const toShow = limit ? items.slice(-limit) : items;
|
|
107
|
+
const skipped = limit && items.length > limit ? items.length - limit : 0;
|
|
108
|
+
const fg: Fg = (c, t) => theme.fg(c, t);
|
|
109
|
+
let text = skipped > 0 ? theme.fg("muted", `... ${skipped} earlier items\n`) : "";
|
|
110
|
+
for (const item of toShow) {
|
|
111
|
+
if (item.type === "text") text += `${theme.fg("toolOutput", expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n"))}\n`;
|
|
112
|
+
else text += `${theme.fg("muted", "→ ")}${formatToolCall(item.name, item.args, fg)}\n`;
|
|
113
|
+
}
|
|
114
|
+
return text.trimEnd();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface CallArgs {
|
|
118
|
+
agent?: string;
|
|
119
|
+
task?: string;
|
|
120
|
+
tasks?: { agent: string; task: string }[];
|
|
121
|
+
chain?: { agent: string; task: string }[];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function renderCall(args: CallArgs, theme: Theme): Text {
|
|
125
|
+
const title = theme.fg("toolTitle", theme.bold("subagent "));
|
|
126
|
+
const preview = (t: string, n: number) => (t.length > n ? `${t.slice(0, n)}...` : t);
|
|
127
|
+
if (args.chain && args.chain.length > 0) {
|
|
128
|
+
let text = title + theme.fg("accent", `chain (${args.chain.length} steps)`);
|
|
129
|
+
args.chain.slice(0, 3).forEach((step, i) => {
|
|
130
|
+
text += `\n ${theme.fg("muted", `${i + 1}.`)} ${theme.fg("accent", step.agent)}${theme.fg("dim", ` ${preview(step.task.replace(/\{previous\}/g, "").trim(), 40)}`)}`;
|
|
131
|
+
});
|
|
132
|
+
if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
|
|
133
|
+
return new Text(text, 0, 0);
|
|
134
|
+
}
|
|
135
|
+
if (args.tasks && args.tasks.length > 0) {
|
|
136
|
+
let text = title + theme.fg("accent", `parallel (${args.tasks.length} tasks)`);
|
|
137
|
+
for (const t of args.tasks.slice(0, 3)) text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview(t.task, 40)}`)}`;
|
|
138
|
+
if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
|
|
139
|
+
return new Text(text, 0, 0);
|
|
140
|
+
}
|
|
141
|
+
return new Text(`${title}${theme.fg("accent", args.agent ?? "...")}\n ${theme.fg("dim", args.task ? preview(args.task, 60) : "...")}`, 0, 0);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function renderOne(r: RunResult, theme: Theme, expanded: boolean, label: string): Container | Text {
|
|
145
|
+
const items = displayItems(r.messages);
|
|
146
|
+
const output = finalOutput(r.messages);
|
|
147
|
+
const fg: Fg = (c, t) => theme.fg(c, t);
|
|
148
|
+
if (expanded) {
|
|
149
|
+
const c = new Container();
|
|
150
|
+
let header = `${statusIcon(r, theme)} ${theme.fg("toolTitle", theme.bold(label))}${theme.fg("muted", ` (${r.agentSource})`)}`;
|
|
151
|
+
if (isFailed(r) && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
|
|
152
|
+
c.addChild(new Text(header, 0, 0));
|
|
153
|
+
if (isFailed(r) && r.errorMessage) c.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
|
|
154
|
+
c.addChild(new Spacer(1));
|
|
155
|
+
c.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
|
|
156
|
+
for (const item of items) {
|
|
157
|
+
if (item.type === "toolCall") c.addChild(new Text(`${theme.fg("muted", "→ ")}${formatToolCall(item.name, item.args, fg)}`, 0, 0));
|
|
158
|
+
}
|
|
159
|
+
if (output) {
|
|
160
|
+
c.addChild(new Spacer(1));
|
|
161
|
+
c.addChild(new Markdown(output.trim(), 0, 0, getMarkdownTheme()));
|
|
162
|
+
} else if (items.length === 0) {
|
|
163
|
+
c.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
|
|
164
|
+
}
|
|
165
|
+
const usage = formatUsage(r.usage, r.model);
|
|
166
|
+
if (usage) c.addChild(new Text(theme.fg("dim", usage), 0, 0));
|
|
167
|
+
return c;
|
|
168
|
+
}
|
|
169
|
+
let text = `${statusIcon(r, theme)} ${theme.fg("toolTitle", theme.bold(label))}${theme.fg("muted", ` (${r.agentSource})`)}`;
|
|
170
|
+
if (isFailed(r) && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
|
|
171
|
+
else if (items.length === 0) text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`;
|
|
172
|
+
else {
|
|
173
|
+
text += `\n${renderItems(items, theme, false, COLLAPSED_ITEM_COUNT)}`;
|
|
174
|
+
if (items.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
|
|
175
|
+
}
|
|
176
|
+
const usage = formatUsage(r.usage, r.model);
|
|
177
|
+
if (usage) text += `\n${theme.fg("dim", usage)}`;
|
|
178
|
+
return new Text(text, 0, 0);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function renderResult(result: AgentToolResult<SubagentDetails>, expanded: boolean, theme: Theme): Container | Text {
|
|
182
|
+
const details = result.details;
|
|
183
|
+
if (!details || details.results.length === 0) {
|
|
184
|
+
const first = result.content[0];
|
|
185
|
+
return new Text(first?.type === "text" ? first.text : "(no output)", 0, 0);
|
|
186
|
+
}
|
|
187
|
+
if (details.mode === "single") return renderOne(details.results[0], theme, expanded, details.results[0].agent);
|
|
188
|
+
|
|
189
|
+
const running = details.results.filter((r) => r.exitCode === -1).length;
|
|
190
|
+
const ok = details.results.filter((r) => r.exitCode !== -1 && !isFailed(r)).length;
|
|
191
|
+
const icon = running > 0 ? theme.fg("warning", "⏳") : ok === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
|
|
192
|
+
const status = running > 0 ? `${details.results.length - running}/${details.results.length} done, ${running} running` : `${ok}/${details.results.length}`;
|
|
193
|
+
const header = `${icon} ${theme.fg("toolTitle", theme.bold(`${details.mode} `))}${theme.fg("accent", status)}`;
|
|
194
|
+
|
|
195
|
+
if (expanded && running === 0) {
|
|
196
|
+
const c = new Container();
|
|
197
|
+
c.addChild(new Text(header, 0, 0));
|
|
198
|
+
for (const r of details.results) {
|
|
199
|
+
c.addChild(new Spacer(1));
|
|
200
|
+
c.addChild(renderOne(r, theme, true, r.step !== undefined ? `Step ${r.step}: ${r.agent}` : r.agent));
|
|
201
|
+
}
|
|
202
|
+
const total = formatUsage(aggregateUsage(details.results));
|
|
203
|
+
if (total) {
|
|
204
|
+
c.addChild(new Spacer(1));
|
|
205
|
+
c.addChild(new Text(theme.fg("dim", `Total: ${total}`), 0, 0));
|
|
206
|
+
}
|
|
207
|
+
return c;
|
|
208
|
+
}
|
|
209
|
+
let text = header;
|
|
210
|
+
for (const r of details.results) {
|
|
211
|
+
const items = displayItems(r.messages);
|
|
212
|
+
text += `\n\n${theme.fg("muted", r.step !== undefined ? `─── Step ${r.step}: ` : "─── ")}${theme.fg("accent", r.agent)} ${statusIcon(r, theme)}`;
|
|
213
|
+
text += items.length === 0 ? `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}` : `\n${renderItems(items, theme, false, 5)}`;
|
|
214
|
+
}
|
|
215
|
+
if (running === 0) {
|
|
216
|
+
const total = formatUsage(aggregateUsage(details.results));
|
|
217
|
+
if (total) text += `\n\n${theme.fg("dim", `Total: ${total}`)}`;
|
|
218
|
+
}
|
|
219
|
+
if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
|
|
220
|
+
return new Text(text, 0, 0);
|
|
221
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
5
|
+
import { pruneSessions, sessionDirFor } from "./sessions.ts";
|
|
6
|
+
|
|
7
|
+
describe("child sessions", () => {
|
|
8
|
+
let root: string;
|
|
9
|
+
beforeEach(() => {
|
|
10
|
+
root = mkdtempSync(join(tmpdir(), "astro-sessions-"));
|
|
11
|
+
});
|
|
12
|
+
afterEach(() => rmSync(root, { recursive: true, force: true }));
|
|
13
|
+
|
|
14
|
+
it("names one directory per agent", () => {
|
|
15
|
+
expect(sessionDirFor("/s", "astro.security")).toBe("/s/astro.security");
|
|
16
|
+
expect(sessionDirFor("/s", "a b/c")).toBe("/s/a_b_c");
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("prunes old session files and leaves recent ones and other files", () => {
|
|
20
|
+
const now = 1_800_000_000_000;
|
|
21
|
+
const old = join(root, "old.jsonl");
|
|
22
|
+
const fresh = join(root, "fresh.jsonl");
|
|
23
|
+
const other = join(root, "notes.txt");
|
|
24
|
+
for (const f of [old, fresh, other]) writeFileSync(f, "x");
|
|
25
|
+
utimesSync(old, new Date(now - 8 * 86_400_000), new Date(now - 8 * 86_400_000));
|
|
26
|
+
utimesSync(other, new Date(now - 8 * 86_400_000), new Date(now - 8 * 86_400_000));
|
|
27
|
+
utimesSync(fresh, new Date(now - 60_000), new Date(now - 60_000));
|
|
28
|
+
expect(pruneSessions(root, 7 * 86_400_000, now)).toBe(1);
|
|
29
|
+
expect(readdirSync(root).sort()).toEqual(["fresh.jsonl", "notes.txt"]);
|
|
30
|
+
expect(pruneSessions(join(root, "missing"), 1, now)).toBe(0);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Saved child sessions older than this are deleted before a run. */
|
|
5
|
+
export const SESSION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
6
|
+
|
|
7
|
+
/** Directory holding one agent's saved child sessions. */
|
|
8
|
+
export function sessionDirFor(root: string, agentName: string): string {
|
|
9
|
+
return path.join(root, agentName.replace(/[^\w.-]+/g, "_"));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Deletes session files not modified within `maxAgeMs`; a missing directory holds nothing to prune. */
|
|
13
|
+
export function pruneSessions(dir: string, maxAgeMs = SESSION_MAX_AGE_MS, now = Date.now()): number {
|
|
14
|
+
let names: string[];
|
|
15
|
+
try {
|
|
16
|
+
names = fs.readdirSync(dir);
|
|
17
|
+
} catch {
|
|
18
|
+
return 0;
|
|
19
|
+
}
|
|
20
|
+
let removed = 0;
|
|
21
|
+
for (const name of names) {
|
|
22
|
+
if (!name.endsWith(".jsonl")) continue;
|
|
23
|
+
const file = path.join(dir, name);
|
|
24
|
+
try {
|
|
25
|
+
if (now - fs.statSync(file).mtimeMs > maxAgeMs) {
|
|
26
|
+
fs.unlinkSync(file);
|
|
27
|
+
removed++;
|
|
28
|
+
}
|
|
29
|
+
} catch {
|
|
30
|
+
// The file vanished between readdir and stat; nothing left to prune.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return removed;
|
|
34
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { formatElapsed, startTicker, tickerText } from "./ticker.ts";
|
|
3
|
+
|
|
4
|
+
describe("ticker", () => {
|
|
5
|
+
it("formats elapsed time as m:ss", () => {
|
|
6
|
+
expect(formatElapsed(0)).toBe("0:00");
|
|
7
|
+
expect(formatElapsed(59_999)).toBe("0:59");
|
|
8
|
+
expect(formatElapsed(61_000)).toBe("1:01");
|
|
9
|
+
expect(formatElapsed(3_600_000)).toBe("60:00");
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it("cycles spinner frames", () => {
|
|
13
|
+
expect(tickerText("astro.arcane", 0, 1000)).toBe("⠋ astro.arcane 0:01");
|
|
14
|
+
expect(tickerText("astro.arcane", 10, 1000)).toBe("⠋ astro.arcane 0:01");
|
|
15
|
+
expect(tickerText("astro.arcane", 1, 65_000)).toBe("⠙ astro.arcane 1:05");
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("paints accent-coloured status until stopped and then clears it", () => {
|
|
19
|
+
vi.useFakeTimers();
|
|
20
|
+
const setStatus = vi.fn();
|
|
21
|
+
const fg = vi.fn((color: string, text: string) => `<${color}>${text}</${color}>`);
|
|
22
|
+
const ctx = { hasUI: true, ui: { setStatus, theme: { fg } } } as unknown as Parameters<typeof startTicker>[0];
|
|
23
|
+
let clock = 0;
|
|
24
|
+
const stop = startTicker(ctx, "astro.network", 100, () => clock);
|
|
25
|
+
expect(setStatus).toHaveBeenLastCalledWith("subagent", "<accent>⠋ astro.network 0:00</accent>");
|
|
26
|
+
clock = 1500;
|
|
27
|
+
vi.advanceTimersByTime(100);
|
|
28
|
+
expect(setStatus).toHaveBeenLastCalledWith("subagent", "<accent>⠙ astro.network 0:01</accent>");
|
|
29
|
+
stop();
|
|
30
|
+
expect(setStatus).toHaveBeenLastCalledWith("subagent", undefined);
|
|
31
|
+
vi.useRealTimers();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("does nothing without a UI", () => {
|
|
35
|
+
const setStatus = vi.fn();
|
|
36
|
+
const stop = startTicker({ hasUI: false, ui: { setStatus } } as unknown as Parameters<typeof startTicker>[0], "x");
|
|
37
|
+
stop();
|
|
38
|
+
expect(setStatus).not.toHaveBeenCalled();
|
|
39
|
+
});
|
|
40
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
4
|
+
const STATUS_KEY = "subagent";
|
|
5
|
+
|
|
6
|
+
export function formatElapsed(ms: number): string {
|
|
7
|
+
const total = Math.max(0, Math.floor(ms / 1000));
|
|
8
|
+
const minutes = Math.floor(total / 60);
|
|
9
|
+
const seconds = total % 60;
|
|
10
|
+
return `${minutes}:${String(seconds).padStart(2, "0")}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function tickerText(label: string, frameIndex: number, elapsedMs: number): string {
|
|
14
|
+
return `${FRAMES[frameIndex % FRAMES.length]} ${label} ${formatElapsed(elapsedMs)}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Animated footer status in the accent colour while a subagent runs.
|
|
19
|
+
* Returns a stop function that clears the status. A no-op without UI.
|
|
20
|
+
*/
|
|
21
|
+
export function startTicker(ctx: ExtensionContext, label: string, intervalMs = 250, now: () => number = Date.now): () => void {
|
|
22
|
+
if (!ctx.hasUI) return () => {};
|
|
23
|
+
const started = now();
|
|
24
|
+
let frame = 0;
|
|
25
|
+
const paint = () => {
|
|
26
|
+
const text = tickerText(label, frame++, now() - started);
|
|
27
|
+
ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme ? ctx.ui.theme.fg("accent", text) : text);
|
|
28
|
+
};
|
|
29
|
+
paint();
|
|
30
|
+
const timer = setInterval(paint, intervalMs);
|
|
31
|
+
timer.unref();
|
|
32
|
+
return () => {
|
|
33
|
+
clearInterval(timer);
|
|
34
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code subagents from the installed pack: one `astro-<service>.md` per
|
|
3
|
+
* specialist, with the pack agent's description and prompt, its skill merged
|
|
4
|
+
* into the prompt (so the main session never loads it), the model and effort
|
|
5
|
+
* the pack sets for Claude Code, and the specialist's MCP server defined
|
|
6
|
+
* inline, so only that subagent has its tool.
|
|
7
|
+
*/
|
|
8
|
+
import { agentName } from "./hook.ts";
|
|
9
|
+
|
|
10
|
+
export const EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
11
|
+
export type Effort = (typeof EFFORTS)[number];
|
|
12
|
+
const MODEL = /^[a-z0-9][a-z0-9.-]{0,80}$/;
|
|
13
|
+
/** Unknown frontmatter fields are ignored by Claude Code; this one marks the files astro may replace. */
|
|
14
|
+
export const GENERATED_FIELD = "generatedBy: astro";
|
|
15
|
+
|
|
16
|
+
export interface ClaudeSettings {
|
|
17
|
+
model: string;
|
|
18
|
+
effort?: Effort;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface PackFile {
|
|
22
|
+
specialists: { service: string; claude?: Partial<ClaudeSettings> }[];
|
|
23
|
+
harness?: { claude?: Partial<ClaudeSettings> };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Markdown {
|
|
27
|
+
fields: Record<string, string>;
|
|
28
|
+
body: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Splits `---` frontmatter of single-line `key: value` fields from the body. */
|
|
32
|
+
export function parseMarkdown(text: string): Markdown {
|
|
33
|
+
const match = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(text);
|
|
34
|
+
if (!match) return { fields: {}, body: text };
|
|
35
|
+
const fields: Record<string, string> = {};
|
|
36
|
+
for (const line of match[1].split("\n")) {
|
|
37
|
+
const colon = line.indexOf(":");
|
|
38
|
+
if (colon > 0) fields[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
|
|
39
|
+
}
|
|
40
|
+
return { fields, body: match[2] };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function check(settings: Partial<ClaudeSettings>, where: string): ClaudeSettings {
|
|
44
|
+
if (typeof settings.model !== "string" || !MODEL.test(settings.model)) throw new Error(`${where}: claude model must be a model id or alias such as claude-opus-5-5`);
|
|
45
|
+
if (settings.effort !== undefined && !EFFORTS.includes(settings.effort)) throw new Error(`${where}: claude effort must be one of ${EFFORTS.join(", ")}`);
|
|
46
|
+
return { model: settings.model, ...(settings.effort ? { effort: settings.effort } : {}) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The pack's Claude Code settings for one specialist: its own entry over the pack-wide one. */
|
|
50
|
+
export function claudeSettings(pack: PackFile, service: string): ClaudeSettings {
|
|
51
|
+
const own = pack.specialists.find((s) => s.service === service)?.claude ?? {};
|
|
52
|
+
return check({ ...(pack.harness?.claude ?? {}), ...own }, `pack.json ${service}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface AgentSource {
|
|
56
|
+
service: string;
|
|
57
|
+
agent: string;
|
|
58
|
+
skill: string | null;
|
|
59
|
+
settings: ClaudeSettings;
|
|
60
|
+
node: string;
|
|
61
|
+
bundle: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The text of `astro-<service>.md`. */
|
|
65
|
+
export function renderAgent(source: AgentSource): string {
|
|
66
|
+
const agent = parseMarkdown(source.agent);
|
|
67
|
+
const description = agent.fields.description;
|
|
68
|
+
if (!description) throw new Error(`${source.service}: the pack agent has no description`);
|
|
69
|
+
const name = agentName(source.service);
|
|
70
|
+
const tool = `mcp__${name}__run`;
|
|
71
|
+
const skill = source.skill === null ? "" : parseMarkdown(source.skill).body.trim();
|
|
72
|
+
const lines = [
|
|
73
|
+
"---",
|
|
74
|
+
`name: ${name}`,
|
|
75
|
+
`description: ${JSON.stringify(description)}`,
|
|
76
|
+
`tools: Read, ${tool}`,
|
|
77
|
+
`model: ${source.settings.model}`,
|
|
78
|
+
...(source.settings.effort ? [`effort: ${source.settings.effort}`] : []),
|
|
79
|
+
"mcpServers:",
|
|
80
|
+
` - ${name}:`,
|
|
81
|
+
" type: stdio",
|
|
82
|
+
` command: ${JSON.stringify(source.node)}`,
|
|
83
|
+
` args: ${JSON.stringify([source.bundle, "serve", source.service])}`,
|
|
84
|
+
GENERATED_FIELD,
|
|
85
|
+
"---",
|
|
86
|
+
`In this harness your \`${source.service}\` tool is \`${tool}\`: pass the same subcommand and arguments as \`args\`. You cannot hand work to another specialist here; when a task needs one, say which and stop.`,
|
|
87
|
+
"",
|
|
88
|
+
agent.body.trim(),
|
|
89
|
+
...(skill ? ["", skill] : []),
|
|
90
|
+
"",
|
|
91
|
+
];
|
|
92
|
+
return lines.join("\n");
|
|
93
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import type { SpecialistsConfig } from "../../extensions/gate/types.ts";
|
|
3
|
+
import { claudeSettings, GENERATED_FIELD, parseMarkdown, renderAgent } from "./agents.ts";
|
|
4
|
+
import { type BridgeApproval, decide, type HookOutput } from "./hook.ts";
|
|
5
|
+
import { type Message, type Runner, SpecialistServer } from "./mcp.ts";
|
|
6
|
+
import { hasGate, HOOK_MATCHER, mergeSettings } from "./settings.ts";
|
|
7
|
+
|
|
8
|
+
const config: SpecialistsConfig = {
|
|
9
|
+
entry: "/usr/local/bin/specialist-cli",
|
|
10
|
+
user: "specialist",
|
|
11
|
+
specialists: [
|
|
12
|
+
{ agent: "astro.media", tool: "media", service: "media", timeoutMs: 780000, risky: [/^sabnzbd pause/] },
|
|
13
|
+
{ agent: "astro.arcane", tool: "arcane", service: "arcane", timeoutMs: 8100000 },
|
|
14
|
+
],
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** The decision a hook result carries: allow, deny, ask, "bridge" for an approval to wait for, or null. */
|
|
18
|
+
function kind(out: HookOutput | BridgeApproval | null): string | null {
|
|
19
|
+
if (out === null) return null;
|
|
20
|
+
return "hookSpecificOutput" in out ? out.hookSpecificOutput.permissionDecision : "bridge";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function reason(out: HookOutput | BridgeApproval | null): string {
|
|
24
|
+
return out && "hookSpecificOutput" in out ? out.hookSpecificOutput.permissionDecisionReason : "";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe("hook", () => {
|
|
28
|
+
const call = (tool_input: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({ tool_name: "mcp__astro-media__run", tool_input, agent_type: "astro-media", permission_mode: "default", ...extra });
|
|
29
|
+
|
|
30
|
+
it("blocks the entry point in Bash and the specialist's home in file tools", () => {
|
|
31
|
+
expect(kind(decide({ tool_name: "Bash", tool_input: { command: "sudo -n -u specialist -H /usr/local/bin/specialist-cli media -- queue" } }, config, {}))).toBe("deny");
|
|
32
|
+
expect(decide({ tool_name: "Bash", tool_input: { command: "ls -la" } }, config, {})).toBeNull();
|
|
33
|
+
expect(kind(decide({ tool_name: "Read", tool_input: { file_path: "/Users/specialist/.specialists/secrets/media/TOKEN" } }, config, {}))).toBe("deny");
|
|
34
|
+
expect(kind(decide({ tool_name: "Grep", tool_input: { path: "../specialist/.config" }, cwd: "/Users/cortex" }, config, {}))).toBe("deny");
|
|
35
|
+
expect(decide({ tool_name: "Read", tool_input: { file_path: "/Users/specialist-notes.md" } }, config, {})).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("lets only the matching subagent use a specialist tool", () => {
|
|
39
|
+
expect(decide(call({ args: ["queue"] }), config, {})).toBeNull();
|
|
40
|
+
expect(reason(decide(call({ args: ["queue"] }, { agent_type: undefined }), config, {}))).toMatch(/only the astro-media subagent/);
|
|
41
|
+
expect(kind(decide(call({ args: ["queue"] }, { agent_type: "astro-arcane" }), config, {}))).toBe("deny");
|
|
42
|
+
expect(reason(decide({ ...call({ args: ["x"] }), tool_name: "mcp__astro-proxmox__run", agent_type: "astro-proxmox" }, config, {}))).toMatch(/no proxmox specialist/);
|
|
43
|
+
expect(kind(decide(call({ args: "queue" }), config, {}))).toBe("deny");
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("asks for a risky call where Claude Code can prompt, and refuses it where it cannot", () => {
|
|
47
|
+
expect(kind(decide(call({ args: ["sabnzbd", "pause"] }), config, {}))).toBe("ask");
|
|
48
|
+
expect(kind(decide(call({ args: ["--confirm", "x"] }), config, {}))).toBe("ask");
|
|
49
|
+
expect(kind(decide(call({ args: ["sabnzbd", "pause"] }, { permission_mode: "bypassPermissions" }), config, {}))).toBe("deny");
|
|
50
|
+
expect(kind(decide(call({ args: ["sabnzbd", "pause"] }, { permission_mode: "auto" }), config, {}))).toBe("ask");
|
|
51
|
+
expect(kind(decide(call({ args: ["sabnzbd", "pause"] }, { permission_mode: "dontAsk" }), config, {}))).toBe("deny");
|
|
52
|
+
// A bridge run: the hook waits for the bridge's owners, whatever the mode.
|
|
53
|
+
expect(decide(call({ args: ["sabnzbd", "pause"] }, { permission_mode: "dontAsk" }), config, { ASTRO_APPROVAL_URL: "http://127.0.0.1:1", ASTRO_APPROVAL_TOKEN: "t", ASTRO_APPROVAL_TASK: "media" })).toEqual({
|
|
54
|
+
url: "http://127.0.0.1:1",
|
|
55
|
+
token: "t",
|
|
56
|
+
request: { agent: "astro.media", service: "media", args: ["sabnzbd", "pause"], task: "media" },
|
|
57
|
+
});
|
|
58
|
+
expect(decide(call({ args: ["queue"] }), config, { ASTRO_APPROVAL_URL: "http://127.0.0.1:1" })).toBeNull();
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/** The result of a response, failing the test when it is an error or missing. */
|
|
63
|
+
function resultOf(message: Message | null): Record<string, unknown> {
|
|
64
|
+
if (!message || !("result" in message)) throw new Error(`no result: ${JSON.stringify(message)}`);
|
|
65
|
+
return message.result;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
describe("mcp server", () => {
|
|
69
|
+
const ok: Runner = async () => ({ code: 0, stdout: '{"paused":false}\n', stderr: "", killed: false });
|
|
70
|
+
const server = (run: Runner = ok) => new SpecialistServer({ service: "media", config, version: "1.2.3", run });
|
|
71
|
+
const send = async (s: SpecialistServer, message: Record<string, unknown>) => s.handle(JSON.stringify({ jsonrpc: "2.0", ...message }));
|
|
72
|
+
|
|
73
|
+
it("answers the legacy handshake, discovery, ping, and the tool list", async () => {
|
|
74
|
+
const s = server();
|
|
75
|
+
expect(await send(s, { id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "c", version: "1" } } })).toEqual({ jsonrpc: "2.0", id: 1, result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "astro-media", version: "1.2.3" } } });
|
|
76
|
+
expect(resultOf(await send(s, { id: 2, method: "initialize", params: { protocolVersion: "1999-01-01" } })).protocolVersion).toBe("2025-11-25");
|
|
77
|
+
expect(await send(s, { method: "notifications/initialized" })).toBeNull();
|
|
78
|
+
expect(await send(s, { id: 3, method: "ping" })).toEqual({ jsonrpc: "2.0", id: 3, result: {} });
|
|
79
|
+
expect(resultOf(await send(s, { id: 4, method: "server/discover", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } } })).supportedVersions).toContain("2026-07-28");
|
|
80
|
+
expect(resultOf(await send(s, { id: 5, method: "tools/list" })).tools).toMatchObject([{ name: "run" }]);
|
|
81
|
+
expect(await send(s, { id: 6, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "1900-01-01" } } })).toMatchObject({ error: { code: -32022 } });
|
|
82
|
+
expect(await send(s, { id: 7, method: "resources/list" })).toMatchObject({ error: { code: -32601 } });
|
|
83
|
+
expect(await s.handle("{not json")).toMatchObject({ id: null, error: { code: -32700 } });
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("runs the entry point with the specialist's caller and returns its output", async () => {
|
|
87
|
+
const run = vi.fn<Runner>(ok);
|
|
88
|
+
const result = await send(server(run), { id: 1, method: "tools/call", params: { name: "run", arguments: { args: ["queue"] } } });
|
|
89
|
+
expect(run).toHaveBeenCalledWith("/usr/bin/sudo", ["-n", "-u", "specialist", "-H", "/usr/local/bin/specialist-cli", "media", "--caller", "astro.media", "--", "queue"], 780000, expect.any(AbortSignal));
|
|
90
|
+
expect(result).toEqual({ jsonrpc: "2.0", id: 1, result: { resultType: "complete", content: [{ type: "text", text: '{"paused":false}' }], isError: false } });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("reports failures, timeouts, bad arguments, and unknown tools", async () => {
|
|
94
|
+
const failed: Runner = async () => ({ code: 2, stdout: "", stderr: "usage: media ...", killed: false });
|
|
95
|
+
expect(await send(server(failed), { id: 1, method: "tools/call", params: { name: "run", arguments: { args: ["nope"] } } })).toMatchObject({ result: { isError: true, content: [{ text: "media specialist exited with code 2\nusage: media ..." }] } });
|
|
96
|
+
const killed: Runner = async () => ({ code: null, stdout: "", stderr: "", killed: true });
|
|
97
|
+
expect(JSON.stringify(await send(server(killed), { id: 2, method: "tools/call", params: { name: "run", arguments: { args: ["queue"] } } }))).toMatch(/was stopped after 780000 ms/);
|
|
98
|
+
expect(await send(server(), { id: 3, method: "tools/call", params: { name: "run", arguments: { args: "queue" } } })).toMatchObject({ result: { isError: true } });
|
|
99
|
+
expect(await send(server(), { id: 4, method: "tools/call", params: { name: "other", arguments: {} } })).toMatchObject({ error: { code: -32602 } });
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe("agents", () => {
|
|
104
|
+
const agent = '---\nname: media\ndescription: Manages the "library" through the media tool.\ntools: read, media, subagent\nmodel: openai-codex/gpt-6-astra\n---\nYou are the media specialist.\n';
|
|
105
|
+
const skill = "---\nname: media\ndescription: How.\n---\n\n# Media specialist\n\nUse `media`.\n";
|
|
106
|
+
|
|
107
|
+
it("reads frontmatter fields and the body", () => {
|
|
108
|
+
expect(parseMarkdown(agent)).toEqual({ fields: { name: "media", description: 'Manages the "library" through the media tool.', tools: "read, media, subagent", model: "openai-codex/gpt-6-astra" }, body: "You are the media specialist.\n" });
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it("takes the pack-wide Claude settings with a specialist's own override, and checks them", () => {
|
|
112
|
+
const pack = { specialists: [{ service: "media" }, { service: "arcane", claude: { effort: "max" as const } }], harness: { claude: { model: "claude-opus-5-5", effort: "xhigh" as const } } };
|
|
113
|
+
expect(claudeSettings(pack, "media")).toEqual({ model: "claude-opus-5-5", effort: "xhigh" });
|
|
114
|
+
expect(claudeSettings(pack, "arcane")).toEqual({ model: "claude-opus-5-5", effort: "max" });
|
|
115
|
+
expect(() => claudeSettings({ specialists: [{ service: "media" }] }, "media")).toThrow(/claude model/);
|
|
116
|
+
expect(() => claudeSettings({ specialists: [{ service: "media", claude: { model: "opus", effort: "huge" as "max" } }] }, "media")).toThrow(/effort/);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("renders a subagent with its own MCP server and the skill in its prompt", () => {
|
|
120
|
+
const text = renderAgent({ service: "media", agent, skill, settings: { model: "claude-opus-5-5", effort: "xhigh" }, node: "/opt/homebrew/bin/node", bundle: "/p/harness/claude.js" });
|
|
121
|
+
expect(text).toBe(
|
|
122
|
+
[
|
|
123
|
+
"---",
|
|
124
|
+
"name: astro-media",
|
|
125
|
+
'description: "Manages the \\"library\\" through the media tool."',
|
|
126
|
+
"tools: Read, mcp__astro-media__run",
|
|
127
|
+
"model: claude-opus-5-5",
|
|
128
|
+
"effort: xhigh",
|
|
129
|
+
"mcpServers:",
|
|
130
|
+
" - astro-media:",
|
|
131
|
+
" type: stdio",
|
|
132
|
+
' command: "/opt/homebrew/bin/node"',
|
|
133
|
+
' args: ["/p/harness/claude.js","serve","media"]',
|
|
134
|
+
GENERATED_FIELD,
|
|
135
|
+
"---",
|
|
136
|
+
"In this harness your `media` tool is `mcp__astro-media__run`: pass the same subcommand and arguments as `args`. You cannot hand work to another specialist here; when a task needs one, say which and stop.",
|
|
137
|
+
"",
|
|
138
|
+
"You are the media specialist.",
|
|
139
|
+
"",
|
|
140
|
+
"# Media specialist\n\nUse `media`.",
|
|
141
|
+
"",
|
|
142
|
+
].join("\n"),
|
|
143
|
+
);
|
|
144
|
+
expect(() => renderAgent({ service: "x", agent: "---\nname: x\n---\nbody", skill: null, settings: { model: "opus" }, node: "n", bundle: "b" })).toThrow(/no description/);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe("settings", () => {
|
|
149
|
+
it("adds the hook, allow rules, and limits, and replaces its earlier entries only", () => {
|
|
150
|
+
const current = {
|
|
151
|
+
theme: "dark",
|
|
152
|
+
env: { KEEP: "1" },
|
|
153
|
+
permissions: { allow: ["Bash(ls:*)", "mcp__astro-old__run"], deny: ["Read(./.env)"] },
|
|
154
|
+
hooks: { PreToolUse: [{ matcher: "Bash", hooks: [{ type: "command", command: "other" }] }, { matcher: "x", hooks: [{ type: "command", command: "/n /p/harness/claude.js hook" }] }], Stop: [] },
|
|
155
|
+
};
|
|
156
|
+
const merged = mergeSettings(current, ["media", "arcane"], "/opt/homebrew/bin/node /pack/harness/claude.js hook", 8100000);
|
|
157
|
+
expect(merged.theme).toBe("dark");
|
|
158
|
+
expect(merged.env).toEqual({ KEEP: "1", CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS: "0", CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT: "0", MCP_TOOL_TIMEOUT: "8160000" });
|
|
159
|
+
expect(merged.permissions).toEqual({ allow: ["Bash(ls:*)", "mcp__astro-media__run", "mcp__astro-arcane__run"], deny: ["Read(./.env)"] });
|
|
160
|
+
expect(merged.hooks?.PreToolUse).toEqual([
|
|
161
|
+
{ matcher: "Bash", hooks: [{ type: "command", command: "other" }] },
|
|
162
|
+
{ matcher: HOOK_MATCHER, hooks: [{ type: "command", command: "/opt/homebrew/bin/node /pack/harness/claude.js hook", timeout: 14460, onFailure: "block" }] },
|
|
163
|
+
]);
|
|
164
|
+
expect(merged.hooks?.Stop).toEqual([]);
|
|
165
|
+
expect(hasGate(merged)).toBe(true);
|
|
166
|
+
expect(hasGate(current)).toBe(true);
|
|
167
|
+
expect(hasGate({})).toBe(false);
|
|
168
|
+
expect(new RegExp(HOOK_MATCHER).test("mcp__astro-media__run")).toBe(true);
|
|
169
|
+
expect(new RegExp(HOOK_MATCHER).test("ReadMcpResourceTool")).toBe(false);
|
|
170
|
+
});
|
|
171
|
+
});
|