@astrofoundry/astrogate 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +2 -2
  2. package/agents/foreman.md +27 -0
  3. package/cli/astro-install.sh +242 -0
  4. package/cli/astro.sh +449 -0
  5. package/cli/astro.test.ts +65 -0
  6. package/dist/bridge.js +9950 -0
  7. package/dist/claude.js +7899 -0
  8. package/dist/extensions/bridge/index.js +9937 -0
  9. package/dist/extensions/gate/index.js +286 -0
  10. package/dist/extensions/guard/index.js +364 -0
  11. package/dist/extensions/subagents/index.js +8458 -0
  12. package/extensions/bridge/admin.ts +86 -0
  13. package/extensions/bridge/approvals.ts +147 -0
  14. package/extensions/bridge/attachments.ts +65 -0
  15. package/extensions/bridge/chunk.ts +50 -0
  16. package/extensions/bridge/claude-run.test.ts +62 -0
  17. package/extensions/bridge/claude-run.ts +301 -0
  18. package/extensions/bridge/commands.ts +89 -0
  19. package/extensions/bridge/config.ts +263 -0
  20. package/extensions/bridge/conversations.ts +144 -0
  21. package/extensions/bridge/daemon.ts +60 -0
  22. package/extensions/bridge/discord.test.ts +547 -0
  23. package/extensions/bridge/gateway.ts +222 -0
  24. package/extensions/bridge/index.ts +951 -0
  25. package/extensions/bridge/launcher.ts +36 -0
  26. package/extensions/bridge/lifecycle.test.ts +78 -0
  27. package/extensions/bridge/open-work.ts +74 -0
  28. package/extensions/bridge/plugin.ts +172 -0
  29. package/extensions/bridge/quote.ts +39 -0
  30. package/extensions/bridge/reports.ts +65 -0
  31. package/extensions/bridge/rest.ts +217 -0
  32. package/extensions/bridge/setup.ts +218 -0
  33. package/extensions/gate/approvals.test.ts +40 -0
  34. package/extensions/gate/config.ts +110 -0
  35. package/extensions/gate/core.ts +114 -0
  36. package/extensions/gate/index.test.ts +202 -0
  37. package/extensions/gate/index.ts +114 -0
  38. package/extensions/gate/risky.ts +14 -0
  39. package/extensions/gate/types.ts +19 -0
  40. package/extensions/guard/config.test.ts +107 -0
  41. package/extensions/guard/config.ts +120 -0
  42. package/extensions/guard/defaults.ts +40 -0
  43. package/extensions/guard/index.test.ts +313 -0
  44. package/extensions/guard/index.ts +183 -0
  45. package/extensions/guard/rules.test.ts +118 -0
  46. package/extensions/guard/rules.ts +101 -0
  47. package/extensions/guard/types.ts +12 -0
  48. package/extensions/subagents/agents.test.ts +137 -0
  49. package/extensions/subagents/agents.ts +207 -0
  50. package/extensions/subagents/bundled.test.ts +29 -0
  51. package/extensions/subagents/child.test.ts +202 -0
  52. package/extensions/subagents/child.ts +367 -0
  53. package/extensions/subagents/index.test.ts +123 -0
  54. package/extensions/subagents/index.ts +352 -0
  55. package/extensions/subagents/pi-paths.test.ts +39 -0
  56. package/extensions/subagents/pi-paths.ts +58 -0
  57. package/extensions/subagents/render.ts +221 -0
  58. package/extensions/subagents/sessions.test.ts +32 -0
  59. package/extensions/subagents/sessions.ts +34 -0
  60. package/extensions/subagents/ticker.test.ts +40 -0
  61. package/extensions/subagents/ticker.ts +36 -0
  62. package/harness/claude/agents.ts +93 -0
  63. package/harness/claude/claude.test.ts +171 -0
  64. package/harness/claude/hook.ts +77 -0
  65. package/harness/claude/main.ts +122 -0
  66. package/harness/claude/mcp.ts +174 -0
  67. package/harness/claude/settings.ts +63 -0
  68. package/package.json +71 -4
  69. package/release.sha256 +95 -0
  70. package/release.sha256.sig +6 -0
  71. package/specialists/AGENTS.md +67 -0
  72. package/specialists/README.md +81 -0
  73. package/specialists/entry/specialist-cli.sh +22 -0
  74. package/specialists/entry/specialist-install.sh +861 -0
  75. package/specialists/entry/specialist-install.test.ts +305 -0
  76. package/specialists/lib/argv.ts +19 -0
  77. package/specialists/lib/audit.ts +20 -0
  78. package/specialists/lib/config.ts +27 -0
  79. package/specialists/lib/errors.ts +8 -0
  80. package/specialists/lib/flush.test.ts +21 -0
  81. package/specialists/lib/lib.test.ts +87 -0
  82. package/specialists/lib/lock.test.ts +42 -0
  83. package/specialists/lib/lock.ts +67 -0
  84. package/specialists/lib/main.ts +40 -0
  85. package/specialists/lib/output.ts +11 -0
  86. package/specialists/lib/paths.ts +22 -0
  87. package/specialists/lib/pinned.test.ts +55 -0
  88. package/specialists/lib/pinned.ts +67 -0
  89. package/specialists/lib/proc.ts +49 -0
  90. package/specialists/lib/repo.ts +198 -0
  91. package/specialists/lib/runtime.test.ts +81 -0
  92. package/specialists/lib/sanitize.ts +43 -0
  93. package/specialists/lib/secrets.ts +28 -0
  94. package/specialists/lib/ssh.ts +38 -0
  95. package/specialists/lib/tunnel.test.ts +44 -0
  96. package/specialists/lib/tunnel.ts +76 -0
  97. package/specialists/provision/provision.sh +96 -0
