@plaiful/cli 0.3.0 → 0.5.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 (4) hide show
  1. package/README.md +4 -2
  2. package/package.json +1 -1
  3. package/src/cli.js +191 -13
  4. package/src/mcp.js +144 -0
package/README.md CHANGED
@@ -24,8 +24,10 @@ npm as a member of the `plaiful` org.
24
24
  ```sh
25
25
  plaiful login # opens the CMS: check the code matches, approve. 12 hours.
26
26
  plaiful clone roadforge # clone the game repo, write .env.development, docs pull, npm install, open Zed
27
- plaiful init roadforge # (a repo you already have) writes .plaiful.json in the repo root (commit it; no secrets)
28
- plaiful docs pull # the latest onboarding docs + client-config.md into docs/plaiful/
27
+ plaiful init roadforge # (a repo you already have) writes .plaiful.json (commit it; no secrets) and makes the resources/ folders
28
+ plaiful docs # the platform docs, live (docs read <doc>, docs search <words>, docs changes)
29
+ plaiful docs pull # your client-config.md into docs/plaiful/ (--copies: local copies of the docs too)
30
+ plaiful mcp # the docs as MCP tools for your coding assistant: claude mcp add plaiful -- plaiful mcp
29
31
  plaiful env # rewrite .env.development from the dev client config (keeps your own lines)
30
32
  plaiful ovid check # checks docs/plaiful/roadforge-ovid-declaration.json
31
33
  plaiful ovid publish # checks it again and publishes it; OVID reads it within ~5 minutes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plaiful/cli",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "The Plaiful CLI: work on your Plaiful product from your game repo, with no AWS access",
5
5
  "bin": {
6
6
  "plaiful": "bin/plaiful.js"
package/src/cli.js CHANGED
@@ -18,8 +18,16 @@ const HELP = `plaiful ${version}: work on your Plaiful product from your game re
18
18
  plaiful login sign in (opens the CMS to approve; 12 hours)
19
19
  plaiful logout sign out
20
20
  plaiful whoami who you're signed in as, your studio, and the products you may manage
21
- plaiful init [product] write .plaiful.json in this repo (product, env, docsDir)
22
- plaiful docs pull write the latest onboarding docs + your client config into docsDir
21
+ plaiful init [product] write .plaiful.json in this repo (product, env, docsDir) and make the folders
22
+ your files go in (resources/world/<product>/, …), each with a README
23
+ plaiful docs the platform docs (live): each doc, its summary, when it last changed
24
+ plaiful docs read <doc> one doc, current (--section "3.5" or a heading for one section)
25
+ plaiful docs search <words...> where the docs say it: each doc's best sections, with a snippet
26
+ plaiful docs changes [--since <date>] the docs changed since a date (default: the last 7 days)
27
+ plaiful docs pull write your product's own files (client-config.md) into docsDir; the platform
28
+ docs stay live (--copies also writes local copies, for offline work)
29
+ plaiful mcp an MCP server on stdio with the docs tools, signed in as you
30
+ (claude mcp add plaiful -- plaiful mcp)
23
31
  plaiful ovid check [file] check your OVID declaration (default: <docsDir>/<product>-ovid-declaration.json)
24
32
  plaiful ovid publish [file] check it and publish it; OVID reads it within about 5 minutes
25
33
  plaiful ovid show the declaration OVID has now
