ai-agentmanager 0.0.0-stage → 1.0.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.
Files changed (58) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +767 -2
  4. package/SECURITY.md +44 -0
  5. package/bin/agentmgr-hub.js +16 -0
  6. package/bin/agentmgr.js +4 -0
  7. package/docs/architecture.md +67 -0
  8. package/docs/distributed.md +147 -0
  9. package/docs/engines.md +177 -0
  10. package/docs/images/agents.jpg +0 -0
  11. package/docs/images/conflict-radar.jpg +0 -0
  12. package/docs/plugins.md +81 -0
  13. package/package.json +56 -4
  14. package/public/app.js +3083 -0
  15. package/public/hub/hub.css +230 -0
  16. package/public/hub/hub.js +766 -0
  17. package/public/hub/index.html +146 -0
  18. package/public/hub/term.js +147 -0
  19. package/public/index.html +342 -0
  20. package/public/share.html +34 -0
  21. package/public/share.js +41 -0
  22. package/public/style.css +541 -0
  23. package/public/touchscroll.js +73 -0
  24. package/public/transport.js +78 -0
  25. package/scripts/build-release.sh +58 -0
  26. package/scripts/fix-pty.js +15 -0
  27. package/src/backlog.js +413 -0
  28. package/src/brief.js +512 -0
  29. package/src/cli.js +1447 -0
  30. package/src/client.js +49 -0
  31. package/src/config.js +109 -0
  32. package/src/conflicts.js +105 -0
  33. package/src/engines/antigravity.js +296 -0
  34. package/src/engines/claude.js +98 -0
  35. package/src/engines/codex.js +331 -0
  36. package/src/engines/index.js +37 -0
  37. package/src/fleet.js +176 -0
  38. package/src/git.js +340 -0
  39. package/src/hub.js +857 -0
  40. package/src/hubactions.js +107 -0
  41. package/src/hubbacklog.js +373 -0
  42. package/src/hublink.js +437 -0
  43. package/src/inbox.js +94 -0
  44. package/src/judge.js +278 -0
  45. package/src/livebrowser.js +637 -0
  46. package/src/manager.js +2554 -0
  47. package/src/notify.js +284 -0
  48. package/src/plugins.js +119 -0
  49. package/src/preview.js +334 -0
  50. package/src/races.js +192 -0
  51. package/src/remote.js +284 -0
  52. package/src/server.js +759 -0
  53. package/src/service.js +150 -0
  54. package/src/sessions.js +160 -0
  55. package/src/store.js +104 -0
  56. package/src/stuck.js +160 -0
  57. package/src/tracker.js +311 -0
  58. package/src/trust.js +44 -0
