@ulm0/gonogo 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Mass Budget: how big each agent's memory.md is, and a request to the agent to condense it (docs/mass-budget-spec.md).
3
+ *
4
+ * gonogo never writes memory.md: the agent may be writing it. A request is a message from the Director through the hub, so Max Q,
5
+ * Redline and held mail apply, and the agent rewrites its own file. What gonogo does write is one copy, memory.md.bak, taken from
6
+ * the bytes it read when the request is sent and put in place only after the hub took the message (so a refused request keeps
7
+ * the older copy). The file is opened without following a symbolic link and is never read past MEMORY_READ_MAX bytes.
8
+ *
9
+ * shortcut: the lines and the bytes of the soft limit are constants (the role text tells an agent to keep its file under 200
10
+ * lines); make them options if anyone runs agents that need more.
11
+ */
12
+ import { randomBytes } from 'node:crypto';
13
+ import { constants } from 'node:fs';
14
+ import { lstat, open, rename, rm, writeFile } from 'node:fs/promises';
15
+ import { basename, dirname, join } from 'node:path';
16
+ import { FILE_MODE, MEMORY_FILE } from './constants.js';
17
+ import { HubError } from './hub.js';
18
+ export const MEMORY_BACKUP_FILE = `${MEMORY_FILE}.bak`;
19
+ /** The role text asks for under 200 lines; the size limit is what 200 lines of notes come to. */
20
+ export const MEMORY_SOFT_LINES = 200;
21
+ export const MEMORY_SOFT_BYTES = 16 * 1024;
22
+ /** What the request asks the agent to bring the file down to. */
23
+ export const MEMORY_TARGET_LINES = 100;
24
+ /** A larger file is not copied or counted: trim it by hand. */
25
+ export const MEMORY_READ_MAX = 1024 * 1024;
26
+ /** The message to the agent. Everything it needs is in it: the file, the size, what to keep, what to drop, how to write it and how to answer. */
27
+ export function reflectBody(input) {
28
+ return [
29
+ 'The Director asks you to condense your memory file.',
30
+ `File: ${input.path} (${input.bytes} bytes, ${input.lines} lines). gonogo copied it to ${input.path}.bak when it sent this message: do not use that copy as notes and do not edit it.`,
31
+ 'When your current step is done:',
32
+ '1. Read the whole file.',
33
+ `2. Write a shorter version of at most ${MEMORY_TARGET_LINES} lines. Keep what is still true and still useful: decisions and their reasons, rules and conventions, paths, commands, names, ids and open problems. Drop what is done, repeated or replaced, and any step-by-step log of what you did. Merge notes on one subject. Add nothing that is not in the file.`,
34
+ '3. A finding that every agent should know goes to the Mission Log with log_write, and leaves your file.',
35
+ `4. Replace the file with the new text in one write. Keep the first line "# Memory of ${input.name}" and plain markdown. Do not change any other file.`,
36
+ '5. Then send_message to "user" with the subject "Memory condensed" and one sentence: the lines before and after. If the file is already short and has nothing to drop, change nothing and say so in one sentence.',
37
+ ].join('\n');
38
+ }
39
+ const conflict = (message) => new HubError('conflict', message);
40
+ const lineCount = (text) => {
41
+ if (text.length === 0)
42
+ return 0;
43
+ let lines = 0;
44
+ for (const byte of text)
45
+ if (byte === 0x0a)
46
+ lines += 1;
47
+ return text[text.length - 1] === 0x0a ? lines : lines + 1;
48
+ };
49
+ /** The file as it is, read without following a link. null when it is not there. A link, a folder or a device is refused. */
50
+ async function readMemory(path) {
51
+ let handle;
52
+ try {
53
+ // O_NONBLOCK: opening a named pipe in that place must not wait for a writer
54
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
55
+ }
56
+ catch (error) {
57
+ const code = error.code;
58
+ if (code === 'ENOENT')
59
+ return null;
60
+ if (code === 'ELOOP')
61
+ throw conflict(`${basename(path)} is a symbolic link: gonogo does not follow it`);
62
+ throw error;
63
+ }
64
+ try {
65
+ const info = await handle.stat();
66
+ if (!info.isFile())
67
+ throw conflict(`${basename(path)} is not a regular file`);
68
+ if (info.size > MEMORY_READ_MAX)
69
+ return { bytes: info.size, data: null, changedAt: info.mtimeMs };
70
+ const data = Buffer.alloc(info.size);
71
+ let got = 0;
72
+ while (got < data.length) {
73
+ const { bytesRead } = await handle.read(data, got, data.length - got, got);
74
+ if (bytesRead === 0)
75
+ break;
76
+ got += bytesRead;
77
+ }
78
+ return { bytes: got, data: data.subarray(0, got), changedAt: info.mtimeMs };
79
+ }
80
+ finally {
81
+ await handle.close();
82
+ }
83
+ }
84
+ export function createMassBudget(options) {
85
+ const { log } = options;
86
+ /** One request per agent at a time: a double click must not send the message twice. */
87
+ const asking = new Set();
88
+ const known = (name) => {
89
+ const agent = options.agent(name);
90
+ if (!agent)
91
+ throw new HubError('not_found', 'unknown agent');
92
+ if (agent.provider === 'custom')
93
+ throw new HubError('not_found', `${name} runs a custom command: it has no memory file`);
94
+ return agent;
95
+ };
96
+ const backupOf = async (path) => {
97
+ try {
98
+ const info = await lstat(`${path}.bak`);
99
+ return info.isFile() ? { bytes: info.size, at: info.mtimeMs } : null;
100
+ }
101
+ catch {
102
+ return null;
103
+ }
104
+ };
105
+ const describe = async (path, read) => {
106
+ const bytes = read?.bytes ?? 0;
107
+ const lines = read === null ? 0 : read.data === null ? null : lineCount(read.data);
108
+ return {
109
+ exists: read !== null,
110
+ bytes,
111
+ lines,
112
+ softLines: MEMORY_SOFT_LINES,
113
+ softBytes: MEMORY_SOFT_BYTES,
114
+ over: bytes > MEMORY_SOFT_BYTES || (lines ?? Infinity) > MEMORY_SOFT_LINES,
115
+ changedAt: read?.changedAt ?? null,
116
+ backup: await backupOf(path),
117
+ };
118
+ };
119
+ return {
120
+ async view(name) {
121
+ known(name);
122
+ const path = options.memoryPath(name);
123
+ return describe(path, await readMemory(path));
124
+ },
125
+ async reflect(name) {
126
+ known(name);
127
+ if (asking.has(name))
128
+ throw conflict(`a request to ${name} is being sent`);
129
+ asking.add(name);
130
+ try {
131
+ const path = options.memoryPath(name);
132
+ const read = await readMemory(path);
133
+ if (read === null)
134
+ throw conflict(`${name} has no memory file yet: start it first`);
135
+ if (read.data === null)
136
+ throw conflict(`${MEMORY_FILE} of ${name} is ${Math.round(read.bytes / 1024)} KiB, more than the ${MEMORY_READ_MAX / 1024} KiB gonogo copies: trim it by hand`);
137
+ // written first, put in place after the hub took the message
138
+ const tmp = join(dirname(path), `.${MEMORY_BACKUP_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
139
+ await writeFile(tmp, read.data, { mode: FILE_MODE, flag: 'wx' }).catch(async (error) => {
140
+ // a full disk leaves half a file behind
141
+ await rm(tmp, { force: true });
142
+ throw error;
143
+ });
144
+ let send;
145
+ try {
146
+ send = options.send({ to: name, subject: 'Mass Budget: condense your memory file', body: reflectBody({ name, path, bytes: read.bytes, lines: lineCount(read.data) }) });
147
+ }
148
+ catch (error) {
149
+ await rm(tmp, { force: true });
150
+ throw error;
151
+ }
152
+ if (send.ok) {
153
+ // rename puts the copy in place of a link too, never through it
154
+ await rename(tmp, `${path}.bak`).catch(async (error) => {
155
+ log.warn(`could not write ${MEMORY_BACKUP_FILE} of ${name}`, error);
156
+ await rm(tmp, { force: true });
157
+ });
158
+ }
159
+ else {
160
+ await rm(tmp, { force: true });
161
+ }
162
+ return { send, memory: await describe(path, await readMemory(path)) };
163
+ }
164
+ finally {
165
+ asking.delete(name);
166
+ }
167
+ },
168
+ };
169
+ }
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
3
  import { z } from 'zod';
4
4
  import { LIVERY_DESCRIPTION_MAX_CHARS, LIVERY_NAME_MAX_CHARS } from '../shared/livery.js';
5
- import { LOG_BODY_MAX_CHARS, LOG_QUERY_MAX_CHARS, LOG_SEARCH_MAX, LOG_TAGS_MAX, LOG_TITLE_MAX_CHARS, MCP_SERVER_NAME, POLL_VOTES, TASK_DETAIL_MAX_CHARS, TASK_NOTE_MAX_CHARS, TASK_STATUSES, TASK_TITLE_MAX_CHARS, } from '../shared/protocol.js';
5
+ import { AGENT_NAME_MAX, DIR_MAX_CHARS, BOARD_MAX_CHARS, LOG_BODY_MAX_CHARS, LOG_QUERY_MAX_CHARS, LOG_SEARCH_MAX, LOG_TAGS_MAX, LOG_TITLE_MAX_CHARS, MCP_SERVER_NAME, POLL_VOTES, ROLE_MAX_CHARS, TASK_DETAIL_MAX_CHARS, TASK_NOTE_MAX_CHARS, TASK_STATUSES, TASK_TITLE_MAX_CHARS, } from '../shared/protocol.js';
6
6
  import { BODY_MAX_CHARS, MAX_MCP_BODY_BYTES, MCP_DESCRIPTIONS, POLL_REASON_MAX_CHARS, READ_MAX_CHARS, SUBJECT_MAX_CHARS } from './constants.js';
7
7
  import { bearerToken, hubErrorInfo, readBody, sendJson, sendUnauthorized } from './hooks.js';
8
8
  /** JSON-RPC error codes: parse error, invalid request, "server error" (the SDK's own value for a refused method), internal error. */
@@ -126,6 +126,20 @@ export function createMcpHandler(deps) {
126
126
  return toolResult({ count: hits.length, results: hits }, false);
127
127
  }));
128
128
  server.registerTool('log_read', { description: MCP_DESCRIPTIONS.log_read, inputSchema: { id: z.string().min(1).max(16) } }, ({ id }) => guarded('log_read', () => (missionLog ? toolResult({ ok: true, entry: missionLog.get(id) }, false) : noLog())));
129
+ const { board } = deps;
130
+ const noPlot = () => toolResult({ ok: false, error: 'the Plot Board is not available' }, true);
131
+ // the boss is the one the hub says it is, asked at each call: a rename or a new boss takes effect at once
132
+ const bossName = () => hub.rosterFor(agent, generation).boss;
133
+ server.registerTool('board_read', { description: MCP_DESCRIPTIONS.board_read }, () => guarded('board_read', () => (board ? toolResult({ ok: true, ...board.get(), canWrite: bossName() === agent }, false) : noPlot())));
134
+ server.registerTool('board_write', { description: MCP_DESCRIPTIONS.board_write, inputSchema: { text: z.string().max(BOARD_MAX_CHARS), revision: z.number().int().min(0) } }, (args) => guarded('board_write', async () => {
135
+ if (!board)
136
+ return noPlot();
137
+ if (bossName() !== agent)
138
+ return toolResult({ ok: false, error: 'only the boss may write the Plot Board' }, true);
139
+ // the author is the caller's own name, never a field of the call
140
+ const view = await board.write(agent, args);
141
+ return toolResult({ ok: true, revision: view.revision, updatedAt: view.updatedAt }, false);
142
+ }));
129
143
  const { liveries } = deps;
130
144
  server.registerTool('livery_submit', {
131
145
  description: MCP_DESCRIPTIONS.livery_submit,
@@ -137,6 +151,24 @@ export function createMcpHandler(deps) {
137
151
  const entry = await liveries.submit(agent, args);
138
152
  return toolResult({ ok: true, slug: entry.slug, note: 'saved; the Director chooses whether to apply it' }, false);
139
153
  }));
154
+ const { relief } = deps;
155
+ server.registerTool('hire_agent', {
156
+ description: MCP_DESCRIPTIONS.hire_agent,
157
+ // strict: a field the tool does not have (confirmBypass, command, payload) is refused, not dropped; the mode is checked by Relief, so that its answer says why
158
+ inputSchema: z.strictObject({
159
+ name: z.string().min(1).max(AGENT_NAME_MAX),
160
+ position: z.string().max(32).optional(),
161
+ role: z.string().max(ROLE_MAX_CHARS).optional(),
162
+ dir: z.string().max(DIR_MAX_CHARS).optional(),
163
+ engine: z.string().max(32).optional(),
164
+ mode: z.string().max(32).optional(),
165
+ }),
166
+ }, (args) => guarded('hire_agent', async () => {
167
+ if (!relief)
168
+ return toolResult({ ok: false, error: 'Relief is not available' }, true);
169
+ // the requester is the agent of the token, never a field of the call
170
+ return toolResult({ ok: true, ...(await relief.request({ agent, generation }, args)) }, false);
171
+ }));
140
172
  return server;
141
173
  };
142
174
  return async (req, res) => {
@@ -10,15 +10,16 @@
10
10
  * To change a format: add a step at the end of `steps` of its entry in FORMATS (version n to n + 1; it gets the parsed file and
11
11
  * returns the new one; the runner sets `version`), and change the store to read and write the new shape.
12
12
  *
13
- * Not run through here: the logs messages.jsonl and fuel.jsonl (a line a reader cannot parse is skipped; a new line format needs a
14
- * new file name) and the Mission Log entries (their front matter has `version`, checked in missionlog.ts).
13
+ * Not run through here: the logs messages.jsonl, fuel.jsonl and the day files of the Black Box (a line a reader cannot parse is
14
+ * skipped; a new line format needs a new file name), and the Mission Log entries and board.md (their front matter has `version`,
15
+ * checked in missionlog.ts and board.ts).
15
16
  * shortcut: a home with one file too new and another to upgrade can upgrade the second before it refuses the first; the copy
16
17
  * makes that harmless, so there is no check pass.
17
18
  */
18
19
  import { randomBytes } from 'node:crypto';
19
20
  import { chmodSync, constants, copyFileSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
20
21
  import { basename, dirname, join } from 'node:path';
21
- import { AGENTS_FILE, DOCKING_FILE, DOWNLINK_FILE, FILE_MODE, LIVERY_DIR, LIVERY_FILE, PROPELLANT_FILE, RELAY_FILE, SCHEDULES_FILE, STATION_FILE, TASKS_FILE, UPLINKS_FILE, } from './constants.js';
22
+ import { AGENTS_FILE, DOCKING_FILE, DOWNLINK_FILE, FILE_MODE, KEYS_FILE, LIVERY_DIR, LIVERY_FILE, PROPELLANT_FILE, RELAY_FILE, ROLLOUT_FILE, SCHEDULES_FILE, STATION_FILE, TASKS_FILE, UPLINKS_FILE, } from './constants.js';
22
23
  const ALL_JSON = '/*.json';
23
24
  /** Everything is still at version 1: no step yet. */
24
25
  export const FORMATS = [
@@ -32,6 +33,8 @@ export const FORMATS = [
32
33
  STATION_FILE,
33
34
  LIVERY_FILE,
34
35
  PROPELLANT_FILE,
36
+ KEYS_FILE,
37
+ ROLLOUT_FILE,
35
38
  LIVERY_DIR + ALL_JSON,
36
39
  ].map((file) => (file === PROPELLANT_FILE ? { file, steps: [], unversionedIs1: true } : { file, steps: [] }));
37
40
  function isRecord(x) {
@@ -20,6 +20,7 @@ import { LOG_BODY_MAX_CHARS, LOG_ENTRIES_MAX, LOG_QUERY_MAX_CHARS, LOG_SEARCH_MA
20
20
  import { DIR_MODE, FILE_MODE, LOG_DIR } from './constants.js';
21
21
  import { isRecord } from './hooks.js';
22
22
  import { HubError } from './hub.js';
23
+ import { buildChart } from './logchart.js';
23
24
  import { createIndex, snippet } from './logsearch.js';
24
25
  import { UNSAFE_IN_NAME } from './schedules.js';
25
26
  const ID_RE = /^l[1-9]\d{0,5}$/;
@@ -162,6 +163,7 @@ export function createMissionLog(options) {
162
163
  return { total: entries.size, hits: found.map((e) => hit(e, q)) };
163
164
  },
164
165
  get: (id) => copy(find(id)),
166
+ chart: () => buildChart([...entries.values()]),
165
167
  create(author, input) {
166
168
  return locked(async () => {
167
169
  const fields = validate(input, true);
@@ -4,10 +4,11 @@
4
4
  * needs in the agent's own folder; what the hub does with the CLI (hooks or output activity, mail or none) is
5
5
  * PROVIDER_INFO in protocol.ts. Nothing here touches the owner's project or the CLI's own home folder.
6
6
  */
7
+ import { execFile } from 'node:child_process';
7
8
  import { accessSync, constants as fsConstants, statSync } from 'node:fs';
8
9
  import { delimiter, join } from 'node:path';
9
10
  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
+ import { ENGINE_VERSION_CHARS, ENGINE_VERSION_MS, HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_PATH } from './constants.js';
11
12
  /** Gemini CLI hook event to the hub's own hook event: the hub handles both CLIs with one set of rules. */
12
13
  export const GEMINI_HOOKS = {
13
14
  BeforeAgent: 'UserPromptSubmit',
@@ -68,11 +69,13 @@ function mcpJson(ctx, extra = {}) {
68
69
  */
69
70
  export function buildProviderStart(provider, ctx) {
70
71
  const file = (name) => join(ctx.agentDir, name);
72
+ // Every engine with a model setting takes `--model <name>` (PROVIDER_INFO.model); the name is one argument, never a shell word.
73
+ const model = ctx.model ? ['--model', ctx.model] : [];
71
74
  switch (provider) {
72
75
  case 'gemini':
73
76
  // GEMINI_CLI_SYSTEM_SETTINGS_PATH is read before the owner's ~/.gemini settings and wins over them; their login stays.
74
77
  return {
75
- args: ['--approval-mode', GEMINI_MODES[ctx.mode], ...(ctx.seed ? ['--skip-trust'] : []), '--prompt-interactive', ctx.roleText],
78
+ args: ['--approval-mode', GEMINI_MODES[ctx.mode], ...(ctx.seed ? ['--skip-trust'] : []), ...model, '--prompt-interactive', ctx.roleText],
76
79
  env: { GEMINI_CLI_SYSTEM_SETTINGS_PATH: file(GEMINI_SETTINGS_FILE) },
77
80
  files: { [GEMINI_SETTINGS_FILE]: JSON.stringify(buildGeminiSettings(ctx), null, 2) },
78
81
  };
@@ -85,6 +88,7 @@ export function buildProviderStart(provider, ctx) {
85
88
  '-c',
86
89
  `mcp_servers.${MCP_SERVER_NAME}.bearer_token_env_var="GONOGO_TOKEN"`,
87
90
  ...CODEX_MODES[ctx.mode],
91
+ ...model,
88
92
  ctx.roleText,
89
93
  ],
90
94
  env: {},
@@ -100,22 +104,25 @@ export function buildProviderStart(provider, ctx) {
100
104
  },
101
105
  };
102
106
  case 'kimi':
103
- return { args: ['--mcp-config-file', file('kimi-mcp.json')], env: {}, files: { 'kimi-mcp.json': mcpJson(ctx) } };
107
+ return { args: ['--mcp-config-file', file('kimi-mcp.json'), ...model], env: {}, files: { 'kimi-mcp.json': mcpJson(ctx) } };
104
108
  case 'copilot':
105
109
  return { args: ['--additional-mcp-config', `@${file('copilot-mcp.json')}`], env: {}, files: { 'copilot-mcp.json': mcpJson(ctx, { tools: ['*'] }) } };
106
110
  case 'pi':
107
111
  // 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: {} };
112
+ return { args: ['--append-system-prompt', ctx.role, ...model], env: {}, files: {} };
113
+ case 'cursor':
114
+ return { args: model, env: {}, files: {} };
109
115
  case 'qwen':
110
116
  case 'grok':
111
117
  case 'crush':
112
- case 'cursor':
113
118
  // No documented per-session MCP config and no checked way to pass a role: a terminal with a lamp, started by name.
114
119
  return { args: [], env: {}, files: {} };
115
120
  }
116
121
  }
117
- /** Whether `name` is an executable file in one of the PATH directories (moved here from cli.ts). */
118
- export function onPath(name, pathVar) {
122
+ /** The path of `name` when it is an executable file in one of the PATH directories, else null. */
123
+ export function findOnPath(name, pathVar) {
124
+ if (name === '')
125
+ return null;
119
126
  for (const dir of (pathVar ?? '').split(delimiter)) {
120
127
  if (dir === '')
121
128
  continue;
@@ -123,13 +130,68 @@ export function onPath(name, pathVar) {
123
130
  const file = join(dir, name);
124
131
  accessSync(file, fsConstants.X_OK);
125
132
  if (statSync(file).isFile())
126
- return true;
133
+ return file;
127
134
  }
128
135
  catch {
129
136
  // not in this directory
130
137
  }
131
138
  }
132
- return false;
139
+ return null;
140
+ }
141
+ /** Whether `name` is an executable file in one of the PATH directories (moved here from cli.ts). */
142
+ export const onPath = (name, pathVar) => findOnPath(name, pathVar) !== null;
143
+ // A terminal sequence (colour, title) whole, then what is left of control, C1 and text-direction characters: the line goes to a terminal and a web page.
144
+ const TERMINAL_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?)/g;
145
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
146
+ /** Pad Check: the first line a program prints for `--version`, with terminal sequences and control characters taken out and cut short. */
147
+ export const versionLine = (output) => {
148
+ const line = output.split('\n').map((l) => l.replace(TERMINAL_SEQUENCE, '').replace(CONTROL, '').trim()).find((l) => l !== '');
149
+ return line === undefined ? null : line.slice(0, ENGINE_VERSION_CHARS);
150
+ };
151
+ /** Versions already read, by path and modification time: a program that was updated is asked again, one that failed is asked every time. */
152
+ const versionCache = new Map();
153
+ /**
154
+ * `<file> --version`, no shell, a few seconds at most, and an environment of PATH, HOME and LANG only, so that no key or token of
155
+ * gonogo's environment reaches a program that is merely asked its version. null when it did not answer or printed nothing.
156
+ */
157
+ async function versionOf(file, env) {
158
+ const key = `${file}\0${statSync(file).mtimeMs}`;
159
+ const known = versionCache.get(key);
160
+ if (known !== undefined)
161
+ return known;
162
+ const output = await new Promise((done) => {
163
+ execFile(file, ['--version'], { timeout: ENGINE_VERSION_MS, maxBuffer: 64 * 1024, env: { PATH: env.PATH, HOME: env.HOME, LANG: env.LANG, NO_COLOR: '1' } }, (error, stdout) => done(error === null ? stdout : ''));
164
+ });
165
+ const line = versionLine(output);
166
+ if (line !== null)
167
+ versionCache.set(key, line);
168
+ return line;
169
+ }
170
+ /** Pad Check: every engine but the custom command, where it was found and what it calls itself. Runs nothing but `--version`; never installs. */
171
+ export function checkEngines(env) {
172
+ return Promise.all(PROVIDERS.filter((provider) => provider !== 'custom').map(async (provider) => {
173
+ const { label, bin, install, docs } = PROVIDER_INFO[provider];
174
+ const path = findOnPath(bin, env.PATH);
175
+ return { provider, label, bin, path, version: path === null ? null : await versionOf(path, env).catch(() => null), install, docs };
176
+ }));
177
+ }
178
+ /** What `gonogo doctor` prints: one line per engine, and under a missing one the vendor's install command to copy. */
179
+ export function formatDoctor(checks, agentCmd) {
180
+ const lines = ['gonogo doctor: which agent CLIs are on the PATH', ''];
181
+ for (const check of checks) {
182
+ if (check.path !== null) {
183
+ lines.push(`ok ${check.label} (${check.bin}) ${check.version ?? 'no version printed'} ${check.path}`);
184
+ continue;
185
+ }
186
+ lines.push(`-- ${check.label} (${check.bin}) not found`);
187
+ lines.push(check.install === null ? ` no install command was checked; see ${check.docs}` : ` install: ${check.install}`);
188
+ if (check.install !== null)
189
+ lines.push(` docs: ${check.docs}`);
190
+ }
191
+ if (agentCmd !== null)
192
+ lines.push('', `GONOGO_AGENT_CMD is set (${agentCmd}): it replaces claude.`);
193
+ lines.push('', 'gonogo never runs an install command: copy the one you want.');
194
+ return lines.join('\n') + '\n';
133
195
  }
134
196
  /** ServerInfo.installed: what the hire form lists first. GONOGO_AGENT_CMD stands in for claude. */
135
197
  export function installedProviders(path, agentCmd) {
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Recorder (docs/recorder-spec.md): git for one agent's folder, or its Clean Room worktree, for the Director's browser.
3
+ * Status, a diff (read-only), the last 50 commits, and a commit of all changes or of what is staged, with a message the
4
+ * Director wrote and the author from his own git config. No push, pull, checkout, reset or any other command. Git runs
5
+ * through execFile with an argument list, hooks off, no prompt, a time limit and an output cap.
6
+ */
7
+ import { execFile } from 'node:child_process';
8
+ import { realpath } from 'node:fs/promises';
9
+ import { RECORDER_LOG_MAX, RECORDER_MESSAGE_MAX_CHARS, RECORDER_SCOPES } from '../shared/protocol.js';
10
+ import { GIT_BIN } from './constants.js';
11
+ import { HubError } from './hub.js';
12
+ import { inside, pathParts } from './hangar.js';
13
+ export const RECORDER_READ_MS = 15_000;
14
+ export const RECORDER_WRITE_MS = 30_000;
15
+ /** Output of a read: status and log are cut at 1 MiB, a diff at 256 KiB. */
16
+ export const RECORDER_LIST_CAP = 1024 * 1024;
17
+ export const RECORDER_DIFF_CAP = 256 * 1024;
18
+ export const RECORDER_FILES_MAX = 1000;
19
+ /** Hooks off, and the programs a repository's own config could name for a read (the file system monitor, an external diff) off. */
20
+ const BASE_ARGS = ['--literal-pathspecs', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'core.quotepath=false'];
21
+ /** What git may see of the environment: no GIT_DIR or GIT_WORK_TREE or GIT_EXTERNAL_DIFF from gonogo's own, no credential. */
22
+ const KEEP_ENV = ['PATH', 'HOME', 'USER', 'LOGNAME', 'XDG_CONFIG_HOME', 'TMPDIR'];
23
+ class GitFailure extends Error {
24
+ status;
25
+ constructor(status, message) {
26
+ super(message);
27
+ this.status = status;
28
+ }
29
+ }
30
+ const bad = (message, field) => new HubError('bad_request', message, field);
31
+ export function createRecorder(roots, env) {
32
+ const gitEnv = { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' };
33
+ for (const key of KEEP_ENV) {
34
+ const value = env[key];
35
+ if (value !== undefined)
36
+ gitEnv[key] = value;
37
+ }
38
+ /** Runs git in the root. A call over its time is stopped with SIGTERM, not SIGKILL: git then removes its own index.lock, which a kill would leave to block every later add and commit. Output over `cap` is cut and `truncated` says so; a failure is a GitFailure with the first line git printed on stderr. */
39
+ function git(at, args, cap, timeout) {
40
+ return new Promise((resolve, reject) => {
41
+ execFile(GIT_BIN, [...BASE_ARGS, ...args], { cwd: at.root, env: gitEnv, timeout, killSignal: 'SIGTERM', maxBuffer: cap + 1, encoding: 'utf8' }, (error, stdout, stderr) => {
42
+ if (error === null)
43
+ return resolve({ out: stdout.slice(0, cap), truncated: stdout.length > cap });
44
+ const code = error.code;
45
+ if (code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')
46
+ return resolve({ out: String(stdout).slice(0, cap), truncated: true });
47
+ if (code === 'ENOENT')
48
+ return reject(new HubError('unavailable', 'git was not found on PATH'));
49
+ if (error.killed)
50
+ return reject(new HubError('unavailable', 'git did not answer in time'));
51
+ const line = stderr.split('\n').find((l) => l.trim() !== '')?.trim() ?? `git exited with ${String(code)}`;
52
+ reject(new GitFailure(typeof code === 'number' || typeof code === 'string' ? code : null, line.slice(0, 300)));
53
+ });
54
+ });
55
+ }
56
+ /** The repository at the root, or why not. It must be the top of a repository, and gonogo's own folder must not be inside it. */
57
+ async function repoProblem(at) {
58
+ let top;
59
+ try {
60
+ top = (await git(at, ['rev-parse', '--show-toplevel'], 4096, RECORDER_READ_MS)).out.trim();
61
+ }
62
+ catch (e) {
63
+ if (e instanceof GitFailure)
64
+ return /not a git repository/i.test(e.message) ? 'this folder is not in a git repository' : `git said: ${e.message}`;
65
+ throw e;
66
+ }
67
+ if ((await realpath(top).catch(() => top)) !== at.root)
68
+ return `this folder is inside the repository at ${top}: the Recorder works at the top of a repository`;
69
+ if (inside(at.root, at.home))
70
+ return 'gonogo\'s own folder is inside this repository, and the Recorder will not commit it';
71
+ return null;
72
+ }
73
+ async function author(at) {
74
+ const get = (key) => git(at, ['config', '--get', key], 1024, RECORDER_READ_MS).then((r) => r.out.trim(), (e) => {
75
+ if (e instanceof GitFailure)
76
+ return ''; // exit 1: the key is not set
77
+ throw e;
78
+ });
79
+ const [name, email] = await Promise.all([get('user.name'), get('user.email')]);
80
+ return name === '' || email === '' ? null : { name, email };
81
+ }
82
+ async function ready(name) {
83
+ const at = await roots(name);
84
+ const problem = await repoProblem(at);
85
+ if (problem !== null)
86
+ throw new HubError('conflict', problem);
87
+ return at;
88
+ }
89
+ async function lastCommits(at, count) {
90
+ let out;
91
+ try {
92
+ out = (await git(at, ['log', '-n', String(count), '--no-color', '--no-decorate', '-z', '--format=%H%x1f%an%x1f%at%x1f%s'], RECORDER_LIST_CAP, RECORDER_READ_MS)).out;
93
+ }
94
+ catch (e) {
95
+ if (e instanceof GitFailure && /does not have any commits yet/.test(e.message))
96
+ return [];
97
+ throw e;
98
+ }
99
+ return out.split('\0').filter((r) => r !== '').map((record) => {
100
+ const [hash = '', who = '', at2 = '0', ...subject] = record.split('\x1f');
101
+ return { hash, author: who.slice(0, 200), at: Number(at2) * 1000, subject: subject.join('\x1f').slice(0, 300) };
102
+ });
103
+ }
104
+ return {
105
+ async status(name) {
106
+ const at = await roots(name);
107
+ const problem = await repoProblem(at);
108
+ if (problem !== null)
109
+ return { repo: false, reason: problem };
110
+ const { out } = await git(at, ['status', '--porcelain=v1', '-z', '--branch', '--untracked-files=normal'], RECORDER_LIST_CAP, RECORDER_READ_MS);
111
+ const records = out.split('\0');
112
+ const files = [];
113
+ let branch = '';
114
+ for (let i = 0; i < records.length; i += 1) {
115
+ const record = records[i] ?? '';
116
+ if (record.startsWith('## '))
117
+ branch = record.slice(3, 203);
118
+ else if (record.length > 3) {
119
+ const file = { path: record.slice(3), index: record[0] ?? ' ', tree: record[1] ?? ' ' };
120
+ if (file.index === 'R' || file.index === 'C')
121
+ file.from = records[(i += 1)];
122
+ files.push(file);
123
+ }
124
+ }
125
+ return { repo: true, branch, files: files.slice(0, RECORDER_FILES_MAX), more: Math.max(0, files.length - RECORDER_FILES_MAX), author: await author(at) };
126
+ },
127
+ async diff(name, raw, staged) {
128
+ const parts = pathParts(raw ?? '');
129
+ const at = await ready(name);
130
+ const args = ['diff', '--no-ext-diff', '--no-textconv', '--no-color', ...(staged ? ['--cached'] : []), '--', ...(parts.length === 0 ? [] : [parts.join('/')])];
131
+ const { out, truncated } = await git(at, args, RECORDER_DIFF_CAP, RECORDER_READ_MS);
132
+ return { diff: out, truncated };
133
+ },
134
+ async log(name) {
135
+ return lastCommits(await ready(name), RECORDER_LOG_MAX);
136
+ },
137
+ async commit(name, input) {
138
+ if (typeof input !== 'object' || input === null || Array.isArray(input))
139
+ throw bad('the body must be an object');
140
+ const { message, scope } = input;
141
+ if (typeof message !== 'string' || message.trim() === '')
142
+ throw bad('write a message for the commit', 'message');
143
+ if (message.length > RECORDER_MESSAGE_MAX_CHARS)
144
+ throw bad(`the message is longer than ${RECORDER_MESSAGE_MAX_CHARS} characters`, 'message');
145
+ if (message.includes('\0'))
146
+ throw bad('the message has a NUL character', 'message');
147
+ if (scope !== 'all' && scope !== 'staged')
148
+ throw bad(`scope must be one of ${RECORDER_SCOPES.join(', ')}`, 'scope');
149
+ const at = await ready(name);
150
+ if ((await author(at)) === null) {
151
+ throw new HubError('conflict', 'git has no author: set user.name and user.email (git config --global user.name "Your Name"), then commit again', 'author');
152
+ }
153
+ try {
154
+ if (scope === 'all')
155
+ await git(at, ['add', '-A'], 4096, RECORDER_WRITE_MS);
156
+ const staged = await git(at, ['diff', '--cached', '--quiet', '--no-ext-diff'], 4096, RECORDER_READ_MS).then(() => false, (e) => {
157
+ if (e instanceof GitFailure && e.status === 1)
158
+ return true; // exit 1: the index differs from HEAD
159
+ throw e;
160
+ });
161
+ if (!staged)
162
+ throw new HubError('conflict', scope === 'all' ? 'nothing to commit: the folder has no changes' : 'nothing is staged', 'scope');
163
+ await git(at, ['-c', 'user.useConfigOnly=true', 'commit', '-m', message], 4096, RECORDER_WRITE_MS);
164
+ }
165
+ catch (e) {
166
+ if (e instanceof GitFailure)
167
+ throw new HubError('conflict', `git refused: ${e.message}`);
168
+ throw e;
169
+ }
170
+ const [commit] = await lastCommits(at, 1);
171
+ if (commit === undefined)
172
+ throw new HubError('internal', 'the commit was made but git does not list it');
173
+ return { commit };
174
+ },
175
+ };
176
+ }