@@ -83,8 +91,8 @@ function parse(argv) {
83
91
  const args = [];
84
92
  for (let i = 0; i < argv.length; i += 1) {
85
93
  const a = argv[i];
86
- if (['--json', '--no-browser', '--help', '-h', '--version', '--apply', '--reset', '--rows', '--no-install', '--no-open'].includes(a)) flags[a.replace(/^-+/, '')] = true;
87
- else if (['--product', '--api', '--dir', '--dest', '--count', '--base', '--per-effort', '--track', '--series', '--state', '--limit'].includes(a)) {
94
+ if (['--json', '--no-browser', '--help', '-h', '--version', '--apply', '--reset', '--rows', '--no-install', '--no-open', '--copies'].includes(a)) flags[a.replace(/^-+/, '')] = true;
95
+ else if (['--product', '--api', '--dir', '--dest', '--count', '--base', '--per-effort', '--track', '--series', '--state', '--limit', '--section', '--since'].includes(a)) {
88
96
  if (argv[i + 1] === undefined) throw new UsageError(`${a} needs a value`);
89
97
  flags[a.slice(2)] = argv[i += 1];
90
98
  } else if (a.startsWith('--')) throw new UsageError(`unknown option ${a}`);
@@ -179,21 +187,127 @@ async function init(ctx, [product]) {
179
187
  const root = existing ? existing.root : ctx.io.cwd();
180
188
  const next = { ...(existing ? existing.config : { env: 'dev', docsDir: config.DEFAULT_DOCS_DIR }), product: chosen };
181
189
  const file = config.writeRepoConfig(root, next);
182
- ctx.out(`Wrote ${path.relative(ctx.io.cwd(), file) || file}: product ${chosen}, docs in ${next.docsDir}. Next: plaiful docs pull`, { success: true, file, config: next });
190
+ const made = makeLayout(root, chosen, next.docsDir);
191
+ const lines = [`Wrote ${path.relative(ctx.io.cwd(), file) || file}: product ${chosen}, docs in ${next.docsDir}.`];
192
+ if (made.length) lines.push(`Made ${made.length} folder(s): ${made.join(', ')}`);
193
+ lines.push('Next: plaiful docs pull');
194
+ ctx.out(lines.join('\n'), { success: true, file, config: next, made });
183
195
  return 0;
184
196
  }
185
197
 
198
+ // ── Where things go (product-repo-template.md) ──────────────────────────────────────────────────────────────────
199
+
200
+ /** The repo folders the platform's steps read from: [folder, what goes there]. */
201
+ function layout(product, docsDir) {
202
+ return [
203
+ [`resources/${product}-resources`, 'SmartBuilder agent specs (one markdown file per agent, pasted into SmartBuilder)'],
204
+ [`resources/agents/${product}`, 'agent configs as JSON, for plaiful agents deploy'],
205
+ [`resources/world/${product}`, 'the narrative scaffold, for plaiful seed world'],
206
+ [`resources/lore/${product}`, 'lore sets, for plaiful seed lore'],
207
+ [`resources/map/${product}`, 'places, for plaiful seed map'],
208
+ [`resources/personas/${product}`, 'THESPIS personas and situations, for plaiful seed personas'],
209
+ [`resources/midas/${product}`, 'quest-pricing.json, for plaiful midas pricing apply'],
210
+ [docsDir, `the pulled docs, and your ${product}-ovid-declaration.json (plaiful ovid check / publish)`],
211
+ ];
212
+ }
213
+
214
+ /** Agent specs (markdown with agent_name and prompt_template) outside resources/<product>-resources/, under docs/ or
215
+ * resources/. → relative paths */
216
+ function misplacedSpecs(root, product, docsDir) {
217
+ const home = path.join(root, 'resources', `${product}-resources`);
218
+ const out = [];
219
+ const walk = (dir, depth) => {
220
+ if (depth > 6 || !fs.existsSync(dir)) return;
221
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
222
+ const full = path.join(dir, e.name);
223
+ if (e.isDirectory()) {
224
+ if (!['node_modules', '.git'].includes(e.name) && full !== home && full !== docsDir) walk(full, depth + 1);
225
+ } else if (e.name.endsWith('.md')) {
226
+ try {
227
+ const text = fs.readFileSync(full, 'utf8');
228
+ if (/\bagent_name\b/.test(text) && /\bprompt_template\b/.test(text)) out.push(path.relative(root, full).replace(/\\/g, '/'));
229
+ } catch { /* unreadable: skip */ }
230
+ }
231
+ }
232
+ };
233
+ walk(path.join(root, 'docs'), 0);
234
+ walk(path.join(root, 'resources'), 0);
235
+ return out;
236
+ }
237
+
238
+ /** What to write in a folder's README when init makes it. */
239
+ const folderReadme = (folder, what) => `# ${folder}\n\n${what[0].toUpperCase()}${what.slice(1)}.\nMade by \`plaiful init\`; see docs/plaiful/product-repo-template.md.\n`;
240
+
241
+ /** The folders the platform's steps read from, each with a README saying what goes in it (an agent puts a file where
242
+ * a folder for it already exists). → the folders made */
243
+ function makeLayout(root, product, docsDir) {
244
+ const made = [];
245
+ for (const [folder, what] of layout(product, docsDir)) {
246
+ const dir = path.join(root, folder);
247
+ if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); made.push(folder); }
248
+ const readme = path.join(dir, 'README.md');
249
+ if (folder !== docsDir && !fs.existsSync(readme)) fs.writeFileSync(readme, folderReadme(folder, what));
250
+ }
251
+ return made;
252
+ }
253
+
254
+ function whereThingsGo(ctx, r) {
255
+ const lines = ['Where things go:'];
256
+ for (const [folder, what] of layout(r.product, path.relative(r.root, r.docsDir).replace(/\\/g, '/') || '.')) {
257
+ lines.push(` ${folder.padEnd(32)} ${what}${fs.existsSync(path.join(r.root, folder)) ? '' : ' (missing: plaiful init makes it)'}`);
258
+ }
259
+ const wrong = misplacedSpecs(r.root, r.product, r.docsDir);
260
+ if (wrong.length) {
261
+ lines.push(`! Agent specs outside resources/${r.product}-resources/ (move them there):`);
262
+ for (const f of wrong) lines.push(` ${f}`);
263
+ }
264
+ return { lines, misplaced: wrong };
265
+ }
266
+
186
267
  const safeName = (key) => {
187
268
  const base = path.basename(String(key));
188
269
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(base)) return null;
189
270
  return base;
