clankoff-bridge 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jaysencpp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # clankoff-bridge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Play games on a Clankoff site with the AI command-line tools installed on your own machine (Claude Code, Codex,
4
+ Copilot, Gemini), using your own subscriptions. The site sends your machine a game position; your CLI answers; the
5
+ bridge sends the answer back. That is all it does.
6
+
7
+ No dependencies: everything that runs is the seven files in `src/`, about 750 lines. Read them before you run them.
8
+
9
+ ## Use
10
+
11
+ You need Node.js 24 or newer, and at least one AI CLI installed and logged in (for example, `claude` works in your
12
+ terminal).
13
+
14
+ 1. Run it, in any folder:
15
+ ```
16
+ npx clankoff-bridge
17
+ ```
18
+ (For a Clankoff site other than `https://clankoff.com`, add `--server https://that-site`.)
19
+ 2. It prints a link to the site's Account page, and opens it if this machine has a browser. Sign in there, check that
20
+ the page shows the same code as your terminal, and click **Connect**. Any device you are signed in on will do.
21
+ 3. The terminal says `ready`. Leave it running; Ctrl-C stops it. On the site, choose **Claude via bridge** (or Codex,
22
+ Copilot, Gemini) as your player. Only you see them, and only while your bridge is running.
23
+
24
+ You do that once. The bridge remembers the site and its token in `~/.config/clankoff-bridge/config.json`
25
+ (`%APPDATA%\clankoff-bridge` on Windows), a file only your user can read, so from then on `npx clankoff-bridge` starts
26
+ straight away. If the site later refuses the token (you revoked it), the bridge forgets it and prints a new link.
27
+
28
+ Options: `--server` is the site (default `https://clankoff.com`, or the one remembered), `--agents claude,codex` offers
29
+ only those CLIs, `--max 2` sets how many turns run at once, and `--forget` deletes the remembered site and token.
30
+
31
+ On a machine with no terminal (a service, a container): on the site, open **Account → Bridge**, make a token by hand,
32
+ and set `CLANKOFF_SERVER` and `CLANKOFF_BRIDGE_TOKEN` in the environment, or in a `.env` file in the folder the bridge
33
+ runs from. They come first when set, and nothing is saved. A site too old to connect from the browser gets the same
34
+ kind of token pasted into the terminal instead (it isn't shown as you paste).
35
+
36
+ ## What it does
37
+
38
+ 0. **Connects to your account**, the first time (`src/pair.js`). It makes a random token on your machine and sends
39
+ the site only the token's SHA-256 (`POST <server>/api/bridge/pair`), getting a short code back. It prints
40
+ `<server>/account.html#pair=<code>` and opens it with your system's opener (`open`, `xdg-open`; not over ssh).
41
+ When you click Connect there, the site starts accepting that token; the bridge finds out by asking
42
+ `GET <server>/api/bridge/whoami` every few seconds, for at most ten minutes. Only connect a code you see in your
43
+ own terminal: whoever holds the bridge behind a code plays your turns.
44
+ 1. **Checks the token** with `GET <server>/api/bridge/whoami` and prints whose account it belongs to. The server
45
+ must be an `https://` address (plain `http://` only for `localhost`), so the token never travels unencrypted.
46
+ 2. **Connects out** to `<server>/api/bridge/connect` over a WebSocket. Nothing listens on your machine. The token
47
+ travels in an `Authorization` header, never in a URL.
48
+ 3. **Says which CLIs it has:** the ones found on your `PATH`, with the model names each one reports (for example from
49
+ `codex debug models`). Nothing else about your machine is sent.
50
+ 4. **Runs turns.** For each `turn` message (`agent`, `model`, `effort`, `prompt`) it:
51
+ - refuses an unknown CLI, a model name that isn't a plain name (it can't start with `-` and be read as a flag), an
52
+ effort the CLI doesn't have, or a prompt that starts with `-`;
53
+ - makes a fresh, empty temporary folder and runs the CLI there, once, without a shell, and with its tools off (see
54
+ below);
55
+ - sends back the CLI's final answer text, or the kind of failure ("claude timed out", "codex is not logged in on
56
+ the bridge machine"); then kills anything the CLI left running and deletes the folder. What the CLI itself
57
+ printed about a failure is shown in the bridge's own output and is not sent: it can name folders or accounts.
58
+ 5. **Stops a turn** when the server sends `cancel` (the game was stopped): the CLI's whole process tree is killed.
59
+ 6. **Reconnects** after a dropped connection (1 s, 2 s, 4 s, … up to 30 s). It stops for good when the server says the
60
+ token was revoked, or when another bridge connects for the same account.
61
+
62
+ ### How each CLI is run (`src/agents.js`)
63
+
64
+ | CLI | Command | Tools |
65
+ |---|---|---|
66
+ | Claude Code | `claude -p --output-format text --tools "" --strict-mcp-config --no-session-persistence [--model …] [--effort …]`, prompt on stdin | none: `--tools ""` for the built-in ones, `--strict-mcp-config` for your MCP servers |
67
+ | Codex | `codex exec --skip-git-repo-check --sandbox read-only --ephemeral --disable shell_tool --disable unified_exec -c web_search="disabled" -c mcp_servers={} … -`, prompt on stdin | read-only sandbox, shell and web search off, code execution removed from its model catalog, your MCP servers left out |
68
+ | Copilot | `copilot -p <prompt> -s --no-color --disable-builtin-mcps [--model …] [--reasoning-effort …]` | none (in `-p` mode Copilot denies every tool unless one is allowed; its built-in MCP servers are off) |
69
+ | Gemini | `gemini -p <prompt> -e none --admin-policy <deny-all.toml> [-m …]` | every tool denied by policy (also loaded through a system settings file), extensions off, MCP off |
70
+
71
+ The CLI runs with your environment **minus** these variables, so it uses its own login and never sees your API keys
72
+ or the bridge token: `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `GEMINI_API_KEY`,
73
+ `GOOGLE_API_KEY`, `GEMINI_BASE_URL`, `OPENROUTER_API_KEY`, `OPENROUTER_BASE_URL`, `TYPESAFE_API_KEY`,
74
+ `TYPESAFE_BASE_URL`, `CLANKOFF_BRIDGE_TOKEN`.
75
+
76
+ ### What leaves your machine
77
+
78
+ The names of your CLIs and their models, and for each turn the CLI's final answer text, or which kind of failure it
79
+ was (never the CLI's own error output). When connecting: the SHA-256 of the bridge's token, then the token itself in a
80
+ header, as on every later run. No files, no environment, no keys, not your machine's name.
81
+
82
+ ## Good to know
83
+
84
+ - **It uses your plans.** Every move is a call to your Claude, Codex, Copilot or Gemini subscription. Start with a
85
+ cheap model and low effort.
86
+ - **Unverified.** The site can't tell what produced an answer that comes from your machine (a model, a person, a
87
+ script), so bridged players are marked unverified, don't count for player ratings, and can only join challenges
88
+ that allow bridges.
89
+ - **The token is like a password** for playing moves as you on that site, and nothing more. Revoke it on the
90
+ Account page at any time; a bridge using it is disconnected at once.
91
+ - **Provider terms** are yours to check: this runs your personal CLI subscriptions for games on someone's website.
92
+
93
+ ## Protocol
94
+
95
+ JSON over a WebSocket (plus text `ping` / `pong`):
96
+
97
+ | Direction | Message |
98
+ |---|---|
99
+ | bridge → server | `{type: "hello", client: "clankoff-bridge@x.y.z", agents: {claude: {models: [...]}, ...}}` |
100
+ | server → bridge | `{type: "welcome", name}` |
101
+ | server → bridge | `{type: "turn", id, agent, model, effort, prompt, timeoutMs}` |
102
+ | bridge → server | `{type: "reply", id, text}` or `{type: "error", id, message, fatal}` |
103
+ | server → bridge | `{type: "cancel", id}` |
104
+
105
+ Close code 4001 means the token was revoked; 4000 means another bridge took over.
106
+
107
+ Connecting from the browser, before any of that (plain HTTPS):
108
+
109
+ | Request | Answer |
110
+ |---|---|
111
+ | `POST /api/bridge/pair` `{tokenHash}` (hex SHA-256 of a token the bridge made) | `{code, expiresIn}` |
112
+ | `GET /api/bridge/whoami` with the token, while waiting | `401 {pairing: "pending"}`, then `200 {name}` once connected; a plain `401` if it was declined or ran out |
113
+
114
+ ## Files
115
+
116
+ ```
117
+ src/cli.js the npx command: reads options, finds the token (environment, remembered, or a new one), starts the bridge
118
+ src/pair.js connects to your account with a link and a click in the browser
119
+ src/saved.js the file the site and token are remembered in; pasting a token, for a site that can't do the above
120
+ src/client.js connection, hello, running and cancelling turns, reconnecting
121
+ src/agents.js how each CLI is run (arguments, empty folder, withheld variables, timeouts)
122
+ src/reap.js finds and kills processes a CLI left behind
123
+ src/meta.js each CLI's label, model suggestions and efforts
124
+ ```
125
+
126
+ ## License
127
+
128
+ MIT, see [LICENSE](LICENSE). This covers the bridge only.
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "clankoff-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Play Clankoff games with the AI CLIs on your own machine (Claude Code, Codex, Copilot, Gemini), tools off. No dependencies; read src/ to see everything it does.",
5
+ "license": "MIT",
6
+ "author": "jaysencpp",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/jaysencpp/clankoff-bridge.git"
10
+ },
11
+ "homepage": "https://github.com/jaysencpp/clankoff-bridge#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/jaysencpp/clankoff-bridge/issues"
14
+ },
15
+ "type": "module",
16
+ "bin": {
17
+ "clankoff-bridge": "src/cli.js"
18
+ },
19
+ "exports": {
20
+ ".": "./src/client.js",
21
+ "./agents": "./src/agents.js",
22
+ "./meta": "./src/meta.js",
23
+ "./pair": "./src/pair.js",
24
+ "./reap": "./src/reap.js"
25
+ },
26
+ "files": [
27
+ "src",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "engines": {
32
+ "node": ">=24"
33
+ },
34
+ "keywords": [
35
+ "clankoff",
36
+ "claude-code",
37
+ "codex",
38
+ "copilot",
39
+ "bridge"
40
+ ]
41
+ }
package/src/agents.js ADDED
@@ -0,0 +1,297 @@
1
+ // AI CLI agents (Claude Code, Codex, Copilot, Gemini): each is run once per turn, non-interactively, with its tools
2
+ // turned off, in a fresh empty folder, and its final text answer returned. Used by the bridge (cli.js) and by
3
+ // Clankoff's local mode. Node only: it spawns processes.
4
+ import { spawn, execFile, execFileSync } from 'node:child_process';
5
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { constants, tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { reapTree } from './reap.js';
9
+ import { CLI_META } from './meta.js';
10
+
11
+ // Variables a CLI never gets. API keys and endpoints (Claude Code would bill an ANTHROPIC_API_KEY instead of using its
12
+ // own login, or follow ANTHROPIC_BASE_URL elsewhere: to run a CLI on an API key, set that up in the CLI itself), and
13
+ // the bridge's own token, which a CLI has no use for.
14
+ export const WITHHELD_VARS = new Set([
15
+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'GEMINI_API_KEY', 'GOOGLE_API_KEY',
16
+ 'GEMINI_BASE_URL', 'OPENROUTER_API_KEY', 'OPENROUTER_BASE_URL', 'TYPESAFE_API_KEY', 'TYPESAFE_BASE_URL', 'CLANKOFF_BRIDGE_TOKEN',
17
+ ]);
18
+ /** The environment a CLI runs with: this process's, minus WITHHELD_VARS, plus `extra`. */
19
+ export function cliEnv(extra = {}) {
20
+ const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !WITHHELD_VARS.has(k)));
21
+ return { ...env, NO_COLOR: '1', ...extra };
22
+ }
23
+
24
+ function which(bin) {
25
+ try {
26
+ return execFileSync('which', [bin], { encoding: 'utf8' }).trim() || null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ // Ask a CLI for its model list; resolves with stdout or rejects on error/timeout.
33
+ const capture = (bin, args, timeout = 8000) => new Promise((resolve, reject) =>
34
+ execFile(bin, args, { timeout, maxBuffer: 32 * 1024 * 1024, env: cliEnv() },
35
+ (err, stdout) => (err ? reject(err) : resolve(stdout))));
36
+
37
+ // Current Codex models are catalogued with tool_mode "code_mode_only": every tool is wrapped in a
38
+ // JavaScript `exec` tool the model can also use to compute (e.g. brute-force the cube). No feature
39
+ // flag turns that off (code_mode_host only changes where it runs), so we hand Codex a copy of its own
40
+ // catalog without tool_mode. Rebuilt every few minutes; on any failure Codex runs with its own catalog.
41
+ const CODEX_CATALOG_TTL_MS = 5 * 60_000;
42
+ let codexCatalog = null; // { at, path?, pending? }
43
+ let codexCatalogDir = null;
44
+ async function codexCatalogPath() {
45
+ if (codexCatalog && (codexCatalog.pending || Date.now() - codexCatalog.at < CODEX_CATALOG_TTL_MS)) {
46
+ return codexCatalog.pending || codexCatalog.path;
47
+ }
48
+ const entry = { at: Date.now(), path: codexCatalog?.path ?? null };
49
+ entry.pending = capture('codex', ['debug', 'models'])
50
+ .then((text) => {
51
+ const catalog = JSON.parse(text);
52
+ if (!Array.isArray(catalog.models)) throw new Error('unexpected catalog shape');
53
+ for (const m of catalog.models) delete m.tool_mode;
54
+ codexCatalogDir ??= mkdtempSync(join(tmpdir(), 'clankoff-codex-catalog-'));
55
+ const path = join(codexCatalogDir, 'models.json');
56
+ writeFileSync(path, JSON.stringify(catalog));
57
+ return (entry.path = path);
58
+ })
59
+ .catch((e) => { console.error('[codex] catalog override unavailable:', e.message); return entry.path; })
60
+ .finally(() => { entry.pending = null; entry.at = Date.now(); });
61
+ codexCatalog = entry;
62
+ return entry.pending;
63
+ }
64
+
65
+ /** GitHub token Copilot runs with: COPILOT_GH_USER's if set, else the active `gh` account's. */
66
+ async function copilotToken() {
67
+ const user = process.env.COPILOT_GH_USER;
68
+ try {
69
+ return (await capture('gh', ['auth', 'token', '--hostname', 'github.com', ...(user ? ['--user', user] : [])])).trim();
70
+ } catch {
71
+ throw new Error(`copilot: no gh token${user ? ` for COPILOT_GH_USER=${user}` : ''} (run \`gh auth login\`)`);
72
+ }
73
+ }
74
+
75
+ /** Models the account can pick in Copilot, from the Copilot API. */
76
+ async function copilotApiModels() {
77
+ const res = await fetch('https://api.githubcopilot.com/models', {
78
+ headers: {
79
+ Authorization: `Bearer ${await copilotToken()}`,
80
+ 'Copilot-Integration-Id': 'copilot-developer-cli',
81
+ 'X-GitHub-Api-Version': '2025-05-01',
82
+ },
83
+ signal: AbortSignal.timeout(8000),
84
+ });
85
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
86
+ const { data } = await res.json();
87
+ if (!Array.isArray(data)) throw new Error('unexpected response shape');
88
+ return data.filter((m) => m.model_picker_enabled && m.policy?.state !== 'disabled').map((m) => m.id);
89
+ }
90
+
91
+ const CLIS = {
92
+ claude: {
93
+ ...CLI_META.claude,
94
+ bin: 'claude',
95
+ build: ({ prompt, model, effort }) => ({
96
+ // No tools: the model has to reason about the cube itself. --tools "" removes the built-in ones;
97
+ // --strict-mcp-config (with no --mcp-config) keeps the MCP servers set up on this machine out too.
98
+ // The prompt goes in on stdin: as an argument, `claude -p` reads one that starts with "-" as a flag.
99
+ args: ['-p', '--output-format', 'text', '--tools', '', '--strict-mcp-config', '--no-session-persistence',
100
+ ...(model ? ['--model', model] : []), ...(effort ? ['--effort', effort] : [])],
101
+ stdin: prompt,
102
+ }),
103
+ },
104
+ codex: {
105
+ ...CLI_META.codex,
106
+ bin: 'codex',
107
+ // `codex debug models` dumps the model catalog as JSON; hidden entries are internal.
108
+ discoverModels: async () => JSON.parse(await capture('codex', ['debug', 'models'])).models
109
+ .filter((m) => m.visibility === 'list').map((m) => m.slug),
110
+ prepare: async () => ({ catalog: await codexCatalogPath() }),
111
+ build: ({ prompt, model, effort, dir, catalog }) => {
112
+ const outFile = join(dir, 'last-message.txt');
113
+ return {
114
+ // No code execution: the model has to reason about the cube itself (and can't leave a
115
+ // brute-force solver running). shell_tool and unified_exec are both ways to run commands;
116
+ // the catalog override removes the JavaScript `exec` tool (see codexCatalogPath). Web search is
117
+ // off too: no looking up solutions, and with tool_mode stripped gpt-6.2 models reject Codex's
118
+ // `web.run` function ("reserved for use by this model") with a 400. mcp_servers={} leaves out the
119
+ // MCP servers in the user's config.toml: their tools run outside the sandbox.
120
+ args: ['exec', '--skip-git-repo-check', '--sandbox', 'read-only', '--ephemeral', '--color', 'never',
121
+ '--disable', 'shell_tool', '--disable', 'unified_exec', '-c', 'web_search="disabled"', '-c', 'mcp_servers={}',
122
+ ...(catalog ? ['-c', `model_catalog_json=${JSON.stringify(catalog)}`] : []),
123
+ '-o', outFile, ...(model ? ['-m', model] : []),
124
+ ...(effort ? ['-c', `model_reasoning_effort="${effort}"`] : []), '-'],
125
+ stdin: prompt,
126
+ readResult: () => readFileSync(outFile, 'utf8'),
127
+ };
128
+ },
129
+ },
130
+ copilot: {
131
+ ...CLI_META.copilot,
132
+ bin: 'copilot',
133
+ // Copilot uses whichever `gh` account is active; COPILOT_GH_USER pins one (token fetched per run).
134
+ prepare: async () => {
135
+ if (!process.env.COPILOT_GH_USER) return {};
136
+ return { env: { COPILOT_GITHUB_TOKEN: await copilotToken() } };
137
+ },
138
+ // The account's live model list (what Copilot's /model picker shows). `copilot help config` only
139
+ // has a fixed example list baked into the CLI, which misses newer models; it is the fallback.
140
+ discoverModels: async () => {
141
+ try {
142
+ return await copilotApiModels();
143
+ } catch (e) {
144
+ console.error('[copilot] model list from API failed, using `copilot help config`:', e.message);
145
+ const text = await capture('copilot', ['help', 'config']);
146
+ const block = text.split(/^ {2}`model`:.*$/m)[1]?.split(/^ {2}`/m)[0] || '';
147
+ return [...block.matchAll(/^\s*- "([^"]+)"/gm)].map((m) => m[1]);
148
+ }
149
+ },
150
+ build: ({ prompt, model, effort }) => ({
151
+ // In -p mode Copilot denies every tool unless explicitly allowed; its built-in MCP servers are off as well.
152
+ args: ['-p', prompt, '-s', '--no-color', '--disable-builtin-mcps', ...(model ? ['--model', model] : []),
153
+ ...(effort ? ['--reasoning-effort', effort] : [])],
154
+ }),
155
+ },
156
+ gemini: {
157
+ ...CLI_META.gemini,
158
+ bin: 'gemini',
159
+ // No tools: the model has to reason about the game itself, and a bridge must not let a prompt reach the machine.
160
+ // Gemini CLI has no single switch for that, so three documented controls are layered (geminicli.com, configuration
161
+ // and policy-engine references):
162
+ // - a policy denying every tool ("*", built-in or MCP), loaded as an admin policy (--admin-policy), the tier that
163
+ // beats the user's own ~/.gemini policies; denied tools are removed from what the model is offered
164
+ // - the same policy again via policyPaths in a system settings file (GEMINI_CLI_SYSTEM_SETTINGS_PATH, the settings
165
+ // layer that overrides all others), which also turns off YOLO mode and MCP servers
166
+ // - -e none: no extensions
167
+ build: ({ prompt, model, dir }) => {
168
+ const policy = join(dir, 'clankoff-no-tools.toml');
169
+ const settings = join(dir, 'clankoff-system-settings.json');
170
+ writeFileSync(policy, GEMINI_DENY_ALL);
171
+ writeFileSync(settings, JSON.stringify({ policyPaths: [policy], security: { disableYoloMode: true }, admin: { mcp: { enabled: false } } }));
172
+ return {
173
+ args: ['-p', prompt, '-e', 'none', '--admin-policy', policy, ...(model ? ['-m', model] : [])],
174
+ env: { GEMINI_CLI_SYSTEM_SETTINGS_PATH: settings },
175
+ };
176
+ },
177
+ },
178
+ };
179
+
180
+ // Gemini CLI policy (TOML) that denies every tool, built-in and MCP, at the highest priority.
181
+ const GEMINI_DENY_ALL = `# Written by Clankoff for one game turn: the model answers from the prompt alone.
182
+ [[rule]]
183
+ toolName = "*"
184
+ decision = "deny"
185
+ priority = 999
186
+ denyMessage = "Tools are disabled in Clankoff games."
187
+
188
+ [[rule]]
189
+ toolName = "*"
190
+ mcpName = "*"
191
+ decision = "deny"
192
+ priority = 999
193
+ denyMessage = "Tools are disabled in Clankoff games."
194
+ `;
195
+
196
+ /**
197
+ * An agent definition (the shape Clankoff's agent registry uses) for a CLI. `spec`: {label, bin, models, efforts, discoverModels?,
198
+ * prepare?() → extra (async; passed to build, e.g. Codex's catalog override, extra.env), build({prompt, model, effort, dir, ...extra})
199
+ * → {args, stdin?, readResult?}}. `build` stays on the definition so tests can check the arguments.
200
+ */
201
+ export function cliAgent(id, spec) {
202
+ return {
203
+ available: () => !!which(spec.bin),
204
+ ...spec,
205
+ call: ({ prompt, model, effort, timeoutMs, signal }) => {
206
+ // A prompt is text for the model, never an option: a CLI that takes it as an argument could read "--x" as a flag.
207
+ if (String(prompt).startsWith('-')) return Promise.reject(Object.assign(new Error(`${id}: refusing a prompt that starts with "-"`), { fatal: true }));
208
+ return spec.prepare
209
+ ? spec.prepare().then((extra) => spawnAgent(id, spec, { prompt, model, effort, timeoutMs, signal, extra }))
210
+ : spawnAgent(id, spec, { prompt, model, effort, timeoutMs, signal });
211
+ },
212
+ };
213
+ }
214
+
215
+ /** Every CLI agent, keyed by agent id. */
216
+ export const cliAgents = () => Object.fromEntries(Object.entries(CLIS).map(([id, spec]) => [id, cliAgent(id, spec)]));
217
+
218
+ // Agent runs in flight (child -> scratch dir), so they can be killed if the server itself exits.
219
+ const active = new Map();
220
+ let exitHooked = false;
221
+ function hookExit() {
222
+ if (exitHooked) return;
223
+ exitHooked = true;
224
+ process.on('exit', () => {
225
+ for (const [child, dir] of active) {
226
+ reapTree({ pid: child.pid, dir, signal: 'SIGKILL' });
227
+ try { rmSync(dir, { recursive: true, force: true }); } catch {}
228
+ }
229
+ if (codexCatalogDir) try { rmSync(codexCatalogDir, { recursive: true, force: true }); } catch {}
230
+ });
231
+ // Without these, Ctrl-C / kill would skip the 'exit' handler (agents run in their own process group).
232
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.once(sig, () => process.exit(128 + constants.signals[sig]));
233
+ }
234
+
235
+ function spawnAgent(agent, def, { prompt, model, effort, timeoutMs, signal, extra = {} }) {
236
+ if (signal?.aborted) return Promise.reject(new Error('aborted'));
237
+ // Run inside an empty scratch directory so the agent has no project context to poke at.
238
+ const dir = mkdtempSync(join(tmpdir(), 'clankoff-ai-'));
239
+ const { args, stdin, readResult, env } = def.build({ prompt, model, effort, dir, ...extra });
240
+
241
+ return new Promise((resolve, reject) => {
242
+ hookExit();
243
+ // detached: the CLI leads its own process group, so the whole tree can be signalled at once.
244
+ const child = spawn(def.bin, args, { cwd: dir, env: cliEnv({ ...extra.env, ...env }), detached: true });
245
+ active.set(child, dir);
246
+ let stdout = '';
247
+ let stderr = '';
248
+ let settled = false;
249
+ const finish = (fn, val) => {
250
+ if (settled) return;
251
+ settled = true;
252
+ clearTimeout(timer);
253
+ signal?.removeEventListener('abort', onAbort);
254
+ // Always, also after a clean exit: tool commands the CLI started may still be running.
255
+ reapTree({ pid: child.pid, dir });
256
+ active.delete(child);
257
+ try { rmSync(dir, { recursive: true, force: true }); } catch {}
258
+ fn(val);
259
+ };
260
+ const onAbort = () => {
261
+ finish(reject, new Error('aborted'));
262
+ };
263
+ const timer = setTimeout(() => {
264
+ finish(reject, new Error(`${agent} timed out after ${Math.round(timeoutMs / 1000)}s`));
265
+ }, timeoutMs);
266
+ signal?.addEventListener('abort', onAbort);
267
+
268
+ child.stdout.on('data', (d) => (stdout += d));
269
+ child.stderr.on('data', (d) => (stderr += d));
270
+ child.on('error', (e) => finish(reject, e));
271
+ // A stray tool process can inherit our stdout and hold it open, so 'close' never fires.
272
+ // Once the CLI itself has exited, give stdio a moment to drain, then kill the leftovers.
273
+ child.on('exit', () => setTimeout(() => { if (!settled) reapTree({ pid: child.pid, dir }); }, 1000).unref());
274
+ child.on('close', (code) => {
275
+ if (settled) return;
276
+ let text = stdout;
277
+ let fromFile = false;
278
+ if (readResult) {
279
+ try { text = readResult(); fromFile = !!text.trim(); } catch { /* fall back to stdout */ }
280
+ }
281
+ // A non-zero exit is a failure even if it printed something (e.g. "Not logged in"),
282
+ // unless the agent wrote its answer to the result file.
283
+ if (code !== 0 && !fromFile) {
284
+ const hint = /not logged in|please run \/login|invalid api key|\b401\b/i.test(stderr + stdout)
285
+ ? ' (is the CLI logged in for the environment the server runs in? Check CLAUDE_CONFIG_DIR / HOME.)' : '';
286
+ // Prefer the CLI's own error lines (Codex echoes the whole prompt before them).
287
+ const output = stderr || stdout;
288
+ const errorLines = [...new Set(output.split('\n').map((l) => l.trim()).filter((l) => /^(ERROR|Error)\b/.test(l)))];
289
+ const detail = errorLines.length ? errorLines.join(' ').slice(0, 600) : output.trim().slice(-600);
290
+ return finish(reject, new Error(`${agent} exited with code ${code}: ${detail}${hint}`));
291
+ }
292
+ finish(resolve, text);
293
+ });
294
+ if (stdin != null) child.stdin.end(stdin);
295
+ else child.stdin.end();
296
+ });
297
+ }
package/src/cli.js ADDED
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ // clankoff-bridge: play turns for a Clankoff site with the AI CLIs installed on this machine. See README.md.
3
+ //
4
+ // npx clankoff-bridge [--server https://…] [--agents claude,codex] [--max 2] [--forget]
5
+ //
6
+ // The first run prints a link to the site's Account page (and opens it): sign in there and click Connect (src/pair.js).
7
+ // The bridge then remembers its token with the site's address (src/saved.js), so later runs ask nothing.
8
+ // A site that can't do that gets a token pasted in the terminal instead. CLANKOFF_BRIDGE_TOKEN and CLANKOFF_SERVER
9
+ // (environment, or a .env file in the current folder) come first if set. The token is never taken from the command
10
+ // line, where other users of this machine could see it.
11
+ // Each turn runs a CLI with its tools off, in a fresh empty folder, without API keys or this token (src/agents.js).
12
+ import { parseArgs } from 'node:util';
13
+ import { readFileSync } from 'node:fs';
14
+ import { cliAgents } from './agents.js';
15
+ import { serverBase, startBridge } from './client.js';
16
+ import { openBrowser, startPairing, waitForApproval } from './pair.js';
17
+ import { askToken, forget, looksLikeToken, readSaved, save, savedPath } from './saved.js';
18
+
19
+ const DEFAULT_SERVER = 'https://clankoff.com';
20
+
21
+ // .env in the current folder, if there is one (variables already set win)
22
+ try { process.loadEnvFile(); } catch { /* none */ }
23
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
24
+
25
+ const { values } = parseArgs({
26
+ options: {
27
+ server: { type: 'string' },
28
+ agents: { type: 'string' },
29
+ max: { type: 'string' },
30
+ forget: { type: 'boolean' },
31
+ help: { type: 'boolean', short: 'h' },
32
+ version: { type: 'boolean', short: 'v' },
33
+ },
34
+ });
35
+ const usage = `clankoff-bridge ${version}
36
+ usage: npx clankoff-bridge [--server https://your-clankoff.example] [--agents claude,codex] [--max 2]
37
+ The first run prints a link: open it, sign in to the site and click Connect. The bridge then remembers its token in
38
+ ${savedPath()}
39
+ --server the site to play on (default ${DEFAULT_SERVER}, or the one remembered)
40
+ --forget delete the remembered site and token, and stop
41
+ Without a terminal (a service, a container), make a token on the site's Account page and set CLANKOFF_BRIDGE_TOKEN
42
+ (and CLANKOFF_SERVER) in the environment or ./.env.`;
43
+ if (values.help) { console.log(usage); process.exit(0); }
44
+ if (values.version) { console.log(version); process.exit(0); }
45
+ if (values.forget) { forget(); console.log(`Forgot the site and token in ${savedPath()}. To switch the token off for good, revoke it on the site's Account page.`); process.exit(0); }
46
+
47
+ const saved = readSaved();
48
+ const server = serverBase(values.server || process.env.CLANKOFF_SERVER || saved?.server || DEFAULT_SERVER);
49
+ if (server instanceof Error) { console.error(`${server.message}\n${usage}`); process.exit(2); }
50
+ const canShow = process.stdout.isTTY; // someone is there to read a link
51
+ const canAsk = canShow && process.stdin.isTTY;
52
+ const stop = (line, code = 1) => { console.error(line); process.exit(code); };
53
+
54
+ /** A token for this machine: connected with a click in the browser, or pasted if the site can't do that. */
55
+ async function connect() {
56
+ console.log(`Site: ${server}`);
57
+ let pairing;
58
+ try { pairing = await startPairing(server); } catch (e) {
59
+ if (!e.status) stop(`Can't reach ${server}: ${e.cause?.message || e.message}`);
60
+ if (!canAsk) stop(`${server} can't connect a bridge from the browser (${e.message}).\n${usage}`, 2);
61
+ console.log(`This site can't connect a bridge from the browser right now (${e.message}).`);
62
+ return ask();
63
+ }
64
+ console.log(`\nOpen this link, sign in, and click Connect (it works for ${Math.round(pairing.expiresIn / 60)} minutes):\n\n ${pairing.url}\n\nThe page must show the code ${pairing.code}. Waiting for the click…`);
65
+ openBrowser(pairing.url);
66
+ try { await waitForApproval(server, pairing); } catch (e) { stop(`Not connected: ${e.message}. Run it again for a new link.`); }
67
+ return pairing.token;
68
+ }
69
+
70
+ /** Ask until something that looks like a token is pasted. */
71
+ async function ask() {
72
+ console.log('Make a bridge token there (Account → Bridge) and paste it here. It won\'t show as you paste.');
73
+ for (;;) {
74
+ const answer = await askToken('Bridge token: ');
75
+ if (looksLikeToken(answer)) return answer;
76
+ if (!answer) { console.error('No token entered.'); process.exit(2); }
77
+ console.log('That isn\'t a bridge token: they start with clk_bridge_. Try again, or Ctrl-C to stop.');
78
+ }
79
+ }
80
+
81
+ // the token: the environment's, else the one remembered for this site, else a new one connected now
82
+ let token = process.env.CLANKOFF_BRIDGE_TOKEN;
83
+ let from = 'the environment';
84
+ if (!token && saved && serverBase(saved.server) === server) { token = saved.token; from = 'saved'; }
85
+ if (!token) {
86
+ if (!canShow) stop(`CLANKOFF_BRIDGE_TOKEN is not set, and there is no terminal to show a link in.\n${usage}`, 2);
87
+ token = await connect();
88
+ from = 'connected';
89
+ }
90
+
91
+ let agents = cliAgents();
92
+ if (values.agents) {
93
+ const wanted = new Set(values.agents.split(',').map((s) => s.trim()));
94
+ agents = Object.fromEntries(Object.entries(agents).filter(([id]) => wanted.has(id)));
95
+ }
96
+ const stamp = () => new Date().toLocaleTimeString();
97
+ let bridge;
98
+ for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { bridge?.close(); process.exit(0); });
99
+ for (;;) {
100
+ bridge = startBridge({ server, token, agents, client: `clankoff-bridge@${version}`, maxConcurrent: Math.max(1, Number(values.max) || 2), log: (line) => console.log(`${stamp()} ${line}`) });
101
+ try {
102
+ const name = await bridge.ready;
103
+ if (from === 'connected') { save({ server, token }); console.log(`${stamp()} remembered in ${savedPath()}: next time, just run npx clankoff-bridge (--forget deletes it)`); }
104
+ console.log(`${stamp()} ready: games on ${server} can now use your CLIs as ${name}. Ctrl-C to stop.`);
105
+ break;
106
+ } catch (e) {
107
+ console.error(`${stamp()} bridge stopped: ${e.message}`);
108
+ // a token the site refuses: drop it if it was the remembered one, and connect again
109
+ if (e.code !== 'bad-token' || from === 'the environment') process.exit(1);
110
+ if (from === 'saved') forget();
111
+ if (!canShow) process.exit(1);
112
+ token = await connect();
113
+ from = 'connected';
114
+ }
115
+ }
package/src/client.js ADDED
@@ -0,0 +1,162 @@
1
+ // The bridge client: lets a Clankoff site play turns with the AI CLIs on this machine.
2
+ // It connects out to the server (nothing listens here), says which CLIs it has, then runs each turn the server sends,
3
+ // with the hardened CLI runner in agents.js (tools off, empty temp folder, API keys withheld), and sends back the
4
+ // reply. A turn the server cancels (the game was stopped) kills the CLI. The protocol is in README.md.
5
+
6
+ const MAX_TURN_MS = 900_000;
7
+ const MODEL_RE = /^(?!-)[\w.:/@-]{0,100}$/; // a model name, never something a CLI could read as a flag
8
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
9
+
10
+ /** The server's base URL, or an Error: https only (the token travels in a header), plain http just for this machine. */
11
+ export function serverBase(server) {
12
+ let url;
13
+ try { url = new URL(server); } catch { return new Error(`"${server}" is not a URL (expected https://…)`); }
14
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname))) {
15
+ return new Error(`refusing ${url.protocol}//${url.host}: the bridge token would travel unencrypted. Use the site's https:// address`);
16
+ }
17
+ return url.origin + url.pathname.replace(/\/+$/, '');
18
+ }
19
+
20
+ // What the server is told when a turn fails. The site shows it to everyone watching the game, so it names the kind of
21
+ // failure and never repeats the CLI's own output, which can mention folders or accounts on this machine. The full
22
+ // message stays in the log here. [what the error says, what the server hears, whether retrying the next turn is pointless]
23
+ const FAILURES = [
24
+ [/refusing a prompt/i, 'got a prompt that starts with "-" and refused it', true],
25
+ [/timed out/i, 'timed out', false],
26
+ [/not logged in|please run \/login|invalid api key|\b401\b|unauthorized|no gh token/i, 'is not logged in on the bridge machine', true],
27
+ [/issue with the selected model|recognize the model|unknown model|model\b.{0,40}\b(not found|not supported|not available|does not exist)/i, 'does not have that model', true],
28
+ [/out of credits|insufficient[_ ]quota|exceeded your (current )?quota|billing|usage limit/i, 'is out of credits or over its usage limit', true],
29
+ [/rate.?limit|\b429\b|overloaded/i, 'was rate limited', false],
30
+ [/ENOENT/, 'is not installed on the bridge machine', true],
31
+ ];
32
+ export function publicError(agent, e) {
33
+ const text = String(e?.message || '');
34
+ const hit = FAILURES.find(([re]) => re.test(text));
35
+ return hit ? { message: `${agent} ${hit[1]}`, fatal: hit[2] || !!e?.fatal }
36
+ : { message: `${agent} failed on the bridge machine (the bridge's own log says why)`, fatal: !!e?.fatal };
37
+ }
38
+
39
+ /**
40
+ * @param {object} o
41
+ * @param {string} o.server the site's URL, e.g. https://clankoff.example.workers.dev
42
+ * @param {string} o.token a bridge token from the Account page
43
+ * @param {object} o.agents agent definitions by CLI id (providers/cli cliAgents(), or fakes in tests)
44
+ * @param {(line: string) => void} [o.log]
45
+ * @param {number} [o.maxConcurrent] turns run at once; more wait their turn
46
+ * @param {string} [o.client] name@version, told to the server
47
+ * @returns {{ready: Promise<string>, close(): void}} ready resolves with the account name once the server welcomes it
48
+ */
49
+ export function startBridge({ server, token, agents, log = (line) => console.log(line), maxConcurrent = 2, client = 'clankoff-bridge' }) {
50
+ const base = serverBase(String(server || ''));
51
+ if (base instanceof Error) {
52
+ const ready = Promise.reject(base);
53
+ ready.catch(() => {});
54
+ return { ready, close() {} };
55
+ }
56
+ let ws = null;
57
+ let closed = false;
58
+ let retry = 1000;
59
+ const running = new Map(); // turn id -> AbortController
60
+ const queue = [];
61
+ let readyResolve;
62
+ let readyReject;
63
+ const ready = new Promise((res, rej) => { readyResolve = res; readyReject = rej; });
64
+ ready.catch(() => {});
65
+
66
+ const send = (msg) => { try { ws?.send(JSON.stringify(msg)); } catch { /* reconnecting */ } };
67
+
68
+ /** The CLIs this machine has, with the models each reports. */
69
+ async function hello() {
70
+ const out = {};
71
+ for (const [id, a] of Object.entries(agents)) {
72
+ if (a.available && !a.available()) continue;
73
+ let models = (a.models || []).filter(Boolean);
74
+ if (a.discoverModels) {
75
+ try { models = [...new Set([...models, ...await a.discoverModels()])]; } catch { /* keep the static list */ }
76
+ }
77
+ out[id] = { models: models.filter((m) => MODEL_RE.test(m)) };
78
+ }
79
+ return out;
80
+ }
81
+
82
+ async function runTurn(t) {
83
+ const a = Object.hasOwn(agents, t.agent) ? agents[t.agent] : null;
84
+ if (!a || (a.available && !a.available())) return send({ type: 'error', id: t.id, message: `no ${t.agent} CLI on this machine`, fatal: true });
85
+ const model = String(t.model || '');
86
+ const effort = String(t.effort || '');
87
+ if (!MODEL_RE.test(model)) return send({ type: 'error', id: t.id, message: `refusing model name "${model.slice(0, 40)}"`, fatal: true });
88
+ if (effort && !(a.efforts || []).includes(effort)) return send({ type: 'error', id: t.id, message: `${t.agent} has no effort "${effort.slice(0, 20)}"`, fatal: true });
89
+ const ctl = new AbortController();
90
+ running.set(t.id, ctl);
91
+ const t0 = Date.now();
92
+ log(`→ ${t.agent}${model ? ` ${model}` : ''}${effort ? ` [${effort}]` : ''}: turn ${t.id.slice(0, 8)}`);
93
+ try {
94
+ const text = await a.call({ prompt: String(t.prompt || ''), model, effort, timeoutMs: Math.min(Number(t.timeoutMs) || MAX_TURN_MS, MAX_TURN_MS), signal: ctl.signal });
95
+ send({ type: 'reply', id: t.id, text });
96
+ log(`← ${t.agent} answered in ${((Date.now() - t0) / 1000).toFixed(1)}s`);
97
+ } catch (e) {
98
+ if (!ctl.signal.aborted) send({ type: 'error', id: t.id, ...publicError(t.agent, e) });
99
+ log(`× ${t.agent}: ${ctl.signal.aborted ? 'stopped by the server' : e.message}`);
100
+ } finally {
101
+ running.delete(t.id);
102
+ pump();
103
+ }
104
+ }
105
+ function pump() {
106
+ while (running.size < maxConcurrent && queue.length) runTurn(queue.shift());
107
+ }
108
+
109
+ function connect() {
110
+ const sock = new WebSocket(`${base.replace(/^http/, 'ws')}/api/bridge/connect`, { headers: { Authorization: `Bearer ${token}` } });
111
+ ws = sock;
112
+ sock.onopen = async () => {
113
+ retry = 1000;
114
+ const list = await hello();
115
+ log(`connected to ${base}; offering ${Object.keys(list).join(', ') || 'no CLIs'}`);
116
+ send({ type: 'hello', client, agents: list });
117
+ };
118
+ sock.onmessage = (m) => {
119
+ if (m.data === 'pong') return;
120
+ let msg;
121
+ try { msg = JSON.parse(m.data); } catch { return; }
122
+ if (msg.type === 'welcome') readyResolve(msg.name);
123
+ else if (msg.type === 'turn' && typeof msg.id === 'string') { queue.push(msg); pump(); }
124
+ else if (msg.type === 'cancel') {
125
+ running.get(msg.id)?.abort();
126
+ const i = queue.findIndex((t) => t.id === msg.id);
127
+ if (i >= 0) queue.splice(i, 1);
128
+ }
129
+ };
130
+ const ping = setInterval(() => sock.readyState === WebSocket.OPEN && sock.send('ping'), 30_000);
131
+ sock.onclose = (e) => {
132
+ clearInterval(ping);
133
+ for (const ctl of running.values()) ctl.abort(); // the server already failed these turns
134
+ if (closed || ws !== sock) return;
135
+ if (e.code === 4001) { log('the server revoked this bridge token; stopping'); closed = true; readyReject(new Error('token revoked')); return; }
136
+ if (e.code === 4000) { log('another bridge connected for this account; stopping'); closed = true; return; }
137
+ log(`disconnected; reconnecting in ${Math.round(retry / 1000)}s`);
138
+ setTimeout(() => !closed && connect(), retry);
139
+ retry = Math.min(retry * 2, 30_000);
140
+ };
141
+ sock.onerror = () => {};
142
+ }
143
+
144
+ // Check the token over plain HTTP first: a refused WebSocket gives no reason.
145
+ fetch(`${base}/api/bridge/whoami`, { headers: { Authorization: `Bearer ${token}` } })
146
+ .then(async (r) => {
147
+ if (r.status === 401) throw Object.assign(new Error('the server doesn\'t know this bridge token (revoked, or for another site?)'), { code: 'bad-token' });
148
+ if (!r.ok) throw new Error(`the server answered ${r.status}`);
149
+ log(`bridge token belongs to ${(await r.json()).name}`);
150
+ connect();
151
+ })
152
+ .catch((e) => { closed = true; readyReject(e); });
153
+
154
+ return {
155
+ ready,
156
+ close() {
157
+ closed = true;
158
+ for (const ctl of running.values()) ctl.abort();
159
+ try { ws?.close(1000, 'bridge stopped'); } catch { /* gone */ }
160
+ },
161
+ };
162
+ }
package/src/meta.js ADDED
@@ -0,0 +1,12 @@
1
+ // What each AI CLI is, without running it: labels, static model suggestions and the reasoning efforts it accepts.
2
+ // No Node APIs, so the cloud can import it too: a bridged lane (bridge/) is validated against these.
3
+ export const CLI_META = {
4
+ claude: {
5
+ label: 'Claude (Claude Code CLI)',
6
+ models: ['', 'opus', 'sonnet', 'haiku', 'claude-fable-5-2', 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5'],
7
+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
8
+ },
9
+ codex: { label: 'Codex (OpenAI Codex CLI)', models: [''], efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'] },
10
+ copilot: { label: 'Copilot (GitHub Copilot CLI)', models: ['', 'auto'], efforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] },
11
+ gemini: { label: 'Gemini (Google Gemini CLI)', models: [''], efforts: [] },
12
+ };
package/src/pair.js ADDED
@@ -0,0 +1,53 @@
1
+ // Connecting to your account with a click in the browser, instead of a copied token.
2
+ // The bridge makes a token here and sends the site only its SHA-256, getting a short code back. You open the site's
3
+ // Account page with that code, signed in, and click Connect: the site then accepts the token this machine is holding.
4
+ // The token itself is not sent until the site says the link was approved.
5
+ import { createHash, randomBytes } from 'node:crypto';
6
+ import { spawn } from 'node:child_process';
7
+
8
+ const CODE_RE = /^[A-Z2-9]{4}-[A-Z2-9]{4}$/;
9
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
10
+
11
+ /**
12
+ * Ask the site for a code. Resolves with {token, code, url, expiresIn (seconds)}. An Error with `.status` means the
13
+ * site answered but can't do this (an older site, or too many waiting); without, it couldn't be reached.
14
+ * @param {string} base the site's address, from serverBase()
15
+ */
16
+ export async function startPairing(base) {
17
+ const token = `clk_bridge_${randomBytes(24).toString('base64url')}`;
18
+ const tokenHash = createHash('sha256').update(token).digest('hex');
19
+ const r = await fetch(`${base}/api/bridge/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tokenHash }) });
20
+ const j = await r.json().catch(() => ({}));
21
+ if (!r.ok) throw Object.assign(new Error(typeof j.error === 'string' ? j.error : `the site answered ${r.status}`), { status: r.status });
22
+ // the code goes into a link that is opened in a browser: only a code, nothing else the site might send
23
+ if (!CODE_RE.test(j.code)) throw Object.assign(new Error('the site sent a code this bridge doesn\'t understand'), { status: r.status });
24
+ return { token, code: j.code, url: `${base}/account.html#pair=${j.code}`, expiresIn: Math.max(30, Math.min(Number(j.expiresIn) || 600, 3600)) };
25
+ }
26
+
27
+ /** Wait for the click. Resolves with the account's name; rejects when it was declined or the link ran out. */
28
+ export async function waitForApproval(base, { token, expiresIn }, { every = 2000 } = {}) {
29
+ const until = Date.now() + expiresIn * 1000;
30
+ for (let n = 0; Date.now() < until; n++) {
31
+ await sleep(n < 60 ? every : every * 2.5); // every 2 s for two minutes, then every 5 s
32
+ let r;
33
+ try { r = await fetch(`${base}/api/bridge/whoami`, { headers: { Authorization: `Bearer ${token}` } }); } catch { continue; } // offline for a moment
34
+ const j = await r.json().catch(() => ({}));
35
+ if (r.ok) return String(j.name || '');
36
+ if (r.status === 401 && j.pairing !== 'pending') throw new Error('it was declined on the site, or the link ran out');
37
+ }
38
+ throw new Error('the link ran out before anyone clicked Connect');
39
+ }
40
+
41
+ /** Open the link in this machine's browser, if it has one. Fails silently: the link is printed too. */
42
+ export function openBrowser(url, { platform = process.platform, env = process.env } = {}) {
43
+ if (platform !== 'darwin' && platform !== 'win32' && !env.DISPLAY && !env.WAYLAND_DISPLAY) return false; // no desktop (ssh, a server)
44
+ const [cmd, args] = platform === 'darwin' ? ['open', [url]]
45
+ : platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
46
+ : ['xdg-open', [url]];
47
+ try {
48
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true }); // no shell: the link is one argument
49
+ child.on('error', () => {});
50
+ child.unref();
51
+ return true;
52
+ } catch { return false; }
53
+ }
package/src/reap.js ADDED
@@ -0,0 +1,63 @@
1
+ // Kill everything an agent CLI left behind. Killing only the direct child is not enough: CLIs like
2
+ // Codex run tool commands through a sandbox helper, and those grandchildren get reparented to init
3
+ // and keep running (one burned a core for hours). Linux-only lookups via /proc; elsewhere we fall
4
+ // back to the process group.
5
+ import { readdirSync, readFileSync, readlinkSync } from 'node:fs';
6
+
7
+ /** Snapshot of all processes we can see: pid, parent, process group, start time (for identity), cwd. */
8
+ function listProcs() {
9
+ const out = [];
10
+ let names;
11
+ try { names = readdirSync('/proc'); } catch { return null; }
12
+ for (const name of names) {
13
+ if (!/^\d+$/.test(name)) continue;
14
+ try {
15
+ const stat = readFileSync(`/proc/${name}/stat`, 'utf8');
16
+ // Fields after "(comm) ": state ppid pgrp ... ; starttime is field 22 overall.
17
+ const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
18
+ let cwd = null;
19
+ try { cwd = readlinkSync(`/proc/${name}/cwd`).replace(/ \(deleted\)$/, ''); } catch {}
20
+ out.push({ pid: +name, ppid: +f[1], pgid: +f[2], start: f[19], cwd });
21
+ } catch { /* exited while we looked, or not ours */ }
22
+ }
23
+ return out;
24
+ }
25
+
26
+ const send = (pid, sig) => { try { process.kill(pid, sig); } catch {} };
27
+
28
+ /**
29
+ * Terminate the process tree of an agent run: the group led by `pid`, all descendants, and any
30
+ * process whose cwd is inside `dir` (catches orphans that escaped the group). SIGTERM first, then
31
+ * SIGKILL after `graceMs` for anything still alive. Pass signal 'SIGKILL' to skip the grace period.
32
+ * Returns the pids that were signalled.
33
+ */
34
+ export function reapTree({ pid, dir, signal = 'SIGTERM', graceMs = 3000 }) {
35
+ const procs = listProcs();
36
+ if (!procs) { // no /proc: best effort via the process group
37
+ if (pid) send(-pid, signal);
38
+ return [];
39
+ }
40
+ const children = new Map();
41
+ for (const p of procs) {
42
+ if (!children.has(p.ppid)) children.set(p.ppid, []);
43
+ children.get(p.ppid).push(p);
44
+ }
45
+ const targets = new Map();
46
+ const add = (p) => {
47
+ if (p.pid === process.pid || targets.has(p.pid)) return;
48
+ targets.set(p.pid, p);
49
+ for (const c of children.get(p.pid) || []) add(c);
50
+ };
51
+ const inDir = (cwd) => dir && cwd && (cwd === dir || cwd.startsWith(dir + '/'));
52
+ for (const p of procs) if ((pid && (p.pid === pid || p.pgid === pid)) || inDir(p.cwd)) add(p);
53
+
54
+ for (const p of targets.values()) send(p.pid, signal);
55
+ if (signal !== 'SIGKILL' && targets.size) {
56
+ setTimeout(() => {
57
+ const alive = new Map((listProcs() || []).map((p) => [p.pid, p]));
58
+ // Same pid AND same start time, so we never hit a recycled pid.
59
+ for (const p of targets.values()) if (alive.get(p.pid)?.start === p.start) send(p.pid, 'SIGKILL');
60
+ }, graceMs).unref();
61
+ }
62
+ return [...targets.keys()];
63
+ }
package/src/saved.js ADDED
@@ -0,0 +1,50 @@
1
+ // The site and token the bridge was given, remembered between runs so it asks only once: one small JSON file in your
2
+ // config folder that only your user can read. Also the question itself, asked in the terminal the first time.
3
+ import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { createInterface } from 'node:readline';
7
+ import { Writable } from 'node:stream';
8
+
9
+ /** Where it is kept: ~/.config/clankoff-bridge/config.json (XDG_CONFIG_HOME if set; %APPDATA% on Windows). */
10
+ export function savedPath(env = process.env) {
11
+ const dir = env.XDG_CONFIG_HOME || (process.platform === 'win32' && env.APPDATA) || join(homedir(), '.config');
12
+ return join(dir, 'clankoff-bridge', 'config.json');
13
+ }
14
+
15
+ /** What was saved, or null (no file, or not one of ours). */
16
+ export function readSaved(path = savedPath()) {
17
+ try {
18
+ const { server, token } = JSON.parse(readFileSync(path, 'utf8'));
19
+ return typeof server === 'string' && typeof token === 'string' ? { server, token } : null;
20
+ } catch { return null; }
21
+ }
22
+
23
+ export function save({ server, token }, path = savedPath()) {
24
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
25
+ writeFileSync(path, `${JSON.stringify({ server, token }, null, 2)}\n`, { mode: 0o600 });
26
+ chmodSync(path, 0o600); // the mode above only counts for a new file
27
+ }
28
+
29
+ export function forget(path = savedPath()) {
30
+ rmSync(path, { force: true });
31
+ }
32
+
33
+ /** A pasted token, tidied: spaces and quotes off, and the `CLANKOFF_BRIDGE_TOKEN=` in front if a whole .env line was pasted. */
34
+ export function cleanToken(text) {
35
+ return String(text || '').trim().replace(/^CLANKOFF_BRIDGE_TOKEN\s*=\s*/, '').replace(/^["']|["']$/g, '').trim();
36
+ }
37
+ export const looksLikeToken = (token) => /^clk_bridge_[\w-]+$/.test(token);
38
+
39
+ /** Ask for the token in the terminal. What is typed or pasted isn't shown, so it stays out of the scrollback. */
40
+ export function askToken(question) {
41
+ return new Promise((resolve) => {
42
+ let hide = false;
43
+ const output = new Writable({ write(chunk, enc, done) { if (!hide) process.stdout.write(chunk, enc); done(); } });
44
+ const rl = createInterface({ input: process.stdin, output, terminal: true });
45
+ rl.on('SIGINT', () => { process.stdout.write('\n'); process.exit(130); });
46
+ rl.on('close', () => resolve('')); // Ctrl-D; after an answer this does nothing
47
+ rl.question(question, (answer) => { process.stdout.write('\n'); resolve(cleanToken(answer)); rl.close(); });
48
+ hide = true; // the question is written; nothing after it is
49
+ });
50
+ }