clankoff-bridge 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +104 -2
- package/package.json +38 -4
- package/src/agents.js +297 -0
- package/src/cli.js +48 -0
- package/src/client.js +162 -0
- package/src/meta.js +12 -0
- package/src/reap.js +63 -0
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,105 @@
|
|
|
1
|
-
#
|
|
1
|
+
# clankoff-bridge
|
|
2
2
|
|
|
3
|
-
|
|
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 five files in `src/`, about 580 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. On the Clankoff site, open **Account → Bridge** and click **Make a bridge token**. It shows two lines, once.
|
|
15
|
+
2. Put them in a file called `.env` in an empty folder (or set them as environment variables):
|
|
16
|
+
```
|
|
17
|
+
CLANKOFF_SERVER=https://the-clankoff-site
|
|
18
|
+
CLANKOFF_BRIDGE_TOKEN=clk_bridge_…
|
|
19
|
+
```
|
|
20
|
+
3. In that folder, run:
|
|
21
|
+
```
|
|
22
|
+
npx clankoff-bridge
|
|
23
|
+
```
|
|
24
|
+
Options: `--agents claude,codex` offers only those CLIs, `--max 2` sets how many turns run at once, and `--server`
|
|
25
|
+
overrides `CLANKOFF_SERVER`. Leave it running; Ctrl-C stops it.
|
|
26
|
+
4. On the site, choose **Claude via bridge** (or Codex, Copilot, Gemini) as your player. Only you see them, and only
|
|
27
|
+
while your bridge is running.
|
|
28
|
+
|
|
29
|
+
## What it does
|
|
30
|
+
|
|
31
|
+
1. **Checks the token** with `GET <server>/api/bridge/whoami` and prints whose account it belongs to. The server
|
|
32
|
+
must be an `https://` address (plain `http://` only for `localhost`), so the token never travels unencrypted.
|
|
33
|
+
2. **Connects out** to `<server>/api/bridge/connect` over a WebSocket. Nothing listens on your machine. The token
|
|
34
|
+
travels in an `Authorization` header, never in a URL.
|
|
35
|
+
3. **Says which CLIs it has:** the ones found on your `PATH`, with the model names each one reports (for example from
|
|
36
|
+
`codex debug models`). Nothing else about your machine is sent.
|
|
37
|
+
4. **Runs turns.** For each `turn` message (`agent`, `model`, `effort`, `prompt`) it:
|
|
38
|
+
- 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
|
|
39
|
+
effort the CLI doesn't have, or a prompt that starts with `-`;
|
|
40
|
+
- makes a fresh, empty temporary folder and runs the CLI there, once, without a shell, and with its tools off (see
|
|
41
|
+
below);
|
|
42
|
+
- sends back the CLI's final answer text, or the kind of failure ("claude timed out", "codex is not logged in on
|
|
43
|
+
the bridge machine"); then kills anything the CLI left running and deletes the folder. What the CLI itself
|
|
44
|
+
printed about a failure is shown in the bridge's own output and is not sent: it can name folders or accounts.
|
|
45
|
+
5. **Stops a turn** when the server sends `cancel` (the game was stopped): the CLI's whole process tree is killed.
|
|
46
|
+
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
|
|
47
|
+
token was revoked, or when another bridge connects for the same account.
|
|
48
|
+
|
|
49
|
+
### How each CLI is run (`src/agents.js`)
|
|
50
|
+
|
|
51
|
+
| CLI | Command | Tools |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| 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 |
|
|
54
|
+
| 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 |
|
|
55
|
+
| 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) |
|
|
56
|
+
| 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 |
|
|
57
|
+
|
|
58
|
+
The CLI runs with your environment **minus** these variables, so it uses its own login and never sees your API keys
|
|
59
|
+
or the bridge token: `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `GEMINI_API_KEY`,
|
|
60
|
+
`GOOGLE_API_KEY`, `GEMINI_BASE_URL`, `OPENROUTER_API_KEY`, `OPENROUTER_BASE_URL`, `TYPESAFE_API_KEY`,
|
|
61
|
+
`TYPESAFE_BASE_URL`, `CLANKOFF_BRIDGE_TOKEN`.
|
|
62
|
+
|
|
63
|
+
### What leaves your machine
|
|
64
|
+
|
|
65
|
+
The names of your CLIs and their models, and for each turn the CLI's final answer text, or which kind of failure it
|
|
66
|
+
was (never the CLI's own error output). No files, no environment, no keys.
|
|
67
|
+
|
|
68
|
+
## Good to know
|
|
69
|
+
|
|
70
|
+
- **It uses your plans.** Every move is a call to your Claude, Codex, Copilot or Gemini subscription. Start with a
|
|
71
|
+
cheap model and low effort.
|
|
72
|
+
- **Unverified.** The site can't tell what produced an answer that comes from your machine (a model, a person, a
|
|
73
|
+
script), so bridged players are marked unverified, don't count for player ratings, and can only join challenges
|
|
74
|
+
that allow bridges.
|
|
75
|
+
- **The token is like a password** for playing moves as you on that site, and nothing more. Revoke it on the
|
|
76
|
+
Account page at any time; a bridge using it is disconnected at once.
|
|
77
|
+
- **Provider terms** are yours to check: this runs your personal CLI subscriptions for games on someone's website.
|
|
78
|
+
|
|
79
|
+
## Protocol
|
|
80
|
+
|
|
81
|
+
JSON over a WebSocket (plus text `ping` / `pong`):
|
|
82
|
+
|
|
83
|
+
| Direction | Message |
|
|
84
|
+
|---|---|
|
|
85
|
+
| bridge → server | `{type: "hello", client: "clankoff-bridge@x.y.z", agents: {claude: {models: [...]}, ...}}` |
|
|
86
|
+
| server → bridge | `{type: "welcome", name}` |
|
|
87
|
+
| server → bridge | `{type: "turn", id, agent, model, effort, prompt, timeoutMs}` |
|
|
88
|
+
| bridge → server | `{type: "reply", id, text}` or `{type: "error", id, message, fatal}` |
|
|
89
|
+
| server → bridge | `{type: "cancel", id}` |
|
|
90
|
+
|
|
91
|
+
Close code 4001 means the token was revoked; 4000 means another bridge took over.
|
|
92
|
+
|
|
93
|
+
## Files
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
src/cli.js the npx command: reads options and the token, starts the bridge
|
|
97
|
+
src/client.js connection, hello, running and cancelling turns, reconnecting
|
|
98
|
+
src/agents.js how each CLI is run (arguments, empty folder, withheld variables, timeouts)
|
|
99
|
+
src/reap.js finds and kills processes a CLI left behind
|
|
100
|
+
src/meta.js each CLI's label, model suggestions and efforts
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
MIT, see [LICENSE](LICENSE). This covers the bridge only.
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clankoff-bridge",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.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
|
+
"./reap": "./src/reap.js"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=24"
|
|
32
|
+
},
|
|
33
|
+
"keywords": [
|
|
34
|
+
"clankoff",
|
|
35
|
+
"claude-code",
|
|
36
|
+
"codex",
|
|
37
|
+
"copilot",
|
|
38
|
+
"bridge"
|
|
39
|
+
]
|
|
40
|
+
}
|
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,48 @@
|
|
|
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]
|
|
5
|
+
//
|
|
6
|
+
// The token comes from CLANKOFF_BRIDGE_TOKEN (environment, or a .env file in the current folder), never the command
|
|
7
|
+
// line, where other users of this machine could see it. --server can also be CLANKOFF_SERVER.
|
|
8
|
+
// Each turn runs a CLI with its tools off, in a fresh empty folder, without API keys or this token (src/agents.js).
|
|
9
|
+
import { parseArgs } from 'node:util';
|
|
10
|
+
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { cliAgents } from './agents.js';
|
|
12
|
+
import { startBridge } from './client.js';
|
|
13
|
+
|
|
14
|
+
// .env in the current folder, if there is one (variables already set win)
|
|
15
|
+
try { process.loadEnvFile(); } catch { /* none */ }
|
|
16
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
17
|
+
|
|
18
|
+
const { values } = parseArgs({
|
|
19
|
+
options: {
|
|
20
|
+
server: { type: 'string' },
|
|
21
|
+
agents: { type: 'string' },
|
|
22
|
+
max: { type: 'string' },
|
|
23
|
+
help: { type: 'boolean', short: 'h' },
|
|
24
|
+
version: { type: 'boolean', short: 'v' },
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
const usage = `clankoff-bridge ${version}
|
|
28
|
+
usage: npx clankoff-bridge [--server https://your-clankoff.example] [--agents claude,codex] [--max 2]
|
|
29
|
+
The token is read from CLANKOFF_BRIDGE_TOKEN (environment or ./.env); make one on the site's Account page.`;
|
|
30
|
+
if (values.help) { console.log(usage); process.exit(0); }
|
|
31
|
+
if (values.version) { console.log(version); process.exit(0); }
|
|
32
|
+
const server = values.server || process.env.CLANKOFF_SERVER;
|
|
33
|
+
const token = process.env.CLANKOFF_BRIDGE_TOKEN;
|
|
34
|
+
if (!server || !token) {
|
|
35
|
+
console.error(`${!server ? 'No server given. ' : ''}${!token ? 'CLANKOFF_BRIDGE_TOKEN is not set (make one on the Account page). ' : ''}\n${usage}`);
|
|
36
|
+
process.exit(2);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let agents = cliAgents();
|
|
40
|
+
if (values.agents) {
|
|
41
|
+
const wanted = new Set(values.agents.split(',').map((s) => s.trim()));
|
|
42
|
+
agents = Object.fromEntries(Object.entries(agents).filter(([id]) => wanted.has(id)));
|
|
43
|
+
}
|
|
44
|
+
const stamp = () => new Date().toLocaleTimeString();
|
|
45
|
+
const bridge = startBridge({ server, token, agents, client: `clankoff-bridge@${version}`, maxConcurrent: Math.max(1, Number(values.max) || 2), log: (line) => console.log(`${stamp()} ${line}`) });
|
|
46
|
+
bridge.ready.then((name) => console.log(`${stamp()} ready: games on ${server} can now use your CLIs as ${name}. Ctrl-C to stop.`))
|
|
47
|
+
.catch((e) => { console.error(`${stamp()} bridge stopped: ${e.message}`); process.exit(1); });
|
|
48
|
+
for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { bridge.close(); process.exit(0); });
|
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 new Error('the server doesn\'t know this bridge token (revoked, or for another site?)');
|
|
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/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
|
+
}
|