190
271
  };
191
272
 
273
+ // What docs pull leaves in docsDir when the platform docs are live (PLATFORM_DOCS_PORTAL.md §4).
274
+ const LIVE_DOCS_README = `# Plaiful docs
275
+
276
+ The platform docs are **live**, not copied here, so you always read the current version. Read them with the CLI, or
277
+ with the plaiful MCP tools in your coding assistant:
278
+
279
+ \`\`\`sh
280
+ plaiful docs # every doc, and when it last changed
281
+ plaiful docs read README # one doc (--section "3.5", or a heading, for one section)
282
+ plaiful docs search "batch template" # where the docs say it
283
+ plaiful docs changes --since 2026-10-20
284
+ plaiful mcp # the same as MCP tools: claude mcp add plaiful -- plaiful mcp
285
+ \`\`\`
286
+
287
+ Start with \`plaiful docs read README\`. Read a doc again when you start a task; don't keep a copy.
288
+
289
+ This folder holds your product's own files: \`client-config.md\` (your keys and endpoints: never commit it) and your
290
+ \`<product>-ovid-declaration.json\`. Written by \`plaiful docs pull\`.
291
+ `;
292
+
192
293
  async function docsPull(ctx, r = repo(ctx)) {
193
- const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/docs`);
294
+ const copies = !!ctx.flags.copies;
295
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/docs${copies ? '' : '?docs=none'}`);
194
296
  fs.mkdirSync(r.docsDir, { recursive: true });
