ropetide-runner 0.0.0-stage → 0.3.5
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 +145 -2
- package/dist/apps/runner/src/agents.js +36 -0
- package/dist/apps/runner/src/browser.js +386 -0
- package/dist/apps/runner/src/browserProxy.js +120 -0
- package/dist/apps/runner/src/cli.js +449 -0
- package/dist/apps/runner/src/commands/redact.js +45 -0
- package/dist/apps/runner/src/commands/sandbox.js +61 -0
- package/dist/apps/runner/src/commands/shell.js +279 -0
- package/dist/apps/runner/src/extension.js +159 -0
- package/dist/apps/runner/src/files.js +163 -0
- package/dist/apps/runner/src/folderChoice.js +40 -0
- package/dist/apps/runner/src/main.js +351 -0
- package/dist/apps/runner/src/mcp/connectors.js +161 -0
- package/dist/apps/runner/src/pairCrypto.js +80 -0
- package/dist/apps/runner/src/planUsage.js +189 -0
- package/dist/apps/runner/src/power.js +11 -0
- package/dist/apps/runner/src/projects/access.js +337 -0
- package/dist/apps/runner/src/projects/http.js +74 -0
- package/dist/apps/runner/src/projects/prompt.js +19 -0
- package/dist/apps/runner/src/projects/rules.js +45 -0
- package/dist/apps/runner/src/projects/shares.js +192 -0
- package/dist/apps/runner/src/room.js +154 -0
- package/dist/apps/runner/src/run.js +182 -0
- package/dist/apps/runner/src/server.js +627 -0
- package/dist/apps/runner/src/skills.js +94 -0
- package/dist/apps/runner/src/tui.js +189 -0
- package/dist/apps/runner/src/video/analyse.js +95 -0
- package/dist/apps/runner/src/video/exec.js +32 -0
- package/dist/apps/runner/src/video/http.js +60 -0
- package/dist/apps/runner/src/video/probe.js +52 -0
- package/dist/apps/runner/src/video/render.js +322 -0
- package/dist/apps/runner/src/video/studio.js +329 -0
- package/dist/apps/runner/src/video/tools.js +24 -0
- package/dist/apps/runner/src/video.js +444 -0
- package/dist/supabase/functions/_shared/effort.js +16 -0
- package/dist/supabase/functions/_shared/folder-rules.js +129 -0
- package/dist/supabase/functions/_shared/github.js +319 -0
- package/dist/supabase/functions/_shared/localVideo.js +24 -0
- package/dist/supabase/functions/_shared/modelLimits.js +47 -0
- package/dist/supabase/functions/_shared/modelPrices.js +28 -0
- package/dist/supabase/functions/_shared/roles.js +18 -0
- package/dist/supabase/functions/_shared/room-command.js +70 -0
- package/dist/supabase/functions/_shared/roomBudget.js +60 -0
- package/dist/supabase/functions/_shared/video-plan.js +567 -0
- package/dist/supabase/functions/_shared/workspace.js +21 -0
- package/dist/supabase/functions/_shared/workspaceMeter.js +40 -0
- package/dist/supabase/functions/room-turn/context.js +154 -0
- package/dist/supabase/functions/room-turn/turn.js +750 -0
- package/package.json +36 -4
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The proxy every request from the agent browser goes through. A redirect, a WebSocket and a
|
|
3
|
+
* subresource each have to ask it for a connection, so the network rules are checked for all of
|
|
4
|
+
* them, and it connects only to the addresses that were checked. It listens on loopback, reads no
|
|
5
|
+
* more of a request than where it is going, and logs nothing.
|
|
6
|
+
*/
|
|
7
|
+
import { once } from 'node:events';
|
|
8
|
+
import http, {} from 'node:http';
|
|
9
|
+
import net, {} from 'node:net';
|
|
10
|
+
const CONNECT_MS = 10_000;
|
|
11
|
+
/** A connection to the first of `addresses` that answers, or null. */
|
|
12
|
+
async function dial(addresses, port) {
|
|
13
|
+
for (const host of addresses) {
|
|
14
|
+
const socket = net.connect({ host, port });
|
|
15
|
+
const timer = setTimeout(() => socket.destroy(new Error('timed out')), CONNECT_MS);
|
|
16
|
+
try {
|
|
17
|
+
await once(socket, 'connect');
|
|
18
|
+
return socket;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
socket.destroy();
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
clearTimeout(timer);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
const parse = (value) => { try {
|
|
30
|
+
return new URL(value);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
} };
|
|
35
|
+
/** Headers meant for the proxy itself, which the server being asked never sees. */
|
|
36
|
+
function forwarded(headers) {
|
|
37
|
+
const out = { ...headers };
|
|
38
|
+
delete out['proxy-connection'];
|
|
39
|
+
delete out['proxy-authorization'];
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
export async function startBrowserProxy(resolve) {
|
|
43
|
+
let own = 0;
|
|
44
|
+
const sockets = new Set();
|
|
45
|
+
const track = (socket) => {
|
|
46
|
+
sockets.add(socket);
|
|
47
|
+
socket.on('close', () => sockets.delete(socket));
|
|
48
|
+
// A connection that breaks is closed; it is not Runner's failure.
|
|
49
|
+
socket.on('error', () => socket.destroy());
|
|
50
|
+
};
|
|
51
|
+
/** A connection for `url`, or the status to answer with instead. */
|
|
52
|
+
async function connect(url) {
|
|
53
|
+
const port = Number(url.port || (url.protocol === 'https:' ? 443 : 80));
|
|
54
|
+
const addresses = await resolve(url.href).catch(() => null);
|
|
55
|
+
// The proxy is never a destination of its own.
|
|
56
|
+
if (!addresses || (port === own && addresses.some((a) => a === '::1' || a.startsWith('127.') || a.startsWith('::ffff:7f'))))
|
|
57
|
+
return 403;
|
|
58
|
+
const socket = await dial(addresses, port);
|
|
59
|
+
if (!socket)
|
|
60
|
+
return 502;
|
|
61
|
+
track(socket);
|
|
62
|
+
return socket;
|
|
63
|
+
}
|
|
64
|
+
// Plain http: the browser sends the whole address as the request target.
|
|
65
|
+
async function forward(req, res) {
|
|
66
|
+
const url = parse(req.url ?? '');
|
|
67
|
+
const socket = url?.protocol === 'http:' ? await connect(url) : 403;
|
|
68
|
+
if (!url || typeof socket === 'number') {
|
|
69
|
+
req.resume();
|
|
70
|
+
res.writeHead(typeof socket === 'number' ? socket : 403, { 'content-type': 'text/plain', connection: 'close' });
|
|
71
|
+
return res.end('Blocked or unreachable.');
|
|
72
|
+
}
|
|
73
|
+
const upstream = http.request({ createConnection: () => socket, method: req.method, path: `${url.pathname}${url.search}`, headers: { ...forwarded(req.headers), host: url.host, connection: 'close' } });
|
|
74
|
+
upstream.on('response', (answer) => {
|
|
75
|
+
res.writeHead(answer.statusCode ?? 502, answer.rawHeaders);
|
|
76
|
+
answer.on('error', () => res.destroy());
|
|
77
|
+
answer.pipe(res);
|
|
78
|
+
});
|
|
79
|
+
upstream.on('error', () => { if (res.headersSent)
|
|
80
|
+
res.destroy();
|
|
81
|
+
else {
|
|
82
|
+
res.writeHead(502, { connection: 'close' });
|
|
83
|
+
res.end();
|
|
84
|
+
} });
|
|
85
|
+
res.on('close', () => { upstream.destroy(); socket.destroy(); });
|
|
86
|
+
req.pipe(upstream);
|
|
87
|
+
}
|
|
88
|
+
// Everything else (https, WebSockets) asks for a tunnel to a host and port.
|
|
89
|
+
async function tunnel(req, client, head) {
|
|
90
|
+
const authority = /^(\[[0-9a-fA-F:.]+\]|[^\s/:@?#[\]]+):(\d{1,5})$/.exec(req.url ?? '');
|
|
91
|
+
const url = authority ? parse(`https://${authority[1]}:${authority[2]}/`) : null;
|
|
92
|
+
const socket = url ? await connect(url) : 403;
|
|
93
|
+
if (typeof socket === 'number')
|
|
94
|
+
return client.end(`HTTP/1.1 ${socket} ${socket === 403 ? 'Forbidden' : 'Bad Gateway'}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
95
|
+
if (client.destroyed)
|
|
96
|
+
return socket.destroy();
|
|
97
|
+
client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
98
|
+
if (head.length)
|
|
99
|
+
socket.write(head);
|
|
100
|
+
client.on('close', () => socket.destroy());
|
|
101
|
+
socket.on('close', () => client.destroy());
|
|
102
|
+
socket.pipe(client);
|
|
103
|
+
client.pipe(socket);
|
|
104
|
+
}
|
|
105
|
+
const server = http.createServer((req, res) => { forward(req, res).catch(() => res.destroy()); });
|
|
106
|
+
server.on('connection', track);
|
|
107
|
+
server.on('connect', (req, client, head) => { tunnel(req, client, head).catch(() => client.destroy()); });
|
|
108
|
+
server.listen(0, '127.0.0.1');
|
|
109
|
+
await once(server, 'listening');
|
|
110
|
+
own = server.address().port;
|
|
111
|
+
return {
|
|
112
|
+
server: `http://127.0.0.1:${own}`,
|
|
113
|
+
async close() {
|
|
114
|
+
const closed = new Promise((done) => server.close(() => done()));
|
|
115
|
+
for (const socket of sockets)
|
|
116
|
+
socket.destroy();
|
|
117
|
+
await closed;
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
import { readUsage } from "../../../supabase/functions/room-turn/turn.js";
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { rateLimitsIn, windowsFromQuota } from "./planUsage.js";
|
|
7
|
+
export const CLI_BIN = { claude: 'claude', chatgpt: 'codex', antigravity: 'agy' };
|
|
8
|
+
/**
|
|
9
|
+
* The command for one turn: the system prompt and the thread so far, answered by `model` at
|
|
10
|
+
* `effort` (Claude Code's --effort, Codex's model_reasoning_effort, Antigravity CLI's --effort).
|
|
11
|
+
* `images` are pictures in the working folder to show the model: Codex takes them with the prompt,
|
|
12
|
+
* while Claude Code and Antigravity CLI open them with their own file tools.
|
|
13
|
+
*/
|
|
14
|
+
export function cliCommand(provider, model, system, prompt, effort, images = []) {
|
|
15
|
+
switch (provider) {
|
|
16
|
+
case 'claude':
|
|
17
|
+
return {
|
|
18
|
+
bin: CLI_BIN.claude,
|
|
19
|
+
// An empty model runs on the plan's default. stream-json (which needs --verbose) is the only
|
|
20
|
+
// output that carries each tool call and the plan's usage windows. Only read-only tools and
|
|
21
|
+
// web search are on; "don't ask" mode refuses anything outside the working folder, and only
|
|
22
|
+
// project settings load (the temporary folder has none), so the person's own allow rules
|
|
23
|
+
// can't widen that.
|
|
24
|
+
args: ['-p', '--output-format', 'stream-json', '--verbose', ...(model ? ['--model', model] : []), ...(effort ? ['--effort', effort] : []), '--system-prompt', system, '--tools', 'Read,Glob,Grep,WebSearch', '--allowedTools', 'WebSearch', '--permission-mode', 'dontAsk', '--setting-sources', 'project', '--no-session-persistence', '--strict-mcp-config'],
|
|
25
|
+
stdin: prompt,
|
|
26
|
+
...(effort ? { effort } : {}),
|
|
27
|
+
};
|
|
28
|
+
case 'chatgpt':
|
|
29
|
+
// Codex has no system-prompt flag, so the room's instructions lead the prompt. An empty model
|
|
30
|
+
// runs on Codex's own configured default.
|
|
31
|
+
return {
|
|
32
|
+
bin: CLI_BIN.chatgpt,
|
|
33
|
+
args: ['exec', '--json', ...(model ? ['--model', model] : []), ...(effort ? ['-c', `model_reasoning_effort="${effort}"`] : []), ...images.map((p) => `--image=${p}`), '--disable', 'shell_tool', '--disable', 'unified_exec', '--sandbox', 'read-only', '--ephemeral', '--skip-git-repo-check', '--color', 'never', '-'],
|
|
34
|
+
stdin: `${system}\n\n${prompt}`,
|
|
35
|
+
};
|
|
36
|
+
case 'antigravity':
|
|
37
|
+
return {
|
|
38
|
+
bin: CLI_BIN.antigravity,
|
|
39
|
+
args: [
|
|
40
|
+
'--output-format', 'json',
|
|
41
|
+
'--sandbox',
|
|
42
|
+
'--disable-slash-commands',
|
|
43
|
+
...(model ? ['--model', model] : []),
|
|
44
|
+
...(effort ? ['--effort', effort] : []),
|
|
45
|
+
'--print', `${system}\n\n${prompt}`,
|
|
46
|
+
],
|
|
47
|
+
stdin: '',
|
|
48
|
+
};
|
|
49
|
+
default: {
|
|
50
|
+
const never = provider;
|
|
51
|
+
throw new Error(`unknown provider ${String(never)}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Keys that would make a CLI bill an API account instead of the plan it is signed in with. */
|
|
56
|
+
const API_KEY_VARS = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY'];
|
|
57
|
+
export function cliEnv(env) {
|
|
58
|
+
const out = {};
|
|
59
|
+
for (const [k, v] of Object.entries(env))
|
|
60
|
+
if (!API_KEY_VARS.includes(k))
|
|
61
|
+
out[k] = v;
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
/** The reply in a CLI's output. Errors are summarised, never echoed, since they can carry account details. */
|
|
65
|
+
export function parseCliOutput(provider, stdout) {
|
|
66
|
+
if (provider === 'claude')
|
|
67
|
+
return parseClaudeStream(stdout);
|
|
68
|
+
if (provider === 'chatgpt')
|
|
69
|
+
return parseCodexOutput(stdout);
|
|
70
|
+
return parseGeminiOutput(stdout);
|
|
71
|
+
}
|
|
72
|
+
const STEP_MAX = 12;
|
|
73
|
+
const obj = (v) => (v && typeof v === 'object' ? v : null);
|
|
74
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
75
|
+
/**
|
|
76
|
+
* Codex `--json` is JSONL: the reply is the last `agent_message` text, and `rate_limits` (when
|
|
77
|
+
* the CLI actually included them) become plan windows. Plain text is still accepted so an older
|
|
78
|
+
* Codex without `--json` keeps working.
|
|
79
|
+
*/
|
|
80
|
+
function parseCodexOutput(stdout) {
|
|
81
|
+
const trimmed = stdout.trim();
|
|
82
|
+
if (!trimmed)
|
|
83
|
+
return { ok: false, reason: 'Codex sent an empty reply.' };
|
|
84
|
+
const lines = trimmed.split('\n').filter((l) => l.trim().startsWith('{'));
|
|
85
|
+
if (!lines.length)
|
|
86
|
+
return { ok: true, text: trimmed };
|
|
87
|
+
let text = '';
|
|
88
|
+
let error = '';
|
|
89
|
+
let plan = [];
|
|
90
|
+
let tokens = 0;
|
|
91
|
+
for (const line of lines) {
|
|
92
|
+
let data;
|
|
93
|
+
try {
|
|
94
|
+
data = obj(JSON.parse(line));
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (!data)
|
|
100
|
+
continue;
|
|
101
|
+
const found = rateLimitsIn(data);
|
|
102
|
+
if (found.length)
|
|
103
|
+
plan = found;
|
|
104
|
+
const item = obj(data.item);
|
|
105
|
+
const payload = obj(data.payload);
|
|
106
|
+
const message = item ?? payload ?? data;
|
|
107
|
+
const kind = str(message.type ?? data.type);
|
|
108
|
+
const body = str(message.text) || str(obj(message.content)?.text);
|
|
109
|
+
if ((kind === 'agent_message' || kind === 'item.completed' || str(item?.type) === 'agent_message') && body)
|
|
110
|
+
text = body;
|
|
111
|
+
if (kind === 'error' || data.type === 'error' || data.type === 'turn.failed') {
|
|
112
|
+
const err = obj(data.error) ?? obj(message.error) ?? data;
|
|
113
|
+
error = str(err.message) || str(err.error) || error;
|
|
114
|
+
}
|
|
115
|
+
const usage = obj(data.usage) ?? obj(obj(data.turn)?.usage);
|
|
116
|
+
if (usage) {
|
|
117
|
+
const n = (k) => { const v = usage[k]; return typeof v === 'number' && v > 0 ? v : 0; };
|
|
118
|
+
const sum = n('input_tokens') + n('output_tokens') + n('cached_input_tokens');
|
|
119
|
+
if (sum)
|
|
120
|
+
tokens = sum;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const used = { ...(plan.length ? { plan } : {}), ...(tokens ? { spend: { tokens, costUsd: 0 } } : {}) };
|
|
124
|
+
if (error)
|
|
125
|
+
return { ok: false, reason: `Codex: ${cliError(error)}`, ...used };
|
|
126
|
+
if (text.trim())
|
|
127
|
+
return { ok: true, text: text.trim(), ...used };
|
|
128
|
+
// JSONL with no reply text: don't dump the events as the room message.
|
|
129
|
+
return { ok: false, reason: 'Codex sent a reply Runner could not read.', ...used };
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Antigravity CLI `--output-format json`: `{ response, usage, error }`. Quota fields are parsed when
|
|
133
|
+
* present; headless stats report tokens, not plan remaining.
|
|
134
|
+
*/
|
|
135
|
+
function parseGeminiOutput(stdout) {
|
|
136
|
+
const trimmed = stdout.trim();
|
|
137
|
+
if (!trimmed)
|
|
138
|
+
return { ok: false, reason: 'Antigravity CLI sent an empty reply.' };
|
|
139
|
+
const jsonStart = trimmed.indexOf('{');
|
|
140
|
+
const candidate = jsonStart >= 0 ? trimmed.slice(jsonStart) : '';
|
|
141
|
+
if (!candidate)
|
|
142
|
+
return { ok: true, text: trimmed };
|
|
143
|
+
let data;
|
|
144
|
+
try {
|
|
145
|
+
data = obj(JSON.parse(candidate));
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return { ok: true, text: trimmed };
|
|
149
|
+
}
|
|
150
|
+
if (!data)
|
|
151
|
+
return { ok: true, text: trimmed };
|
|
152
|
+
const plan = windowsFromQuota(data);
|
|
153
|
+
const usage = obj(data.usage);
|
|
154
|
+
const totalTokens = typeof usage?.total_tokens === 'number' && usage.total_tokens > 0 ? usage.total_tokens : 0;
|
|
155
|
+
const used = { ...(plan.length ? { plan } : {}), ...(totalTokens ? { spend: { tokens: totalTokens, costUsd: 0 } } : {}) };
|
|
156
|
+
const errMsg = typeof data.error === 'string' ? data.error : str(obj(data.error)?.message);
|
|
157
|
+
if (errMsg)
|
|
158
|
+
return { ok: false, reason: `Antigravity CLI: ${cliError(errMsg)}`, ...used };
|
|
159
|
+
const text = str(data.response).trim();
|
|
160
|
+
if (text)
|
|
161
|
+
return { ok: true, text, ...used };
|
|
162
|
+
return { ok: false, reason: 'Antigravity CLI sent an empty reply.', ...used };
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Claude Code's stream-json: one JSON object a line. Tool calls come as `tool_use` blocks in
|
|
166
|
+
* `assistant` lines, their outcomes as `tool_result` blocks in `user` lines; a call that failed or
|
|
167
|
+
* was refused didn't happen, so it isn't a step. The reply is the `result` line.
|
|
168
|
+
*/
|
|
169
|
+
function parseClaudeStream(stdout) {
|
|
170
|
+
const calls = new Map();
|
|
171
|
+
const results = new Map();
|
|
172
|
+
const failed = new Set();
|
|
173
|
+
let plan;
|
|
174
|
+
let result = null;
|
|
175
|
+
for (const line of stdout.split('\n')) {
|
|
176
|
+
if (!line.trim().startsWith('{'))
|
|
177
|
+
continue;
|
|
178
|
+
let data;
|
|
179
|
+
try {
|
|
180
|
+
data = obj(JSON.parse(line));
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (!data)
|
|
186
|
+
continue;
|
|
187
|
+
if (data.type === 'result')
|
|
188
|
+
result = data;
|
|
189
|
+
else if (data.type === 'rate_limit_event') {
|
|
190
|
+
const w = planWindows(data.rate_limit_info);
|
|
191
|
+
if (w.length)
|
|
192
|
+
plan = w;
|
|
193
|
+
}
|
|
194
|
+
else if (data.type === 'assistant' || data.type === 'user') {
|
|
195
|
+
const content = obj(data.message)?.content;
|
|
196
|
+
if (!Array.isArray(content))
|
|
197
|
+
continue;
|
|
198
|
+
for (const block of content.map(obj)) {
|
|
199
|
+
if (block?.type === 'tool_use') {
|
|
200
|
+
const step = toolStep(str(block.name), obj(block.input));
|
|
201
|
+
if (step)
|
|
202
|
+
calls.set(str(block.id), { tool: str(block.name), step });
|
|
203
|
+
}
|
|
204
|
+
if (block?.type === 'tool_result') {
|
|
205
|
+
if (block.is_error === true)
|
|
206
|
+
failed.add(str(block.tool_use_id));
|
|
207
|
+
else
|
|
208
|
+
results.set(str(block.tool_use_id), resultText(block.content));
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const used = plan ? { plan } : {};
|
|
214
|
+
if (!result || typeof result.result !== 'string')
|
|
215
|
+
return { ok: false, reason: 'Claude Code sent a reply Runner could not read.', ...used };
|
|
216
|
+
// A failed call can still have used tokens, so its spend is kept too.
|
|
217
|
+
const spend = claudeSpend(result);
|
|
218
|
+
if (spend)
|
|
219
|
+
Object.assign(used, { spend });
|
|
220
|
+
if (result.is_error === true)
|
|
221
|
+
return { ok: false, reason: `Claude Code: ${cliError(result.result) || 'could not answer. Check that `claude` is signed in.'}`, ...used };
|
|
222
|
+
const text = result.result.trim();
|
|
223
|
+
if (!text)
|
|
224
|
+
return { ok: false, reason: 'Claude Code sent an empty reply.', ...used };
|
|
225
|
+
const steps = [...calls].filter(([id]) => !failed.has(id)).map(([id, { tool, step }]) => withResult(tool, step, results.get(id))).slice(0, STEP_MAX);
|
|
226
|
+
return { ok: true, text, ...used, ...(steps.length ? { steps } : {}) };
|
|
227
|
+
}
|
|
228
|
+
/** A path inside the turn's temporary folder, as the room knows it. */
|
|
229
|
+
const roomPath = (p) => p.replace(/^.*\/ropetide-turn-[^/]+\//, '');
|
|
230
|
+
const short = (s) => (s.length > 120 ? `${s.slice(0, 119)}…` : s);
|
|
231
|
+
function toolStep(name, input) {
|
|
232
|
+
if (!input)
|
|
233
|
+
return null;
|
|
234
|
+
switch (name) {
|
|
235
|
+
case 'Read': {
|
|
236
|
+
const p = roomPath(str(input.file_path));
|
|
237
|
+
return p ? { verb: 'Read', target: short(p), code: true } : null;
|
|
238
|
+
}
|
|
239
|
+
case 'Glob': {
|
|
240
|
+
const p = str(input.pattern);
|
|
241
|
+
return p ? { verb: 'Explored', target: short(p), code: true } : null;
|
|
242
|
+
}
|
|
243
|
+
case 'Grep': {
|
|
244
|
+
const p = str(input.pattern);
|
|
245
|
+
return p ? { verb: 'Searched', target: short(p), code: true } : null;
|
|
246
|
+
}
|
|
247
|
+
case 'WebSearch': {
|
|
248
|
+
const q = str(input.query);
|
|
249
|
+
return q ? { verb: 'Searched', target: short(`the web for “${q}”`) } : null;
|
|
250
|
+
}
|
|
251
|
+
default: return null;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/** A tool result's text: a plain string, or the text parts of a list of content blocks. */
|
|
255
|
+
function resultText(content) {
|
|
256
|
+
if (typeof content === 'string')
|
|
257
|
+
return content;
|
|
258
|
+
if (!Array.isArray(content))
|
|
259
|
+
return '';
|
|
260
|
+
return content.map((c) => { const o = obj(c); return o?.type === 'text' ? str(o.text) : ''; }).join('\n');
|
|
261
|
+
}
|
|
262
|
+
const DETAIL_LINES = 30;
|
|
263
|
+
const DETAIL_MAX = 2000;
|
|
264
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
265
|
+
/** The first lines of a result for the room to open, with temporary-folder paths and key-like strings taken out. */
|
|
266
|
+
const detailOf = (lines) => {
|
|
267
|
+
// A found web address stays whole (long article slugs look like keys); every other line loses key-like runs. Each line is capped.
|
|
268
|
+
const shown = lines.slice(0, DETAIL_LINES).map((l) => { const line = roomPath(l); return (/^https?:\/\/\S+$/.test(line) ? line : line.replace(KEY_LIKE, '…')).slice(0, LINE_MAX); }).join('\n');
|
|
269
|
+
const more = lines.length > DETAIL_LINES ? `\n${plural(lines.length - DETAIL_LINES, 'more line')}` : '';
|
|
270
|
+
return (shown + more).slice(0, DETAIL_MAX);
|
|
271
|
+
};
|
|
272
|
+
/**
|
|
273
|
+
* What a step found, from its tool's result as Claude Code returned it. Only what the result
|
|
274
|
+
* itself shows: a read's line count, the files a pattern matched, the lines a search found, the
|
|
275
|
+
* sites a web search's results link to. An empty or unrecognised result adds nothing.
|
|
276
|
+
*/
|
|
277
|
+
function withResult(tool, step, raw) {
|
|
278
|
+
const text = (raw ?? '').trim();
|
|
279
|
+
if (!text)
|
|
280
|
+
return step;
|
|
281
|
+
const lines = text.split('\n').filter((l) => l.trim());
|
|
282
|
+
switch (tool) {
|
|
283
|
+
case 'Read': return { ...step, result: plural(lines.length, 'line') };
|
|
284
|
+
case 'Glob':
|
|
285
|
+
case 'Grep': {
|
|
286
|
+
if (/^no (files|matches) found/i.test(text))
|
|
287
|
+
return { ...step, result: 'No matches' };
|
|
288
|
+
// A "Found 3 files" line heading the list is a count, not a match.
|
|
289
|
+
if (/^found \d+ /i.test(lines[0] ?? ''))
|
|
290
|
+
lines.shift();
|
|
291
|
+
const noun = tool === 'Glob' || lines.every((l) => !/:\d+:/.test(l)) ? 'file' : 'matching line';
|
|
292
|
+
return { ...step, result: plural(lines.length, noun), detail: detailOf(lines) };
|
|
293
|
+
}
|
|
294
|
+
case 'WebSearch': {
|
|
295
|
+
const urls = [...new Set(text.match(/https?:\/\/[^\s"'<>)\]]+/g) ?? [])];
|
|
296
|
+
const hosts = [...new Set(urls.flatMap((u) => { try {
|
|
297
|
+
return [new URL(u).hostname.replace(/^www\./, '')];
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return [];
|
|
301
|
+
} }))];
|
|
302
|
+
return hosts.length ? { ...step, result: short(hosts.slice(0, 4).join(', ') + (hosts.length > 4 ? ` and ${hosts.length - 4} more` : '')), detail: detailOf(urls) } : step;
|
|
303
|
+
}
|
|
304
|
+
default: return step;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* The usage windows in a `rate_limit_event`: each of `unifiedWindows` that reports a `utilization`
|
|
309
|
+
* (a share, 0 to 1) and a `resetsAt` (Unix seconds). A window with only a reset time says nothing
|
|
310
|
+
* about what is left, so it is left out.
|
|
311
|
+
*/
|
|
312
|
+
function planWindows(v) {
|
|
313
|
+
const windows = obj(obj(v)?.unifiedWindows);
|
|
314
|
+
if (!windows)
|
|
315
|
+
return [];
|
|
316
|
+
return Object.entries(windows).flatMap(([kind, w]) => {
|
|
317
|
+
const o = obj(w);
|
|
318
|
+
const used = o?.utilization;
|
|
319
|
+
const resetsAt = o?.resetsAt;
|
|
320
|
+
return typeof used === 'number' && Number.isFinite(used) && typeof resetsAt === 'number' && resetsAt > 0
|
|
321
|
+
? [{ kind, used: Math.max(0, Math.min(1, used)), resetsAt: resetsAt * 1000 }]
|
|
322
|
+
: [];
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
function claudeSpend(data) {
|
|
326
|
+
const usage = obj(data.usage);
|
|
327
|
+
if (!usage)
|
|
328
|
+
return null;
|
|
329
|
+
const count = (k) => { const n = usage[k]; return typeof n === 'number' && n > 0 ? n : 0; };
|
|
330
|
+
const tokens = count('input_tokens') + count('cache_read_input_tokens') + count('cache_creation_input_tokens') + count('output_tokens');
|
|
331
|
+
const cost = typeof data.total_cost_usd === 'number' && data.total_cost_usd > 0 ? data.total_cost_usd : 0;
|
|
332
|
+
return { tokens, costUsd: cost };
|
|
333
|
+
}
|
|
334
|
+
/** Long runs of letters and digits, as keys and tokens look; replaced before any CLI text is shown. */
|
|
335
|
+
/** The longest one line of a step's detail may be. */
|
|
336
|
+
const LINE_MAX = 200;
|
|
337
|
+
const KEY_LIKE = /\b(?:sk-[\w-]{8,}|[A-Za-z0-9_-]{32,})\b/g;
|
|
338
|
+
/**
|
|
339
|
+
* What a CLI said went wrong, short enough to show in the room: the last line that looks like an
|
|
340
|
+
* error (or the last line), with key-like strings removed and JSON error messages unwrapped.
|
|
341
|
+
*/
|
|
342
|
+
export function cliError(text) {
|
|
343
|
+
const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
|
|
344
|
+
const line = [...lines].reverse().find((l) => /error|refus|limit|not supported|denied|login|sign in|expired|quota/i.test(l)) ?? lines.at(-1) ?? '';
|
|
345
|
+
const message = line.match(/"message"\s*:\s*"((?:[^"\\]|\\.)*)"/)?.[1] ?? line.replace(/^ERROR:\s*/, '');
|
|
346
|
+
return message.replace(KEY_LIKE, '…').slice(0, 240);
|
|
347
|
+
}
|
|
348
|
+
/** Files each CLI reads as its own instructions when they sit in its working folder. */
|
|
349
|
+
const CLI_INSTRUCTIONS = new Set(['claude.md', 'claude.local.md', 'agents.md', 'gemini.md']);
|
|
350
|
+
/**
|
|
351
|
+
* Where a room file goes in the working folder, or null when it must not be written there: a path
|
|
352
|
+
* that would leave the folder, a dot-folder or dotfile (where the CLIs keep settings and hooks that
|
|
353
|
+
* could run commands), or a file a CLI would follow as instructions. Room files are written by
|
|
354
|
+
* other people, so they stay material to read.
|
|
355
|
+
*/
|
|
356
|
+
export function fileIn(cwd, p) {
|
|
357
|
+
const parts = p.split(/[\\/]/);
|
|
358
|
+
if (!p || path.isAbsolute(p) || parts.some((s) => s.startsWith('.')) || CLI_INSTRUCTIONS.has((parts.at(-1) ?? '').toLowerCase()))
|
|
359
|
+
return null;
|
|
360
|
+
const full = path.resolve(cwd, p);
|
|
361
|
+
return full.startsWith(cwd + path.sep) ? full : null;
|
|
362
|
+
}
|
|
363
|
+
/** Runs one CLI in a temporary folder holding `cmd.files`, with the prompt on stdin, and stops it after `timeoutMs`. */
|
|
364
|
+
export const runCli = async (cmd, { timeoutMs }) => {
|
|
365
|
+
const cwd = await mkdtemp(path.join(os.tmpdir(), 'ropetide-turn-'));
|
|
366
|
+
try {
|
|
367
|
+
for (const f of cmd.files ?? []) {
|
|
368
|
+
const full = fileIn(cwd, f.path);
|
|
369
|
+
if (!full)
|
|
370
|
+
continue;
|
|
371
|
+
await mkdir(path.dirname(full), { recursive: true });
|
|
372
|
+
await writeFile(full, 'bytes' in f ? f.bytes : f.text, { mode: 0o600 });
|
|
373
|
+
}
|
|
374
|
+
const env = cliEnv(process.env);
|
|
375
|
+
// Claude's environment setting outranks --effort; keep the room's explicit selection.
|
|
376
|
+
if (cmd.effort)
|
|
377
|
+
env.CLAUDE_CODE_EFFORT_LEVEL = cmd.effort;
|
|
378
|
+
return await new Promise((resolve) => {
|
|
379
|
+
let stdout = '';
|
|
380
|
+
let stderr = '';
|
|
381
|
+
let settled = false;
|
|
382
|
+
const done = (r) => { if (!settled) {
|
|
383
|
+
settled = true;
|
|
384
|
+
clearTimeout(timer);
|
|
385
|
+
resolve(r);
|
|
386
|
+
} };
|
|
387
|
+
const child = spawn(cmd.bin, cmd.args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
388
|
+
const timer = setTimeout(() => { child.kill('SIGKILL'); done({ ok: false, code: 'timeout' }); }, timeoutMs);
|
|
389
|
+
child.stdout.setEncoding('utf8');
|
|
390
|
+
child.stdout.on('data', (d) => { if (stdout.length < 1_000_000)
|
|
391
|
+
stdout += d; });
|
|
392
|
+
child.stderr.setEncoding('utf8');
|
|
393
|
+
// Only the end matters: that is where CLIs print the error they stopped on.
|
|
394
|
+
child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-8000); });
|
|
395
|
+
child.on('error', (err) => done({ ok: false, code: err.code === 'ENOENT' ? 'missing' : 'failed' }));
|
|
396
|
+
child.on('close', (code) => done(code === 0 ? { ok: true, stdout } : { ok: false, code: 'failed', detail: cliError(stderr || stdout), stdout }));
|
|
397
|
+
child.stdin.on('error', () => { });
|
|
398
|
+
child.stdin.end(cmd.stdin);
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
finally {
|
|
402
|
+
await rm(cwd, { recursive: true, force: true });
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
/** Each CLI's version as it reports it, or null when it isn't installed. */
|
|
406
|
+
export async function cliVersion(p, run = runCli) {
|
|
407
|
+
const r = await run({ bin: CLI_BIN[p], args: ['--version'], stdin: '' }, { timeoutMs: 8000 });
|
|
408
|
+
return r.ok ? r.stdout.trim() : null;
|
|
409
|
+
}
|
|
410
|
+
/** Which CLIs are installed here: each one answers `--version` within a few seconds. */
|
|
411
|
+
export async function detectClis(run = runCli) {
|
|
412
|
+
const check = async (p) => (await run({ bin: CLI_BIN[p], args: ['--version'], stdin: '' }, { timeoutMs: 8000 })).ok;
|
|
413
|
+
const [claude, chatgpt, antigravity] = await Promise.all([check('claude'), check('chatgpt'), check('antigravity')]);
|
|
414
|
+
return { claude, chatgpt, antigravity };
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* The models Codex may use with the account it is signed in with, from the list Codex itself
|
|
418
|
+
* keeps in ~/.codex/models_cache.json (shown models only, in Codex's order). A ChatGPT plan allows
|
|
419
|
+
* fewer models than the API, so a room's choice can be refused; this is what to fall back to.
|
|
420
|
+
*/
|
|
421
|
+
export async function codexPlanModels(home = path.join(os.homedir(), '.codex')) {
|
|
422
|
+
try {
|
|
423
|
+
const data = JSON.parse(await readFile(path.join(home, 'models_cache.json'), 'utf8'));
|
|
424
|
+
const models = data && typeof data === 'object' && 'models' in data && Array.isArray(data.models) ? data.models : [];
|
|
425
|
+
return models
|
|
426
|
+
.filter((m) => !!m && typeof m === 'object' && 'slug' in m && typeof m.slug === 'string')
|
|
427
|
+
.filter((m) => m.visibility !== 'hide')
|
|
428
|
+
.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0))
|
|
429
|
+
.map((m) => m.slug);
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
return [];
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
/** Provider counts for accounting, separate from the existing CLI reply contract. */
|
|
436
|
+
export function readCliUsage(provider, stdout) {
|
|
437
|
+
if (provider !== 'claude')
|
|
438
|
+
return null;
|
|
439
|
+
let usage = null;
|
|
440
|
+
for (const line of stdout.split('\n')) {
|
|
441
|
+
try {
|
|
442
|
+
const data = obj(JSON.parse(line));
|
|
443
|
+
if (data?.type === 'result')
|
|
444
|
+
usage = readUsage('claude', data);
|
|
445
|
+
}
|
|
446
|
+
catch { /* text-only output */ }
|
|
447
|
+
}
|
|
448
|
+
return usage;
|
|
449
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Takes keys and passwords out of a command's output before it leaves this computer for a room's
|
|
3
|
+
* AI. A second line of defence: the sandbox already refuses files that usually hold them. It knows
|
|
4
|
+
* common shapes only, so it can't promise to catch every secret.
|
|
5
|
+
*/
|
|
6
|
+
const GONE = '[removed]';
|
|
7
|
+
/** A private key block, whether or not its end was printed. */
|
|
8
|
+
const PRIVATE_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----(?:[\s\S]*?-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----|[\s\S]*$)/g;
|
|
9
|
+
/** Keys recognisable by how they start. */
|
|
10
|
+
const KNOWN = [
|
|
11
|
+
/\bsk-[A-Za-z0-9_-]{16,}/g,
|
|
12
|
+
/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g,
|
|
13
|
+
/\bsb_secret_[A-Za-z0-9_-]{10,}/g,
|
|
14
|
+
/\bgh[pousr]_[A-Za-z0-9]{16,}/g,
|
|
15
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
16
|
+
/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
|
|
17
|
+
/\bAIza[0-9A-Za-z_-]{30,}/g,
|
|
18
|
+
/\bya29\.[0-9A-Za-z_-]{20,}/g,
|
|
19
|
+
/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
|
|
20
|
+
/\bfigd_[A-Za-z0-9_-]{10,}/g,
|
|
21
|
+
/\bnpm_[A-Za-z0-9]{30,}/g,
|
|
22
|
+
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{5,}/g,
|
|
23
|
+
];
|
|
24
|
+
const AUTHORIZATION = /\b(Bearer|Basic)[ \t]+[A-Za-z0-9._~+/=-]{16,}/g;
|
|
25
|
+
const URL_LOGIN = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s:@'"]*:[^/\s@'"]+@/gi;
|
|
26
|
+
const SECRET_NAME = '[A-Za-z0-9_.-]*(?:secret|passw(?:or)?d|api[_-]?key|private[_-]?key|access[_-]?key|token)[A-Za-z0-9_.-]*';
|
|
27
|
+
/** SOME_TOKEN=value, as environment files and shells write it. */
|
|
28
|
+
const ENV_STYLE = /\b([A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|API_?KEY|PRIVATE_KEY|ACCESS_KEY|TOKEN)[A-Z0-9_]*=)(["']?)[^\s"';]{6,}/g;
|
|
29
|
+
/** name: value or "name": "value", when the value mixes letters and digits as keys do. */
|
|
30
|
+
const ASSIGNED = new RegExp(`(${SECRET_NAME}["']?[ \\t]*[:=][ \\t]*["']?)(?=[^\\s"',;]*[A-Za-z])(?=[^\\s"',;]*[0-9])[^\\s"',;()]{8,}`, 'gi');
|
|
31
|
+
/** Whether text holds a private key or something that starts the way a well-known key does. */
|
|
32
|
+
export function holdsKnownKey(text) {
|
|
33
|
+
// `search` starts at the beginning every time, whatever the pattern's flags.
|
|
34
|
+
return [PRIVATE_KEY, ...KNOWN].some((pattern) => text.search(pattern) >= 0);
|
|
35
|
+
}
|
|
36
|
+
export function redactOutput(text) {
|
|
37
|
+
let out = text.replace(PRIVATE_KEY, '[private key removed]');
|
|
38
|
+
for (const pattern of KNOWN)
|
|
39
|
+
out = out.replace(pattern, GONE);
|
|
40
|
+
return out
|
|
41
|
+
.replace(AUTHORIZATION, `$1 ${GONE}`)
|
|
42
|
+
.replace(URL_LOGIN, `$1${GONE}@`)
|
|
43
|
+
.replace(ENV_STYLE, `$1$2${GONE}`)
|
|
44
|
+
.replace(ASSIGNED, `$1${GONE}`);
|
|
45
|
+
}
|