@ulm0/gonogo 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -2
  3. package/bin/gonogo.js +18 -0
  4. package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
  7. package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  8. package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  9. package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  10. package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  11. package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
  12. package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
  13. package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  18. package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  19. package/dist/client/assets/index-B6MsSoeo.css +1 -0
  20. package/dist/client/assets/index-DRtiRh1Y.js +31 -0
  21. package/dist/client/favicon.ico +0 -0
  22. package/dist/client/favicon.svg +1 -0
  23. package/dist/client/index.html +19 -0
  24. package/dist/server/cleanroom.js +214 -0
  25. package/dist/server/cli.js +630 -0
  26. package/dist/server/command.js +44 -0
  27. package/dist/server/constants.js +427 -0
  28. package/dist/server/docking.js +541 -0
  29. package/dist/server/downlink.js +191 -0
  30. package/dist/server/home.js +497 -0
  31. package/dist/server/hooks.js +166 -0
  32. package/dist/server/hub.js +2484 -0
  33. package/dist/server/launcher.js +542 -0
  34. package/dist/server/livery.js +210 -0
  35. package/dist/server/logsearch.js +112 -0
  36. package/dist/server/mcp.js +196 -0
  37. package/dist/server/migrate.js +119 -0
  38. package/dist/server/missionlog.js +209 -0
  39. package/dist/server/payload.js +168 -0
  40. package/dist/server/propellant.js +314 -0
  41. package/dist/server/providers.js +137 -0
  42. package/dist/server/relay.js +300 -0
  43. package/dist/server/relaykinds.js +182 -0
  44. package/dist/server/schedules.js +277 -0
  45. package/dist/server/tasks.js +272 -0
  46. package/dist/server/terminal.js +635 -0
  47. package/dist/server/uplinks.js +356 -0
  48. package/dist/server/web.js +1466 -0
  49. package/dist/shared/cron.js +149 -0
  50. package/dist/shared/fuel.js +18 -0
  51. package/dist/shared/livery.js +348 -0
  52. package/dist/shared/positions.js +132 -0
  53. package/dist/shared/protocol.js +212 -0
  54. package/package.json +84 -3
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Propellant: token use per agent and for the room, read from Claude Code's own transcripts, kept in a ledger, checked
3
+ * against the Director's limits over rolling windows (docs/redline-propellant-spec.md).
4
+ *
5
+ * A transcript is JSON lines; an assistant line carries `message.usage`, and one reply is written as several lines (one
6
+ * per content block) that repeat the same `message.id` and the same usage, so only the first line of an id counts.
7
+ * Tokens = input + cache creation + output. Cache reads are left out: in a long session they dwarf the rest and would
8
+ * make every limit meaningless.
9
+ *
10
+ * shortcut: subagent (Task tool) transcripts are other files and are not counted; read them too if that spend matters.
11
+ * shortcut: the ledger and the limits are keyed by agent name, so a rename starts from zero; key by record id if renames get common.
12
+ */
13
+ import { appendFile, open, readFile, realpath, rename, writeFile } from 'node:fs/promises';
14
+ import { join, sep } from 'node:path';
15
+ import { randomBytes } from 'node:crypto';
16
+ import { AGENT_NAME_PATTERN, FUEL_WINDOWS } from '../shared/protocol.js';
17
+ import { tokenText } from '../shared/fuel.js';
18
+ import { FILE_MODE, FUEL_KEEP_MS, FUEL_LIMIT_MAX, METER_READ_MAX_BYTES, PROPELLANT_FILE as LIMITS_FILE } from './constants.js';
19
+ const HOUR = 3_600_000;
20
+ export const WINDOW_MS = { '5h': 5 * HOUR, day: 24 * HOUR, week: 7 * 24 * HOUR, month: 30 * 24 * HOUR };
21
+ const LEDGER_FILE = 'fuel.jsonl';
22
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
23
+ function isRecord(value) {
24
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
25
+ }
26
+ /** The tokens of one transcript line and its message id, or null for a line without usage. */
27
+ export function lineUsage(line) {
28
+ let value;
29
+ try {
30
+ value = JSON.parse(line);
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ if (!isRecord(value) || !isRecord(value.message) || !isRecord(value.message.usage))
36
+ return null;
37
+ const usage = value.message.usage;
38
+ const id = typeof value.message.id === 'string' ? value.message.id : typeof value.requestId === 'string' ? value.requestId : '';
39
+ if (id === '')
40
+ return null;
41
+ const n = (key) => {
42
+ const v = usage[key];
43
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0;
44
+ };
45
+ const at = typeof value.timestamp === 'string' ? Date.parse(value.timestamp) : NaN;
46
+ return { id, at: Number.isFinite(at) ? at : null, tokens: n('input_tokens') + n('cache_creation_input_tokens') + n('output_tokens') };
47
+ }
48
+ /** Limits from untrusted JSON: whole numbers from 1 to FUEL_LIMIT_MAX per known window; anything else is refused. */
49
+ export function parseLimits(value, what) {
50
+ if (!isRecord(value))
51
+ return `${what} must be an object of windows (${FUEL_WINDOWS.join(', ')})`;
52
+ const limits = {};
53
+ for (const [key, v] of Object.entries(value)) {
54
+ if (!FUEL_WINDOWS.includes(key))
55
+ return `${what}: unknown window "${key}"`;
56
+ if (v === null)
57
+ continue;
58
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 1 || v > FUEL_LIMIT_MAX) {
59
+ return `${what}.${key} must be a whole number of tokens from 1 to ${FUEL_LIMIT_MAX}, or null`;
60
+ }
61
+ limits[key] = v;
62
+ }
63
+ return limits;
64
+ }
65
+ export function parsePropellantRequest(body) {
66
+ const value = {};
67
+ for (const key of Object.keys(body)) {
68
+ if (key !== 'room' && key !== 'agents')
69
+ return { ok: false, error: `unknown field "${key}"`, field: key };
70
+ }
71
+ if (body.room !== undefined) {
72
+ const room = parseLimits(body.room, 'room');
73
+ if (typeof room === 'string')
74
+ return { ok: false, error: room, field: 'room' };
75
+ value.room = room;
76
+ }
77
+ if (body.agents !== undefined) {
78
+ if (!isRecord(body.agents))
79
+ return { ok: false, error: 'agents must be an object of agent names', field: 'agents' };
80
+ value.agents = {};
81
+ for (const [name, raw] of Object.entries(body.agents)) {
82
+ if (!NAME_RE.test(name))
83
+ return { ok: false, error: `agents: invalid name "${name}"`, field: 'agents' };
84
+ const limits = parseLimits(raw, `agents.${name}`);
85
+ if (typeof limits === 'string')
86
+ return { ok: false, error: limits, field: 'agents' };
87
+ value.agents[name] = limits;
88
+ }
89
+ }
90
+ return { ok: true, value };
91
+ }
92
+ export { tokenText };
93
+ export function createPropellant(options) {
94
+ const { dir, now, log } = options;
95
+ const ledgerPath = join(dir, LEDGER_FILE);
96
+ const limitsPath = join(dir, LIMITS_FILE);
97
+ let entries = [];
98
+ let saved = { room: {}, agents: {}, cursors: {} };
99
+ /** The last message id counted per transcript: the repeated lines of one reply follow each other. */
100
+ const lastId = new Map();
101
+ /** One read per transcript at a time, and the ledger and limits file written in order. */
102
+ const reading = new Map();
103
+ let chain = Promise.resolve();
104
+ let projectsReal = null;
105
+ const later = (fn) => {
106
+ const run = chain.then(fn);
107
+ chain = run.catch((error) => log.error('propellant could not write', error));
108
+ return run.then(() => undefined);
109
+ };
110
+ const saveLimits = () => {
111
+ // a file from before it had a version has none and reads as version 1 (src/server/migrate.ts)
112
+ const json = JSON.stringify({ version: 1, ...saved }, null, 2);
113
+ return later(async () => {
114
+ const tmp = join(dir, `.${LIMITS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
115
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
116
+ await rename(tmp, limitsPath);
117
+ });
118
+ };
119
+ const prune = () => {
120
+ const cut = now() - FUEL_KEEP_MS;
121
+ const before = entries.length;
122
+ entries = entries.filter((e) => e.at >= cut);
123
+ return entries.length !== before;
124
+ };
125
+ const gauge = (agent, limits) => {
126
+ const t = now();
127
+ const used = { '5h': 0, day: 0, week: 0, month: 0 };
128
+ for (const e of entries) {
129
+ if (agent !== null && e.agent !== agent)
130
+ continue;
131
+ for (const w of FUEL_WINDOWS)
132
+ if (t - e.at < WINDOW_MS[w])
133
+ used[w] += e.tokens;
134
+ }
135
+ return { used, limits: { ...limits } };
136
+ };
137
+ const firstOver = (g) => {
138
+ for (const w of FUEL_WINDOWS) {
139
+ const limit = g.limits[w];
140
+ if (limit !== undefined && g.used[w] >= limit)
141
+ return w;
142
+ }
143
+ return null;
144
+ };
145
+ const inside = async (path) => {
146
+ projectsReal ??= await realpath(options.projectsRoot).catch(() => null);
147
+ if (projectsReal === null || !path.endsWith('.jsonl'))
148
+ return null;
149
+ const real = await realpath(path).catch(() => null);
150
+ return real !== null && real.startsWith(projectsReal + sep) ? real : null;
151
+ };
152
+ const readNew = async (agent, transcriptPath) => {
153
+ const path = await inside(transcriptPath);
154
+ if (path === null) {
155
+ log.debug(`propellant ignored a transcript outside ${options.projectsRoot}`);
156
+ return 0;
157
+ }
158
+ const handle = await open(path, 'r');
159
+ let tokens = 0;
160
+ try {
161
+ const size = (await handle.stat()).size;
162
+ let offset = saved.cursors[path] ?? 0;
163
+ if (offset > size)
164
+ offset = 0; // the file was replaced: count it again from the start
165
+ const length = Math.min(size - offset, METER_READ_MAX_BYTES);
166
+ if (length <= 0)
167
+ return 0;
168
+ const buffer = Buffer.alloc(length);
169
+ const { bytesRead } = await handle.read(buffer, 0, length, offset);
170
+ const end = buffer.subarray(0, bytesRead).lastIndexOf(0x0a);
171
+ if (end < 0)
172
+ return 0; // no complete line yet
173
+ const fresh = [];
174
+ for (const line of buffer.subarray(0, end).toString('utf8').split('\n')) {
175
+ const usage = lineUsage(line);
176
+ if (usage === null || usage.id === lastId.get(path))
177
+ continue;
178
+ lastId.set(path, usage.id);
179
+ if (usage.tokens === 0)
180
+ continue;
181
+ const at = usage.at ?? now();
182
+ // one ledger line per minute and agent keeps the file small
183
+ const last = fresh[fresh.length - 1];
184
+ if (last && Math.floor(last.at / 60_000) === Math.floor(at / 60_000))
185
+ last.tokens += usage.tokens;
186
+ else
187
+ fresh.push({ at, agent, tokens: usage.tokens });
188
+ tokens += usage.tokens;
189
+ }
190
+ saved.cursors[path] = offset + end + 1;
191
+ const cut = now() - FUEL_KEEP_MS;
192
+ const kept = fresh.filter((e) => e.at >= cut);
193
+ entries.push(...kept);
194
+ if (kept.length > 0) {
195
+ const text = kept.map((e) => JSON.stringify(e)).join('\n') + '\n';
196
+ await later(() => appendFile(ledgerPath, text, { mode: FILE_MODE }));
197
+ }
198
+ await saveLimits();
199
+ }
200
+ finally {
201
+ await handle.close();
202
+ }
203
+ return tokens;
204
+ };
205
+ const view = () => {
206
+ prune();
207
+ const agents = {};
208
+ const names = new Set([...entries.map((e) => e.agent), ...Object.keys(saved.agents)]);
209
+ for (const name of [...names].sort())
210
+ agents[name] = gauge(name, saved.agents[name] ?? {});
211
+ return { room: gauge(null, saved.room), agents };
212
+ };
213
+ return {
214
+ async load() {
215
+ try {
216
+ const data = JSON.parse(await readFile(limitsPath, 'utf8'));
217
+ if (isRecord(data)) {
218
+ const room = parseLimits(data.room ?? {}, 'room');
219
+ if (typeof room !== 'string')
220
+ saved.room = room;
221
+ if (isRecord(data.agents)) {
222
+ for (const [name, raw] of Object.entries(data.agents)) {
223
+ const limits = parseLimits(raw, name);
224
+ if (NAME_RE.test(name) && typeof limits !== 'string')
225
+ saved.agents[name] = limits;
226
+ }
227
+ }
228
+ if (isRecord(data.cursors)) {
229
+ for (const [path, n] of Object.entries(data.cursors)) {
230
+ if (typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)
231
+ saved.cursors[path] = n;
232
+ }
233
+ }
234
+ }
235
+ }
236
+ catch (error) {
237
+ if (error.code !== 'ENOENT')
238
+ log.warn(`${LIMITS_FILE} could not be read; limits start empty`, error);
239
+ }
240
+ let text = '';
241
+ try {
242
+ text = await readFile(ledgerPath, 'utf8');
243
+ }
244
+ catch (error) {
245
+ if (error.code !== 'ENOENT')
246
+ log.warn(`${LEDGER_FILE} could not be read; token use starts at 0`, error);
247
+ }
248
+ for (const line of text.split('\n')) {
249
+ if (line === '')
250
+ continue;
251
+ try {
252
+ const e = JSON.parse(line);
253
+ if (isRecord(e) && typeof e.at === 'number' && typeof e.agent === 'string' && typeof e.tokens === 'number' && e.tokens > 0) {
254
+ entries.push({ at: e.at, agent: e.agent, tokens: e.tokens });
255
+ }
256
+ }
257
+ catch {
258
+ // a torn last line after a crash: skipped
259
+ }
260
+ }
261
+ if (prune()) {
262
+ const kept = entries.map((e) => JSON.stringify(e)).join('\n');
263
+ await later(() => writeFile(ledgerPath, kept === '' ? '' : kept + '\n', { mode: FILE_MODE }));
264
+ }
265
+ },
266
+ record(agent, transcriptPath) {
267
+ const previous = reading.get(transcriptPath) ?? Promise.resolve(0);
268
+ const run = previous
269
+ .catch(() => 0)
270
+ .then(() => readNew(agent, transcriptPath))
271
+ .catch((error) => {
272
+ log.warn(`propellant could not read the transcript of ${agent}`, error);
273
+ return 0;
274
+ });
275
+ reading.set(transcriptPath, run);
276
+ void run.then(() => {
277
+ if (reading.get(transcriptPath) === run)
278
+ reading.delete(transcriptPath);
279
+ });
280
+ return run;
281
+ },
282
+ view,
283
+ async setLimits(request) {
284
+ if (request.room !== undefined)
285
+ saved.room = { ...request.room };
286
+ for (const [name, limits] of Object.entries(request.agents ?? {})) {
287
+ if (Object.keys(limits).length === 0)
288
+ delete saved.agents[name];
289
+ else
290
+ saved.agents[name] = { ...limits };
291
+ }
292
+ await saveLimits();
293
+ return view();
294
+ },
295
+ over(agent) {
296
+ const own = gauge(agent, saved.agents[agent] ?? {});
297
+ const ownWindow = firstOver(own);
298
+ if (ownWindow !== null) {
299
+ const limit = own.limits[ownWindow] ?? 0;
300
+ return { scope: 'agent', reason: `out of propellant: ${tokenText(own.used[ownWindow])} of ${tokenText(limit)} tokens in ${ownWindow}` };
301
+ }
302
+ const room = gauge(null, saved.room);
303
+ const roomWindow = firstOver(room);
304
+ if (roomWindow !== null) {
305
+ const limit = room.limits[roomWindow] ?? 0;
306
+ return { scope: 'room', reason: `room out of propellant: ${tokenText(room.used[roomWindow])} of ${tokenText(limit)} tokens in ${roomWindow}` };
307
+ }
308
+ return null;
309
+ },
310
+ close() {
311
+ return chain.then(() => undefined);
312
+ },
313
+ };
314
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Engine Bay (docs/engine-bay-spec.md): how each agent CLI other than Claude Code and the custom command is started.
3
+ * Claude Code stays in launcher.ts as it was. An adapter names the arguments, the extra environment and the files it
4
+ * needs in the agent's own folder; what the hub does with the CLI (hooks or output activity, mail or none) is
5
+ * PROVIDER_INFO in protocol.ts. Nothing here touches the owner's project or the CLI's own home folder.
6
+ */
7
+ import { accessSync, constants as fsConstants, statSync } from 'node:fs';
8
+ import { delimiter, join } from 'node:path';
9
+ import { MCP_SERVER_NAME, PROVIDER_INFO, PROVIDERS } from '../shared/protocol.js';
10
+ import { HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_PATH } from './constants.js';
11
+ /** Gemini CLI hook event to the hub's own hook event: the hub handles both CLIs with one set of rules. */
12
+ export const GEMINI_HOOKS = {
13
+ BeforeAgent: 'UserPromptSubmit',
14
+ BeforeTool: 'PreToolUse',
15
+ AfterTool: 'PostToolUse',
16
+ Notification: 'Notification',
17
+ AfterAgent: 'Stop',
18
+ };
19
+ export const GEMINI_SETTINGS_FILE = 'gemini-settings.json';
20
+ // shortcut: 'auto' is Claude Code's own classifier; the other CLIs have none, so it maps to their nearest mode (edits run, the rest asks). Give them their own mode if they ever ship one.
21
+ const GEMINI_MODES = { default: 'default', acceptEdits: 'auto_edit', auto: 'auto_edit', bypassPermissions: 'yolo' };
22
+ const CODEX_MODES = {
23
+ default: [],
24
+ acceptEdits: ['--full-auto'],
25
+ auto: ['--full-auto'],
26
+ bypassPermissions: ['--dangerously-bypass-approvals-and-sandbox'],
27
+ };
28
+ /**
29
+ * Gemini CLI runs only command hooks, so each one runs this with `node -e`: it reads the hook input from stdin, forwards
30
+ * the fields the hub reads to the hook URL with the token from the token file, and prints the hub's answer (a Stop
31
+ * block becomes Gemini's AfterAgent block). The transcript path is not forwarded: Propellant reads only Claude's.
32
+ * Any failure prints `{}`, which lets Gemini go on. No single quote inside: it is passed in single quotes.
33
+ */
34
+ export const HOOK_SHIM = [
35
+ 'let d="";process.stdin.on("data",c=>d+=c).on("end",async()=>{try{',
36
+ 'const i=JSON.parse(d||"{}"),b={};',
37
+ 'for(const k of ["prompt","tool_name","tool_input","notification_type","message"])if(i[k]!==undefined)b[k]=i[k];',
38
+ 'const t=require("fs").readFileSync(process.argv[2],"utf8").trim();',
39
+ 'const r=await fetch(process.argv[1],{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t},',
40
+ `body:JSON.stringify(b),signal:AbortSignal.timeout(${HOOK_TIMEOUT_S * 1000})});`,
41
+ 'process.stdout.write(r.ok?await r.text():"{}")}catch{process.stdout.write("{}")}})',
42
+ ].join('');
43
+ /** One shell word: Gemini runs a hook command through the shell. */
44
+ export const shellQuote = (word) => `'${word.replace(/'/g, `'\\''`)}'`;
45
+ export function buildGeminiSettings(ctx, node = process.execPath) {
46
+ const hooks = {};
47
+ for (const [event, ours] of Object.entries(GEMINI_HOOKS)) {
48
+ const url = `${ctx.hubUrl}${HOOK_PATH_PREFIX}${ctx.name}/${ours}`;
49
+ const command = [node, '-e', HOOK_SHIM, url, ctx.tokenFile].map(shellQuote).join(' ');
50
+ // Gemini's timeout is in milliseconds; the shim gives up one second earlier and answers {}.
51
+ hooks[event] = [{ hooks: [{ type: 'command', command, timeout: (HOOK_TIMEOUT_S + 1) * 1000 }] }];
52
+ }
53
+ return {
54
+ // trust: the gonogo tools run without a confirmation, like the --allowedTools of a Claude agent.
55
+ // Payload servers come first and carry no `trust`: Gemini asks before their tools run. Its schema takes the mcp.json fields as they are.
56
+ mcpServers: { ...ctx.servers, [MCP_SERVER_NAME]: { httpUrl: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: 'Bearer ${GONOGO_TOKEN}' }, trust: true } },
57
+ hooks,
58
+ };
59
+ }
60
+ /** The MCP entry for a CLI that reads Claude's mcp.json shape but may not expand variables: the token is written in. */
61
+ function mcpJson(ctx, extra = {}) {
62
+ const server = { type: 'http', url: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: `Bearer ${ctx.token}` }, ...extra };
63
+ return JSON.stringify({ mcpServers: { ...ctx.servers, [MCP_SERVER_NAME]: server } }, null, 2);
64
+ }
65
+ /**
66
+ * Every start of these CLIs is a new session: none of them is resumed by gonogo.
67
+ * shortcut: a restart loses the conversation, upgrade when a CLI's resume by id is checked against a real run.
68
+ */
69
+ export function buildProviderStart(provider, ctx) {
70
+ const file = (name) => join(ctx.agentDir, name);
71
+ switch (provider) {
72
+ case 'gemini':
73
+ // GEMINI_CLI_SYSTEM_SETTINGS_PATH is read before the owner's ~/.gemini settings and wins over them; their login stays.
74
+ return {
75
+ args: ['--approval-mode', GEMINI_MODES[ctx.mode], ...(ctx.seed ? ['--skip-trust'] : []), '--prompt-interactive', ctx.roleText],
76
+ env: { GEMINI_CLI_SYSTEM_SETTINGS_PATH: file(GEMINI_SETTINGS_FILE) },
77
+ files: { [GEMINI_SETTINGS_FILE]: JSON.stringify(buildGeminiSettings(ctx), null, 2) },
78
+ };
79
+ case 'codex':
80
+ // -c overrides config.toml for this run only, so CODEX_HOME (and the owner's login in it) stays as it is.
81
+ return {
82
+ args: [
83
+ '-c',
84
+ `mcp_servers.${MCP_SERVER_NAME}.url=${JSON.stringify(`${ctx.hubUrl}${MCP_PATH}`)}`,
85
+ '-c',
86
+ `mcp_servers.${MCP_SERVER_NAME}.bearer_token_env_var="GONOGO_TOKEN"`,
87
+ ...CODEX_MODES[ctx.mode],
88
+ ctx.roleText,
89
+ ],
90
+ env: {},
91
+ files: {},
92
+ };
93
+ case 'opencode':
94
+ // OPENCODE_CONFIG is merged over the owner's config; {env:...} is opencode's own substitution.
95
+ return {
96
+ args: ['--prompt', ctx.roleText],
97
+ env: { OPENCODE_CONFIG: file('opencode.json') },
98
+ files: {
99
+ 'opencode.json': JSON.stringify({ mcp: { [MCP_SERVER_NAME]: { type: 'remote', url: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: 'Bearer {env:GONOGO_TOKEN}' }, enabled: true } } }, null, 2),
100
+ },
101
+ };
102
+ case 'kimi':
103
+ return { args: ['--mcp-config-file', file('kimi-mcp.json')], env: {}, files: { 'kimi-mcp.json': mcpJson(ctx) } };
104
+ case 'copilot':
105
+ return { args: ['--additional-mcp-config', `@${file('copilot-mcp.json')}`], env: {}, files: { 'copilot-mcp.json': mcpJson(ctx, { tools: ['*'] }) } };
106
+ case 'pi':
107
+ // pi reads MCP servers only from its own files, so it gets no gonogo tools: the role alone, without the preamble about them.
108
+ return { args: ['--append-system-prompt', ctx.role], env: {}, files: {} };
109
+ case 'qwen':
110
+ case 'grok':
111
+ case 'crush':
112
+ case 'cursor':
113
+ // No documented per-session MCP config and no checked way to pass a role: a terminal with a lamp, started by name.
114
+ return { args: [], env: {}, files: {} };
115
+ }
116
+ }
117
+ /** Whether `name` is an executable file in one of the PATH directories (moved here from cli.ts). */
118
+ export function onPath(name, pathVar) {
119
+ for (const dir of (pathVar ?? '').split(delimiter)) {
120
+ if (dir === '')
121
+ continue;
122
+ try {
123
+ const file = join(dir, name);
124
+ accessSync(file, fsConstants.X_OK);
125
+ if (statSync(file).isFile())
126
+ return true;
127
+ }
128
+ catch {
129
+ // not in this directory
130
+ }
131
+ }
132
+ return false;
133
+ }
134
+ /** ServerInfo.installed: what the hire form lists first. GONOGO_AGENT_CMD stands in for claude. */
135
+ export function installedProviders(path, agentCmd) {
136
+ return PROVIDERS.filter((p) => p === 'custom' || (p === 'claude' && agentCmd) || onPath(PROVIDER_INFO[p].bin, path));
137
+ }