@@ -0,0 +1,331 @@
1
+ // OpenAI's Codex CLI as an agent engine (checked against codex-cli 0.163.0; fixtures in
2
+ // test/fixtures/codex). Differences from Claude Code that shape this adapter:
3
+ // - Codex picks its own session IDs; the manager adopts the one it creates (adoptSessions).
4
+ // - Sessions live in $CODEX_HOME/sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl, and the
5
+ // first line (session_meta) records the folder it ran in.
6
+ // - No flag for extra instructions: they go in the first message of a new session.
7
+ // - Token counts but no cost figure.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { norm, tailOf } from '../stuck.js';
12
+ import { extractRefs } from '../tracker.js';
13
+
14
+ const home = () => process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
15
+ const sessionsDir = () => path.join(home(), 'sessions');
16
+ const real = (p) => {
17
+ try {
18
+ return fs.realpathSync(p);
19
+ } catch {
20
+ return path.resolve(p);
21
+ }
22
+ };
23
+ const ANSI = /\x1b(\[[0-9;?<>=]*[ -\/]*[@-~]|\][^\x07\x1b]*(\x07|\x1b\\)|[()][0-9A-B]|[=>78c])/g;
24
+
25
+ /** Day folders from `sinceMs` to today (sessions are filed by local start date). */
26
+ function dayDirs(sinceMs) {
27
+ const out = [];
28
+ const d = new Date(Math.min(sinceMs, Date.now()));
29
+ d.setHours(0, 0, 0, 0);
30
+ for (let i = 0; i < 400 && d.getTime() <= Date.now(); i++, d.setDate(d.getDate() + 1)) {
31
+ out.push(path.join(sessionsDir(), String(d.getFullYear()), String(d.getMonth() + 1).padStart(2, '0'), String(d.getDate()).padStart(2, '0')));
32
+ }
33
+ return out;
34
+ }
35
+
36
+ const idOf = (name) => /^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/.exec(name)?.[1] ?? null;
37
+
38
+ /** The folder a session ran in, from its first line. */
39
+ function sessionCwd(file) {
40
+ try {
41
+ const fd = fs.openSync(file, 'r');
42
+ try {
43
+ // The first line carries Codex's own instructions too, so it is often tens of KB.
44
+ const buf = Buffer.alloc(512 * 1024);
45
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
46
+ const head = buf.subarray(0, n).toString('utf8');
47
+ const first = head.split('\n')[0];
48
+ try {
49
+ const rec = JSON.parse(first);
50
+ return rec.type === 'session_meta' ? rec.payload?.cwd ?? null : null;
51
+ } catch {
52
+ // Longer than we read: the session_meta's cwd is the first one in the line.
53
+ if (!first.includes('"session_meta"')) return null;
54
+ const m = /"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/.exec(first);
55
+ return m ? JSON.parse(m[1]) : null;
56
+ }
57
+ } finally {
58
+ fs.closeSync(fd);
59
+ }
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ const found = new Map(); // session id -> file
66
+ function findSession(sessionId) {
67
+ const hit = found.get(sessionId);
68
+ if (hit && fs.existsSync(hit)) return hit;
69
+ // Newest days first; a session started long ago and resumed today is still filed under its start day.
70
+ let years;
71
+ try {
72
+ years = fs.readdirSync(sessionsDir()).sort().reverse();
73
+ } catch {
74
+ return null;
75
+ }
76
+ for (const y of years) {
77
+ for (const m of fs.readdirSync(path.join(sessionsDir(), y)).sort().reverse()) {
78
+ for (const d of fs.readdirSync(path.join(sessionsDir(), y, m)).sort().reverse()) {
79
+ const dir = path.join(sessionsDir(), y, m, d);
80
+ const name = fs.readdirSync(dir).find((n) => idOf(n) === sessionId);
81
+ if (name) {
82
+ found.set(sessionId, path.join(dir, name));
83
+ return found.get(sessionId);
84
+ }
85
+ }
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+
91
+ /** Read the complete lines added since the cursor's offset. */
92
+ function newRecords(file, cursor) {
93
+ let fd;
94
+ try {
95
+ fd = fs.openSync(file, 'r');
96
+ } catch {
97
+ return null;
98
+ }
99
+ try {
100
+ const { size, mtime } = fs.fstatSync(fd);
101
+ cursor.lastActivity = mtime.toISOString();
102
+ if (size < cursor.offset) cursor.offset = 0;
103
+ if (size === cursor.offset) return [];
104
+ const buf = Buffer.alloc(size - cursor.offset);
105
+ fs.readSync(fd, buf, 0, buf.length, cursor.offset);
106
+ const lastNl = buf.lastIndexOf(0x0a);
107
+ if (lastNl < 0) return [];
108
+ const start = cursor.offset;
109
+ cursor.offset += lastNl + 1;
110
+ const out = [];
111
+ let at = start;
112
+ for (const line of buf.subarray(0, lastNl).toString('utf8').split('\n')) {
113
+ const here = at;
114
+ at += Buffer.byteLength(line) + 1;
115
+ if (!line) continue;
116
+ try {
117
+ out.push({ rec: JSON.parse(line), at: here });
118
+ } catch {}
119
+ }
120
+ return out;
121
+ } finally {
122
+ fs.closeSync(fd);
123
+ }
124
+ }
125
+
126
+ const itemText = (item) =>
127
+ (Array.isArray(item?.content) ? item.content : [])
128
+ .map((c) => (typeof c?.text === 'string' ? c.text : ''))
129
+ .join('\n');
130
+ const commandOf = (item) => (Array.isArray(item?.command) ? (item.command.length >= 3 && /sh$/.test(item.command[0]) ? item.command.at(-1) : item.command.join(' ')) : String(item?.command ?? ''));
131
+ /** Files a FileChange item touched (its shape varies between versions). */
132
+ const changedFiles = (item) => {
133
+ const c = item?.changes ?? item?.files ?? [];
134
+ if (Array.isArray(c)) return c.map((x) => (typeof x === 'string' ? x : x?.path ?? x?.file)).filter(Boolean);
135
+ return Object.keys(c);
136
+ };
137
+
138
+ /** Approval modes in Codex terms: sandbox plus when to ask. The hub never starts the last one. */
139
+ const MODES = {
140
+ default: ['--sandbox', 'workspace-write', '--ask-for-approval', 'on-request'],
141
+ acceptEdits: ['--sandbox', 'workspace-write', '--ask-for-approval', 'on-request'],
142
+ plan: ['--sandbox', 'read-only', '--ask-for-approval', 'on-request'],
143
+ bypassPermissions: ['--dangerously-bypass-approvals-and-sandbox'],
144
+ };
145
+
146
+ export default {
147
+ id: 'codex',
148
+ label: 'Codex',
149
+ supports: { chooseSessionId: false, cost: false, planHandoff: false, fork: false, oneShot: true },
150
+ permissionModes: Object.keys(MODES),
151
+ rulesFiles: ['AGENTS.md'],
152
+
153
+ bin: (config) => config.engines?.codex?.bin ?? 'codex',
154
+ extraArgs: (config) => [...(config.engines?.codex?.args ?? [])],
155
+
156
+ /** Full arguments for a launch. Codex takes options after `resume`, and instructions only as text. */
157
+ launchArgs({ extra = [], permissionMode, model, writableDir, instructions, sessionId, resume, prompt }) {
158
+ // Inline mode keeps the conversation in the terminal's scrollback, which Agent Manager replays.
159
+ const opts = [...extra, '--no-alt-screen', ...(MODES[permissionMode] ?? MODES.default)];
160
+ if (model) opts.push('--model', model);
161
+ if (writableDir) opts.push('--add-dir', writableDir);
162
+ if (resume) return ['resume', ...opts, sessionId, ...(prompt ? [prompt] : [])];
163
+ const first = [instructions, prompt && (instructions ? `Your task:\n${prompt}` : prompt)].filter(Boolean).join('\n\n---\n\n');
164
+ return [...opts, ...(first ? [first] : [])];
165
+ },
166
+
167
+ sessionFile: (cwd, sessionId) => findSession(sessionId) ?? path.join(sessionsDir(), `missing-${sessionId}.jsonl`),
168
+ hasSession: (cwd, sessionId) => Boolean(findSession(sessionId)),
169
+ subagentFiles: () => [],
170
+
171
+ /** Sessions Codex started in this folder since a time; the manager adopts a new one. */
172
+ recentSessions(cwd, sinceMs) {
173
+ const want = real(cwd);
174
+ const out = [];
175
+ for (const dir of dayDirs(sinceMs)) {
176
+ let names;
177
+ try {
178
+ names = fs.readdirSync(dir);
179
+ } catch {
180
+ continue;
181
+ }
182
+ for (const n of names) {
183
+ const id = idOf(n);
184
+ if (!id) continue;
185
+ const file = path.join(dir, n);
186
+ const st = fs.statSync(file);
187
+ if (st.mtimeMs < sinceMs) continue;
188
+ const where = sessionCwd(file);
189
+ if (!where || real(where) !== want) continue;
190
+ found.set(id, file);
191
+ out.push({ sessionId: id, file, mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs });
192
+ }
193
+ }
194
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
195
+ },
196
+
197
+ /** Usage (one entry per model response), PR and bug links from messages and command output. */
198
+ scan(file, cursor, bugPatterns = []) {
199
+ const result = { prs: [], bugs: [], title: null, lastPrompt: null, cost: null, lastActivity: null };
200
+ cursor.usage ??= new Map();
201
+ cursor.offset ??= 0;
202
+ const recs = newRecords(file, cursor);
203
+ result.lastActivity = cursor.lastActivity ?? null;
204
+ if (!recs) return result;
205
+ for (const { rec, at } of recs) {
206
+ const p = rec.payload ?? {};
207
+ if (p.type === 'token_count' && p.info?.last_token_usage) {
208
+ const u = p.info.last_token_usage;
209
+ const cached = u.cached_input_tokens ?? 0;
210
+ // Codex counts cached tokens inside input_tokens; Claude Code counts them apart.
211
+ cursor.usage.set(`r${at}`, {
212
+ input: Math.max(0, (u.input_tokens ?? 0) - cached),
213
+ output: u.output_tokens ?? 0,
214
+ cacheCreation: u.cache_write_input_tokens ?? 0,
215
+ cacheRead: cached,
216
+ });
217
+ } else if (p.type === 'item_completed') {
218
+ const item = p.item ?? {};
219
+ const text = item.type === 'CommandExecution' ? String(item.aggregated_output ?? '') : itemText(item);
220
+ if (item.type === 'UserMessage' && text) result.lastPrompt = text.slice(0, 500);
221
+ const refs = extractRefs(text, bugPatterns);
222
+ result.prs.push(...refs.prs);
223
+ result.bugs.push(...refs.bugs);
224
+ }
225
+ }
226
+ return result;
227
+ },
228
+
229
+ /** Commands and file edits, for stuck detection. */
230
+ activity(file, state) {
231
+ state.events ??= [];
232
+ state.offset ??= 0;
233
+ const recs = newRecords(file, state);
234
+ if (!recs) return state;
235
+ for (const { rec } of recs) {
236
+ const item = rec.payload?.type === 'item_completed' ? rec.payload.item : null;
237
+ if (!item) continue;
238
+ const t = Date.parse(rec.timestamp ?? '') || Date.now();
239
+ if (item.type === 'CommandExecution') {
240
+ const out = String(item.aggregated_output ?? '');
241
+ state.events.push({ t, kind: 'cmd', cmd: norm(commandOf(item)).slice(0, 300), failed: Number(item.exit_code ?? 0) !== 0, result: tailOf(out), shown: out.replace(/\s+/g, ' ').trim().slice(-160) });
242
+ } else if (item.type === 'FileChange') {
243
+ // Each change's diff becomes one (removed, added) pair, so edits that undo earlier ones show up.
244
+ const changes = item.changes && !Array.isArray(item.changes) ? item.changes : {};
245
+ for (const f of changedFiles(item)) {
246
+ const diff = String(changes[f]?.unified_diff ?? '').split('\n');
247
+ const side = (c) => norm(diff.filter((l) => l.startsWith(c) && !l.startsWith(c.repeat(3))).map((l) => l.slice(1)).join('\n'));
248
+ state.events.push({ t, kind: 'edit', file: f, edits: diff.length > 1 ? [[side('-'), side('+')]] : [] });
249
+ }
250
+ }
251
+ }
252
+ if (state.events.length > 400) state.events = state.events.slice(-400);
253
+ return state;
254
+ },
255
+
256
+ /** A readable digest of the conversation, for Explain and documents. */
257
+ digest(file, { maxChars = 24_000 } = {}) {
258
+ const events = [];
259
+ const edited = new Set();
260
+ for (const { rec } of newRecords(file, { offset: 0 }) ?? []) {
261
+ const item = rec.payload?.type === 'item_completed' ? rec.payload.item : null;
262
+ if (!item) continue;
263
+ if (item.type === 'UserMessage') events.push(`[user] ${itemText(item).slice(0, 1200)}`);
264
+ else if (item.type === 'AgentMessage') events.push(`[agent] ${itemText(item).slice(0, 1800)}`);
265
+ else if (item.type === 'CommandExecution') events.push(`[action] ran \`${commandOf(item).slice(0, 200)}\`${Number(item.exit_code ?? 0) ? ` (exit ${item.exit_code})` : ''}`);
266
+ else if (item.type === 'FileChange') for (const f of changedFiles(item)) edited.add(f), events.push(`[action] edited ${f}`);
267
+ }
268
+ const head = events.find((e) => e.startsWith('[user]'));
269
+ const tail = [];
270
+ let used = head?.length ?? 0;
271
+ for (let i = events.length - 1; i >= 0 && events[i] !== head; i--) {
272
+ if (used + events[i].length > maxChars) {
273
+ tail.unshift('… (earlier events omitted) …');
274
+ break;
275
+ }
276
+ tail.unshift(events[i]);
277
+ used += events[i].length + 1;
278
+ }
279
+ return { digest: [head, ...tail].filter(Boolean).join('\n'), events: events.length, edited: [...edited] };
280
+ },
281
+
282
+ copySession: () => false,
283
+
284
+ attention: [
285
+ [/Trustthisfolder\?/i, 'Folder trust prompt'],
286
+ [/Wouldyouliketo(run|make|apply|allow|grant)/i, 'Permission prompt'],
287
+ ],
288
+
289
+ /** Codex's menus: "› 1. Yes, proceed (y)" ... "3. No, and tell Codex what to do differently (esc)". */
290
+ promptChoices(screen) {
291
+ const text = String(screen ?? '')
292
+ .replace(/\x1b\[(\d*)C/g, ' ')
293
+ .replace(ANSI, ' ')
294
+ .replace(/\s+/g, ' ');
295
+ const at = Math.max(text.lastIndexOf('Would you like'), text.lastIndexOf('Trust this folder'));
296
+ if (at < 0) return { question: '', choices: [] };
297
+ const tail = text.slice(at);
298
+ const question = (/^(.*?\?)/.exec(tail)?.[1] ?? '').slice(0, 200);
299
+ const choices = new Map();
300
+ for (const m of tail.matchAll(/(?:›\s*)?\b(\d)\.\s*(.+?)(?=\s+(?:›\s*)?\d\.\s|\s+Press enter|\s+enter continue|$)/g)) {
301
+ if (!choices.has(m[1])) choices.set(m[1], m[2].replace(/\s*\(\s*(?:y|p|esc|n|a)\s*\)\s*$/, '').trim().slice(0, 80));
302
+ }
303
+ return { question, choices: [...choices.entries()].sort(([a], [b]) => a - b).map(([key, label]) => ({ key, label })) };
304
+ },
305
+
306
+ /**
307
+ * Mark the folder trusted in $CODEX_HOME/config.toml, the record Codex writes for
308
+ * "Trust and continue". Appends a table only when the folder isn't listed yet.
309
+ */
310
+ trust(dir) {
311
+ const file = path.join(home(), 'config.toml');
312
+ const key = real(dir).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
313
+ let raw = '';
314
+ try {
315
+ raw = fs.readFileSync(file, 'utf8');
316
+ } catch (err) {
317
+ if (err.code !== 'ENOENT') throw err;
318
+ }
319
+ if (raw.includes(`[projects."${key}"]`)) return false;
320
+ const backup = `${file}.agentmgr-backup`;
321
+ if (raw && !fs.existsSync(backup)) fs.writeFileSync(backup, raw, { mode: 0o600 });
322
+ fs.mkdirSync(home(), { recursive: true });
323
+ fs.appendFileSync(file, `${raw && !raw.endsWith('\n') ? '\n' : ''}\n[projects."${key}"]\ntrust_level = "trusted"\n`);
324
+ return true;
325
+ },
326
+
327
+ /** One-shot, read-only and not saved; the prompt goes on stdin and only the answer is printed. */
328
+ oneShotArgs: (config, { model } = {}) => ['exec', '--ephemeral', '--skip-git-repo-check', '--sandbox', 'read-only', '--color', 'never', ...(model ? ['--model', model] : []), '-'],
329
+
330
+ stripEnv: [],
331
+ };
@@ -0,0 +1,37 @@
1
+ // The agent engines Agent Manager can run. Each agent records its engine; agents from
2
+ // before engines existed are Claude Code agents.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import antigravity from './antigravity.js';
6
+ import claude from './claude.js';
7
+ import codex from './codex.js';
8
+
9
+ export const ENGINES = { claude, codex, antigravity };
10
+ export const DEFAULT_ENGINE = 'claude';
11
+
12
+ /** Adds an engine from a plugin. Built-in engines can't be replaced. */
13
+ export function registerEngine(def) {
14
+ if (!def?.id || typeof def.id !== 'string') throw new Error('An engine needs an id');
15
+ if (Object.hasOwn(ENGINES, def.id)) throw new Error(`Engine "${def.id}" already exists`);
16
+ ENGINES[def.id] = def;
17
+ }
18
+
19
+ /** Whether an engine's command is on this machine (an absolute path, or found on PATH). */
20
+ export function installed(engine, config) {
21
+ const bin = engine.bin(config);
22
+ if (path.isAbsolute(bin)) return fs.existsSync(bin);
23
+ return (process.env.PATH ?? '').split(path.delimiter).some((d) => d && fs.existsSync(path.join(d, bin)));
24
+ }
25
+
26
+ /** Every engine, with whether it can run here, for pickers and the hub. */
27
+ export function listEngines(config) {
28
+ return Object.values(ENGINES).map((e) => ({ id: e.id, label: e.label, installed: installed(e, config), permissionModes: e.permissionModes, supports: e.supports }));
29
+ }
30
+
31
+ /** The engine for an agent (or an engine id). */
32
+ export function engineOf(ref) {
33
+ const id = typeof ref === 'string' ? ref : ref?.engine ?? DEFAULT_ENGINE;
34
+ const engine = Object.hasOwn(ENGINES, id) ? ENGINES[id] : null;
35
+ if (!engine) throw Object.assign(new Error(`Unknown engine "${String(id).slice(0, 30)}" (known: ${Object.keys(ENGINES).join(', ')})`), { status: 400 });
36
+ return engine;
37
+ }
package/src/fleet.js ADDED
@@ -0,0 +1,176 @@
1
+ // What a runner tells its hub: a small, whitelisted view of each agent and of what is
2
+ // waiting on the user. No transcripts, terminal output, file contents or local paths.
3
+ // The hub runs the same functions again on what it receives, so a misbehaving runner
4
+ // can't push arbitrary fields or huge strings into the fleet UI.
5
+
6
+ export const PROTOCOL = 1;
7
+ const MAX_AGENTS = 500;
8
+ const MAX_INBOX = 500;
9
+
10
+ const str = (v, n = 200) => (v == null ? null : String(v).slice(0, n));
11
+ const num = (v) => (Number.isFinite(Number(v)) && v !== null && v !== '' ? Number(v) : null);
12
+ const iso = (v) => (typeof v === 'string' && !Number.isNaN(Date.parse(v)) ? v.slice(0, 40) : null);
13
+ // Busy agents print constantly; to the minute is enough, and keeps unchanged states unsent.
14
+ const minute = (v) => (iso(v) ? new Date(Math.floor(Date.parse(v) / 60_000) * 60_000).toISOString() : null);
15
+ const httpUrl = (v) => (typeof v === 'string' && /^https?:\/\/[^\s"'<>]+$/i.test(v) ? v.slice(0, 500) : null);
16
+ const list = (v, n) => (Array.isArray(v) ? v.slice(0, n) : []);
17
+
18
+ /** One agent, from a manager view (runner side) or a received fleet agent (hub side). */
19
+ export function fleetAgent(a) {
20
+ if (!a || typeof a !== 'object') return null;
21
+ const rt = a.runtime ?? {};
22
+ return {
23
+ id: str(a.id, 40),
24
+ name: str(a.name, 120),
25
+ status: str(a.status, 20),
26
+ kind: str(a.kind, 20),
27
+ engine: str(a.engine ?? 'claude', 20),
28
+ intent: str(a.intent, 600),
29
+ project: str(a.projectInfo ? (a.projectInfo.key === 'other' ? null : a.projectInfo.name) : a.project, 60),
30
+ repo: httpUrl(a.repo) ?? (typeof a.repo === 'string' && /^[\w.-]+@[\w.-]+:[\w./-]+$/.test(a.repo) ? a.repo.slice(0, 300) : null),
31
+ branch: str(a.git?.branch ?? a.branch, 200),
32
+ priority: num(a.priority) ?? 2,
33
+ working: Boolean(rt.busy ?? a.working),
34
+ planning: Boolean(rt.planning ?? a.planning),
35
+ attention: str(rt.attention ?? a.attention, 120),
36
+ outcome: str(a.results?.outcome ?? a.outcome, 40),
37
+ briefStatus: str(a.brief?.status ?? a.briefStatus, 40),
38
+ briefAt: iso(a.brief?.updatedAt ?? a.briefAt),
39
+ prs: list(a.prs, 20)
40
+ .map((p) => ({ url: httpUrl(p?.url), number: num(p?.number), state: str(p?.state, 20), title: str(p?.title, 200) }))
41
+ .filter((p) => p.url),
42
+ costUsd: num(a.costUsd),
43
+ tokens: num(a.usage?.io ?? a.tokens) ?? 0,
44
+ questions: Array.isArray(a.questions) ? a.questions.filter((q) => !q.answer).length : num(a.questions) ?? 0,
45
+ stuck: Array.isArray(a.stuck) ? a.stuck.length : num(a.stuck) ?? 0,
46
+ conflicts: Array.isArray(a.conflicts) ? a.conflicts.length : num(a.conflicts) ?? 0,
47
+ raceId: str(a.raceId, 20),
48
+ error: str(a.error, 300),
49
+ createdAt: iso(a.createdAt),
50
+ updatedAt: iso(a.updatedAt),
51
+ lastOutputAt: minute(rt.lastOutputAt ?? a.lastOutputAt),
52
+ };
53
+ }
54
+
55
+ /** One inbox item (see AgentManager.inbox), trimmed to what the fleet inbox shows. */
56
+ export function fleetInboxItem(it) {
57
+ if (!it || typeof it !== 'object' || !['prompt', 'question', 'stuck', 'conflict'].includes(it.kind)) return null;
58
+ const out = {
59
+ kind: it.kind,
60
+ key: str(it.key, 200),
61
+ agentId: str(it.agentId, 40),
62
+ agentName: str(it.agentName, 120),
63
+ project: str(it.project, 60),
64
+ priority: num(it.priority) ?? 2,
65
+ title: str(it.title, 500),
66
+ at: iso(it.at),
67
+ };
68
+ if (it.kind === 'prompt') out.choices = list(it.prompt?.choices ?? it.choices, 9).map((c) => ({ key: str(c?.key, 4), label: str(c?.label, 120) }));
69
+ if (it.kind === 'question') {
70
+ const q = it.question ?? {};
71
+ out.question = { id: str(q.id, 40), options: list(q.options, 10).map((o) => str(o, 200)), context: str(q.context, 500), default: str(q.default, 200) };
72
+ }
73
+ if (it.kind === 'stuck') {
74
+ out.detail = str(it.finding?.detail ?? it.detail, 500);
75
+ out.stuckKey = str(it.finding?.key ?? it.stuckKey, 100);
76
+ out.nudge = str(it.finding?.nudge ?? it.nudge, 2000);
77
+ }
78
+ if (it.kind === 'conflict') {
79
+ const c = it.conflict ?? {};
80
+ out.with = str(c.agent?.name ?? it.with, 120);
81
+ out.withId = str(c.agent?.id ?? it.withId, 40);
82
+ out.mergeFirst = str(c.mergeFirst ?? it.mergeFirst, 40);
83
+ out.files = list(c.files ?? it.files, 20).map((f) => str(typeof f === 'string' ? f : f?.file, 300));
84
+ }
85
+ return out;
86
+ }
87
+
88
+ /** Projects a runner shares with the hub: ["*"] for all, else project names or shortcuts ("cc"). */
89
+ export function allowedProject(projects, ...names) {
90
+ const allow = Array.isArray(projects) && projects.length ? projects : ['*'];
91
+ return allow.includes('*') || names.some((n) => n != null && allow.includes(n));
92
+ }
93
+
94
+ /** A whole runner state, as sent in a `state` frame. Inbox items follow their agent's project. */
95
+ export function fleetState({ agents = [], inbox = [], projects: registered = [], capacity = null, labels = [] } = {}, { projects } = {}) {
96
+ const shared = list(agents, MAX_AGENTS).filter((a) => allowedProject(projects, a?.projectInfo?.name ?? a?.project, a?.projectInfo?.shortcut));
97
+ const out = shared.map(fleetAgent).filter((a) => a?.id);
98
+ const byId = new Map(out.map((a) => [a.id, a]));
99
+ return {
100
+ agents: out,
101
+ inbox: list(inbox, MAX_INBOX)
102
+ .map(fleetInboxItem)
103
+ .filter((i) => i?.agentId && byId.has(i.agentId))
104
+ .map((i) => ({ ...i, project: byId.get(i.agentId).project })),
105
+ // Projects new agents can be started in (sent only when the machine allows "create").
106
+ // ref names the project across machines (its repo, else its name); warm: already cloned here.
107
+ projects: list(registered, 200)
108
+ .filter((p) => p && allowedProject(projects, p.name, p.shortcut))
109
+ .map((p) => ({ shortcut: str(p.shortcut, 16), name: str(p.name, 60), ref: projectRef(p), warm: p.warm !== false }))
110
+ .filter((p) => p.shortcut),
111
+ capacity: fleetCapacity(capacity),
112
+ labels: list(labels, 20).map((l) => label(l)).filter(Boolean),
113
+ };
114
+ }
115
+
116
+ /** A label for scheduling, like "os:mac", "gpu" or "fast-net". */
117
+ export const label = (v) => {
118
+ const s = String(v ?? '').trim().toLowerCase().slice(0, 40);
119
+ return /^[a-z0-9][\w.:-]*$/.test(s) ? s : null;
120
+ };
121
+
122
+ /**
123
+ * How a project is known across machines: its repo ("github.com/org/repo"), so two clones
124
+ * of one repo match, else "name:<name>". Never a local path.
125
+ */
126
+ export function projectRef(p) {
127
+ if (typeof p?.ref === 'string' && /^(repo|name):[^\s]{1,200}$/.test(p.ref)) return p.ref.toLowerCase().slice(0, 205);
128
+ if (typeof p?.key === 'string' && p.key.startsWith('repo:') && !p.key.startsWith('repo:/')) return p.key.toLowerCase().slice(0, 205);
129
+ return `name:${String(p?.name ?? '').toLowerCase().slice(0, 60)}`;
130
+ }
131
+
132
+ /** Room for scheduled work: limits in total and per project, and what is busy outside the hub. */
133
+ function fleetCapacity(c) {
134
+ if (!c || typeof c !== 'object') return null;
135
+ const n = (v, d) => Math.max(0, Math.min(50, Math.floor(num(v) ?? d)));
136
+ const busyBy = {};
137
+ for (const [k, v] of Object.entries(c.busyBy ?? {}).slice(0, 200)) busyBy[projectRef({ ref: k })] = n(v, 0);
138
+ return { max: n(c.max, 4), perProject: n(c.perProject, 2), busy: n(c.busy, 0), busyBy };
139
+ }
140
+
141
+ /** The UI addresses a runner reports (its remote-access URLs), for "Open on <machine>". */
142
+ export function fleetUrls(urls) {
143
+ return list(urls, 10)
144
+ .map((u) => ({ url: httpUrl(u?.url), label: str(u?.label, 40), tailscale: Boolean(u?.tailscale) }))
145
+ .filter((u) => u.url);
146
+ }
147
+
148
+ /** Tailscale (CGNAT 100.64.0.0/10) addresses and MagicDNS names. */
149
+ export function isTailscaleHost(host) {
150
+ const h = String(host ?? '').toLowerCase().replace(/^\[|\]$/g, '');
151
+ if (h.endsWith('.ts.net')) return true;
152
+ const m = h.match(/^100\.(\d+)\.\d+\.\d+$/);
153
+ return Boolean(m && Number(m[1]) >= 64 && Number(m[1]) <= 127);
154
+ }
155
+
156
+ export const isLoopback = (h) => ['127.0.0.1', 'localhost', '[::1]', '::1'].includes(String(h).toLowerCase());
157
+
158
+ /**
159
+ * Hub URLs a runner accepts: https anywhere; plain http only on this machine or over
160
+ * Tailscale, which already encrypts the traffic.
161
+ */
162
+ export function checkHubUrl(raw) {
163
+ let u;
164
+ try {
165
+ u = new URL(String(raw ?? '').trim());
166
+ } catch {
167
+ throw Object.assign(new Error('Hub URL must look like https://hub.example.com'), { status: 400 });
168
+ }
169
+ if (u.protocol === 'https:' || (u.protocol === 'http:' && (isLoopback(u.hostname) || isTailscaleHost(u.hostname)))) {
170
+ return u.origin;
171
+ }
172
+ throw Object.assign(new Error('Use https:// for the hub (plain http only for localhost or a Tailscale address)'), { status: 400 });
173
+ }
174
+
175
+ /** Signed by the runner's key on every connection, so the hub knows which runner it is. */
176
+ export const challengePayload = (nonce, runnerId) => Buffer.from(`agentmgr-hub-v${PROTOCOL}:${nonce}:${runnerId}`);