195
- const files = [...data.docs, { key: data.client_config.key, title: 'Client config', content: data.client_config.content }];
196
- const result = { written: [], unchanged: [], skipped: [] };
297
+ const platform = copies ? (data.docs || []) : [];
298
+ const files = [...platform, { key: data.client_config.key, title: 'Client config', content: data.client_config.content }];
299
+ const result = { written: [], unchanged: [], skipped: [], removed: [] };
300
+ // The platform-doc copies an earlier pull wrote ("replaced on every pull, never edit these"): gone, now they're live.
301
+ const indexFile = path.join(r.docsDir, '.plaiful-docs.json');
302
+ let before = [];
303
+ try { before = (JSON.parse(fs.readFileSync(indexFile, 'utf8')).docs || []).map((d) => d.file).filter(Boolean); } catch { before = []; }
304
+ const keep = new Set(files.map((f) => safeName(f.key)).filter(Boolean));
305
+ if (!copies) keep.add('README.md');
306
+ for (const name of before) {
307
+ const safe = safeName(name);
308
+ if (safe && !keep.has(safe) && fs.existsSync(path.join(r.docsDir, safe))) { fs.unlinkSync(path.join(r.docsDir, safe)); result.removed.push(safe); }
309
+ }
310
+ if (!copies) files.push({ key: 'README.md', title: 'Plaiful docs (live)', content: LIVE_DOCS_README });
197
311
  for (const f of files) {
198
312
  const name = safeName(f.key);
199
313
  if (!name) { result.skipped.push(f.key); continue; }
@@ -204,24 +318,78 @@ async function docsPull(ctx, r = repo(ctx)) {
204
318
  result.written.push(name);
205
319
  }
206
320
  const index = {
207
- _note: 'Written by `plaiful docs pull`. These files are replaced on every pull; keep your own files beside them under other names.',
321
+ _note: copies
322
+ ? 'Written by `plaiful docs pull --copies`: copies as of pulled_at; the live docs are `plaiful docs`. Replaced on every pull.'
323
+ : 'Written by `plaiful docs pull`. The platform docs are live (`plaiful docs`); this folder holds the product\'s own files.',
324
+ mode: copies ? 'copies' : 'live',
208
325
  product: r.product, env: data.env, pulled_at: new Date().toISOString(),
209
326
  docs: files.map((f) => ({ file: safeName(f.key), title: f.title, description: f.description || '' })).filter((f) => f.file),
210
327
  };
211
- fs.writeFileSync(path.join(r.docsDir, '.plaiful-docs.json'), `${JSON.stringify(index, null, 2)}\n`);
328
+ fs.writeFileSync(indexFile, `${JSON.stringify(index, null, 2)}\n`);
212
329
  const ignore = ignoreClientConfig(r.docsDir);
213
330
  const rel = path.relative(ctx.io.cwd(), r.docsDir) || '.';
214
331
  const lines = [
215
332
  `${rel}: ${result.written.length} updated, ${result.unchanged.length} unchanged${result.skipped.length ? `, ${result.skipped.length} skipped` : ''}.`,
216
333
  ...result.written.map((n) => ` updated ${n}`),
334
+ ...result.removed.map((n) => ` removed ${n} (a platform doc: read it live, plaiful docs read ${n.replace(/\.md$/, '')})`),
217
335
  ];
218
336
  if (ignore.added.length) lines.push(` ${path.join(rel, '.gitignore')}: now keeps ${ignore.added.join(', ')} out of git`);
219
337
  if (ignore.tracked.length) {
220
338
  lines.push(`! Already committed, and holding your keys: ${ignore.tracked.join(', ')}. Take them out of git (the files stay):`);
221
339
  lines.push(` git rm --cached ${ignore.tracked.map((f) => `"${path.relative(ctx.io.cwd(), path.join(r.docsDir, f)).replace(/\\/g, '/')}"`).join(' ')}`);
222
340
  }
223
- lines.push('Start with README.md.');
224
- ctx.out(lines.join('\n'), { success: true, dir: r.docsDir, ...result, gitignore: ignore });
341
+ const where = whereThingsGo(ctx, r);
342
+ lines.push(...where.lines);
343
+ lines.push(copies ? 'Local copies as of now; the live docs are `plaiful docs`.' : 'The platform docs are live: plaiful docs (start with plaiful docs read README).');
344
+ ctx.out(lines.join('\n'), { success: true, dir: r.docsDir, ...result, gitignore: ignore, misplaced_specs: where.misplaced });
345
+ return 0;
346
+ }
347
+
348
+ // ── The live docs ─────────────────────────────────────────────────────────────────────────────────────────────────
349
+
350
+ const docsRoute = (rest = '', query = {}) => {
351
+ const qs = new URLSearchParams(Object.entries(query).filter(([, v]) => v !== undefined && v !== null && v !== ''));
352
+ return `/partner/platform/docs${rest}${qs.toString() ? `?${qs}` : ''}`;
353
+ };
354
+ const docName = (k) => String(k).replace(/\.md$/, '');
355
+ const day = (iso) => (iso ? String(iso).slice(0, 10) : ' ');
356
+
357
+ async function docsList(ctx) {
358
+ const { data } = await ctx.call('GET', docsRoute());
359
+ const docs = data.docs || [];
360
+ const lines = [`Plaiful docs (live): ${docs.length}. plaiful docs read <doc>`];
361
+ for (const d of docs) lines.push(` ${docName(d.key).padEnd(40)} ${day(d.updated_at)} ${d.title || ''}`);
362
+ ctx.out(lines.join('\n'), data);
363
+ return 0;
364
+ }
365
+
366
+ async function docsRead(ctx, [name]) {
367
+ if (!name) throw new UsageError('which doc? plaiful docs read <doc> (plaiful docs lists them)');
368
+ const { data } = await ctx.call('GET', docsRoute(`/${encodeURIComponent(docName(name))}`, { section: ctx.flags.section }));
369
+ ctx.out(data.content, data);
370
+ return 0;
371
+ }
372
+
373
+ async function docsSearch(ctx, words) {
374
+ const q = words.join(' ').trim();
375
+ if (!q) throw new UsageError('search for what? plaiful docs search <words...>');
376
+ const { data } = await ctx.call('GET', docsRoute('', { q, limit: ctx.flags.limit }));
377
+ const lines = data.results.length ? [`"${q}" in the docs:`] : [`Nothing in the docs mentions all of: ${q}`];
378
+ for (const r of data.results) {
379
+ lines.push(` ${docName(r.key)} (${r.title})`);
380
+ for (const sct of r.sections) lines.push(` § ${sct.heading || r.title}: ${sct.snippet}`);
381
+ }
382
+ if (data.results.length) lines.push('plaiful docs read <doc> --section "<heading>" for the whole section');
383
+ ctx.out(lines.join('\n'), data);
384
+ return 0;
385
+ }
386
+
387
+ async function docsChanges(ctx) {
388
+ const since = ctx.flags.since || new Date(Date.now() - 7 * 864e5).toISOString().slice(0, 10);
389
+ const { data } = await ctx.call('GET', docsRoute('', { since }));
390
+ const lines = [data.docs.length ? `Changed since ${since}:` : `No doc changed since ${since}.`];
391
+ for (const d of data.docs) lines.push(` ${day(d.updated_at)} ${docName(d.key).padEnd(40)} ${d.title || ''}`);
392
+ ctx.out(lines.join('\n'), data);
225
393
  return 0;
226
394
  }
