agentpier-runner 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.
@@ -0,0 +1,207 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import os from 'node:os';
4
+ import Anthropic from '@anthropic-ai/sdk';
5
+ import { agentBySlug, agents } from "./agents.js";
6
+ import { MODEL, parseEffort, runTask } from "./run.js";
7
+ import { detectClis, runCli } from "./cli.js";
8
+ import { roomTurnOnCli } from "./room.js";
9
+ export const VERSION = '0.1.1';
10
+ const MAX_BODY = 20_000;
11
+ /** A room turn carries up to 40 thread lines of 4,000 characters. */
12
+ const MAX_TURN_BODY = 400_000;
13
+ const MAX_FAILED_PAIRS = 10;
14
+ /**
15
+ * Pairing state. The website shows a code, the user types it into Runner, and
16
+ * only then does the website's poll receive a session token. A page that never
17
+ * showed the code (another site, another tab) cannot learn it.
18
+ */
19
+ export class Pairing {
20
+ expected = null;
21
+ tokens = new Set();
22
+ failures = 0;
23
+ /** Called when the user types a code into the Runner terminal. */
24
+ expect(code) {
25
+ this.expected = normalize(code);
26
+ this.failures = 0;
27
+ }
28
+ /** The website asks with the code it showed; returns a token once the user has typed the same code. */
29
+ claim(code) {
30
+ if (this.failures >= MAX_FAILED_PAIRS)
31
+ return { ok: false, reason: 'locked' };
32
+ const given = normalize(code);
33
+ if (!this.expected || given.length !== this.expected.length || !timingSafeEqual(Buffer.from(given), Buffer.from(this.expected))) {
34
+ if (this.expected)
35
+ this.failures++;
36
+ return { ok: false, reason: 'waiting' };
37
+ }
38
+ this.expected = null;
39
+ const token = randomBytes(32).toString('hex');
40
+ this.tokens.add(token);
41
+ return { ok: true, token };
42
+ }
43
+ check(token) {
44
+ return !!token && this.tokens.has(token);
45
+ }
46
+ revoke(token) {
47
+ this.tokens.delete(token);
48
+ }
49
+ get waitingForCode() {
50
+ return this.expected !== null;
51
+ }
52
+ }
53
+ export const normalize = (code) => code.toUpperCase().replace(/[^A-Z0-9]/g, '');
54
+ function bearer(req) {
55
+ const h = req.headers.authorization;
56
+ return h?.startsWith('Bearer ') ? h.slice(7) : null;
57
+ }
58
+ async function body(req, max = MAX_BODY) {
59
+ let size = 0;
60
+ const chunks = [];
61
+ for await (const chunk of req) {
62
+ const b = chunk;
63
+ size += b.length;
64
+ if (size > max)
65
+ return null;
66
+ chunks.push(b);
67
+ }
68
+ try {
69
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
70
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ export function startServer(opts) {
77
+ const { origins, folders, pairing, client, log } = opts;
78
+ const run = opts.run ?? runCli;
79
+ const detect = opts.detect ?? (() => detectClis());
80
+ // Checked at most once a minute, so installing a CLI shows up without restarting Runner.
81
+ let clis = null;
82
+ const installed = () => {
83
+ if (!clis || Date.now() - clis.at > 60_000)
84
+ clis = { at: Date.now(), value: detect() };
85
+ return clis.value;
86
+ };
87
+ void installed();
88
+ let busy = 0;
89
+ const allowed = (origin) => !!origin && origins.includes(origin);
90
+ const send = (res, status, data) => {
91
+ res.writeHead(status, { 'content-type': 'application/json' });
92
+ res.end(JSON.stringify(data));
93
+ };
94
+ const server = createServer(async (req, res) => {
95
+ const origin = req.headers.origin;
96
+ // Only the AgentPier site may talk to Runner. Requests without an allowed Origin are refused,
97
+ // so other websites in the same browser cannot drive it.
98
+ if (!allowed(origin))
99
+ return send(res, 403, { error: 'origin not allowed' });
100
+ res.setHeader('access-control-allow-origin', origin);
101
+ res.setHeader('vary', 'origin');
102
+ if (req.method === 'OPTIONS') {
103
+ res.writeHead(204, {
104
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
105
+ 'access-control-allow-headers': 'authorization, content-type',
106
+ 'access-control-allow-private-network': 'true',
107
+ 'access-control-max-age': '600',
108
+ });
109
+ return res.end();
110
+ }
111
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
112
+ const token = bearer(req);
113
+ if (req.method === 'GET' && url.pathname === '/v1/hello') {
114
+ return send(res, 200, { name: 'AgentPier Runner', version: VERSION, paired: pairing.check(token) });
115
+ }
116
+ if (req.method === 'POST' && url.pathname === '/v1/pair') {
117
+ const b = await body(req);
118
+ const code = typeof b?.code === 'string' ? b.code : '';
119
+ const result = pairing.claim(code);
120
+ if (result.ok) {
121
+ log('Paired with the AgentPier website.');
122
+ return send(res, 200, { token: result.token });
123
+ }
124
+ return send(res, result.reason === 'locked' ? 429 : 202, { status: result.reason });
125
+ }
126
+ if (!pairing.check(token))
127
+ return send(res, 401, { error: 'not paired' });
128
+ if (req.method === 'GET' && url.pathname === '/v1/info') {
129
+ return send(res, 200, {
130
+ device: os.hostname().replace(/\.local$/, ''),
131
+ model: MODEL,
132
+ agents: agents.map((a) => a.slug),
133
+ folders: folders.map((f) => ({ name: f.name, mode: f.mode })),
134
+ clis: await installed(),
135
+ });
136
+ }
137
+ if (req.method === 'POST' && url.pathname === '/v1/unpair') {
138
+ if (token)
139
+ pairing.revoke(token);
140
+ return send(res, 200, { ok: true });
141
+ }
142
+ // One room turn on the speaker's own CLI (Claude Code, Codex or Gemini CLI), signed in with
143
+ // the person's plan. Two at a time at most, so a busy room can't swamp this computer.
144
+ if (req.method === 'POST' && url.pathname === '/v1/room-turn') {
145
+ const b = await body(req, MAX_TURN_BODY);
146
+ if (!b)
147
+ return send(res, 400, { error: 'This turn could not be read.', code: 'bad_request' });
148
+ if (busy >= 2)
149
+ return send(res, 429, { error: 'Runner is already answering two turns.', code: 'busy' });
150
+ busy++;
151
+ try {
152
+ const started = Date.now();
153
+ const r = await roomTurnOnCli(b, { run, available: await installed() });
154
+ if (r.ok) {
155
+ log(`Room turn answered on your plan · ${((Date.now() - started) / 1000).toFixed(1)}s`);
156
+ return send(res, 200, { text: r.text });
157
+ }
158
+ log(`Room turn failed: ${r.code}`);
159
+ return send(res, r.code === 'bad_request' ? 400 : r.code === 'not_installed' ? 404 : r.code === 'timeout' ? 504 : 502, { error: r.reason, code: r.code });
160
+ }
161
+ finally {
162
+ busy--;
163
+ }
164
+ }
165
+ if (req.method === 'POST' && url.pathname === '/v1/runs') {
166
+ const b = await body(req);
167
+ const agent = agentBySlug(typeof b?.agent === 'string' ? b.agent : '');
168
+ const prompt = typeof b?.prompt === 'string' ? b.prompt.trim().slice(0, 8000) : '';
169
+ const effort = parseEffort(b?.effort);
170
+ if (!agent || !prompt)
171
+ return send(res, 400, { error: 'unknown agent or empty prompt' });
172
+ res.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-store' });
173
+ const abort = new AbortController();
174
+ res.on('close', () => abort.abort());
175
+ const emit = (e) => {
176
+ if (!res.writableEnded)
177
+ res.write(`${JSON.stringify(e)}\n`);
178
+ };
179
+ log(`${agent.name}${effort === 'medium' ? '' : effort === 'ultra' ? ' (Ultrarun)' : ` (${effort} effort)`}: ${prompt.slice(0, 80)}`);
180
+ try {
181
+ await runTask({ client, agent, prompt, folders, signal: abort.signal, emit, effort });
182
+ }
183
+ catch (err) {
184
+ if (!abort.signal.aborted)
185
+ emit({ type: 'error', message: describe(err) });
186
+ }
187
+ log(abort.signal.aborted ? `${agent.name}: stopped` : `${agent.name}: finished`);
188
+ return res.end();
189
+ }
190
+ send(res, 404, { error: 'not found' });
191
+ });
192
+ server.listen(opts.port, '127.0.0.1');
193
+ return server;
194
+ }
195
+ function describe(err) {
196
+ if (err instanceof Anthropic.AuthenticationError)
197
+ return 'Runner has no working Anthropic credentials. Set ANTHROPIC_API_KEY in the terminal where Runner runs, then restart it.';
198
+ if (err instanceof Anthropic.PermissionDeniedError)
199
+ return 'This Anthropic key is not allowed to use the model Runner asked for.';
200
+ if (err instanceof Anthropic.RateLimitError)
201
+ return 'Anthropic is rate-limiting this key. Try again in a minute.';
202
+ if (err instanceof Anthropic.APIConnectionError)
203
+ return 'Runner could not reach Anthropic. Check your internet connection.';
204
+ if (err instanceof Anthropic.APIError)
205
+ return `Anthropic returned an error (${String(err.status)}).`;
206
+ return err instanceof Error ? err.message : 'Something went wrong in Runner.';
207
+ }
@@ -0,0 +1,65 @@
1
+ export function painter(enabled) {
2
+ return enabled ? (code, text) => `\x1b[${code}m${text}\x1b[0m` : (_code, text) => text;
3
+ }
4
+ /** Colours as 256-colour codes: AgentPier orange, a calm green, a soft red, and dim grey. */
5
+ export const C = { orange: '38;5;209', amber: '38;5;215', green: '38;5;114', red: '38;5;203', dim: '2', bold: '1', white: '38;5;255' };
6
+ // "AGENTPIER" in a two-row block font.
7
+ const BANNER = [
8
+ '▄▀█ █▀▀ █▀▀ █▄ █ ▀█▀ █▀█ █ █▀▀ █▀█',
9
+ '█▀█ █▄█ ██▄ █ ▀█ █ █▀▀ █ ██▄ █▀▄',
10
+ ];
11
+ // Built from the escape character's code so the pattern holds no literal control character.
12
+ const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g');
13
+ export const stripAnsi = (s) => s.replace(ANSI, '');
14
+ const visible = (s) => stripAnsi(s).length;
15
+ export function banner(p, version) {
16
+ return [
17
+ '',
18
+ ` ${p(C.orange, BANNER[0] ?? '')}`,
19
+ ` ${p(C.amber, BANNER[1] ?? '')} ${p(C.dim, `runner v${version}`)}`,
20
+ '',
21
+ ].join('\n');
22
+ }
23
+ /** A rounded box around `lines`, padded to the widest one. */
24
+ export function box(p, lines) {
25
+ const width = Math.max(44, ...lines.map(visible));
26
+ const edge = (l, r) => ` ${p(C.dim, `${l}${'─'.repeat(width + 4)}${r}`)}`;
27
+ return [
28
+ edge('╭', '╮'),
29
+ ...lines.map((l) => ` ${p(C.dim, '│')} ${l}${' '.repeat(width - visible(l))} ${p(C.dim, '│')}`),
30
+ edge('╰', '╯'),
31
+ ].join('\n');
32
+ }
33
+ /** The status panel: where Runner listens, which plans can answer, and which folders agents see. */
34
+ export function statusPanel(p, opts) {
35
+ const label = (s) => p(C.dim, s.toUpperCase());
36
+ const rows = opts.plans.map((r) => r.ready
37
+ ? `${p(C.green, '✓')} ${p(C.bold, r.ai.padEnd(9))} ${r.cli.padEnd(12)} ${p(C.green, 'ready')}`
38
+ : `${p(C.red, '✗')} ${p(C.dim, r.ai.padEnd(9))} ${p(C.dim, r.cli.padEnd(12))} ${p(C.dim, r.install)}`);
39
+ const files = opts.folders.length
40
+ ? opts.folders.map((f) => `${p(C.green, '▸')} ${f.name} ${p(C.dim, `(${f.mode})`)}`)
41
+ : [p(C.dim, 'none shared · add one with --share <folder>')];
42
+ return box(p, [
43
+ `${p(C.green, '●')} ${p(C.bold, 'online')} ${p(C.dim, opts.url)}`,
44
+ '',
45
+ label('your plans · no api keys'),
46
+ ...rows,
47
+ '',
48
+ label('files agents can see'),
49
+ ...files,
50
+ ]);
51
+ }
52
+ export function nextStep(p) {
53
+ return [
54
+ '',
55
+ ` ${p(C.orange, '→')} Open AgentPier ${p(C.dim, '›')} Your AIs ${p(C.dim, '›')} ${p(C.bold, 'Connect this computer')}`,
56
+ ` and type the 6-letter code it shows.`,
57
+ '',
58
+ ].join('\n');
59
+ }
60
+ export const prompt = (p) => ` ${p(C.orange, '❯')} ${p(C.bold, 'pairing code')} ${p(C.dim, '›')} `;
61
+ /** One log line: dim time, a coloured marker by tone, then the message. */
62
+ export function logLine(p, time, tone, text) {
63
+ const mark = tone === 'ok' ? p(C.green, '✓') : tone === 'warn' ? p(C.red, '!') : p(C.orange, '•');
64
+ return ` ${p(C.dim, time)} ${mark} ${text}`;
65
+ }
@@ -0,0 +1,99 @@
1
+ // GitHub, as the edge functions use it: who a token belongs to, which repositories it can see,
2
+ // and a compact view of one repository (its file tree, its README, and files an agent asks to
3
+ // read). Plain code with the network passed in, so tests run against a local simulator.
4
+ const API = "https://api.github.com";
5
+ const LIMITS = { treeEntries: 400, readme: 6000, file: 12000, reads: 3 };
6
+ // Paths that are noise for an agent trying to understand a codebase.
7
+ const SKIP = /(^|\/)(node_modules|dist|build|\.git|\.next|vendor|coverage|\.turbo|\.cache)(\/|$)|\.(png|jpe?g|gif|webp|ico|mp4|webm|woff2?|ttf|lock|map|min\.js)$/i;
8
+ export const isRepoName = (v) => typeof v === "string" && /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/.test(v) && !v.includes("..");
9
+ const headers = (token) => ({
10
+ Authorization: `Bearer ${token}`,
11
+ Accept: "application/vnd.github+json",
12
+ "X-GitHub-Api-Version": "2022-11-28",
13
+ "User-Agent": "AgentPier",
14
+ });
15
+ /** Who a token belongs to, and what it may do. Never returns the token. */
16
+ export async function githubUser(token, fetcher) {
17
+ try {
18
+ const res = await fetcher(`${API}/user`, { headers: headers(token) });
19
+ if (!res.ok)
20
+ return { ok: false };
21
+ const body = await res.json();
22
+ if (typeof body.login !== "string")
23
+ return { ok: false };
24
+ return { ok: true, login: body.login, scopes: res.headers.get("x-oauth-scopes") ?? "" };
25
+ }
26
+ catch {
27
+ return { ok: false };
28
+ }
29
+ }
30
+ /** The repositories the token can see, most recently pushed first. */
31
+ export async function listRepos(token, fetcher) {
32
+ try {
33
+ const res = await fetcher(`${API}/user/repos?per_page=100&sort=pushed&affiliation=owner,collaborator,organization_member`, { headers: headers(token) });
34
+ if (!res.ok)
35
+ return null;
36
+ const body = await res.json();
37
+ if (!Array.isArray(body))
38
+ return null;
39
+ return body.flatMap((r) => typeof r.full_name === "string" && isRepoName(r.full_name)
40
+ ? [{ name: r.full_name, private: r.private === true, description: typeof r.description === "string" ? r.description.slice(0, 200) : "", pushedAt: typeof r.pushed_at === "string" ? r.pushed_at : "" }]
41
+ : []);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ /** A compact view of a repository: its default branch, file paths and README. */
48
+ export async function repoContext(token, repo, fetcher) {
49
+ if (!isRepoName(repo))
50
+ return null;
51
+ try {
52
+ const meta = await fetcher(`${API}/repos/${repo}`, { headers: headers(token) });
53
+ if (!meta.ok)
54
+ return null;
55
+ const { default_branch: branch } = await meta.json();
56
+ if (typeof branch !== "string")
57
+ return null;
58
+ const treeRes = await fetcher(`${API}/repos/${repo}/git/trees/${encodeURIComponent(branch)}?recursive=1`, { headers: headers(token) });
59
+ const treeBody = treeRes.ok ? await treeRes.json() : {};
60
+ const paths = (treeBody.tree ?? []).flatMap((e) => (e.type === "blob" && typeof e.path === "string" && !SKIP.test(e.path) ? [e.path] : []));
61
+ const readmeRes = await fetcher(`${API}/repos/${repo}/readme`, { headers: { ...headers(token), Accept: "application/vnd.github.raw+json" } });
62
+ const readme = readmeRes.ok ? (await readmeRes.text()).slice(0, LIMITS.readme) : "";
63
+ return { repo, branch, tree: paths.slice(0, LIMITS.treeEntries), truncated: paths.length > LIMITS.treeEntries || treeBody.truncated === true, readme };
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /** The repository as a section of an agent's instructions. */
70
+ export function describeRepo(ctx) {
71
+ return `The room is working on the GitHub repository ${ctx.repo} (branch ${ctx.branch}).
72
+
73
+ Its files${ctx.truncated ? " (the first " + ctx.tree.length + ")" : ""}:
74
+ ${ctx.tree.join("\n")}
75
+ ${ctx.readme ? `\nREADME:\n"""\n${ctx.readme}\n"""\n` : ""}
76
+ To read a file before you reply, answer with only <read>path/to/file</read> tags (up to ${LIMITS.reads}), using paths from the list above; you'll then get their contents and can reply properly. Don't ask to read files you've already been shown. You can't change the repository yet: describe the changes you'd make.`;
77
+ }
78
+ /** Paths an agent asked to read, cleaned: at most three, relative, inside the repo. */
79
+ export function parseReads(text) {
80
+ const paths = [...text.matchAll(/<read>\s*([^<\n]{1,300}?)\s*<\/read>/g)].map((m) => (m[1] ?? "").replace(/^\.\//, ""));
81
+ return [...new Set(paths.filter((p) => p && !p.includes("..") && !p.startsWith("/")))].slice(0, LIMITS.reads);
82
+ }
83
+ export const stripReads = (text) => text.replace(/<read>[^<]*<\/read>/g, "").trim();
84
+ /** One file's text from the default branch, trimmed to a size an agent can take in. */
85
+ export async function readFile(token, ctx, path, fetcher) {
86
+ if (!ctx.tree.includes(path))
87
+ return null;
88
+ try {
89
+ const url = `${API}/repos/${ctx.repo}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ctx.branch)}`;
90
+ const res = await fetcher(url, { headers: { ...headers(token), Accept: "application/vnd.github.raw+json" } });
91
+ if (!res.ok)
92
+ return null;
93
+ const text = await res.text();
94
+ return text.length > LIMITS.file ? `${text.slice(0, LIMITS.file)}\n… (cut off at ${LIMITS.file} characters)` : text;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }