@ulm0/gonogo 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +30 -2
- package/bin/gonogo.js +18 -0
- package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
- package/dist/client/apple-touch-icon.png +0 -0
- package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
- package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
- package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
- package/dist/client/assets/index-B6MsSoeo.css +1 -0
- package/dist/client/assets/index-DRtiRh1Y.js +31 -0
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.svg +1 -0
- package/dist/client/index.html +19 -0
- package/dist/server/cleanroom.js +214 -0
- package/dist/server/cli.js +630 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +427 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/home.js +497 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2484 -0
- package/dist/server/launcher.js +542 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/mcp.js +196 -0
- package/dist/server/migrate.js +119 -0
- package/dist/server/missionlog.js +209 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +137 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1466 -0
- package/dist/shared/cron.js +149 -0
- package/dist/shared/fuel.js +18 -0
- package/dist/shared/livery.js +348 -0
- package/dist/shared/positions.js +132 -0
- package/dist/shared/protocol.js +212 -0
- package/package.json +84 -3
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Livery: the look of the page, and an agent that designs one (docs/livery-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* Four liveries ship (src/shared/livery.ts). Custom ones are `<home>/liveries/<slug>.json` (mode 0600, in a 0700 folder), each
|
|
5
|
+
* `{ version, name, description, author, tokens }`; the chosen slug is `<home>/livery.json`. Both are written whole through a
|
|
6
|
+
* temporary file and a rename, before the memory changes. A livery is checked on the way in (every token present, each a plain
|
|
7
|
+
* colour, every text pair readable: checkLivery) and again when a file is read, so a hand-made file cannot put a value that is not a
|
|
8
|
+
* colour into the page. An agent submits one with the tool livery_submit; the Director chooses it. Submitting never applies a
|
|
9
|
+
* livery. The send and the clock are injected for tests.
|
|
10
|
+
*
|
|
11
|
+
* shortcut: the custom liveries are read once, at start, so a file put in the folder by hand shows after a restart; watch the
|
|
12
|
+
* folder if that gets in the way.
|
|
13
|
+
* shortcut: a submit under the name of a custom livery replaces it, whoever made it (never the one in use); keep a version per
|
|
14
|
+
* author if that ever matters.
|
|
15
|
+
*/
|
|
16
|
+
import { randomBytes } from 'node:crypto';
|
|
17
|
+
import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { AGENT_NAME_PATTERN } from '../shared/protocol.js';
|
|
20
|
+
import { builtinEntries, checkLivery, contrastRules, DEFAULT_LIVERY, LIVERIES_MAX, LIVERY_BRIEF_MAX_CHARS, LIVERY_DESCRIPTION_MAX_CHARS, LIVERY_NAME_MAX_CHARS, LIVERY_SLUG_PATTERN, LIVERY_TOKENS, MIN_CONTRAST, slugOf, } from '../shared/livery.js';
|
|
21
|
+
import { DIR_MODE, FILE_MODE, LIVERY_DIR, LIVERY_FILE } from './constants.js';
|
|
22
|
+
import { isRecord } from './hooks.js';
|
|
23
|
+
import { HubError } from './hub.js';
|
|
24
|
+
import { UNSAFE_IN_NAME } from './schedules.js';
|
|
25
|
+
const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
|
|
26
|
+
const SLUG_RE = new RegExp(LIVERY_SLUG_PATTERN);
|
|
27
|
+
const FILE_RE = /^([a-z0-9][a-z0-9-]{0,39})\.json$/;
|
|
28
|
+
const SUBMIT_FIELDS = ['name', 'description', 'tokens'];
|
|
29
|
+
/** The answer to a refused submit names this many faults, then says how many more there are. */
|
|
30
|
+
const PROBLEMS_SHOWN = 12;
|
|
31
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
32
|
+
/** The message that asks an agent for a livery: the brief, the tokens with their roles, the contrast rule and what to call. */
|
|
33
|
+
export function designBody(brief) {
|
|
34
|
+
return [
|
|
35
|
+
'The Director asks you to design a livery, a colour theme for gonogo.',
|
|
36
|
+
'',
|
|
37
|
+
`Brief: ${brief}`,
|
|
38
|
+
'',
|
|
39
|
+
`Call mcp__gonogo__livery_submit with a name (1 to ${LIVERY_NAME_MAX_CHARS} characters), a one-line description and tokens: an object that holds every token below and no other. Each value is a CSS colour written as #rgb, #rrggbb, rgb(), hsl() or oklch(), with no alpha, no colour names and no var().`,
|
|
40
|
+
'',
|
|
41
|
+
'Tokens:',
|
|
42
|
+
...LIVERY_TOKENS.map((t) => `${t.name}: ${t.role}`),
|
|
43
|
+
'',
|
|
44
|
+
`Contrast (WCAG 2): a text must reach ${MIN_CONTRAST}:1 on the surfaces it sits on.`,
|
|
45
|
+
...contrastRules().map((line) => `- ${line}`),
|
|
46
|
+
'',
|
|
47
|
+
'If the livery is refused, the answer lists what fails: fix it and submit again. Submitting does not apply it; the Director picks it in the Livery view.',
|
|
48
|
+
].join('\n');
|
|
49
|
+
}
|
|
50
|
+
export function createLiveries(options) {
|
|
51
|
+
const { log } = options;
|
|
52
|
+
const dir = join(options.dir, LIVERY_DIR);
|
|
53
|
+
const choice = join(options.dir, LIVERY_FILE);
|
|
54
|
+
const builtin = builtinEntries();
|
|
55
|
+
const custom = new Map();
|
|
56
|
+
let current = DEFAULT_LIVERY;
|
|
57
|
+
let chain = Promise.resolve();
|
|
58
|
+
/** One write at a time, so the limit holds; a failure goes to the caller and the next write goes on. */
|
|
59
|
+
const locked = (fn) => {
|
|
60
|
+
const run = chain.then(fn);
|
|
61
|
+
chain = run.catch(() => undefined);
|
|
62
|
+
return run;
|
|
63
|
+
};
|
|
64
|
+
const writeAtomic = async (path, value) => {
|
|
65
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
66
|
+
await writeFile(tmp, JSON.stringify(value, null, 2), { mode: FILE_MODE, flag: 'wx' });
|
|
67
|
+
await rename(tmp, path);
|
|
68
|
+
};
|
|
69
|
+
const view = () => ({
|
|
70
|
+
current,
|
|
71
|
+
liveries: [...builtin, ...[...custom.values()].sort((a, b) => (a.slug < b.slug ? -1 : 1))].map((e) => ({ ...e, tokens: { ...e.tokens } })),
|
|
72
|
+
});
|
|
73
|
+
const changed = () => {
|
|
74
|
+
const now = view();
|
|
75
|
+
options.emit({ t: 'livery', livery: now });
|
|
76
|
+
return now;
|
|
77
|
+
};
|
|
78
|
+
const exists = (slug) => builtin.some((b) => b.slug === slug) || custom.has(slug);
|
|
79
|
+
/** A livery from the wire or a file: the name, the description and the tokens, checked. Throws a HubError that says what to fix. */
|
|
80
|
+
function read(input) {
|
|
81
|
+
const name = typeof input.name === 'string' ? input.name.trim() : '';
|
|
82
|
+
if (name === '' || name.length > LIVERY_NAME_MAX_CHARS || UNSAFE_IN_NAME.test(name) || slugOf(name) === '') {
|
|
83
|
+
throw bad(`name must be 1 to ${LIVERY_NAME_MAX_CHARS} characters on one line, with a letter or a digit`, 'name');
|
|
84
|
+
}
|
|
85
|
+
const description = input.description === undefined ? '' : typeof input.description === 'string' ? input.description.trim() : null;
|
|
86
|
+
if (description === null || description.length > LIVERY_DESCRIPTION_MAX_CHARS || UNSAFE_IN_NAME.test(description)) {
|
|
87
|
+
throw bad(`description must be at most ${LIVERY_DESCRIPTION_MAX_CHARS} characters on one line`, 'description');
|
|
88
|
+
}
|
|
89
|
+
const problems = checkLivery(input.tokens);
|
|
90
|
+
if (problems.length > 0) {
|
|
91
|
+
const shown = problems.slice(0, PROBLEMS_SHOWN).join('; ');
|
|
92
|
+
throw bad(problems.length > PROBLEMS_SHOWN ? `${shown}; and ${problems.length - PROBLEMS_SHOWN} more` : shown, 'tokens');
|
|
93
|
+
}
|
|
94
|
+
const tokens = Object.fromEntries(Object.entries(input.tokens).map(([k, v]) => [k, v.trim()]));
|
|
95
|
+
return { name, description, tokens };
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
async load() {
|
|
99
|
+
await mkdir(dir, { recursive: true, mode: DIR_MODE });
|
|
100
|
+
for (const file of await readdir(dir)) {
|
|
101
|
+
const slug = FILE_RE.exec(file)?.[1];
|
|
102
|
+
if (slug === undefined)
|
|
103
|
+
continue;
|
|
104
|
+
try {
|
|
105
|
+
const saved = JSON.parse(await readFile(join(dir, file), 'utf8'));
|
|
106
|
+
if (!isRecord(saved) || saved.version !== 1)
|
|
107
|
+
throw new Error('not a version 1 livery file');
|
|
108
|
+
if (builtin.some((b) => b.slug === slug))
|
|
109
|
+
throw new Error('the name is taken by a livery that ships');
|
|
110
|
+
const { name, description, tokens } = read(saved);
|
|
111
|
+
if (slugOf(name) !== slug)
|
|
112
|
+
throw new Error('the name does not match the name of the file');
|
|
113
|
+
custom.set(slug, { slug, name, description, builtin: false, author: typeof saved.author === 'string' ? saved.author : null, tokens });
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
// the file stays as it is: it may be a hand edit that the Director wants to mend
|
|
117
|
+
log.warn(`${LIVERY_DIR}/${file} was skipped: ${error instanceof Error ? error.message : String(error)}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const saved = JSON.parse(await readFile(choice, 'utf8'));
|
|
122
|
+
if (isRecord(saved) && saved.version === 1 && typeof saved.current === 'string' && exists(saved.current))
|
|
123
|
+
current = saved.current;
|
|
124
|
+
else
|
|
125
|
+
log.warn(`${LIVERY_FILE} does not name a livery that exists; the default is used`);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (error.code !== 'ENOENT')
|
|
129
|
+
log.warn(`${LIVERY_FILE} could not be read; the default is used`);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
view,
|
|
133
|
+
select(input) {
|
|
134
|
+
return locked(async () => {
|
|
135
|
+
if (!isRecord(input))
|
|
136
|
+
throw bad('request body must be a JSON object');
|
|
137
|
+
for (const key of Object.keys(input))
|
|
138
|
+
if (key !== 'slug')
|
|
139
|
+
throw bad(`unknown field "${key}"`, key);
|
|
140
|
+
if (typeof input.slug !== 'string' || !SLUG_RE.test(input.slug))
|
|
141
|
+
throw bad('slug must be the slug of a livery', 'slug');
|
|
142
|
+
if (!exists(input.slug))
|
|
143
|
+
throw new HubError('not_found', 'unknown livery', 'slug');
|
|
144
|
+
if (input.slug === current)
|
|
145
|
+
return view();
|
|
146
|
+
await writeAtomic(choice, { version: 1, current: input.slug });
|
|
147
|
+
current = input.slug;
|
|
148
|
+
return changed();
|
|
149
|
+
});
|
|
150
|
+
},
|
|
151
|
+
remove(slug) {
|
|
152
|
+
return locked(async () => {
|
|
153
|
+
if (builtin.some((b) => b.slug === slug))
|
|
154
|
+
throw new HubError('forbidden', 'a livery that ships cannot be deleted');
|
|
155
|
+
if (!SLUG_RE.test(slug) || !custom.has(slug))
|
|
156
|
+
throw new HubError('not_found', 'unknown livery');
|
|
157
|
+
if (current === slug) {
|
|
158
|
+
await writeAtomic(choice, { version: 1, current: DEFAULT_LIVERY });
|
|
159
|
+
current = DEFAULT_LIVERY;
|
|
160
|
+
}
|
|
161
|
+
// force: a file already deleted by hand must not leave a livery that can never be removed
|
|
162
|
+
await rm(join(dir, `${slug}.json`), { force: true });
|
|
163
|
+
custom.delete(slug);
|
|
164
|
+
return changed();
|
|
165
|
+
});
|
|
166
|
+
},
|
|
167
|
+
submit(author, input) {
|
|
168
|
+
return locked(async () => {
|
|
169
|
+
if (!isRecord(input))
|
|
170
|
+
throw bad('request body must be a JSON object');
|
|
171
|
+
for (const key of Object.keys(input))
|
|
172
|
+
if (!SUBMIT_FIELDS.includes(key))
|
|
173
|
+
throw bad(`unknown field "${key}"`, key);
|
|
174
|
+
const { name, description, tokens } = read(input);
|
|
175
|
+
const slug = slugOf(name);
|
|
176
|
+
if (builtin.some((b) => b.slug === slug))
|
|
177
|
+
throw bad(`"${name}" is the name of a livery that ships: pick another name`, 'name');
|
|
178
|
+
// a replace of the one in use would change the look on every device: the Director chooses, an agent only submits
|
|
179
|
+
if (slug === current)
|
|
180
|
+
throw new HubError('conflict', `"${name}" is the livery in use: pick another name`, 'name');
|
|
181
|
+
if (!custom.has(slug) && custom.size >= LIVERIES_MAX) {
|
|
182
|
+
throw new HubError('conflict', `there are ${LIVERIES_MAX} custom liveries already: the Director has to delete one first`, 'livery');
|
|
183
|
+
}
|
|
184
|
+
const entry = { slug, name, description, builtin: false, author, tokens };
|
|
185
|
+
await writeAtomic(join(dir, `${slug}.json`), { version: 1, name, description, author, tokens });
|
|
186
|
+
custom.set(slug, entry);
|
|
187
|
+
changed();
|
|
188
|
+
options.notify?.('livery', `${author} submitted the livery "${name}". Pick it in the Livery view to try it.`);
|
|
189
|
+
return { ...entry, tokens: { ...tokens } };
|
|
190
|
+
});
|
|
191
|
+
},
|
|
192
|
+
design(input) {
|
|
193
|
+
if (!isRecord(input))
|
|
194
|
+
throw bad('request body must be a JSON object');
|
|
195
|
+
for (const key of Object.keys(input))
|
|
196
|
+
if (key !== 'to' && key !== 'brief')
|
|
197
|
+
throw bad(`unknown field "${key}"`, key);
|
|
198
|
+
const to = input.to === undefined ? 'boss' : input.to;
|
|
199
|
+
if (typeof to !== 'string' || (to !== 'boss' && (to === 'user' || !NAME_RE.test(to))))
|
|
200
|
+
throw bad('to must be an agent name or "boss"', 'to');
|
|
201
|
+
const brief = typeof input.brief === 'string' ? input.brief.trim() : '';
|
|
202
|
+
if (brief === '' || brief.length > LIVERY_BRIEF_MAX_CHARS)
|
|
203
|
+
throw bad(`brief must be 1 to ${LIVERY_BRIEF_MAX_CHARS} characters`, 'brief');
|
|
204
|
+
return options.send({ to, subject: 'Livery: design request', body: designBody(brief) });
|
|
205
|
+
},
|
|
206
|
+
close() {
|
|
207
|
+
return chain.then(() => undefined);
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mission Log search (docs/mission-log-spec.md): BM25 over the title and the body, in memory.
|
|
3
|
+
*
|
|
4
|
+
* The title and the tags count as TITLE_WEIGHT copies of themselves, so a word in a title weighs more than the same word in a body (the
|
|
5
|
+
* usual way to weight a field in BM25). A word is a run of letters or digits, lowercased, two characters or more; there is no stemming,
|
|
6
|
+
* so "builds" does not find "build". The index holds only counts: the text stays with the entry, and `snippet` reads it.
|
|
7
|
+
*
|
|
8
|
+
* shortcut: no stemming, no phrase or prefix search, and the words are Unicode letters and digits, so Chinese or Japanese text is one
|
|
9
|
+
* long word; upgrade if the log is not mostly in a language that a space separates.
|
|
10
|
+
*/
|
|
11
|
+
import { LOG_SNIPPET_CHARS, LOG_SNIPPET_LEAD_CHARS } from './constants.js';
|
|
12
|
+
const K1 = 1.2;
|
|
13
|
+
const B = 0.75;
|
|
14
|
+
const TITLE_WEIGHT = 3;
|
|
15
|
+
const WORD = /[\p{L}\p{N}]{2,}/gu;
|
|
16
|
+
/** The words of a text, lowercased. */
|
|
17
|
+
export const tokenize = (text) => text.toLowerCase().match(WORD) ?? [];
|
|
18
|
+
export function createIndex() {
|
|
19
|
+
/** word -> id -> weighted count */
|
|
20
|
+
const postings = new Map();
|
|
21
|
+
const docs = new Map();
|
|
22
|
+
let total = 0;
|
|
23
|
+
const remove = (id) => {
|
|
24
|
+
const doc = docs.get(id);
|
|
25
|
+
if (doc === undefined)
|
|
26
|
+
return;
|
|
27
|
+
for (const term of doc.terms) {
|
|
28
|
+
const posting = postings.get(term);
|
|
29
|
+
posting?.delete(id);
|
|
30
|
+
if (posting?.size === 0)
|
|
31
|
+
postings.delete(term);
|
|
32
|
+
}
|
|
33
|
+
total -= doc.length;
|
|
34
|
+
docs.delete(id);
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
add(doc) {
|
|
38
|
+
remove(doc.id);
|
|
39
|
+
const counts = new Map();
|
|
40
|
+
let length = 0;
|
|
41
|
+
const count = (words, weight) => {
|
|
42
|
+
for (const word of words)
|
|
43
|
+
counts.set(word, (counts.get(word) ?? 0) + weight);
|
|
44
|
+
length += words.length * weight;
|
|
45
|
+
};
|
|
46
|
+
count(tokenize(`${doc.title} ${doc.tags.join(' ')}`), TITLE_WEIGHT);
|
|
47
|
+
count(tokenize(doc.body), 1);
|
|
48
|
+
for (const [term, n] of counts) {
|
|
49
|
+
const posting = postings.get(term) ?? new Map();
|
|
50
|
+
posting.set(doc.id, n);
|
|
51
|
+
postings.set(term, posting);
|
|
52
|
+
}
|
|
53
|
+
docs.set(doc.id, { length, terms: [...counts.keys()], at: doc.at });
|
|
54
|
+
total += length;
|
|
55
|
+
},
|
|
56
|
+
remove,
|
|
57
|
+
search(query, limit) {
|
|
58
|
+
const average = total / Math.max(docs.size, 1);
|
|
59
|
+
const scores = new Map();
|
|
60
|
+
for (const term of new Set(tokenize(query))) {
|
|
61
|
+
const posting = postings.get(term);
|
|
62
|
+
if (posting === undefined)
|
|
63
|
+
continue;
|
|
64
|
+
const idf = Math.log(1 + (docs.size - posting.size + 0.5) / (posting.size + 0.5));
|
|
65
|
+
for (const [id, tf] of posting) {
|
|
66
|
+
const length = docs.get(id)?.length ?? 0;
|
|
67
|
+
scores.set(id, (scores.get(id) ?? 0) + (idf * tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * length) / average)));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return [...scores]
|
|
71
|
+
.map(([id, score]) => ({ id, score }))
|
|
72
|
+
.sort((a, b) => b.score - a.score || (docs.get(b.id)?.at ?? 0) - (docs.get(a.id)?.at ?? 0))
|
|
73
|
+
.slice(0, limit);
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A piece of `text` around the place where the most different words of the query come close together (the first such place on a
|
|
79
|
+
* tie), on one line, with "…" where it was cut. A text with no match gives its start.
|
|
80
|
+
*/
|
|
81
|
+
export function snippet(text, query) {
|
|
82
|
+
const wanted = new Set(tokenize(query));
|
|
83
|
+
const hits = [...text.matchAll(WORD)].filter((m) => wanted.has(m[0].toLowerCase()));
|
|
84
|
+
let at = 0;
|
|
85
|
+
let best = -1;
|
|
86
|
+
for (let i = 0; i < hits.length; i += 1) {
|
|
87
|
+
const start = hits[i]?.index ?? 0;
|
|
88
|
+
const seen = new Set();
|
|
89
|
+
for (let j = i; j < hits.length && (hits[j]?.index ?? 0) < start + LOG_SNIPPET_CHARS - LOG_SNIPPET_LEAD_CHARS; j += 1)
|
|
90
|
+
seen.add(hits[j]?.[0].toLowerCase() ?? '');
|
|
91
|
+
if (seen.size > best) {
|
|
92
|
+
best = seen.size;
|
|
93
|
+
at = start;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// a match near the end gets the window back, so that the piece is as long as it can be
|
|
97
|
+
let from = Math.max(0, Math.min(at - LOG_SNIPPET_LEAD_CHARS, text.length - LOG_SNIPPET_CHARS));
|
|
98
|
+
// start at a word, unless that would cut off the match itself
|
|
99
|
+
if (from > 0 && /\S/.test(text[from - 1] ?? '')) {
|
|
100
|
+
const space = text.slice(from, at).search(/\s/);
|
|
101
|
+
if (space >= 0)
|
|
102
|
+
from += space + 1;
|
|
103
|
+
}
|
|
104
|
+
let to = Math.min(text.length, from + LOG_SNIPPET_CHARS);
|
|
105
|
+
if (to < text.length && /\S/.test(text[to] ?? '')) {
|
|
106
|
+
const space = text.slice(at, to).search(/\s\S*$/);
|
|
107
|
+
if (space > 0)
|
|
108
|
+
to = at + space;
|
|
109
|
+
}
|
|
110
|
+
const piece = text.slice(from, to).replace(/\s+/g, ' ').trim();
|
|
111
|
+
return `${from > 0 ? '…' : ''}${piece}${to < text.length ? '…' : ''}`;
|
|
112
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
3
|
+
import { z } from 'zod';
|
|
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';
|
|
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
|
+
import { bearerToken, hubErrorInfo, readBody, sendJson, sendUnauthorized } from './hooks.js';
|
|
8
|
+
/** JSON-RPC error codes: parse error, invalid request, "server error" (the SDK's own value for a refused method), internal error. */
|
|
9
|
+
const RPC_PARSE_ERROR = -32700;
|
|
10
|
+
const RPC_INVALID_REQUEST = -32600;
|
|
11
|
+
const RPC_METHOD_NOT_ALLOWED = -32000;
|
|
12
|
+
const RPC_INTERNAL_ERROR = -32603;
|
|
13
|
+
function rpcError(code, message) {
|
|
14
|
+
return { jsonrpc: '2.0', error: { code, message }, id: null };
|
|
15
|
+
}
|
|
16
|
+
function toolResult(object, isError) {
|
|
17
|
+
const result = { content: [{ type: 'text', text: JSON.stringify(object) }] };
|
|
18
|
+
if (isError)
|
|
19
|
+
result.isError = true;
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
export function createMcpHandler(deps) {
|
|
23
|
+
const { hub, log } = deps;
|
|
24
|
+
const logClose = (e) => log.debug('mcp close failed', e);
|
|
25
|
+
/** A HubError tells the agent why; anything else is a bug, logged here and reported without its text. */
|
|
26
|
+
const guarded = async (what, run) => {
|
|
27
|
+
try {
|
|
28
|
+
return await run();
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
const info = hubErrorInfo(e);
|
|
32
|
+
if (info)
|
|
33
|
+
return toolResult({ ok: false, error: info.message }, true);
|
|
34
|
+
log.error(`mcp tool ${what} failed`, e);
|
|
35
|
+
return toolResult({ ok: false, error: 'internal error' }, true);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
// The identity is captured here, from the token: no tool argument can name a sender.
|
|
39
|
+
const buildServer = ({ agent, generation }) => {
|
|
40
|
+
const server = new McpServer({ name: MCP_SERVER_NAME, version: deps.version?.() ?? '0.0.0' });
|
|
41
|
+
server.registerTool('send_message', {
|
|
42
|
+
description: MCP_DESCRIPTIONS.send_message,
|
|
43
|
+
inputSchema: {
|
|
44
|
+
to: z.string().min(1).max(64),
|
|
45
|
+
subject: z.string().max(SUBJECT_MAX_CHARS).optional(),
|
|
46
|
+
body: z.string().min(1).max(BODY_MAX_CHARS),
|
|
47
|
+
in_reply_to: z.string().max(40).optional(),
|
|
48
|
+
},
|
|
49
|
+
}, (args) => guarded('send_message', () => {
|
|
50
|
+
const request = { to: args.to, subject: args.subject ?? '', body: args.body };
|
|
51
|
+
if (args.in_reply_to !== undefined)
|
|
52
|
+
request.inReplyTo = args.in_reply_to;
|
|
53
|
+
const r = hub.sendFromAgent(agent, generation, request);
|
|
54
|
+
return toolResult({ ok: r.ok, id: r.id, to: r.to, status: r.status, note: r.note }, !r.ok);
|
|
55
|
+
}));
|
|
56
|
+
server.registerTool('list_roster', { description: MCP_DESCRIPTIONS.list_roster }, () => guarded('list_roster', () => toolResult(hub.rosterFor(agent, generation), false)));
|
|
57
|
+
server.registerTool('read_messages', { description: MCP_DESCRIPTIONS.read_messages }, () => guarded('read_messages', () => toolResult(hub.readMessages(agent, generation), false)));
|
|
58
|
+
server.registerTool('go_nogo', {
|
|
59
|
+
description: MCP_DESCRIPTIONS.go_nogo,
|
|
60
|
+
inputSchema: { vote: z.enum(POLL_VOTES), reason: z.string().max(POLL_REASON_MAX_CHARS).optional() },
|
|
61
|
+
}, (args) => guarded('go_nogo', () => {
|
|
62
|
+
const r = hub.vote(agent, generation, args.vote, args.reason ?? '');
|
|
63
|
+
return toolResult({ ok: r.ok, note: r.note }, !r.ok);
|
|
64
|
+
}));
|
|
65
|
+
const { tasks } = deps;
|
|
66
|
+
const noBoard = () => toolResult({ ok: false, error: 'the Flight Plan is not available' }, true);
|
|
67
|
+
const actor = { kind: 'agent', name: agent, generation };
|
|
68
|
+
server.registerTool('task_list', {
|
|
69
|
+
description: MCP_DESCRIPTIONS.task_list,
|
|
70
|
+
inputSchema: { mine: z.boolean().optional(), status: z.enum(TASK_STATUSES).optional() },
|
|
71
|
+
}, (args) => guarded('task_list', () => {
|
|
72
|
+
if (!tasks)
|
|
73
|
+
return noBoard();
|
|
74
|
+
const found = tasks
|
|
75
|
+
.list()
|
|
76
|
+
.filter((t) => (args.mine !== true || t.assignee === agent) && (args.status === undefined || t.status === args.status))
|
|
77
|
+
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
78
|
+
// the same cap as read_messages: Claude Code refuses a tool result of more than 25,000 tokens; the first task always goes
|
|
79
|
+
const shown = [];
|
|
80
|
+
let chars = 0;
|
|
81
|
+
for (const t of found) {
|
|
82
|
+
chars += JSON.stringify(t).length;
|
|
83
|
+
if (shown.length > 0 && chars > READ_MAX_CHARS)
|
|
84
|
+
break;
|
|
85
|
+
shown.push(t);
|
|
86
|
+
}
|
|
87
|
+
return toolResult(found.length === shown.length ? { count: shown.length, tasks: shown } : { count: shown.length, tasks: shown, remaining: found.length - shown.length, note: 'filter by status or mine to see the rest' }, false);
|
|
88
|
+
}));
|
|
89
|
+
server.registerTool('task_create', {
|
|
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() },
|
|
92
|
+
}, (args) => guarded('task_create', async () => (tasks ? toolResult({ ok: true, task: await tasks.create(actor, args) }, false) : noBoard())));
|
|
93
|
+
server.registerTool('task_update', {
|
|
94
|
+
description: MCP_DESCRIPTIONS.task_update,
|
|
95
|
+
inputSchema: {
|
|
96
|
+
id: z.string().min(1).max(16),
|
|
97
|
+
status: z.enum(TASK_STATUSES).optional(),
|
|
98
|
+
assignee: z.string().min(1).max(64).nullable().optional(),
|
|
99
|
+
note: z.string().max(TASK_NOTE_MAX_CHARS).optional(),
|
|
100
|
+
},
|
|
101
|
+
}, ({ id, ...patch }) => guarded('task_update', async () => (tasks ? toolResult({ ok: true, task: await tasks.update(actor, id, patch) }, false) : noBoard())));
|
|
102
|
+
const { missionLog } = deps;
|
|
103
|
+
const noLog = () => toolResult({ ok: false, error: 'the Mission Log is not available' }, true);
|
|
104
|
+
server.registerTool('log_write', {
|
|
105
|
+
description: MCP_DESCRIPTIONS.log_write,
|
|
106
|
+
inputSchema: {
|
|
107
|
+
id: z.string().min(1).max(16).optional(),
|
|
108
|
+
title: z.string().min(1).max(LOG_TITLE_MAX_CHARS).optional(),
|
|
109
|
+
body: z.string().min(1).max(LOG_BODY_MAX_CHARS).optional(),
|
|
110
|
+
tags: z.array(z.string().min(1).max(64)).max(LOG_TAGS_MAX).optional(),
|
|
111
|
+
},
|
|
112
|
+
}, ({ id, ...fields }) => guarded('log_write', async () => {
|
|
113
|
+
if (!missionLog)
|
|
114
|
+
return noLog();
|
|
115
|
+
// the author is the caller's own name, never a field of the call
|
|
116
|
+
const entry = await (id === undefined ? missionLog.create(agent, fields) : missionLog.update(id, fields, agent));
|
|
117
|
+
return toolResult({ ok: true, id: entry.id, title: entry.title, tags: entry.tags }, false);
|
|
118
|
+
}));
|
|
119
|
+
server.registerTool('log_search', {
|
|
120
|
+
description: MCP_DESCRIPTIONS.log_search,
|
|
121
|
+
inputSchema: { query: z.string().min(1).max(LOG_QUERY_MAX_CHARS), limit: z.number().int().min(1).max(LOG_SEARCH_MAX).optional() },
|
|
122
|
+
}, ({ query, limit }) => guarded('log_search', () => {
|
|
123
|
+
if (!missionLog)
|
|
124
|
+
return noLog();
|
|
125
|
+
const { hits } = missionLog.search(query, limit ?? LOG_SEARCH_MAX);
|
|
126
|
+
return toolResult({ count: hits.length, results: hits }, false);
|
|
127
|
+
}));
|
|
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 { liveries } = deps;
|
|
130
|
+
server.registerTool('livery_submit', {
|
|
131
|
+
description: MCP_DESCRIPTIONS.livery_submit,
|
|
132
|
+
inputSchema: { name: z.string().min(1).max(LIVERY_NAME_MAX_CHARS), description: z.string().max(LIVERY_DESCRIPTION_MAX_CHARS).optional(), tokens: z.record(z.string().max(64), z.string().max(64)) },
|
|
133
|
+
}, (args) => guarded('livery_submit', async () => {
|
|
134
|
+
if (!liveries)
|
|
135
|
+
return toolResult({ ok: false, error: 'Livery is not available' }, true);
|
|
136
|
+
// the author is the caller's own name, never a field of the call
|
|
137
|
+
const entry = await liveries.submit(agent, args);
|
|
138
|
+
return toolResult({ ok: true, slug: entry.slug, note: 'saved; the Director chooses whether to apply it' }, false);
|
|
139
|
+
}));
|
|
140
|
+
return server;
|
|
141
|
+
};
|
|
142
|
+
return async (req, res) => {
|
|
143
|
+
const token = bearerToken(req.headers.authorization);
|
|
144
|
+
const identity = token === null ? null : deps.resolveToken(token);
|
|
145
|
+
if (!identity) {
|
|
146
|
+
sendUnauthorized(res);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
// stateless: there is no session to resume (GET) or end (DELETE); claude opens one GET, gets this, and carries on
|
|
150
|
+
if (req.method !== 'POST') {
|
|
151
|
+
sendJson(res, 405, rpcError(RPC_METHOD_NOT_ALLOWED, 'Method not allowed.'), { Allow: 'POST' });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const body = await readBody(req, MAX_MCP_BODY_BYTES);
|
|
156
|
+
if (!body.ok) {
|
|
157
|
+
if (body.reason === 'too_large')
|
|
158
|
+
sendJson(res, 413, rpcError(RPC_INVALID_REQUEST, 'Request body too large.'));
|
|
159
|
+
else
|
|
160
|
+
res.destroy();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
let parsed;
|
|
164
|
+
try {
|
|
165
|
+
parsed = JSON.parse(body.body.toString('utf8'));
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
sendJson(res, 400, rpcError(RPC_PARSE_ERROR, 'Parse error: the body is not valid JSON.'));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
// The SDK writes its own Cache-Control for the event stream, over the one set here; contract 3.2 wants no-store on every MCP answer.
|
|
172
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
173
|
+
const setHeader = res.setHeader.bind(res);
|
|
174
|
+
res.setHeader = (name, value) => (name.toLowerCase() === 'cache-control' ? res : setHeader(name, value));
|
|
175
|
+
const server = buildServer(identity);
|
|
176
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
177
|
+
const closeBoth = () => {
|
|
178
|
+
void transport.close().catch(logClose);
|
|
179
|
+
void server.close().catch(logClose);
|
|
180
|
+
};
|
|
181
|
+
if (res.destroyed)
|
|
182
|
+
closeBoth();
|
|
183
|
+
else
|
|
184
|
+
res.on('close', closeBoth);
|
|
185
|
+
await server.connect(transport);
|
|
186
|
+
await transport.handleRequest(req, res, parsed);
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
log.error('mcp request failed', e);
|
|
190
|
+
if (res.headersSent)
|
|
191
|
+
res.destroy();
|
|
192
|
+
else
|
|
193
|
+
sendJson(res, 500, rpcError(RPC_INTERNAL_ERROR, 'Internal error.'));
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Versions of the saved state (docs/release-readiness-spec.md, docs/reference/configuration.md "Versions of the saved state").
|
|
3
|
+
*
|
|
4
|
+
* Every JSON file under the home that has a format holds `"version": <n>`. `migrateHome` runs at start, under the home's lock and
|
|
5
|
+
* before any store reads its file: a file of an older version is upgraded one version at a time, after a copy of it was made as
|
|
6
|
+
* `<file>.bak-v<old>`; a file of a newer version stops the start with a message, because the older code would read it wrongly or
|
|
7
|
+
* overwrite it. A file that is missing, is not JSON or has no version is left to the store that owns it: it reports it its own way.
|
|
8
|
+
* The exception is a format marked `unversionedIs1` (propellant.json), which gonogo wrote without a version before: that is version 1.
|
|
9
|
+
*
|
|
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
|
+
* returns the new one; the runner sets `version`), and change the store to read and write the new shape.
|
|
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).
|
|
15
|
+
* shortcut: a home with one file too new and another to upgrade can upgrade the second before it refuses the first; the copy
|
|
16
|
+
* makes that harmless, so there is no check pass.
|
|
17
|
+
*/
|
|
18
|
+
import { randomBytes } from 'node:crypto';
|
|
19
|
+
import { chmodSync, constants, copyFileSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
20
|
+
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
|
+
const ALL_JSON = '/*.json';
|
|
23
|
+
/** Everything is still at version 1: no step yet. */
|
|
24
|
+
export const FORMATS = [
|
|
25
|
+
AGENTS_FILE,
|
|
26
|
+
SCHEDULES_FILE,
|
|
27
|
+
UPLINKS_FILE,
|
|
28
|
+
TASKS_FILE,
|
|
29
|
+
DOWNLINK_FILE,
|
|
30
|
+
RELAY_FILE,
|
|
31
|
+
DOCKING_FILE,
|
|
32
|
+
STATION_FILE,
|
|
33
|
+
LIVERY_FILE,
|
|
34
|
+
PROPELLANT_FILE,
|
|
35
|
+
LIVERY_DIR + ALL_JSON,
|
|
36
|
+
].map((file) => (file === PROPELLANT_FILE ? { file, steps: [], unversionedIs1: true } : { file, steps: [] }));
|
|
37
|
+
function isRecord(x) {
|
|
38
|
+
return typeof x === 'object' && x !== null && !Array.isArray(x);
|
|
39
|
+
}
|
|
40
|
+
function errMessage(e) {
|
|
41
|
+
return e instanceof Error ? e.message : String(e);
|
|
42
|
+
}
|
|
43
|
+
function filesOf(home, file) {
|
|
44
|
+
if (!file.endsWith(ALL_JSON))
|
|
45
|
+
return [join(home, file)];
|
|
46
|
+
const folder = join(home, file.slice(0, -ALL_JSON.length));
|
|
47
|
+
try {
|
|
48
|
+
return readdirSync(folder)
|
|
49
|
+
.filter((name) => name.endsWith('.json'))
|
|
50
|
+
.sort()
|
|
51
|
+
.map((name) => join(folder, name));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// no folder yet, or one the store will complain about
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function migrateFile(path, { steps, unversionedIs1 }, log) {
|
|
59
|
+
let data;
|
|
60
|
+
try {
|
|
61
|
+
data = JSON.parse(readFileSync(path, 'utf8'));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (!isRecord(data))
|
|
67
|
+
return;
|
|
68
|
+
const old = data.version === undefined && unversionedIs1 ? 1 : data.version;
|
|
69
|
+
if (typeof old !== 'number' || !Number.isInteger(old) || old < 1)
|
|
70
|
+
return;
|
|
71
|
+
const known = steps.length + 1;
|
|
72
|
+
if (old > known) {
|
|
73
|
+
throw new Error(`${path} was saved by a newer gonogo (format version ${old}; this one reads up to ${known}). Start the gonogo that saved it, or move the file away to start without it.`);
|
|
74
|
+
}
|
|
75
|
+
if (old === known)
|
|
76
|
+
return;
|
|
77
|
+
const backup = `${path}.bak-v${old}`;
|
|
78
|
+
try {
|
|
79
|
+
// an existing copy is the one made by an earlier try that failed after the copy: the file has not changed since
|
|
80
|
+
copyFileSync(path, backup, constants.COPYFILE_EXCL);
|
|
81
|
+
chmodSync(backup, FILE_MODE);
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
if (e.code !== 'EEXIST')
|
|
85
|
+
throw new Error(`cannot copy ${path} to ${backup}: ${errMessage(e)}; nothing was changed`);
|
|
86
|
+
}
|
|
87
|
+
let next = data;
|
|
88
|
+
let version = old;
|
|
89
|
+
for (const step of steps.slice(old - 1)) {
|
|
90
|
+
try {
|
|
91
|
+
next = { ...step(next), version: version + 1 };
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
throw new Error(`${path}: the step from version ${version} to ${version + 1} failed (${errMessage(e)}); the file was not changed, and a copy is ${backup}`);
|
|
95
|
+
}
|
|
96
|
+
version += 1;
|
|
97
|
+
}
|
|
98
|
+
const tmp = join(dirname(path), `.${basename(path)}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
99
|
+
try {
|
|
100
|
+
writeFileSync(tmp, JSON.stringify(next, null, 2), { mode: FILE_MODE, flag: 'wx' });
|
|
101
|
+
renameSync(tmp, path);
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
try {
|
|
105
|
+
unlinkSync(tmp);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// never written
|
|
109
|
+
}
|
|
110
|
+
throw new Error(`cannot write ${path}: ${errMessage(e)}; the file was not changed, and a copy is ${backup}`);
|
|
111
|
+
}
|
|
112
|
+
log.info(`${path} was upgraded from format version ${old} to ${known}; the old file is kept as ${backup}`);
|
|
113
|
+
}
|
|
114
|
+
/** Throws an Error whose message names the file; the caller lets the start fail with it. */
|
|
115
|
+
export function migrateHome(home, log, formats = FORMATS) {
|
|
116
|
+
for (const format of formats)
|
|
117
|
+
for (const path of filesOf(home, format.file))
|
|
118
|
+
migrateFile(path, format, log);
|
|
119
|
+
}
|