@@ -0,0 +1,11 @@
1
+ export function printJson(value: unknown): void {
2
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
3
+ }
4
+
5
+ export function printRaw(text: string): void {
6
+ process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
7
+ }
8
+
9
+ export function printError(message: string): void {
10
+ process.stderr.write(`${message}\n`);
11
+ }
@@ -0,0 +1,22 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+
4
+ export function specialistsHome(): string {
5
+ return join(homedir(), ".specialists");
6
+ }
7
+
8
+ export function secretsDir(service: string): string {
9
+ return join(specialistsHome(), "secrets", service);
10
+ }
11
+
12
+ export function configFile(service: string): string {
13
+ return join(specialistsHome(), "config", `${service}.json`);
14
+ }
15
+
16
+ export function workDir(name: string): string {
17
+ return join(specialistsHome(), "work", name);
18
+ }
19
+
20
+ export function auditLogPath(): string {
21
+ return join(specialistsHome(), "audit.log");
22
+ }
@@ -0,0 +1,55 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { X509Certificate } from "node:crypto";
3
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4
+ import { createServer, type Server } from "node:https";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
8
+ import { pinnedRequest } from "./pinned.ts";
9
+
10
+ describe("pinnedRequest", () => {
11
+ let dir: string;
12
+ let server: Server;
13
+ let url: URL;
14
+ let pin: string;
15
+ const seen: string[] = [];
16
+
17
+ beforeAll(async () => {
18
+ dir = mkdtempSync(join(tmpdir(), "astro-pin-"));
19
+ const key = join(dir, "key.pem");
20
+ const cert = join(dir, "cert.pem");
21
+ execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-subj", "/CN=console", "-days", "1", "-keyout", key, "-out", cert], { stdio: "ignore" });
22
+ pin = new X509Certificate(readFileSync(cert)).fingerprint256;
23
+ server = createServer({ key: readFileSync(key), cert: readFileSync(cert) }, (req, res) => {
24
+ let body = "";
25
+ req.on("data", (chunk: Buffer) => (body += chunk.toString()));
26
+ req.on("end", () => {
27
+ seen.push(`${req.method} ${req.headers["x-api-key"]} ${body}`);
28
+ res.end('{"ok":true}');
29
+ });
30
+ });
31
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
32
+ url = new URL(`https://127.0.0.1:${(server.address() as { port: number }).port}/x`);
33
+ });
34
+ afterAll(() => {
35
+ server.close();
36
+ rmSync(dir, { recursive: true, force: true });
37
+ });
38
+
39
+ const call = (expectedFingerprint: string | null) =>
40
+ pinnedRequest(url, { method: "POST", headers: { "X-API-KEY": "key" }, body: "{}", expectedFingerprint, timeoutMs: 5000 });
41
+
42
+ it("sends nothing to a certificate that does not match the pin", async () => {
43
+ await expect(call("00:11")).rejects.toThrow("does not match the pinned value");
44
+ expect(seen).toEqual([]);
45
+ });
46
+
47
+ it("sends the request after the pin matched, in any letter case", async () => {
48
+ await expect(call(pin.toLowerCase())).resolves.toEqual({ status: 200, body: '{"ok":true}', fingerprint: pin });
49
+ expect(seen).toEqual(["POST key {}"]);
50
+ });
51
+
52
+ it("reports a refused connection", async () => {
53
+ await expect(pinnedRequest(new URL("https://127.0.0.1:1/"), { method: "GET", headers: {}, expectedFingerprint: null, timeoutMs: 2000 })).rejects.toThrow("connection failed");
54
+ });
55
+ });
@@ -0,0 +1,67 @@
1
+ import { request as httpsRequest } from "node:https";
2
+ import { isIP } from "node:net";
3
+ import { connect as tlsConnect, type TLSSocket } from "node:tls";
4
+ import { ServiceError } from "./errors.ts";
5
+
6
+ export interface PinnedResponse {
7
+ status: number;
8
+ body: string;
9
+ fingerprint: string;
10
+ }
11
+
12
+ export interface PinnedOptions {
13
+ method: string;
14
+ headers: Record<string, string>;
15
+ body?: string;
16
+ /** SHA-256 fingerprint of the expected certificate (colon-separated hex); null probes without checking. */
17
+ expectedFingerprint: string | null;
18
+ timeoutMs: number;
19
+ }
20
+
21
+ /** Opens the TLS connection and checks the pin before any byte of the request, so a wrong peer never sees the API key. */
22
+ function pinnedSocket(url: URL, options: PinnedOptions): Promise<{ socket: TLSSocket; fingerprint: string }> {
23
+ return new Promise((resolve, reject) => {
24
+ const socket = tlsConnect({
25
+ host: url.hostname,
26
+ port: Number(url.port || 443),
27
+ servername: isIP(url.hostname) === 0 ? url.hostname : undefined,
28
+ rejectUnauthorized: false,
29
+ timeout: options.timeoutMs,
30
+ });
31
+ socket.once("secureConnect", () => {
32
+ const fingerprint = socket.getPeerCertificate().fingerprint256 ?? "";
33
+ if (options.expectedFingerprint !== null && fingerprint.toUpperCase() !== options.expectedFingerprint.toUpperCase()) {
34
+ socket.destroy();
35
+ reject(new ServiceError(`${url.host}: certificate fingerprint ${fingerprint} does not match the pinned value`));
36
+ return;
37
+ }
38
+ socket.setTimeout(0);
39
+ resolve({ socket, fingerprint });
40
+ });
41
+ socket.once("timeout", () => socket.destroy(new ServiceError(`${url.host}: connection timed out`)));
42
+ socket.once("error", (err) => reject(err instanceof ServiceError ? err : new ServiceError(`${url.host}: connection failed: ${err.message}`)));
43
+ });
44
+ }
45
+
46
+ /**
47
+ * HTTPS request to a self-signed service, sent only after the peer
48
+ * certificate matched the pinned fingerprint. Used for consoles that
49
+ * cannot present a CA-signed certificate (UniFi, Proxmox VE).
50
+ */
51
+ export async function pinnedRequest(url: URL, options: PinnedOptions): Promise<PinnedResponse> {
52
+ const { socket, fingerprint } = await pinnedSocket(url, options);
53
+ return new Promise((resolve, reject) => {
54
+ // No agent: the request runs on the socket whose certificate was checked, and that socket closes with it.
55
+ const req = httpsRequest(url, { method: options.method, headers: options.headers, timeout: options.timeoutMs, createConnection: () => socket }, (res) => {
56
+ let body = "";
57
+ res.setEncoding("utf-8");
58
+ res.on("data", (chunk: string) => {
59
+ body += chunk;
60
+ });
61
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body, fingerprint }));
62
+ });
63
+ req.on("timeout", () => req.destroy(new ServiceError(`${url.host}: request timed out`)));
64
+ req.on("error", (err) => reject(err instanceof ServiceError ? err : new ServiceError(`${url.host}: request failed: ${err.message}`)));
65
+ req.end(options.body);
66
+ });
67
+ }
@@ -0,0 +1,49 @@
1
+ import { spawn } from "node:child_process";
2
+ import { ServiceError } from "./errors.ts";
3
+
4
+ export interface RunOptions {
5
+ env?: Record<string, string>;
6
+ input?: string;
7
+ timeoutMs: number;
8
+ cwd?: string;
9
+ }
10
+
11
+ export interface RunResult {
12
+ stdout: string;
13
+ stderr: string;
14
+ code: number;
15
+ }
16
+
17
+ /** Runs one executable without a shell; secrets travel in env or stdin, never argv. */
18
+ export function run(file: string, args: string[], options: RunOptions): Promise<RunResult> {
19
+ return new Promise((resolve, reject) => {
20
+ const child = spawn(file, args, {
21
+ cwd: options.cwd,
22
+ env: { PATH: "/usr/bin:/bin:/usr/sbin:/sbin", HOME: process.env.HOME ?? "", ...options.env },
23
+ stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
24
+ });
25
+ let stdout = "";
26
+ let stderr = "";
27
+ const timer = setTimeout(() => {
28
+ child.kill("SIGKILL");
29
+ reject(new ServiceError(`${file} timed out after ${options.timeoutMs} ms`));
30
+ }, options.timeoutMs);
31
+ child.stdout?.on("data", (chunk: Buffer) => {
32
+ stdout += chunk.toString("utf-8");
33
+ });
34
+ child.stderr?.on("data", (chunk: Buffer) => {
35
+ stderr += chunk.toString("utf-8");
36
+ });
37
+ child.on("error", (err) => {
38
+ clearTimeout(timer);
39
+ reject(new ServiceError(`${file}: ${err.message}`));
40
+ });
41
+ child.on("close", (code) => {
42
+ clearTimeout(timer);
43
+ resolve({ stdout, stderr, code: code ?? 1 });
44
+ });
45
+ if (options.input !== undefined && child.stdin) {
46
+ child.stdin.end(options.input);
47
+ }
48
+ });
49
+ }
@@ -0,0 +1,198 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import { ServiceError, UsageError } from "./errors.ts";
4
+ import { printJson, printRaw } from "./output.ts";
5
+ import { specialistsHome, workDir } from "./paths.ts";
6
+ import { run } from "./proc.ts";
7
+ import { secretPath } from "./secrets.ts";
8
+
9
+ /** A Git repository the specialist edits through a write deploy key. */
10
+ export interface RepoSpec {
11
+ /** Specialist that owns the deploy key. */
12
+ service: string;
13
+ /** Folder name under ~/.specialists/work. */
14
+ checkoutName: string;
15
+ remote: string;
16
+ branch: string;
17
+ /** Secret field holding the private deploy key. */
18
+ deployKeyField: string;
19
+ /** Folder inside the repository that `git write` may touch; the whole checkout when absent. */
20
+ writeRoot?: string;
21
+ /** Wrapper help, printed with usage errors. */
22
+ help: string;
23
+ }
24
+
25
+ export const REPO_HELP = ` git status branch, ahead/behind, changed files of the repository checkout
26
+ git pull fast-forward the checkout from origin
27
+ git ls [dir] list files in the checkout
28
+ git show <path> print a file from the checkout
29
+ git diff unstaged and staged changes
30
+ git log [n] last n commits (default 10)
31
+ git write <path> <content> write a file inside the checkout (creates folders)
32
+ git commit <message> stage everything and commit
33
+ git push push the branch to origin
34
+ git key public key and fingerprint of the deploy key in use`;
35
+
36
+ const TIMEOUT_MS = 240_000;
37
+
38
+ export interface RepoStatus {
39
+ branch: string;
40
+ ahead: number;
41
+ behind: number;
42
+ changed: string[];
43
+ }
44
+
45
+ function gitEnv(spec: RepoSpec): Record<string, string> {
46
+ const key = secretPath(spec.service, spec.deployKeyField);
47
+ const knownHosts = join(specialistsHome(), "config", "known_hosts");
48
+ return {
49
+ GIT_SSH_COMMAND: `/usr/bin/ssh -i ${key} -o IdentitiesOnly=yes -o BatchMode=yes -o UserKnownHostsFile=${knownHosts} -o StrictHostKeyChecking=accept-new`,
50
+ GIT_AUTHOR_NAME: "specialist",
51
+ GIT_AUTHOR_EMAIL: "specialists@monadeo.com",
52
+ GIT_COMMITTER_NAME: "specialist",
53
+ GIT_COMMITTER_EMAIL: "specialists@monadeo.com",
54
+ };
55
+ }
56
+
57
+ /** One git command in a specialist checkout, with its deploy key; for wrappers that commit a fixed change of their own. */
58
+ export async function git(spec: RepoSpec, dir: string, args: string[]): Promise<string> {
59
+ const result = await run("/usr/bin/git", ["-C", dir, "-c", "core.fsmonitor=false", ...args], { env: gitEnv(spec), timeoutMs: TIMEOUT_MS });
60
+ if (result.code !== 0) throw new ServiceError(`git ${args[0]} failed: ${result.stderr.trim()}`);
61
+ return result.stdout;
62
+ }
63
+
64
+ export async function ensureCheckout(spec: RepoSpec): Promise<string> {
65
+ const dir = workDir(spec.checkoutName);
66
+ if (existsSync(join(dir, ".git"))) return dir;
67
+ mkdirSync(dirname(dir), { recursive: true, mode: 0o700 });
68
+ const result = await run("/usr/bin/git", ["clone", "--branch", spec.branch, "--single-branch", spec.remote, dir], {
69
+ env: gitEnv(spec),
70
+ timeoutMs: TIMEOUT_MS,
71
+ });
72
+ if (result.code !== 0) throw new ServiceError(`git clone failed: ${result.stderr.trim()}`);
73
+ return dir;
74
+ }
75
+
76
+ export function safeRepoPath(dir: string, rel: string): string {
77
+ if (rel.length === 0 || rel.startsWith("/") || rel.split("/").includes("..") || rel.includes("\0")) {
78
+ throw new UsageError(`invalid repository path: ${rel}`);
79
+ }
80
+ const target = resolve(dir, rel);
81
+ const inside = relative(dir, target);
82
+ // APFS ignores case, so `.GIT/config` is `.git/config`.
83
+ if (inside.startsWith("..") || inside.split("/").some((segment) => segment.toLowerCase() === ".git")) {
84
+ throw new UsageError(`path escapes the checkout: ${rel}`);
85
+ }
86
+ return target;
87
+ }
88
+
89
+ /**
90
+ * `git write` target; refuses paths outside `writeRoot` when the spec has one, and its `system/` folders,
91
+ * which hold the host's entry script and sudoers file.
92
+ */
93
+ export function safeWritePath(dir: string, rel: string, writeRoot?: string): string {
94
+ const target = safeRepoPath(dir, rel);
95
+ if (writeRoot !== undefined) {
96
+ const inside = relative(resolve(dir, writeRoot), target);
97
+ if (inside.length === 0 || inside.startsWith("..")) throw new UsageError(`writes are limited to ${writeRoot}/`);
98
+ if (inside.split("/").some((segment) => segment.toLowerCase() === "system")) throw new UsageError(`writes under ${writeRoot}/ never reach system/`);
99
+ }
100
+ return target;
101
+ }
102
+
103
+ /** Fetches origin and reports how the checkout relates to it. */
104
+ export async function repoStatus(spec: RepoSpec, dir: string): Promise<RepoStatus> {
105
+ await git(spec, dir, ["fetch", "--quiet", "origin", spec.branch]);
106
+ const branch = (await git(spec, dir, ["rev-parse", "--abbrev-ref", "HEAD"])).trim();
107
+ const counts = (await git(spec, dir, ["rev-list", "--left-right", "--count", `HEAD...origin/${spec.branch}`])).trim();
108
+ const [ahead, behind] = counts.split(/\s+/).map(Number);
109
+ const changed = (await git(spec, dir, ["status", "--porcelain"])).split("\n").filter(Boolean);
110
+ return { branch, ahead, behind, changed };
111
+ }
112
+
113
+ /** Content of a tracked file, only when the checkout equals origin: nothing uncommitted, nothing unpushed, nothing behind. */
114
+ export async function trackedFile(spec: RepoSpec, rel: string): Promise<string> {
115
+ const dir = await ensureCheckout(spec);
116
+ const status = await repoStatus(spec, dir);
117
+ if (status.changed.length > 0) throw new UsageError(`checkout has uncommitted changes: ${status.changed.join(", ")}; commit and push first`);
118
+ if (status.ahead > 0) throw new UsageError(`checkout is ${status.ahead} commit(s) ahead of origin; push first`);
119
+ if (status.behind > 0) throw new UsageError(`checkout is ${status.behind} commit(s) behind origin; run git pull first`);
120
+ return readFileSync(safeRepoPath(dir, rel), "utf-8");
121
+ }
122
+
123
+ export async function repoCommand(spec: RepoSpec, args: string[]): Promise<number> {
124
+ const [sub, ...rest] = args;
125
+ if (sub === "key") {
126
+ const key = secretPath(spec.service, spec.deployKeyField);
127
+ const [pub, fingerprint] = await Promise.all([
128
+ run("/usr/bin/ssh-keygen", ["-y", "-f", key], { timeoutMs: 10_000 }),
129
+ run("/usr/bin/ssh-keygen", ["-l", "-f", key], { timeoutMs: 10_000 }),
130
+ ]);
131
+ if (pub.code !== 0) throw new ServiceError(`deploy key unreadable: ${pub.stderr.trim()}`);
132
+ printJson({ publicKey: pub.stdout.trim(), fingerprint: fingerprint.stdout.trim() });
133
+ return 0;
134
+ }
135
+ const dir = await ensureCheckout(spec);
136
+ switch (sub) {
137
+ case "status":
138
+ printJson(await repoStatus(spec, dir));
139
+ return 0;
140
+ case "pull":
141
+ printRaw(await git(spec, dir, ["pull", "--ff-only", "origin", spec.branch]));
142
+ return 0;
143
+ case "diff":
144
+ printRaw((await git(spec, dir, ["diff", "--no-ext-diff", "HEAD"])) || "(no changes)");
145
+ return 0;
146
+ case "ls": {
147
+ if (rest.length > 1) throw new UsageError("git ls [dir]");
148
+ const target = rest[0] === undefined ? dir : safeRepoPath(dir, rest[0]);
149
+ if (!existsSync(target) || !statSync(target).isDirectory()) throw new UsageError(`not a directory in the checkout: ${rest[0] ?? "."}`);
150
+ printJson(
151
+ readdirSync(target, { withFileTypes: true })
152
+ .filter((e) => e.name !== ".git")
153
+ .map((e) => (e.isDirectory() ? `${e.name}/` : e.name))
154
+ .sort(),
155
+ );
156
+ return 0;
157
+ }
158
+ case "show": {
159
+ if (rest.length !== 1) throw new UsageError("git show <path>");
160
+ const target = safeRepoPath(dir, rest[0]);
161
+ if (!existsSync(target) || !statSync(target).isFile()) throw new UsageError(`not a file in the checkout: ${rest[0]}`);
162
+ printRaw(readFileSync(target, "utf-8"));
163
+ return 0;
164
+ }
165
+ case "log": {
166
+ const n = rest[0] === undefined ? 10 : Number(rest[0]);
167
+ if (!Number.isInteger(n) || n <= 0 || n > 200) throw new UsageError("git log [n]: n must be 1..200");
168
+ printRaw(await git(spec, dir, ["log", `-n${n}`, "--format=%h %ad %s", "--date=short"]));
169
+ return 0;
170
+ }
171
+ case "write": {
172
+ if (rest.length !== 2) throw new UsageError("git write <path> <content>");
173
+ const target = safeWritePath(dir, rest[0], spec.writeRoot);
174
+ mkdirSync(dirname(target), { recursive: true });
175
+ writeFileSync(target, rest[1].endsWith("\n") ? rest[1] : `${rest[1]}\n`, { mode: 0o600 });
176
+ printJson({ written: rest[0], bytes: Buffer.byteLength(rest[1]) });
177
+ return 0;
178
+ }
179
+ case "commit": {
180
+ const message = rest.join(" ").trim();
181
+ if (message.length === 0) throw new UsageError("git commit <message>");
182
+ await git(spec, dir, ["add", "--all"]);
183
+ const staged = (await git(spec, dir, ["diff", "--cached", "--name-only"])).split("\n").filter(Boolean);
184
+ if (staged.length === 0) throw new UsageError("nothing to commit");
185
+ await git(spec, dir, ["commit", "--quiet", "-m", message]);
186
+ printJson({ committed: (await git(spec, dir, ["rev-parse", "--short", "HEAD"])).trim(), files: staged });
187
+ return 0;
188
+ }
189
+ case "push": {
190
+ const result = await run("/usr/bin/git", ["-C", dir, "push", "origin", spec.branch], { env: gitEnv(spec), timeoutMs: TIMEOUT_MS });
191
+ if (result.code !== 0) throw new ServiceError(`git push failed: ${result.stderr.trim()}`);
192
+ printRaw(result.stderr.trim() || "pushed");
193
+ return 0;
194
+ }
195
+ default:
196
+ throw new UsageError(`unknown git subcommand: ${sub ?? "(none)"}\n${spec.help}`);
197
+ }
198
+ }
@@ -0,0 +1,81 @@
1
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { ServiceError, UsageError } from "./errors.ts";
6
+ import { main } from "./main.ts";
7
+ import { run } from "./proc.ts";
8
+
9
+ describe("run", () => {
10
+ it("captures stdout, stderr, exit code, and feeds stdin", async () => {
11
+ const result = await run("/bin/sh", ["-c", "cat; echo err >&2; exit 3"], { input: "hello", timeoutMs: 5000 });
12
+ expect(result).toEqual({ stdout: "hello", stderr: "err\n", code: 3 });
13
+ });
14
+
15
+ it("kills the child on timeout", async () => {
16
+ await expect(run("/bin/sleep", ["5"], { timeoutMs: 100 })).rejects.toThrow(/timed out/);
17
+ });
18
+
19
+ it("reports a missing executable", async () => {
20
+ await expect(run("/nonexistent/bin", [], { timeoutMs: 1000 })).rejects.toThrow(ServiceError);
21
+ });
22
+ });
23
+
24
+ describe("main", () => {
25
+ let home: string;
26
+ const originalHome = process.env.HOME;
27
+ let exit: ReturnType<typeof vi.spyOn>;
28
+ let stderr: ReturnType<typeof vi.spyOn>;
29
+
30
+ beforeEach(() => {
31
+ home = mkdtempSync(join(tmpdir(), "spec-main-"));
32
+ process.env.HOME = home;
33
+ mkdirSync(join(home, ".specialists"), { recursive: true });
34
+ exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never);
35
+ // Like a real stream, call the write callback: main waits for it before exiting.
36
+ stderr = vi.spyOn(process.stderr, "write").mockImplementation(((...args: unknown[]) => {
37
+ const done = args.find((a) => typeof a === "function") as (() => void) | undefined;
38
+ done?.();
39
+ return true;
40
+ }) as typeof process.stderr.write);
41
+ });
42
+
43
+ afterEach(() => {
44
+ exit.mockRestore();
45
+ stderr.mockRestore();
46
+ process.env.HOME = originalHome;
47
+ rmSync(home, { recursive: true, force: true });
48
+ });
49
+
50
+ function auditLines(): Record<string, unknown>[] {
51
+ return readFileSync(join(home, ".specialists", "audit.log"), "utf-8")
52
+ .trim()
53
+ .split("\n")
54
+ .map((l) => JSON.parse(l) as Record<string, unknown>);
55
+ }
56
+
57
+ it("passes args to the command, audits the call, and exits with its code", async () => {
58
+ const command = vi.fn().mockResolvedValue(0);
59
+ await main("arcane", command, ["--caller", "astro.arcane", "--", "projects", "list"]);
60
+ expect(command).toHaveBeenCalledWith(["projects", "list"]);
61
+ expect(exit).toHaveBeenCalledWith(0);
62
+ expect(auditLines()[0]).toMatchObject({ service: "arcane", caller: "astro.arcane", argv: ["projects", "list"], code: 0 });
63
+ });
64
+
65
+ it("maps usage errors to 2 and service errors to 1", async () => {
66
+ await main("arcane", async () => {
67
+ throw new UsageError("bad");
68
+ }, ["--", "x"]);
69
+ expect(exit).toHaveBeenLastCalledWith(2);
70
+ await main("arcane", async () => {
71
+ throw new ServiceError("down");
72
+ }, ["--", "y"]);
73
+ expect(exit).toHaveBeenLastCalledWith(1);
74
+ await main("arcane", async () => {
75
+ throw new Error("boom");
76
+ }, ["--", "z"]);
77
+ expect(exit).toHaveBeenLastCalledWith(1);
78
+ expect(auditLines().map((l) => l.code)).toEqual([2, 1, 1]);
79
+ expect(String(stderr.mock.calls[0][0])).toBe("arcane: bad\n");
80
+ });
81
+ });
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Output filters. A service's responses can carry secrets: a wrapper strips the
3
+ * keys its service is known to put them under (`stripKeys` with the pack's own
4
+ * list) and redacts values under secret-like key names (`redactSecrets`) before
5
+ * anything reaches the agent.
6
+ */
7
+ export const SECRET_KEY_PATTERN = /(secret|token|password|passwd|passphrase|psk|privatekey|private_key|apikey|api_key|pat|credential)s?$/i;
8
+
9
+ export function stripKeys(value: unknown, denied: readonly string[]): unknown {
10
+ if (Array.isArray(value)) return value.map((item) => stripKeys(item, denied));
11
+ if (typeof value === "object" && value !== null) {
12
+ const out: Record<string, unknown> = {};
13
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
14
+ if (denied.includes(k)) continue;
15
+ out[k] = stripKeys(v, denied);
16
+ }
17
+ return out;
18
+ }
19
+ return value;
20
+ }
21
+
22
+ export function redactSecrets(value: unknown): unknown {
23
+ if (Array.isArray(value)) return value.map(redactSecrets);
24
+ if (typeof value === "object" && value !== null) {
25
+ const out: Record<string, unknown> = {};
26
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
27
+ out[k] = SECRET_KEY_PATTERN.test(k) && typeof v === "string" ? "[redacted]" : redactSecrets(v);
28
+ }
29
+ return out;
30
+ }
31
+ return value;
32
+ }
33
+
34
+ /** Applies a filter to JSON text; non-JSON text passes through untouched. */
35
+ export function filterJsonText(text: string, filter: (value: unknown) => unknown): string {
36
+ const trimmed = text.trim();
37
+ if (trimmed.length === 0) return text;
38
+ try {
39
+ return JSON.stringify(filter(JSON.parse(trimmed)), null, 2);
40
+ } catch {
41
+ return text;
42
+ }
43
+ }
@@ -0,0 +1,28 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { ServiceError } from "./errors.ts";
4
+ import { secretsDir } from "./paths.ts";
5
+
6
+ const NAME = /^[A-Z][A-Z0-9_]*$/;
7
+
8
+ /** Path of one secret file; the name must be UPPER_SNAKE so it cannot escape the folder. */
9
+ export function secretPath(service: string, field: string): string {
10
+ if (!NAME.test(field)) throw new ServiceError(`invalid secret name: ${field}`);
11
+ return join(secretsDir(service), field);
12
+ }
13
+
14
+ /**
15
+ * Read a secret written by specialist-provision. Refuses files readable by
16
+ * anyone but the owner, so a permission slip is caught before use.
17
+ */
18
+ export function readSecret(service: string, field: string): string {
19
+ const path = secretPath(service, field);
20
+ let mode: number;
21
+ try {
22
+ mode = statSync(path).mode;
23
+ } catch {
24
+ throw new ServiceError(`secret ${field} for ${service} is missing; run specialist-cli provision`);
25
+ }
26
+ if ((mode & 0o077) !== 0) throw new ServiceError(`secret ${path} must be mode 0600`);
27
+ return readFileSync(path, "utf-8").replace(/\r?\n$/, "");
28
+ }
@@ -0,0 +1,38 @@
1
+ import { run, type RunResult } from "./proc.ts";
2
+
3
+ export interface SshTarget {
4
+ host: string;
5
+ user: string;
6
+ keyFile: string;
7
+ knownHostsFile: string;
8
+ /** TCP port; ssh's default when absent. */
9
+ port?: number;
10
+ /** known_hosts name when `host` is a local tunnel endpoint. */
11
+ hostKeyAlias?: string;
12
+ }
13
+
14
+ /**
15
+ * Runs one fixed remote command through a key that the target pins to a
16
+ * forced command. `remote` is a string from the wrapper's own table, never
17
+ * agent input. `input`, when given, becomes the remote command's stdin.
18
+ */
19
+ export function sshFixed(target: SshTarget, remote: string, timeoutMs: number, input?: string): Promise<RunResult> {
20
+ const args = [
21
+ "-i",
22
+ target.keyFile,
23
+ "-o",
24
+ "IdentitiesOnly=yes",
25
+ "-o",
26
+ "BatchMode=yes",
27
+ "-o",
28
+ `UserKnownHostsFile=${target.knownHostsFile}`,
29
+ "-o",
30
+ "StrictHostKeyChecking=accept-new",
31
+ "-o",
32
+ "ConnectTimeout=10",
33
+ ];
34
+ if (target.port !== undefined) args.push("-p", String(target.port));
35
+ if (target.hostKeyAlias !== undefined) args.push("-o", `HostKeyAlias=${target.hostKeyAlias}`);
36
+ args.push(`${target.user}@${target.host}`, remote);
37
+ return run("/usr/bin/ssh", args, { timeoutMs, input });
38
+ }
@@ -0,0 +1,44 @@
1
+ import { connect } from "node:net";
2
+ import { describe, expect, it } from "vitest";
3
+ import { ServiceError } from "./errors.ts";
4
+ import { openTunnel } from "./tunnel.ts";
5
+
6
+ function freePort(): Promise<number> {
7
+ return new Promise((resolve, reject) => {
8
+ import("node:net").then(({ createServer }) => {
9
+ const server = createServer();
10
+ server.listen(0, "127.0.0.1", () => {
11
+ const address = server.address();
12
+ server.close(() => (typeof address === "object" && address ? resolve(address.port) : reject(new Error("no port"))));
13
+ });
14
+ });
15
+ });
16
+ }
17
+
18
+ describe("openTunnel", () => {
19
+ it("resolves once the process listens and closes it afterwards", async () => {
20
+ const port = await freePort();
21
+ const script = `setTimeout(() => require("node:net").createServer().listen(${port}, "127.0.0.1"), 300); setInterval(() => {}, 1000);`;
22
+ const tunnel = await openTunnel(process.execPath, ["-e", script], { env: {}, port, readyTimeoutMs: 5000 });
23
+ await tunnel.close();
24
+ const closed = await new Promise<boolean>((resolve) => {
25
+ const socket = connect({ port, host: "127.0.0.1" });
26
+ socket.once("connect", () => {
27
+ socket.destroy();
28
+ resolve(false);
29
+ });
30
+ socket.once("error", () => resolve(true));
31
+ });
32
+ expect(closed).toBe(true);
33
+ });
34
+
35
+ it("reports a process that exits before listening", async () => {
36
+ const port = await freePort();
37
+ await expect(openTunnel("/bin/sh", ["-c", "echo denied >&2; exit 3"], { env: {}, port, readyTimeoutMs: 5000 })).rejects.toThrow(/exited with code 3: denied/);
38
+ });
39
+
40
+ it("gives up when nothing listens in time", async () => {
41
+ const port = await freePort();
42
+ await expect(openTunnel("/bin/sleep", ["5"], { env: {}, port, readyTimeoutMs: 600 })).rejects.toThrow(ServiceError);
43
+ });
44
+ });