227
395
 
@@ -789,6 +957,8 @@ async function clone(ctx, [productArg, dirArg]) {
789
957
  const existing = config.findRepoConfig(dir);
790
958
  const own = existing && existing.root === dir ? existing.config : null;
791
959
  if (!own) config.writeRepoConfig(dir, { product, env: 'dev', docsDir: config.DEFAULT_DOCS_DIR });
960
+ const made = makeLayout(dir, product, (own && own.docsDir) || config.DEFAULT_DOCS_DIR);
961
+ if (made.length) steps.push(`Made ${made.length} folder(s) your files go in: ${made.join(', ')}`);
792
962
  const r = { product, root: dir, docsDir: path.resolve(dir, (own && own.docsDir) || config.DEFAULT_DOCS_DIR) };
793
963
  steps.push(...envLines(writeEnv(dir, game), game));
794
964
  await docsPull({ ...ctx, out: () => {} }, r);
@@ -814,6 +984,14 @@ const COMMANDS = {
814
984
  whoami: (ctx) => whoami(ctx),
815
985
  init: (ctx, rest) => init(ctx, rest),
816
986
  'docs pull': (ctx) => docsPull(ctx),
987
+ 'docs read': (ctx, rest) => docsRead(ctx, rest),
988
+ 'docs search': (ctx, rest) => docsSearch(ctx, rest),
989
+ 'docs changes': (ctx) => docsChanges(ctx),
990
+ docs: (ctx, rest) => {
991
+ if (rest.length) throw new UsageError(`plaiful docs, or docs read | search | changes | pull (not "${rest[0]}")`);
992
+ return docsList(ctx);
993
+ },
994
+ mcp: (ctx) => require('./mcp').serve(ctx),
817
995
  'ovid check': (ctx, rest) => ovidCheck(ctx, rest),
818
996
  'ovid publish': (ctx, rest) => ovidPublish(ctx, rest),
819
997
  'ovid show': (ctx) => ovidShow(ctx),
@@ -872,7 +1050,7 @@ async function main(argv, io = defaultIo()) {
872
1050
  const one = COMMANDS[a];
873
1051
  const ctx = makeContext(io, flags);
874
1052
  if (two) return await two(ctx, rest);
875
- if (one && !['docs', 'ovid', 'midas'].includes(a)) return await one(ctx, b === undefined ? rest : [b, ...rest]);
1053
+ if (one && !['ovid', 'midas'].includes(a)) return await one(ctx, b === undefined ? rest : [b, ...rest]);
876
1054
  throw new UsageError(`unknown command "${parsed.args.join(' ')}"`);
877
1055
  } catch (e) {
878
1056
  if (e instanceof UsageError) {
package/src/mcp.js ADDED
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * `plaiful mcp`: an MCP server on stdio (docs/system/product/PLATFORM_DOCS_PORTAL.md §4). It gives a coding assistant
5
+ * (Claude Code, Zed, any MCP client) the live platform docs as tools, signed in as the CLI is (`plaiful login`, or
6
+ * PLAIFUL_TOKEN). Newline-delimited JSON-RPC 2.0 on stdin/stdout; nothing else is written to stdout.
7
+ *
8
+ * claude mcp add plaiful -- plaiful mcp
9
+ */
10
+
11
+ const { version } = require('../package.json');
12
+
13
+ const TOOLS = [
14
+ {
15
+ name: 'list_docs',
16
+ description: 'List the Plaiful platform docs (live): each doc\'s name, title, summary and when it last changed. Read one with read_doc.',
17
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
18
+ },
19
+ {
20
+ name: 'read_doc',
21
+ description: 'Read one Plaiful platform doc, current. Give `section` (a heading, or a number like "3.5") for one section of a long doc.',
22
+ inputSchema: {
23
+ type: 'object',
24
+ properties: {
25
+ doc: { type: 'string', description: 'The doc name from list_docs, e.g. "ovid-client" or "README"' },
26
+ section: { type: 'string', description: 'Optional: a heading or section number' },
27
+ },
28
+ required: ['doc'],
29
+ additionalProperties: false,
30
+ },
31
+ },
32
+ {
33
+ name: 'search_docs',
34
+ description: 'Search the Plaiful platform docs: the docs and sections that mention every word, best first, with a snippet. Then read_doc with the section.',
35
+ inputSchema: {
36
+ type: 'object',
37
+ properties: { query: { type: 'string' }, limit: { type: 'number', description: 'At most this many docs (default 10)' } },
38
+ required: ['query'],
39
+ additionalProperties: false,
40
+ },
41
+ },
42
+ {
43
+ name: 'docs_changes',
44
+ description: 'The Plaiful platform docs that changed since a date (default: the last 7 days), newest first.',
45
+ inputSchema: { type: 'object', properties: { since: { type: 'string', description: 'A date, e.g. 2026-10-20' } }, additionalProperties: false },
46
+ },
47
+ ];
48
+
49
+ const INSTRUCTIONS = 'Plaiful\'s platform docs, live. Read the relevant doc before working on a Plaiful integration, and again at the start of a task; never rely on a copy. Start with read_doc { doc: "README" }.';
50
+
51
+ const docName = (k) => String(k).replace(/\.md$/, '');
52
+ const route = (rest = '', query = {}) => {
53
+ const qs = new URLSearchParams(Object.entries(query).filter(([, v]) => v !== undefined && v !== null && v !== ''));
54
+ return `/partner/platform/docs${rest}${qs.toString() ? `?${qs}` : ''}`;
55
+ };
56
+
57
+ /** Run one tool → the text it answers with. Throws on a platform error (reported as a tool error). */
58
+ async function runTool(ctx, name, args = {}) {
59
+ if (name === 'list_docs') {
60
+ const { data } = await ctx.call('GET', route());
61
+ return (data.docs || []).map((d) => `${docName(d.key)} | ${d.title || ''} | updated ${String(d.updated_at || '').slice(0, 10)} | ${d.description || ''}`).join('\n');
62
+ }
63
+ if (name === 'read_doc') {
64
+ if (!args.doc) throw new Error('doc is required');
65
+ const { data } = await ctx.call('GET', route(`/${encodeURIComponent(docName(args.doc))}`, { section: args.section }));
66
+ return `${data.title || data.key} (${data.key}, updated ${String(data.updated_at || '').slice(0, 10)}${data.section ? `, section "${data.section}"` : ''})\n\n${data.content}`;
67
+ }
68
+ if (name === 'search_docs') {
69
+ if (!args.query) throw new Error('query is required');
70
+ const { data } = await ctx.call('GET', route('', { q: args.query, limit: args.limit }));
71
+ if (!data.results.length) return `Nothing in the docs mentions all of: ${args.query}`;
72
+ return data.results.map((r) => [`${docName(r.key)} (${r.title})`, ...r.sections.map((s) => ` § ${s.heading || r.title}: ${s.snippet}`)].join('\n')).join('\n');
73
+ }
74
+ if (name === 'docs_changes') {
75
+ const since = args.since || new Date(Date.now() - 7 * 864e5).toISOString().slice(0, 10);
76
+ const { data } = await ctx.call('GET', route('', { since }));
77
+ return data.docs.length ? data.docs.map((d) => `${String(d.updated_at).slice(0, 10)} ${docName(d.key)} | ${d.title || ''}`).join('\n') : `No doc changed since ${since}.`;
78
+ }
79
+ throw Object.assign(new Error(`unknown tool ${name}`), { rpc: -32602 });
80
+ }
81
+
82
+ /** One JSON-RPC message → the response object, or null for a notification. */
83
+ async function handle(ctx, msg) {
84
+ const reply = (result) => ({ jsonrpc: '2.0', id: msg.id, result });
85
+ const fail = (code, message) => ({ jsonrpc: '2.0', id: msg.id, error: { code, message } });
86
+ const isNotification = msg.id === undefined || msg.id === null;
87
+ switch (msg.method) {
88
+ case 'initialize':
89
+ return reply({
90
+ protocolVersion: (msg.params && msg.params.protocolVersion) || '2025-06-18',
91
+ capabilities: { tools: {} },
92
+ serverInfo: { name: 'plaiful', version },
93
+ instructions: INSTRUCTIONS,
94
+ });
95
+ case 'notifications/initialized':
96
+ case 'notifications/cancelled':
97
+ return null;
98
+ case 'ping':
99
+ return reply({});
100
+ case 'tools/list':
101
+ return reply({ tools: TOOLS });
102
+ case 'tools/call': {
103
+ const { name, arguments: args } = msg.params || {};
104
+ if (!TOOLS.some((t) => t.name === name)) return fail(-32602, `unknown tool ${name}`);
105
+ try {
106
+ return reply({ content: [{ type: 'text', text: await runTool(ctx, name, args || {}) }] });
107
+ } catch (e) {
108
+ return reply({ content: [{ type: 'text', text: `Plaiful: ${e.message}` }], isError: true });
109
+ }
110
+ }
111
+ default:
112
+ return isNotification ? null : fail(-32601, `method not found: ${msg.method}`);
113
+ }
114
+ }
115
+
116
+ /** Serve until stdin closes. → exit code */
117
+ function serve(ctx) {
118
+ const stdin = ctx.io.stdin || process.stdin;
119
+ const write = (obj) => ctx.io.stdout.write(`${JSON.stringify(obj)}\n`);
120
+ let buf = '';
121
+ let pending = Promise.resolve();
122
+ return new Promise((resolve) => {
123
+ stdin.setEncoding && stdin.setEncoding('utf8');
124
+ stdin.on('data', (chunk) => {
125
+ buf += chunk;
126
+ let nl;
127
+ while ((nl = buf.indexOf('\n')) >= 0) {
128
+ const line = buf.slice(0, nl).trim();
129
+ buf = buf.slice(nl + 1);
130
+ if (!line) continue;
131
+ let msg;
132
+ try { msg = JSON.parse(line); } catch {
133
+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
134
+ continue;
135
+ }
136
+ pending = pending.then(() => handle(ctx, msg)).then((r) => { if (r) write(r); })
137
+ .catch((e) => { if (msg.id !== undefined) write({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: e.message } }); });
138
+ }
139
+ });
140
+ stdin.on('end', () => pending.then(() => resolve(0)));
141
+ });
142
+ }
143
+
144
+ module.exports = { serve, handle, TOOLS };