@ulm0/gonogo 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,9 @@ import { chmod, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, sym
9
9
  import { homedir } from 'node:os';
10
10
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
11
11
  import { cleanRoomBranch, HOOK_EVENTS, MCP_SERVER_NAME, PERMISSION_MODES, PROVIDER_INFO } from '../shared/protocol.js';
12
- import { AGENT_NAME_PATTERN, AGENT_TOKEN_FILE, AGENTS_DIR, ALLOWED_TOOLS, API_KEY_HELPER_COMMAND, CLAUDE_BIN, CLEAN_ROOM_CREDENTIALS, CLEAN_ROOM_ENV, CLEAN_ROOM_NOTE, COLORTERM_VALUE, DENIED_TOOLS, DIR_MODE, DOCKER_BIN, FILE_MODE, HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_FILE, MCP_PATH, MEMORY_FILE, nullLogger, PAYLOAD_PLUGIN_DIR, PAYLOAD_PLUGIN_NAME, ROLE_PREAMBLE, SCRUB_ENV_EXACT, SCRUB_ENV_PREFIXES, SETTINGS_FILE, TERM_VALUE, TOKEN_BYTES, TRUST_VERIFY_ATTEMPTS, TRUST_VERIFY_DELAY_MS, } from './constants.js';
12
+ import { AGENT_NAME_PATTERN, AGENT_TOKEN_FILE, AGENTS_DIR, ALLOWED_TOOLS, API_KEY_HELPER_COMMAND, CLAUDE_BIN, CLEAN_ROOM_CREDENTIALS, CLEAN_ROOM_ENV, CLEAN_ROOM_NOTE, WORKTREE_NOTE, COLORTERM_VALUE, DENIED_TOOLS, DIR_MODE, DOCKER_BIN, FILE_MODE, HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_FILE, MCP_PATH, MEMORY_FILE, nullLogger, PAYLOAD_PLUGIN_DIR, PAYLOAD_PLUGIN_NAME, ROLE_PREAMBLE, SCRUB_ENV_EXACT, SCRUB_ENV_PREFIXES, SETTINGS_FILE, TERM_VALUE, TOKEN_BYTES, TRUST_VERIFY_ATTEMPTS, TRUST_VERIFY_DELAY_MS, } from './constants.js';
13
+ import { prepareWorktree } from './worktree.js';
14
+ import { remoteControlName } from './remotecontrol.js';
13
15
  import { buildDockerArgs, cleanRoomImage, containerUrl, prepareCleanRoom, removeContainer } from './cleanroom.js';
14
16
  import { parseAgentCmd } from './command.js';
15
17
  import { buildProviderStart } from './providers.js';
@@ -99,6 +101,7 @@ export function buildArgv(input) {
99
101
  input.mcpPath,
100
102
  ...(input.pluginDir ? ['--plugin-dir', input.pluginDir] : []),
101
103
  ...(input.model ? ['--model', input.model] : []),
104
+ ...(input.remoteControl ? ['--remote-control', input.remoteControl] : []),
102
105
  '--append-system-prompt',
103
106
  input.roleText,
104
107
  '--system-prompt-snapshot',
@@ -393,9 +396,11 @@ export function createLauncher(options) {
393
396
  const dirInfo = await stat(agent.dir).catch(() => null);
394
397
  if (!dirInfo?.isDirectory())
395
398
  throw new Error(`working directory does not exist: ${agent.dir}`);
396
- return { spec: { file, args, env: buildChildEnv({ base: options.env ?? process.env, token: null, seed: false, keys: options.keys?.(name) }), cwd: agent.dir }, flag: 'session-id', token: '' };
399
+ return { spec: { file, args, env: buildChildEnv({ base: options.env ?? process.env, token: null, seed: false, keys: options.keys?.(name) }), cwd: (await plainWorktree(agent, options.env ?? process.env))?.cwd ?? agent.dir }, flag: 'session-id', token: '' };
397
400
  };
398
401
  /** Engine Bay: another agent CLI, started by its program name with the files and flags of its adapter (providers.ts). */
402
+ /** A plain worktree (not a Clean Room's): made or found, and the folder the agent starts in; null when the agent starts in its own folder. */
403
+ const plainWorktree = async (agent, from) => (agent.worktree === undefined || agent.cleanRoom !== undefined ? null : prepareWorktree(agent, homeDir, from));
399
404
  const prepareOther = async (agent, provider, base, hubUrl, memoryPath, token) => {
400
405
  const ctx = {
401
406
  name: agent.name,
@@ -408,14 +413,14 @@ export function createLauncher(options) {
408
413
  tokenFile: join(base, AGENT_TOKEN_FILE),
409
414
  token,
410
415
  seed: options.seed,
411
- model: agent.model,
416
+ model: agent.model ?? options.defaultModel?.(provider),
412
417
  };
413
418
  const start = buildProviderStart(provider, ctx);
414
419
  for (const [file, content] of Object.entries(start.files))
415
420
  await writeFileAtomic(join(base, file), content, FILE_MODE);
416
421
  const env = { ...buildChildEnv({ base: options.env ?? process.env, token, seed: false, keys: options.keys?.(agent.name) }), ...start.env };
417
422
  log.debug(`prepared ${agent.name} to run ${provider}`);
418
- return { spec: { file: PROVIDER_INFO[provider].bin, args: start.args, env, cwd: agent.dir }, flag: 'session-id', token };
423
+ return { spec: { file: PROVIDER_INFO[provider].bin, args: start.args, env, cwd: (await plainWorktree(agent, options.env ?? process.env))?.cwd ?? agent.dir }, flag: 'session-id', token };
419
424
  };
420
425
  const prepareStart = async (agent, opts) => {
421
426
  const { name } = agent;
@@ -458,6 +463,7 @@ export function createLauncher(options) {
458
463
  await removals.get(name);
459
464
  const clean = agent.cleanRoom === undefined ? null : await prepareCleanRoom(agent, homeDir, base, env);
460
465
  // A fresh container home has no folder trust and no login, so its dialogs are skipped as in seed mode.
466
+ const plain = await plainWorktree(agent, env);
461
467
  const seed = options.seed || clean !== null;
462
468
  const agentUrl = clean === null ? hubUrl : containerUrl(hubUrl);
463
469
  const settingsPath = join(base, SETTINGS_FILE);
@@ -469,8 +475,9 @@ export function createLauncher(options) {
469
475
  await writeFileAtomic(mcpPath, JSON.stringify(buildMcpConfig(agentUrl, agent.payload?.mcpServers), null, 2), FILE_MODE);
470
476
  const pluginDir = await writeSkillsPlugin(base, agent.payload?.skills);
471
477
  const configDir = hasText(env.CLAUDE_CONFIG_DIR) ? env.CLAUDE_CONFIG_DIR : null;
472
- const realDir = await realpath(dir).catch(() => dir);
473
- const trustDirs = clean === null ? [...new Set([realDir, dir])] : [clean.cwd];
478
+ const startDir = plain?.cwd ?? dir;
479
+ const realDir = await realpath(startDir).catch(() => startDir);
480
+ const trustDirs = clean === null ? [...new Set([realDir, startDir])] : [clean.cwd];
474
481
  // the folder of the config that claude reads: the owner's, or the container's own home
475
482
  const claudeRoot = clean === null ? configDir ?? homedir() : clean.home;
476
483
  const claudeJson = join(claudeRoot, CLAUDE_JSON);
@@ -491,14 +498,14 @@ export function createLauncher(options) {
491
498
  recheck = () => recheckTrust(name, claudeJson, written, trustDirs);
492
499
  }
493
500
  const projectsRoot = join(clean === null ? configDir ?? join(homedir(), '.claude') : clean.home, 'projects');
494
- const flag = opts.flag ?? ((await transcriptExists(projectsRoot, clean === null ? [dir, realDir] : [clean.cwd], agent.sessionId)) ? 'resume' : 'session-id');
495
- const roleText = buildRoleText(name, agent.role, memoryPath) + (clean === null ? '' : `\n${CLEAN_ROOM_NOTE.replace('{branch}', cleanRoomBranch(name))}`);
496
- const claudeArgs = buildArgv({ flag, sessionId: agent.sessionId, mode: agent.mode, settingsPath, mcpPath, roleText, pluginDir, model: agent.model });
501
+ const flag = opts.flag ?? ((await transcriptExists(projectsRoot, clean === null ? [startDir, realDir] : [clean.cwd], agent.sessionId)) ? 'resume' : 'session-id');
502
+ const roleText = buildRoleText(name, agent.role, memoryPath) + (clean === null ? '' : `\n${CLEAN_ROOM_NOTE.replace('{branch}', cleanRoomBranch(name))}`) + (plain === null ? '' : `\n${WORKTREE_NOTE.replace('{branch}', plain.branch)}`);
503
+ const claudeArgs = buildArgv({ flag, sessionId: agent.sessionId, mode: agent.mode, settingsPath, mcpPath, roleText, pluginDir, model: agent.model ?? options.defaultModel?.('claude'), remoteControl: agent.remoteControl === undefined ? undefined : remoteControlName(name) });
497
504
  const [file, ...leading] = options.agentCmd?.length ? options.agentCmd : [options.claudeBin ?? CLAUDE_BIN];
498
505
  const childEnv = buildChildEnv({ base: env, token, seed, keys });
499
506
  let spec;
500
507
  if (clean === null) {
501
- spec = { file, args: [...leading, ...claudeArgs], env: childEnv, cwd: agent.dir };
508
+ spec = { file, args: [...leading, ...claudeArgs], env: childEnv, cwd: startDir };
502
509
  }
503
510
  else {
504
511
  const uid = process.getuid?.();
@@ -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 { 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';
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, MISSION_GOAL_MAX_CHARS, MISSION_NAME_MAX_CHARS, MISSION_NOTE_MAX_CHARS, MISSION_STATUSES, 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. */
@@ -88,7 +88,7 @@ export function createMcpHandler(deps) {
88
88
  }));
89
89
  server.registerTool('task_create', {
90
90
  description: MCP_DESCRIPTIONS.task_create,
91
- inputSchema: { title: z.string().min(1).max(TASK_TITLE_MAX_CHARS), detail: z.string().max(TASK_DETAIL_MAX_CHARS).optional(), assignee: z.string().min(1).max(64).optional() },
91
+ inputSchema: { title: z.string().min(1).max(TASK_TITLE_MAX_CHARS), detail: z.string().max(TASK_DETAIL_MAX_CHARS).optional(), assignee: z.string().min(1).max(64).optional(), missionId: z.string().min(1).max(16).optional() },
92
92
  }, (args) => guarded('task_create', async () => (tasks ? toolResult({ ok: true, task: await tasks.create(actor, args) }, false) : noBoard())));
93
93
  server.registerTool('task_update', {
94
94
  description: MCP_DESCRIPTIONS.task_update,
@@ -97,8 +97,47 @@ export function createMcpHandler(deps) {
97
97
  status: z.enum(TASK_STATUSES).optional(),
98
98
  assignee: z.string().min(1).max(64).nullable().optional(),
99
99
  note: z.string().max(TASK_NOTE_MAX_CHARS).optional(),
100
+ missionId: z.string().min(1).max(16).nullable().optional(),
100
101
  },
101
102
  }, ({ id, ...patch }) => guarded('task_update', async () => (tasks ? toolResult({ ok: true, task: await tasks.update(actor, id, patch) }, false) : noBoard())));
103
+ const { missions } = deps;
104
+ const noMissions = () => toolResult({ ok: false, error: 'Missions are not available' }, true);
105
+ const bossOnly = () => toolResult({ ok: false, error: 'only the boss may change missions' }, true);
106
+ const isBoss = () => hub.rosterFor(agent, generation).boss === agent;
107
+ server.registerTool('mission_list', { description: MCP_DESCRIPTIONS.mission_list, inputSchema: { status: z.enum(MISSION_STATUSES).optional() } }, (args) => guarded('mission_list', () => {
108
+ if (!missions)
109
+ return noMissions();
110
+ const found = missions
111
+ .list()
112
+ .filter((m) => args.status === undefined || m.status === args.status)
113
+ .sort((a, b) => b.updatedAt - a.updatedAt);
114
+ const taskList = tasks?.list() ?? [];
115
+ const shown = found.map((m) => {
116
+ const mine = taskList.filter((t) => t.missionId === m.id);
117
+ return { ...m, tasksDone: mine.filter((t) => t.status === 'done').length, tasksTotal: mine.length };
118
+ });
119
+ return toolResult({ count: shown.length, missions: shown }, false);
120
+ }));
121
+ server.registerTool('mission_create', {
122
+ description: MCP_DESCRIPTIONS.mission_create,
123
+ inputSchema: { name: z.string().min(1).max(MISSION_NAME_MAX_CHARS), goal: z.string().max(MISSION_GOAL_MAX_CHARS).optional(), lead: z.string().min(1).max(64).optional() },
124
+ }, (args) => guarded('mission_create', async () => {
125
+ if (!missions)
126
+ return noMissions();
127
+ if (!isBoss())
128
+ return bossOnly();
129
+ return toolResult({ ok: true, mission: await missions.create(actor, args) }, false);
130
+ }));
131
+ server.registerTool('mission_update', {
132
+ description: MCP_DESCRIPTIONS.mission_update,
133
+ inputSchema: { id: z.string().min(1).max(16), status: z.enum(MISSION_STATUSES).optional(), note: z.string().max(MISSION_NOTE_MAX_CHARS).optional() },
134
+ }, ({ id, ...patch }) => guarded('mission_update', async () => {
135
+ if (!missions)
136
+ return noMissions();
137
+ if (!isBoss())
138
+ return bossOnly();
139
+ return toolResult({ ok: true, mission: await missions.update(actor, id, patch) }, false);
140
+ }));
102
141
  const { missionLog } = deps;
103
142
  const noLog = () => toolResult({ ok: false, error: 'the Mission Log is not available' }, true);
104
143
  server.registerTool('log_write', {
@@ -19,7 +19,7 @@
19
19
  import { randomBytes } from 'node:crypto';
20
20
  import { chmodSync, constants, copyFileSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
21
21
  import { basename, dirname, join } from 'node:path';
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
+ import { AGENTS_FILE, DOCKING_FILE, DOWNLINK_FILE, FILE_MODE, KEYS_FILE, LIVERY_DIR, LIVERY_FILE, PRICES_FILE, PROPELLANT_FILE, RELAY_FILE, ROLLOUT_FILE, SCHEDULES_FILE, STATION_FILE, TASKS_FILE, UPLINKS_FILE, } from './constants.js';
23
23
  const ALL_JSON = '/*.json';
24
24
  /** Everything is still at version 1: no step yet. */
25
25
  export const FORMATS = [
@@ -33,6 +33,7 @@ export const FORMATS = [
33
33
  STATION_FILE,
34
34
  LIVERY_FILE,
35
35
  PROPELLANT_FILE,
36
+ PRICES_FILE,
36
37
  KEYS_FILE,
37
38
  ROLLOUT_FILE,
38
39
  LIVERY_DIR + ALL_JSON,
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Missions (docs/missions-spec.md): a named goal with a status, a lead and a history. Its tasks are the tasks of the Flight Plan
3
+ * whose `missionId` is its id, so the list of a mission is derived and a task is in one place only.
4
+ *
5
+ * The Director (the browser) changes everything; the boss may make a mission and change its status through the MCP tools
6
+ * (mission_create, mission_update), every other agent only reads. The server stamps the actor on each history line. Becoming
7
+ * `active` briefs the boss once (a message from the Director, or from the boss itself when it did it). Nothing closes a mission by
8
+ * itself: when the last open task of an active mission is done, the Director is told once and decides. The clock, the lists of the
9
+ * room and the send are injected for tests.
10
+ *
11
+ * shortcut: the whole list is in every frame and every snapshot; at the limits (50 open missions with 2000-character goals) that
12
+ * is far below the 4 MB socket buffer of web.ts.
13
+ * shortcut: `lead` is an agent name, so a mission does not follow a renamed console, as `assignee` of a task does not.
14
+ */
15
+ import { randomBytes } from 'node:crypto';
16
+ import { readFile, rename, writeFile } from 'node:fs/promises';
17
+ import { join } from 'node:path';
18
+ import { AGENT_NAME_PATTERN, MISSION_GOAL_MAX_CHARS, MISSION_NAME_MAX_CHARS, MISSION_NOTE_MAX_CHARS, MISSION_STATUSES, MISSIONS_OPEN_MAX, missionSubject, SUBJECT_MAX_CHARS, } from '../shared/protocol.js';
19
+ import { FILE_MODE, MISSION_NOTES_MAX, MISSIONS_DONE_KEEP, MISSIONS_FILE } from './constants.js';
20
+ import { isRecord } from './hooks.js';
21
+ import { HubError } from './hub.js';
22
+ import { UNSAFE_IN_NAME } from './schedules.js';
23
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
24
+ const ID_RE = /^ms[1-9]\d{0,5}$/;
25
+ const CREATE_FIELDS = ['name', 'goal', 'lead'];
26
+ const PATCH_FIELDS = ['name', 'goal', 'status', 'lead', 'note'];
27
+ const bad = (message, field) => new HubError('bad_request', message, field);
28
+ const copy = (m) => ({ ...m, history: [...m.history] });
29
+ const isFinished = (m) => m.status === 'done' || m.status === 'aborted';
30
+ const stamp = (at) => `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
31
+ const line = (actor, text, at) => `${stamp(at)} ${actor.kind === 'agent' ? actor.name : 'Director'}: ${text}`;
32
+ function validate(input, whole, isAgent) {
33
+ if (!isRecord(input))
34
+ throw bad('request body must be a JSON object');
35
+ const allowed = whole ? CREATE_FIELDS : PATCH_FIELDS;
36
+ for (const key of Object.keys(input))
37
+ if (!allowed.includes(key))
38
+ throw bad(`unknown field "${key}"`, key);
39
+ if (whole && input.name === undefined)
40
+ throw bad('name is required', 'name');
41
+ if (!whole && Object.keys(input).length === 0)
42
+ throw bad('nothing to change: give a name, a goal, a status, a lead or a note');
43
+ const out = {};
44
+ if (input.name !== undefined) {
45
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
46
+ if (name === '' || name.length > MISSION_NAME_MAX_CHARS || UNSAFE_IN_NAME.test(name))
47
+ throw bad(`name must be 1 to ${MISSION_NAME_MAX_CHARS} characters on one line`, 'name');
48
+ out.name = name;
49
+ }
50
+ if (input.goal !== undefined) {
51
+ if (typeof input.goal !== 'string' || input.goal.length > MISSION_GOAL_MAX_CHARS)
52
+ throw bad(`goal must be text of at most ${MISSION_GOAL_MAX_CHARS} characters`, 'goal');
53
+ out.goal = input.goal.trim();
54
+ }
55
+ if (input.status !== undefined) {
56
+ if (typeof input.status !== 'string' || !MISSION_STATUSES.includes(input.status))
57
+ throw bad(`status must be one of: ${MISSION_STATUSES.join(', ')}`, 'status');
58
+ out.status = input.status;
59
+ }
60
+ if (input.lead !== undefined) {
61
+ if (input.lead !== null && (typeof input.lead !== 'string' || !NAME_RE.test(input.lead) || !isAgent(input.lead)))
62
+ throw bad('lead must be the name of an agent in the room, or null', 'lead');
63
+ out.lead = input.lead;
64
+ }
65
+ if (input.note !== undefined) {
66
+ const note = typeof input.note === 'string' ? input.note.replace(/\s+/g, ' ').trim() : '';
67
+ if (note === '' || note.length > MISSION_NOTE_MAX_CHARS || UNSAFE_IN_NAME.test(note))
68
+ throw bad(`note must be 1 to ${MISSION_NOTE_MAX_CHARS} characters`, 'note');
69
+ out.note = note;
70
+ }
71
+ return out;
72
+ }
73
+ /** A saved record read back; one that is not a mission throws, and the caller skips it. */
74
+ function fromRecord(raw, at) {
75
+ if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
76
+ throw new Error('no valid id');
77
+ const { id, name, goal, status, lead, createdBy, createdAt, updatedAt, startedAt, endedAt, history } = raw;
78
+ if (typeof name !== 'string' || name === '' || name.length > MISSION_NAME_MAX_CHARS)
79
+ throw new Error('no valid name');
80
+ if (typeof status !== 'string' || !MISSION_STATUSES.includes(status))
81
+ throw new Error('no valid status');
82
+ const time = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
83
+ return {
84
+ id,
85
+ name,
86
+ goal: typeof goal === 'string' ? goal.slice(0, MISSION_GOAL_MAX_CHARS) : '',
87
+ status: status,
88
+ lead: typeof lead === 'string' && NAME_RE.test(lead) ? lead : null,
89
+ createdBy: typeof createdBy === 'string' && NAME_RE.test(createdBy) ? createdBy : 'user',
90
+ createdAt: time(createdAt) ?? at,
91
+ updatedAt: time(updatedAt) ?? at,
92
+ startedAt: time(startedAt),
93
+ endedAt: time(endedAt),
94
+ history: Array.isArray(history) ? history.filter((n) => typeof n === 'string').slice(-MISSION_NOTES_MAX) : [],
95
+ };
96
+ }
97
+ export function createMissions(options) {
98
+ const { dir, now, log } = options;
99
+ const path = join(dir, MISSIONS_FILE);
100
+ let missions = [];
101
+ let seq = 0;
102
+ let chain = Promise.resolve();
103
+ /** Open tasks of each active mission at the last look, to tell once when the last one is done. */
104
+ const openBefore = new Map();
105
+ const later = (fn) => {
106
+ const run = chain.then(fn);
107
+ chain = run.catch((error) => log.error('missions could not write', error));
108
+ return run.then(() => undefined);
109
+ };
110
+ const save = () => {
111
+ // `seq` is the number of the last id given, so an id that was removed or trimmed is not given again after a restart
112
+ const json = JSON.stringify({ version: 1, seq, missions }, null, 2);
113
+ return later(async () => {
114
+ const tmp = join(dir, `.${MISSIONS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
115
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
116
+ await rename(tmp, path);
117
+ });
118
+ };
119
+ const list = () => missions.map(copy);
120
+ const changed = () => {
121
+ options.emit(list());
122
+ return save();
123
+ };
124
+ const find = (id) => {
125
+ const mission = ID_RE.test(id) ? missions.find((x) => x.id === id) : undefined;
126
+ if (!mission)
127
+ throw new HubError('not_found', 'unknown mission');
128
+ return mission;
129
+ };
130
+ const linked = (id) => options.tasks().filter((t) => t.missionId === id);
131
+ const open = (id) => linked(id).filter((t) => t.status !== 'done');
132
+ const full = () => new HubError('conflict', `at most ${MISSIONS_OPEN_MAX} missions that are not finished: finish or remove one first`, 'missions');
133
+ /** The 20 most recent finished missions stay, so the file and every frame stop growing. */
134
+ const prune = () => {
135
+ const done = missions.filter(isFinished);
136
+ if (done.length <= MISSIONS_DONE_KEEP)
137
+ return;
138
+ const drop = new Set(done.sort((a, b) => (b.endedAt ?? b.updatedAt) - (a.endedAt ?? a.updatedAt)).slice(MISSIONS_DONE_KEEP));
139
+ missions = missions.filter((x) => !drop.has(x));
140
+ for (const m of drop)
141
+ void options.unlink(m.id).catch(() => undefined);
142
+ };
143
+ /** The briefing of the boss when a mission starts: once, as a message from whoever started it. A refusal is a note, not a failure. */
144
+ const brief = (actor, mission, at) => {
145
+ const boss = options.boss();
146
+ if (boss === null || (actor.kind === 'agent' && actor.name === boss))
147
+ return;
148
+ const tasks = open(mission.id);
149
+ const taskLines = tasks.length === 0 ? 'No tasks are linked yet.' : `Open tasks:\n${tasks.map((t) => `- ${t.id} [${t.status}] ${t.title}${t.assignee === null ? '' : ` (${t.assignee})`}`).join('\n')}`;
150
+ const body = `${mission.goal === '' ? '(no goal written)' : mission.goal}\n\n${taskLines}\n\nStarted by ${actor.kind === 'agent' ? actor.name : 'the Director'}. See mission_list; link tasks with missionId.`;
151
+ try {
152
+ const sent = options.send(actor, { to: boss, subject: missionSubject(mission.name).slice(0, SUBJECT_MAX_CHARS), body });
153
+ if (!sent.ok)
154
+ mission.history.push(line(actor, `the briefing to ${boss} was not delivered: ${sent.note ?? 'no reason given'}`, at));
155
+ }
156
+ catch (error) {
157
+ mission.history.push(line(actor, `the briefing to ${boss} was not sent: ${error instanceof HubError ? error.message : 'it failed'}`, at));
158
+ }
159
+ };
160
+ return {
161
+ async load() {
162
+ let saved = null;
163
+ try {
164
+ saved = JSON.parse(await readFile(path, 'utf8'));
165
+ if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.missions))
166
+ throw new Error('not a version 1 missions file');
167
+ }
168
+ catch (error) {
169
+ saved = null;
170
+ if (error.code !== 'ENOENT') {
171
+ // kept aside, so that the next save cannot overwrite what the Director and the boss wrote
172
+ log.error(`${MISSIONS_FILE} could not be read; the room starts with no missions and the file is kept as ${MISSIONS_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
173
+ await rename(path, `${path}.bad`).catch(() => undefined);
174
+ }
175
+ }
176
+ const records = isRecord(saved) && Array.isArray(saved.missions) ? saved.missions : [];
177
+ if (isRecord(saved) && typeof saved.seq === 'number' && Number.isSafeInteger(saved.seq) && saved.seq > 0)
178
+ seq = saved.seq;
179
+ for (const raw of records) {
180
+ try {
181
+ const mission = fromRecord(raw, now());
182
+ if (missions.some((x) => x.id === mission.id))
183
+ throw new Error(`the id ${mission.id} is used twice`);
184
+ missions.push(mission);
185
+ seq = Math.max(seq, Number(mission.id.slice(2)));
186
+ }
187
+ catch (error) {
188
+ log.warn(`${MISSIONS_FILE}: a mission was skipped: ${error instanceof Error ? error.message : String(error)}`);
189
+ }
190
+ }
191
+ },
192
+ list,
193
+ has: (id) => ID_RE.test(id) && missions.some((x) => x.id === id),
194
+ async create(actor, input) {
195
+ const request = validate(input, true, options.isAgent);
196
+ if (missions.filter((m) => !isFinished(m)).length >= MISSIONS_OPEN_MAX)
197
+ throw full();
198
+ const at = now();
199
+ const lead = request.lead === undefined ? options.boss() : request.lead;
200
+ const mission = {
201
+ id: `ms${seq + 1}`,
202
+ name: request.name ?? '',
203
+ goal: request.goal ?? '',
204
+ status: 'planned',
205
+ lead,
206
+ createdBy: actor.kind === 'agent' ? actor.name : 'user',
207
+ createdAt: at,
208
+ updatedAt: at,
209
+ startedAt: null,
210
+ endedAt: null,
211
+ history: [line(actor, lead === null ? 'created' : `created; lead ${lead}`, at)],
212
+ };
213
+ seq += 1;
214
+ missions.push(mission);
215
+ prune();
216
+ await changed();
217
+ return copy(mission);
218
+ },
219
+ async update(actor, id, input) {
220
+ const mission = find(id);
221
+ const patch = validate(input, false, options.isAgent);
222
+ // an agent (the boss) changes the status and writes notes; the name, the goal and the lead are the Director's
223
+ if (actor.kind === 'agent') {
224
+ for (const key of ['name', 'goal', 'lead'])
225
+ if (patch[key] !== undefined)
226
+ throw new HubError('forbidden', `only the Director changes the ${key} of a mission`, key);
227
+ }
228
+ const at = now();
229
+ const next = copy(mission);
230
+ const parts = [];
231
+ if (patch.name !== undefined && patch.name !== mission.name) {
232
+ next.name = patch.name;
233
+ parts.push('renamed');
234
+ }
235
+ if (patch.goal !== undefined && patch.goal !== mission.goal) {
236
+ next.goal = patch.goal;
237
+ parts.push('goal changed');
238
+ }
239
+ if (patch.lead !== undefined && patch.lead !== mission.lead) {
240
+ next.lead = patch.lead;
241
+ parts.push(patch.lead === null ? 'lead removed' : `lead ${patch.lead}`);
242
+ }
243
+ let started = false;
244
+ let ended = false;
245
+ if (patch.status !== undefined && patch.status !== mission.status) {
246
+ if (isFinished(mission) && !isFinished({ ...mission, status: patch.status }) && missions.filter((m) => !isFinished(m)).length >= MISSIONS_OPEN_MAX)
247
+ throw full();
248
+ next.status = patch.status;
249
+ parts.push(`status ${patch.status}`);
250
+ if (patch.status === 'active') {
251
+ next.startedAt = at;
252
+ started = true;
253
+ }
254
+ next.endedAt = isFinished(next) ? at : null;
255
+ ended = isFinished(next);
256
+ }
257
+ if (patch.note !== undefined)
258
+ parts.push(patch.note);
259
+ if (parts.length === 0)
260
+ return copy(mission);
261
+ next.updatedAt = at;
262
+ next.history.push(line(actor, parts.join('; '), at));
263
+ if (started)
264
+ brief(actor, next, at);
265
+ next.history = next.history.slice(-MISSION_NOTES_MAX);
266
+ missions[missions.indexOf(mission)] = next;
267
+ if (started) {
268
+ openBefore.set(next.id, open(next.id).length);
269
+ options.notify?.('mission', `Mission started: ${next.name}`);
270
+ }
271
+ if (ended) {
272
+ openBefore.delete(next.id);
273
+ const counted = linked(next.id);
274
+ options.notify?.('mission', `Mission ${next.status}: ${next.name} (${counted.filter((t) => t.status === 'done').length} of ${counted.length} tasks done)`);
275
+ }
276
+ if (next.status !== 'active')
277
+ openBefore.delete(next.id);
278
+ prune();
279
+ await changed();
280
+ return copy(next);
281
+ },
282
+ async remove(id, unlink) {
283
+ const mission = find(id);
284
+ const tasks = linked(id);
285
+ if (tasks.length > 0 && !unlink)
286
+ throw new HubError('conflict', `the mission has ${tasks.length} linked ${tasks.length === 1 ? 'task' : 'tasks'}: remove it with unlink to keep them on the board`, 'unlink');
287
+ if (tasks.length > 0)
288
+ await options.unlink(id);
289
+ missions = missions.filter((x) => x !== mission);
290
+ openBefore.delete(id);
291
+ await changed();
292
+ },
293
+ observe(tasks) {
294
+ for (const mission of missions) {
295
+ if (mission.status !== 'active')
296
+ continue;
297
+ const mine = tasks.filter((t) => t.missionId === mission.id);
298
+ const openNow = mine.filter((t) => t.status !== 'done').length;
299
+ const before = openBefore.get(mission.id);
300
+ openBefore.set(mission.id, openNow);
301
+ if (before !== undefined && before > 0 && openNow === 0 && mine.length > 0) {
302
+ options.notify?.('mission', `All ${mine.length} ${mine.length === 1 ? 'task' : 'tasks'} of ${mission.name} are done: close it?`);
303
+ }
304
+ }
305
+ },
306
+ close() {
307
+ return chain.then(() => undefined);
308
+ },
309
+ };
310
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Default models (docs/engine-bay-spec.md): the room's model for each engine that takes one, used at an agent's start when the agent
3
+ * has no `model` of its own. models.json holds `{ version: 1, models: { claude: 'sonnet' } }`; names only, no secret. A model of the
4
+ * agent always wins, and a change applies at the next start of each agent (the launcher asks at every start).
5
+ */
6
+ import { randomBytes } from 'node:crypto';
7
+ import { readFile, rename, rm, writeFile } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import { MODEL_PATTERN, PROVIDERS, providerInfo } from '../shared/protocol.js';
10
+ import { FILE_MODE, MODELS_FILE, nullLogger } from './constants.js';
11
+ import { HubError } from './hub.js';
12
+ const MODEL_RE = new RegExp(MODEL_PATTERN);
13
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ export function createModelDefaults(options) {
15
+ const log = options.log ?? nullLogger;
16
+ const path = join(options.dir, MODELS_FILE);
17
+ let models = {};
18
+ let chain = Promise.resolve();
19
+ const usable = (provider, model) => typeof provider === 'string' && PROVIDERS.includes(provider) && providerInfo(provider).model !== null && typeof model === 'string' && MODEL_RE.test(model);
20
+ return {
21
+ async load() {
22
+ try {
23
+ const saved = JSON.parse(await readFile(path, 'utf8'));
24
+ if (!isRecord(saved) || saved.version !== 1 || !isRecord(saved.models))
25
+ throw new Error('not a version 1 models file');
26
+ models = Object.fromEntries(Object.entries(saved.models).filter(([provider, model]) => usable(provider, model)));
27
+ }
28
+ catch (error) {
29
+ if (error.code === 'ENOENT')
30
+ return;
31
+ log.error(`${MODELS_FILE} could not be read; the room has no default models and the file is kept as ${MODELS_FILE}.bad`, error);
32
+ await rename(path, `${path}.bad`).catch(() => undefined);
33
+ }
34
+ },
35
+ view: () => ({ models: { ...models } }),
36
+ get: (provider) => models[provider],
37
+ async set(provider, model) {
38
+ if (typeof provider !== 'string' || !PROVIDERS.includes(provider))
39
+ throw new HubError('bad_request', 'unknown engine', 'provider');
40
+ if (providerInfo(provider).model === null)
41
+ throw new HubError('bad_request', `${providerInfo(provider).label} takes no model setting`, 'provider');
42
+ const name = model === null || model === undefined ? '' : typeof model === 'string' ? model.trim() : null;
43
+ if (name === null)
44
+ throw new HubError('bad_request', 'model must be text or null', 'model');
45
+ if (name !== '' && !MODEL_RE.test(name))
46
+ throw new HubError('bad_request', 'model must be 1 to 100 letters, digits or . _ : / @ + -, starting with a letter or digit', 'model');
47
+ const run = chain.then(async () => {
48
+ const before = models;
49
+ const next = { ...models };
50
+ if (name === '')
51
+ delete next[provider];
52
+ else
53
+ next[provider] = name;
54
+ if (JSON.stringify(next) === JSON.stringify(before))
55
+ return;
56
+ models = next;
57
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
58
+ try {
59
+ await writeFile(temp, JSON.stringify({ version: 1, models }, null, 2), { flag: 'wx', mode: FILE_MODE });
60
+ await rename(temp, path);
61
+ }
62
+ catch (error) {
63
+ models = before;
64
+ await rm(temp, { force: true }).catch(() => undefined);
65
+ throw new Error(`could not save the default models: ${error instanceof Error ? error.message : String(error)}`);
66
+ }
67
+ });
68
+ chain = run.catch(() => undefined);
69
+ return run.then(() => ({ models: { ...models } }));
70
+ },
71
+ close: () => chain.then(() => undefined),
72
+ };
73
+ }