@plaiful/cli 0.0.0-stage → 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.
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
1
+ # The Plaiful CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `plaiful` is how a product team's person or agent works on their Plaiful product from the game repo, with no AWS
4
+ access. Every command runs as the signed-in CMS account (or a product API key that account issued), so it can only see
5
+ and change that account's products. Design: `docs/system/product/PARTNER_API_AND_CLI.md`.
6
+
7
+ ## Install
8
+
9
+ Node 18 or later:
10
+
11
+ ```sh
12
+ npm install -g @plaiful/cli
13
+ plaiful --version
14
+ ```
15
+
16
+ It's public on npmjs.com (it holds no secrets; everything it does needs a CMS sign-in or a key). From a PlaifulCMS
17
+ checkout instead: `npm install -g <path to PlaifulCMS>/packages/plaiful-cli`.
18
+
19
+ **Publishing a new version** (Plaiful staff): bump `version` here, then `npm publish` from this folder, signed in to
20
+ npm as a member of the `plaiful` org.
21
+
22
+ ## Use
23
+
24
+ ```sh
25
+ plaiful login # opens the CMS: check the code matches, approve. 12 hours.
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/
29
+ plaiful env # rewrite .env.development from the dev client config (keeps your own lines)
30
+ plaiful ovid check # checks docs/plaiful/roadforge-ovid-declaration.json
31
+ plaiful ovid publish # checks it again and publishes it; OVID reads it within ~5 minutes
32
+ plaiful ovid show # what OVID has now
33
+ plaiful seed world # dry run: what resources/world/roadforge/*.json make, and what changes in dev
34
+ plaiful seed world --apply # write it (then lore, then map); --reset also puts the clock, reveals and NPC bindings back
35
+ plaiful seed personas # THESPIS personas and situations from resources/personas/roadforge/ (same dry run / --apply)
36
+ plaiful status # what OVID and THESPIS have in dev: counts per store, the clock, the declaration
37
+ plaiful lists # the product's SSM lists
38
+ plaiful lists set shop_type tavern blacksmith healer # write one (lists get shop_type reads it)
39
+ plaiful upload ovid-map-biomes-tiles.json ovid-map-kingdoms-tiles.json ovid-map-colors.json # map tiles → map-data/
40
+ plaiful whoami # who you are (or which key), and your products
41
+ plaiful logout
42
+ ```
43
+
44
+ - `--json` on any command prints the platform's answer as JSON (for agents). Exit codes: `0` done, `1` the platform
45
+ said no (invalid, not allowed, not signed in), `2` the command itself was wrong.
46
+ - Everything works in **dev**. Staging and prod get your content through Plaiful's promotion.
47
+ - `docs pull` keeps `client-config.md` (your keys) out of git with `docs/plaiful/.gitignore`, and prints the
48
+ `git rm --cached` line if it was committed before.
49
+ - `clone` needs access to the repo on GitHub (git signed in: `gh auth login` or Git Credential Manager), and
50
+ `npm install` needs npm access to the `@plaiful` packages. It writes `.env.development` only when the repo has the
51
+ web template's `.env.development.example`.
52
+ - `lists set` writes a StringList in your product's namespace. It won't touch a key (SecureString), a setting (a plain
53
+ String), or `access/*` (who may play).
54
+ - The sign-in is kept in `~/.plaiful/credentials`, never in the repo. `PLAIFUL_API_URL` or `--api` points at another API.
55
+ - You need to be on the Plaiful allowlist, and own or be shared the product (Plaiful staff: every product).
56
+
57
+ ## Keys for agents and CI
58
+
59
+ A product's owner issues keys in the CMS: Product deployment → the product → **CLI keys**. A key is shown once; set
60
+ it as `PLAIFUL_TOKEN` in CI or the agent's environment (never in the repo) and the CLI uses it instead of a sign-in:
61
+
62
+ ```sh
63
+ PLAIFUL_TOKEN=plf_k_… plaiful seed world --apply
64
+ ```
65
+
66
+ A key acts as the owner who issued it, on that one product, in dev, for the scopes picked (`docs`, `status`, `seed`,
67
+ `ovid:publish`, `lists`, `upload`). Revoking it in the CMS stops it at once; so does its issuer losing the product. The
68
+ same screen shows the product's activity: everything the CLI and its keys did.
69
+
70
+ ## Tests
71
+
72
+ The end-to-end tests run this CLI against the partner API handler:
73
+ `lambda/functions/partner-api/__tests__/partner-api.test.js`.
package/bin/plaiful.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ require('../src/cli').main(process.argv.slice(2)).then((code) => { process.exitCode = code; });
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@plaiful/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The Plaiful CLI: work on your Plaiful product from your game repo, with no AWS access",
5
+ "bin": {
6
+ "plaiful": "bin/plaiful.js"
7
+ },
8
+ "files": [
9
+ "bin",
10
+ "src",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "license": "UNLICENSED",
17
+ "publishConfig": {
18
+ "registry": "https://registry.npmjs.org/",
19
+ "access": "public"
20
+ }
21
+ }
package/src/cli.js ADDED
@@ -0,0 +1,692 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The Plaiful CLI (PlaifulCMS docs/system/product/PARTNER_API_AND_CLI.md §4). Every command talks to the partner API
5
+ * as the signed-in person; nothing needs AWS. `--json` prints the API's answer as JSON, for agents.
6
+ *
7
+ * Exit codes: 0 done; 1 the platform said no (invalid, denied, not signed in); 2 the command was wrong.
8
+ */
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { spawn, spawnSync } = require('child_process');
13
+ const config = require('./config');
14
+ const { version } = require('../package.json');
15
+
16
+ const HELP = `plaiful ${version}: work on your Plaiful product from your game repo
17
+
18
+ plaiful login sign in (opens the CMS to approve; 12 hours)
19
+ plaiful logout sign out
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
23
+ plaiful ovid check [file] check your OVID declaration (default: <docsDir>/<product>-ovid-declaration.json)
24
+ plaiful ovid publish [file] check it and publish it; OVID reads it within about 5 minutes
25
+ plaiful ovid show the declaration OVID has now
26
+ plaiful seed world|lore|map|personas [paths] dry run: the rows your files make and what changes in dev
27
+ (default: every .json in resources/<store>/<product>/; personas = THESPIS
28
+ personas and situations)
29
+ --apply write them; --reset also put runtime state back to the files
30
+ --rows print every row
31
+ plaiful status what OVID and THESPIS have for your product in dev
32
+ plaiful lists your product's SSM lists (NPC roles, SmartBuilder list values, ...)
33
+ plaiful lists get <name> one list (a name in your namespace, e.g. shop_type, or the full /path)
34
+ plaiful lists set <name> <values...> write a list (values as words, or one comma-separated argument)
35
+ plaiful agents your product's SmartBuilder agents in dev
36
+ plaiful agents show <name> one agent's deployed config
37
+ plaiful agents deploy [files...] deploy or redeploy agents from their config files (default: every .json in
38
+ resources/agents/<product>/); a redeploy keeps the agent's own settings
39
+ plaiful agents run <name> [key=value...] make one record (placeholder values as key=value)
40
+ plaiful agents batch <name> [file] start a batch (a batch body file, or --count <n>) → a job id
41
+ plaiful agents status <name> <jobId> a batch's progress
42
+ plaiful upload <files...> upload map tiles into your dev assets bucket (map-data/; --dest map-data)
43
+ plaiful clone [product] [dir] clone the game repo, write .env.development, docs pull, npm install, open Zed
44
+ --no-install --no-open
45
+ plaiful env (re)write .env.development from your dev client config (keeps your own lines)
46
+
47
+ Options: --json (machine-readable output) --product <id> --api <url> --no-browser (login)
48
+ Environment: PLAIFUL_API_URL, PLAIFUL_TOKEN (instead of login: CI, with a product API key from the CMS)
49
+ Docs: docs/plaiful/README.md after \`plaiful docs pull\``;
50
+
51
+ class UsageError extends Error {}
52
+ class ApiError extends Error {
53
+ constructor(status, body) {
54
+ super((body && body.error) || `the platform answered ${status}`);
55
+ this.status = status;
56
+ this.body = body;
57
+ }
58
+ }
59
+
60
+ function parse(argv) {
61
+ const flags = {};
62
+ const args = [];
63
+ for (let i = 0; i < argv.length; i += 1) {
64
+ const a = argv[i];
65
+ if (['--json', '--no-browser', '--help', '-h', '--version', '--apply', '--reset', '--rows', '--no-install', '--no-open'].includes(a)) flags[a.replace(/^-+/, '')] = true;
66
+ else if (a === '--product' || a === '--api' || a === '--dir' || a === '--dest' || a === '--count') {
67
+ if (argv[i + 1] === undefined) throw new UsageError(`${a} needs a value`);
68
+ flags[a.slice(2)] = argv[i += 1];
69
+ } else if (a.startsWith('--')) throw new UsageError(`unknown option ${a}`);
70
+ else args.push(a);
71
+ }
72
+ return { flags, args };
73
+ }
74
+
75
+ function makeContext(io, flags) {
76
+ const url = config.apiUrl(flags);
77
+ const out = (text, json) => io.stdout.write(`${flags.json ? JSON.stringify(json === undefined ? text : json, null, 2) : text}\n`);
78
+ async function call(method, route, body, { auth = true } = {}) {
79
+ const headers = { Accept: 'application/json' };
80
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
81
+ if (auth) {
82
+ const token = config.tokenFor(url);
83
+ if (!token) throw new ApiError(401, { error: 'not signed in: run `plaiful login`', code: 'no_session' });
84
+ headers.Authorization = `Bearer ${token}`;
85
+ }
86
+ let res;
87
+ try {
88
+ res = await io.fetch(`${url}${route}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
89
+ } catch (e) {
90
+ throw new ApiError(0, { error: `can't reach the Plaiful API at ${url} (${e.message})`, code: 'network' });
91
+ }
92
+ let data = {};
93
+ try { data = await res.json(); } catch { /* empty body */ }
94
+ if (!res.ok && !(res.status === 422 || (res.status === 409 && data.errors))) throw new ApiError(res.status, data);
95
+ return { status: res.status, data };
96
+ }
97
+ return { url, flags, out, call, io };
98
+ }
99
+
100
+ function repo(ctx, { required = true } = {}) {
101
+ const found = config.findRepoConfig(ctx.io.cwd());
102
+ const product = ctx.flags.product || (found && found.config.product);
103
+ if (required && !product) throw new UsageError('no product: run `plaiful init <product>` in your repo, or pass --product');
104
+ const root = found ? found.root : ctx.io.cwd();
105
+ const docsDir = path.resolve(root, ctx.flags.dir || (found && found.config.docsDir) || config.DEFAULT_DOCS_DIR);
106
+ return { product, root, docsDir, found };
107
+ }
108
+
109
+ // ── Commands ────────────────────────────────────────────────────────────────────────────────────────────────────
110
+
111
+ async function login(ctx) {
112
+ const start = (await ctx.call('POST', '/partner/cli-login', undefined, { auth: false })).data;
113
+ ctx.io.stderr.write(`\nTo sign in, open:\n\n ${start.verification_url}\n\nand check the code matches: ${start.user_code}\n\n`);
114
+ if (!ctx.flags['no-browser']) ctx.io.openUrl(start.verification_url);
115
+ const deadline = Date.now() + start.expires_in * 1000;
116
+ let interval = (start.interval || 3) * 1000;
117
+ while (Date.now() < deadline) {
118
+ await ctx.io.sleep(interval);
119
+ const r = (await ctx.call('POST', '/partner/cli-login/token', { device_code: start.device_code }, { auth: false })).data;
120
+ if (r.status === 'approved') {
121
+ config.writeCredentials({ api_url: ctx.url, token: r.token, email: r.email, expires_at: r.expires_at });
122
+ ctx.out(`Signed in as ${r.email} until ${new Date(r.expires_at).toLocaleString()}.`, { success: true, email: r.email, expires_at: r.expires_at });
123
+ return 0;
124
+ }
125
+ interval = (r.interval || 3) * 1000;
126
+ }
127
+ throw new ApiError(410, { error: 'the sign-in wasn\'t approved in time; run `plaiful login` again', code: 'expired' });
128
+ }
129
+
130
+ async function logout(ctx) {
131
+ if (config.tokenFor(ctx.url)) {
132
+ try { await ctx.call('POST', '/partner/logout'); } catch { /* the local sign-out is what matters */ }
133
+ }
134
+ config.clearCredentials();
135
+ ctx.out('Signed out.', { success: true });
136
+ return 0;
137
+ }
138
+
139
+ async function whoami(ctx) {
140
+ const { data } = await ctx.call('GET', '/partner/whoami');
141
+ const lines = data.key
142
+ ? [`Product API key "${data.key.name}" for ${data.key.product} (${data.key.env}), issued by ${data.email}; scopes: ${data.key.scopes.join(', ')}`]
143
+ : [`${data.email}${data.staff ? ' (Plaiful staff)' : ''}, signed in until ${new Date(data.session_expires_at).toLocaleString()}`];
144
+ for (const st of data.studios || []) lines.push(`Studio: ${st.name} (${st.role}${st.preset ? `, ${st.preset}` : ''}${st.status !== 'active' ? `, ${st.status}` : ''})`);
145
+ lines.push(data.products.length ? 'Products:' : 'No products yet: create one in the CMS (Product deployment), or ask its owner to share it.');
146
+ for (const p of data.products) lines.push(` ${p.product_id} (${p.role})`);
147
+ ctx.out(lines.join('\n'), data);
148
+ return 0;
149
+ }
150
+
151
+ async function init(ctx, [product]) {
152
+ const { data } = await ctx.call('GET', '/partner/whoami');
153
+ const mine = data.products.map((p) => p.product_id);
154
+ const chosen = product || ctx.flags.product || (mine.length === 1 ? mine[0] : null);
155
+ if (!chosen) throw new UsageError(`which product? ${mine.length ? `yours: ${mine.join(', ')}` : 'you have none yet'} (plaiful init <product>)`);
156
+ if (!mine.includes(chosen)) throw new ApiError(403, { error: `${data.email} can't manage "${chosen}"${mine.length ? ` (yours: ${mine.join(', ')})` : ''}`, code: 'product_access' });
157
+ const existing = config.findRepoConfig(ctx.io.cwd());
158
+ const root = existing ? existing.root : ctx.io.cwd();
159
+ const next = { ...(existing ? existing.config : { env: 'dev', docsDir: config.DEFAULT_DOCS_DIR }), product: chosen };
160
+ const file = config.writeRepoConfig(root, next);
161
+ 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 });
162
+ return 0;
163
+ }
164
+
165
+ const safeName = (key) => {
166
+ const base = path.basename(String(key));
167
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(base)) return null;
168
+ return base;
169
+ };
170
+
171
+ async function docsPull(ctx, r = repo(ctx)) {
172
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/docs`);
173
+ fs.mkdirSync(r.docsDir, { recursive: true });
174
+ const files = [...data.docs, { key: data.client_config.key, title: 'Client config', content: data.client_config.content }];
175
+ const result = { written: [], unchanged: [], skipped: [] };
176
+ for (const f of files) {
177
+ const name = safeName(f.key);
178
+ if (!name) { result.skipped.push(f.key); continue; }
179
+ const target = path.join(r.docsDir, name);
180
+ const prev = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : null;
181
+ if (prev === f.content) { result.unchanged.push(name); continue; }
182
+ fs.writeFileSync(target, f.content);
183
+ result.written.push(name);
184
+ }
185
+ const index = {
186
+ _note: 'Written by `plaiful docs pull`. These files are replaced on every pull; keep your own files beside them under other names.',
187
+ product: r.product, env: data.env, pulled_at: new Date().toISOString(),
188
+ docs: files.map((f) => ({ file: safeName(f.key), title: f.title, description: f.description || '' })).filter((f) => f.file),
189
+ };
190
+ fs.writeFileSync(path.join(r.docsDir, '.plaiful-docs.json'), `${JSON.stringify(index, null, 2)}\n`);
191
+ const ignore = ignoreClientConfig(r.docsDir);
192
+ const rel = path.relative(ctx.io.cwd(), r.docsDir) || '.';
193
+ const lines = [
194
+ `${rel}: ${result.written.length} updated, ${result.unchanged.length} unchanged${result.skipped.length ? `, ${result.skipped.length} skipped` : ''}.`,
195
+ ...result.written.map((n) => ` updated ${n}`),
196
+ ];
197
+ if (ignore.added.length) lines.push(` ${path.join(rel, '.gitignore')}: now keeps ${ignore.added.join(', ')} out of git`);
198
+ if (ignore.tracked.length) {
199
+ lines.push(`! Already committed, and holding your keys: ${ignore.tracked.join(', ')}. Take them out of git (the files stay):`);
200
+ lines.push(` git rm --cached ${ignore.tracked.map((f) => `"${path.relative(ctx.io.cwd(), path.join(r.docsDir, f)).replace(/\\/g, '/')}"`).join(' ')}`);
201
+ }
202
+ lines.push('Start with README.md.');
203
+ ctx.out(lines.join('\n'), { success: true, dir: r.docsDir, ...result, gitignore: ignore });
204
+ return 0;
205
+ }
206
+
207
+ // client-config.md holds the product's keys and endpoints (the Firebase web key among them), so it never goes in git;
208
+ // nor do the older hand-made `<product>-client-config.md` copies.
209
+ const CLIENT_CONFIG_IGNORES = ['client-config.md', '*-client-config.md'];
210
+
211
+ function ignoreClientConfig(docsDir) {
212
+ const file = path.join(docsDir, '.gitignore');
213
+ const prev = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
214
+ const have = new Set(prev.split(/\r?\n/).map((l) => l.trim()));
215
+ const added = CLIENT_CONFIG_IGNORES.filter((p) => !have.has(p));
216
+ if (added.length) {
217
+ const head = prev ? `${prev.replace(/\s*$/, '')}\n` : '# Written by `plaiful docs pull`: these files hold your product\'s keys.\n';
218
+ fs.writeFileSync(file, `${head}${added.join('\n')}\n`);
219
+ }
220
+ // A .gitignore doesn't untrack what's already committed; say so rather than leave the keys in the repo.
221
+ const git = spawnSync('git', ['ls-files', '--', ...CLIENT_CONFIG_IGNORES], { cwd: docsDir, encoding: 'utf8' });
222
+ const tracked = git.status === 0 ? git.stdout.split('\n').map((l) => l.trim()).filter(Boolean) : [];
223
+ return { added, tracked };
224
+ }
225
+
226
+ function readDeclaration(ctx, r, file) {
227
+ const target = path.resolve(ctx.io.cwd(), file || path.join(r.docsDir, `${r.product}-ovid-declaration.json`));
228
+ if (!fs.existsSync(target)) throw new UsageError(`no declaration at ${target} (write it first: ovid-declaration.md)`);
229
+ try { return { target, declaration: JSON.parse(fs.readFileSync(target, 'utf8')) }; } catch (e) {
230
+ throw new UsageError(`${target} isn't valid JSON: ${e.message}`);
231
+ }
232
+ }
233
+
234
+ function findingsText(data) {
235
+ const lines = [];
236
+ const where = (x) => `${x.file ? `${x.file} ` : ''}${x.path || '(top level)'}`;
237
+ for (const e of data.errors || []) lines.push(` ✗ ${where(e)}: ${e.message} [${e.doc}]`);
238
+ for (const w of data.warnings || []) lines.push(` ! ${where(w)}: ${w.message} [${w.doc}]`);
239
+ for (const n of data.notes || []) lines.push(` · ${n}`);
240
+ return lines;
241
+ }
242
+
243
+ async function ovidCheck(ctx, [file]) {
244
+ const r = repo(ctx);
245
+ const { target, declaration } = readDeclaration(ctx, r, file);
246
+ const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/ovid/declaration/check`, { declaration });
247
+ const head = data.ok
248
+ ? `${path.basename(target)} is valid${(data.warnings || []).length ? `, with ${data.warnings.length} warning(s)` : ''}. Publish it with: plaiful ovid publish`
249
+ : `${path.basename(target)} has ${data.errors.length} error(s); fix them and check again.`;
250
+ ctx.out([head, ...findingsText(data)].join('\n'), data);
251
+ return data.ok ? 0 : 1;
252
+ }
253
+
254
+ async function ovidPublish(ctx, [file]) {
255
+ const r = repo(ctx);
256
+ const { target, declaration } = readDeclaration(ctx, r, file);
257
+ const { data } = await ctx.call('PUT', `/partner/${encodeURIComponent(r.product)}/ovid/declaration`, { declaration });
258
+ if (!data.published) {
259
+ ctx.out([`Not published: ${data.error || `${path.basename(target)} has ${(data.errors || []).length} error(s)`}`, ...findingsText(data)].join('\n'), data);
260
+ return 1;
261
+ }
262
+ const lines = [`Published ${path.basename(target)} for ${r.product}; OVID reads it ${data.takes_effect}.`];
263
+ if (data.tabs && data.tabs.error) lines.push(` ! ${data.tabs.error}`);
264
+ lines.push(...findingsText(data));
265
+ lines.push('Check it took: GameMaster shows your tier labels, tracks and regions (plaiful ovid show prints what OVID has).');
266
+ ctx.out(lines.join('\n'), data);
267
+ return 0;
268
+ }
269
+
270
+ async function ovidShow(ctx) {
271
+ const r = repo(ctx);
272
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/ovid/declaration`);
273
+ if (ctx.flags.json) { ctx.out(data); return 0; }
274
+ if (!data.declaration) ctx.out(data.packaged ? `${r.product}'s declaration is packaged: ${data.packaged}` : `${r.product} has no OVID declaration yet (OVID uses its defaults).`);
275
+ else ctx.out(`Published ${data.updated_at || '(date unknown)'}${data.published_by ? ` by ${data.published_by}` : ''}:\n${JSON.stringify(data.declaration, null, 2)}`);
276
+ return 0;
277
+ }
278
+
279
+ // ── Seeding (phase 2) ──────────────────────────────────────────────────────────────────────────────────────────
280
+
281
+ const STORES = ['world', 'lore', 'map', 'personas'];
282
+ const SEED_ROUTE = { world: 'ovid/world', lore: 'ovid/lore', map: 'ovid/map', personas: 'thespis/personas' };
283
+ const MARK = { create: '+', update: '~', remove: '-', keep: '=' };
284
+
285
+ /** The JSON files to send: the paths given (files or folders), else resources/<store>/<product>/. */
286
+ function seedFiles(ctx, r, store, paths) {
287
+ const targets = paths.length ? paths.map((x) => path.resolve(ctx.io.cwd(), x)) : [path.join(r.root, 'resources', store, r.product)];
288
+ const files = [];
289
+ for (const t of targets) {
290
+ if (!fs.existsSync(t)) throw new UsageError(`${t} doesn't exist${paths.length ? '' : ` (put your ${store} files there, or pass their paths)`}`);
291
+ const list = fs.statSync(t).isDirectory()
292
+ ? fs.readdirSync(t).filter((n) => n.toLowerCase().endsWith('.json')).sort().map((n) => path.join(t, n))
293
+ : [t];
294
+ for (const file of list) {
295
+ let content;
296
+ try { content = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { throw new UsageError(`${file} isn't valid JSON: ${e.message}`); }
297
+ files.push({ name: path.relative(r.root, file).replace(/\\/g, '/'), content });
298
+ }
299
+ }
300
+ if (!files.length) throw new UsageError(`no .json files in ${targets.join(', ')}`);
301
+ return files;
302
+ }
303
+
304
+ async function seedStore(ctx, store, paths) {
305
+ if (!STORES.includes(store)) throw new UsageError(`seed what? world, lore, map or personas (plaiful seed ${STORES.join('|')})`);
306
+ const r = repo(ctx);
307
+ const files = seedFiles(ctx, r, store, paths);
308
+ const apply = !!ctx.flags.apply;
309
+ const reset = !!ctx.flags.reset;
310
+ const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/${SEED_ROUTE[store]}/seed`, { files, apply, reset, rows: !!ctx.flags.rows });
311
+ if (ctx.flags.json) { ctx.out(data); return data.ok ? 0 : 1; }
312
+ const lines = [];
313
+ if (!data.ok) {
314
+ lines.push(`${files.length} ${store} file(s) have ${data.errors.length} error(s); nothing was ${apply ? 'written' : 'planned'}. Fix them and run it again.`);
315
+ lines.push(...findingsText(data));
316
+ ctx.out(lines.join('\n'));
317
+ return 1;
318
+ }
319
+ const s = data.summary;
320
+ const counts = Object.entries(data.counts || {}).map(([k, v]) => `${v} ${k}`).join(', ');
321
+ lines.push(`${store} for ${r.product} (dev, ${data.table}): ${counts}.`);
322
+ lines.push(`${apply ? 'Wrote' : 'Would write'}: ${s.create} new, ${s.update} changed, ${s.remove} removed, ${s.unchanged} unchanged${s.kept ? `, ${s.kept} kept as they are` : ''}.`);
323
+ if (data.unmanaged) lines.push(` · ${data.unmanaged} row(s) there weren't written by plaiful seed (${store === 'personas' ? 'the Tuning Studio\'s' : 'OVID\'s, the CMS\'s'}, or an older seeder's): left alone.`);
324
+ const shown = data.items.slice(0, 40);
325
+ for (const i of shown) lines.push(` ${MARK[i.action] || '?'} ${i.action.padEnd(6)} ${String(i.kind).padEnd(14)} ${i.id}${i.note ? ` (${i.note})` : ''}`);
326
+ if (data.items.length > shown.length) lines.push(` … and ${data.items.length - shown.length} more (--json lists them all)`);
327
+ lines.push(...findingsText(data));
328
+ if (ctx.flags.rows) lines.push(JSON.stringify(data.rows, null, 2));
329
+ if (!apply) lines.push(data.writes ? `Dry run: nothing written. Write it with: plaiful seed ${store}${paths.length ? ` ${paths.join(' ')}` : ''}${reset ? ' --reset' : ''} --apply` : 'Dry run: dev already matches your files.');
330
+ else if (data.writes) lines.push('Check it with: plaiful status');
331
+ ctx.out(lines.join('\n'));
332
+ return 0;
333
+ }
334
+
335
+ async function status(ctx) {
336
+ const r = repo(ctx);
337
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/status`);
338
+ if (ctx.flags.json) { ctx.out(data); return 0; }
339
+ const w = data.world || {};
340
+ const l = data.lore || {};
341
+ const m = data.map || {};
342
+ const d = data.declaration || {};
343
+ const err = (x) => (x.error ? ` ${x.error}` : null);
344
+ const lines = [`${r.product} in dev:`];
345
+ lines.push(` world ${err(w) || `${w.events} events (${w.macro} macro, ${w.meso} meso, ${w.micro} micro), ${w.seeded} seeded`}`);
346
+ if (!w.error) lines.push(` clock: ${w.clock ? `${w.clock.mode}, at ${w.clock.currentMicro} (${w.clock.chapterTitle})` : 'not set (seed a worldClock, or set it in GameMaster)'}`);
347
+ lines.push(` lore ${err(l) || `${l.sets} sets, ${l.snippets} snippets (${l.known} known, ${l.hidden} hidden), ${l.seeded} rows seeded${l.without_product ? `; ${l.without_product} snippets lack "product" and never reach a character` : ''}`}`);
348
+ lines.push(` map ${err(m) || `${m.locations} locations, ${m.settlements} settlements (${m.settlements_with_npcs} with NPCs), ${m.seeded} seeded`}`);
349
+ const t = data.thespis || {};
350
+ lines.push(` thespis ${err(t) || `${t.personas} personas (${t.active_personas} active), ${t.situations} situations, ${t.seeded} seeded`}`);
351
+ lines.push(` declaration ${d.declared ? `published ${d.updated_at || ''}: tiers ${d.timeline ? [d.timeline.macro, d.timeline.meso, d.timeline.micro].join(' / ') : '(defaults)'}; regions ${(d.regions || []).join(', ') || 'none'}; tracks ${(d.tracks || []).join(', ') || '(default)'}` : 'none yet (plaiful ovid publish)'}`);
352
+ ctx.out(lines.join('\n'));
353
+ return 0;
354
+ }
355
+
356
+ // ── Lists and uploads (phase 3) ──────────────────────────────────────────────────────────────────────────────────
357
+
358
+ /** The route for a list: a name in the namespace goes in the path; a full /path goes in ?path=. */
359
+ function listRoute(r, name) {
360
+ const base = `/partner/${encodeURIComponent(r.product)}/lists`;
361
+ if (!name) return base;
362
+ if (name.startsWith('/')) return `${base}?path=${encodeURIComponent(name)}`;
363
+ return `${base}/${name.split('/').map(encodeURIComponent).join('/')}`;
364
+ }
365
+
366
+ async function lists(ctx, [sub, name, ...values]) {
367
+ const r = repo(ctx);
368
+ if (!sub) {
369
+ const { data } = await ctx.call('GET', listRoute(r));
370
+ const lines = [`${r.product}'s lists in dev (${data.namespace}):`];
371
+ if (!data.lists.length) lines.push(' none yet (plaiful lists set <name> <values...>)');
372
+ for (const l of data.lists) lines.push(` ${l.name}${l.type === 'String' ? ' (a setting)' : ''} ${l.values.join(', ')}`);
373
+ ctx.out(lines.join('\n'), data);
374
+ return 0;
375
+ }
376
+ if (sub === 'get') {
377
+ if (!name) throw new UsageError('which list? plaiful lists get <name>');
378
+ const { data } = await ctx.call('GET', listRoute(r, name));
379
+ ctx.out(`${data.name}: ${data.values.join(', ')}`, data);
380
+ return 0;
381
+ }
382
+ if (sub === 'set') {
383
+ if (!name || !values.length) throw new UsageError('plaiful lists set <name> <values...> (e.g. plaiful lists set shop_type tavern blacksmith healer)');
384
+ const parsed = (values.length === 1 ? values[0].split(',') : values).map((v) => v.trim()).filter(Boolean);
385
+ const { data } = await ctx.call('PUT', listRoute(r, name), { values: parsed });
386
+ const was = data.previous === null ? 'new' : `was: ${data.previous.join(', ')}`;
387
+ ctx.out(`${data.name} = ${data.values.join(', ')} (${was})`, data);
388
+ return 0;
389
+ }
390
+ throw new UsageError(`plaiful lists, lists get <name> or lists set <name> <values...> (not "${sub}")`);
391
+ }
392
+
393
+ // ── SmartBuilder agents ─────────────────────────────────────────────────────────────────────────────────────
394
+
395
+ const agentRoute = (r, rest = '') => `/partner/${encodeURIComponent(r.product)}/agents${rest}`;
396
+ const AGENT_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
397
+
398
+ function readJsonFile(ctx, f) {
399
+ const file = path.resolve(ctx.io.cwd(), f);
400
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new UsageError(`${file} isn't a file`);
401
+ try { return { file, json: JSON.parse(fs.readFileSync(file, 'utf8')) }; } catch (e) { throw new UsageError(`${file} isn't valid JSON (${e.message})`); }
402
+ }
403
+
404
+ /** The config files to deploy: the ones named, or every .json in resources/agents/<product>/. */
405
+ function agentFiles(ctx, r, files) {
406
+ if (files.length) return files;
407
+ const dir = path.join(ctx.io.cwd(), 'resources', 'agents', r.product);
408
+ if (!fs.existsSync(dir)) throw new UsageError(`no files named, and no ${path.relative(ctx.io.cwd(), dir)}/ folder: plaiful agents deploy <file.json>`);
409
+ const found = fs.readdirSync(dir).filter((n) => n.endsWith('.json')).map((n) => path.join(dir, n));
410
+ if (!found.length) throw new UsageError(`${path.relative(ctx.io.cwd(), dir)}/ has no .json agent configs`);
411
+ return found;
412
+ }
413
+
414
+ async function agents(ctx, [sub, name, ...rest]) {
415
+ const r = repo(ctx);
416
+ if (!sub) {
417
+ const { data } = await ctx.call('GET', agentRoute(r));
418
+ const list = data.agents || [];
419
+ const lines = [`${r.product}'s SmartBuilder agents in dev:`];
420
+ if (!list.length) lines.push(' none yet (plaiful agents deploy <file.json>, or SmartBuilder in the CMS)');
421
+ for (const a of list) lines.push(` ${a.name || a.agent_name}${a.display_name ? ` ${a.display_name}` : ''}${a.business_purpose ? ` (${a.business_purpose})` : ''}`);
422
+ ctx.out(lines.join('\n'), data);
423
+ return 0;
424
+ }
425
+ if (sub === 'show') {
426
+ if (!name) throw new UsageError('which agent? plaiful agents show <name>');
427
+ const { data } = await ctx.call('GET', agentRoute(r, `/${encodeURIComponent(name)}`));
428
+ const a = data.agent || {};
429
+ const lines = [`${a.agent_name || name}: ${a.display_name || ''}`.trim(),
430
+ ` table ${(a.storage || {}).table_name || '?'}, version ${(a.metadata || {}).version || '?'}, ${(a.metadata || {}).business_purpose || 'content'}`,
431
+ ` fields ${(a.output_fields || []).join(', ')}`,
432
+ ` lists ${Object.entries(a.ssm_parameters || {}).map(([k, v]) => `${k} ← ${v}`).join('; ') || 'none'}`,
433
+ ` dedup ${a.duplicate_detection && a.duplicate_detection.enabled !== false ? `on ${[].concat(a.duplicate_detection.field || 'name').join(', ')}` : 'off'}`,
434
+ ' (--json prints the whole config)'];
435
+ ctx.out(lines.join('\n'), data);
436
+ return 0;
437
+ }
438
+ if (sub === 'deploy') {
439
+ const files = agentFiles(ctx, r, [name, ...rest].filter(Boolean));
440
+ const done = [];
441
+ for (const f of files) {
442
+ const { file, json } = readJsonFile(ctx, f);
443
+ const agentName = json.agent_name || path.basename(file, '.json');
444
+ if (!AGENT_NAME.test(agentName)) throw new UsageError(`${path.basename(file)}: "${agentName}" isn't an agent name (lowercase letters, digits, hyphens)`);
445
+ const { data } = await ctx.call('POST', agentRoute(r, `/${agentName}`), { config: json });
446
+ done.push(data);
447
+ if (!ctx.flags.json) ctx.out(`${data.redeployed ? 'redeployed' : 'deployed'} ${data.agent_name}: table ${data.table_name}${data.table === 'created' ? ' (new)' : ''}, version ${data.version}`);
448
+ }
449
+ if (ctx.flags.json) ctx.out('', { success: true, product: r.product, deployed: done });
450
+ return 0;
451
+ }
452
+ if (sub === 'run') {
453
+ if (!name) throw new UsageError('which agent? plaiful agents run <name> [key=value...]');
454
+ const body = {};
455
+ for (const kv of rest) {
456
+ const i = kv.indexOf('=');
457
+ if (i < 1) throw new UsageError(`"${kv}" isn't key=value`);
458
+ body[kv.slice(0, i)] = kv.slice(i + 1);
459
+ }
460
+ const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/run`), body);
461
+ const rec = data.item || data.record || data;
462
+ ctx.out(`made ${rec.uuid || 'a record'}${rec.name ? `: ${rec.name}` : ''}`, data);
463
+ return 0;
464
+ }
465
+ if (sub === 'batch') {
466
+ if (!name) throw new UsageError('which agent? plaiful agents batch <name> [batch-body.json] (or --count <n>)');
467
+ let body;
468
+ if (rest[0]) body = readJsonFile(ctx, rest[0]).json;
469
+ else if (ctx.flags.count) body = { count: Number(ctx.flags.count) };
470
+ else throw new UsageError('give a batch body file, or --count <n>');
471
+ const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/batch`), body);
472
+ ctx.out(`started batch ${data.job_id} (${data.total_items || '?'} records). plaiful agents status ${name} ${data.job_id}`, data);
473
+ return 0;
474
+ }
475
+ if (sub === 'status') {
476
+ const [jobId] = rest;
477
+ if (!name || !jobId) throw new UsageError('plaiful agents status <name> <jobId>');
478
+ const { data } = await ctx.call('GET', agentRoute(r, `/${encodeURIComponent(name)}/batch/${encodeURIComponent(jobId)}`));
479
+ ctx.out(`${data.status || '?'}: ${data.completed_items ?? '?'} done, ${data.failed_items ?? 0} failed of ${data.total_items ?? '?'}`, data);
480
+ return 0;
481
+ }
482
+ throw new UsageError(`plaiful agents, or agents show | deploy | run | batch | status (not "${sub}")`);
483
+ }
484
+
485
+ async function upload(ctx, files) {
486
+ const r = repo(ctx);
487
+ if (!files.length) throw new UsageError('upload what? plaiful upload <files...> (map tiles: ovid-map-*.json)');
488
+ const dest = ctx.flags.dest || 'map-data';
489
+ const done = [];
490
+ for (const f of files) {
491
+ const file = path.resolve(ctx.io.cwd(), f);
492
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new UsageError(`${file} isn't a file`);
493
+ const body = fs.readFileSync(file);
494
+ const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/uploads`, { dest, name: path.basename(file), size: body.length });
495
+ let res;
496
+ try {
497
+ res = await ctx.io.fetch(data.url, { method: data.method || 'PUT', headers: data.headers, body });
498
+ } catch (e) {
499
+ throw new ApiError(0, { error: `the upload of ${path.basename(file)} didn't go through (${e.message})`, code: 'network' });
500
+ }
501
+ if (!res.ok) throw new ApiError(res.status, { error: `storage refused ${path.basename(file)} (${res.status}); run the upload again`, code: 'upload_failed' });
502
+ done.push({ file: path.basename(file), bucket: data.bucket, key: data.key, size: body.length });
503
+ }
504
+ ctx.out([`Uploaded ${done.length} file(s) to ${r.product}'s dev assets:`, ...done.map((d) => ` ${d.file} → s3://${d.bucket}/${d.key} (${d.size} bytes)`)].join('\n'), { success: true, uploaded: done });
505
+ return 0;
506
+ }
507
+
508
+ // ── Clone and .env (the New-Game Flow) ───────────────────────────────────────────────────────────────────────────
509
+
510
+ /** The game template's .env variables (plaiful-kit packages/client config.ts ENV_KEYS) ← the client config. */
511
+ const ENV_FROM_CONFIG = {
512
+ VITE_PLAIFUL_PRODUCT: (c) => c.productId,
513
+ VITE_PLAIFUL_ENV: (c) => c.environment,
514
+ VITE_PLAIFUL_API_BASE: (c) => c.apiBaseUrl,
515
+ VITE_PLAIFUL_CDN_BASE: (c) => c.assetCdnUrl,
516
+ VITE_FIREBASE_PROJECT_ID: (c) => c.firebase && c.firebase.projectId,
517
+ VITE_FIREBASE_API_KEY: (c) => c.firebase && c.firebase.webApiKey,
518
+ VITE_FIREBASE_AUTH_DOMAIN: (c) => c.firebase && c.firebase.authDomain,
519
+ VITE_PLAIFUL_OVID_BASE: (c) => c.ovidApiUrl,
520
+ VITE_PLAIFUL_PRISM_WS_URL: (c) => c.prismWsUrl,
521
+ VITE_PLAIFUL_ANALYTICS_INGEST: (c) => c.analyticsIngestUrl,
522
+ VITE_PLAIFUL_ANALYTICS_KEY: (c, game) => game.analytics_ingest_key,
523
+ };
524
+ const ENV_FILE = '.env.development';
525
+ // "(pending)", "(not deployed ...)" and "<...>" placeholders aren't values (the template's config.ts treats them as missing).
526
+ const usable = (v) => typeof v === 'string' && v !== '' && !/^\(|not deployed|^</.test(v);
527
+
528
+ /**
529
+ * Write .env.development in `root` from the game's dev client config: start from the file as it is (or the
530
+ * template's .env.development.example), set the variables the platform knows, keep every other line.
531
+ * → { file, set: [names], missing: [names] } or null when the repo has neither file (not the web template).
532
+ */
533
+ function writeEnv(root, game) {
534
+ const file = path.join(root, ENV_FILE);
535
+ const example = path.join(root, `${ENV_FILE}.example`);
536
+ const base = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : fs.existsSync(example) ? fs.readFileSync(example, 'utf8') : null;
537
+ if (base === null) return null;
538
+ const set = [];
539
+ const missing = [];
540
+ const lines = base.split(/\r?\n/).map((line) => {
541
+ const m = /^\s*([A-Z0-9_]+)\s*=(.*)$/.exec(line);
542
+ if (!m || !ENV_FROM_CONFIG[m[1]]) return line;
543
+ const v = ENV_FROM_CONFIG[m[1]](game.client_config || {}, game);
544
+ if (!usable(v)) { if (!m[2].trim()) missing.push(m[1]); return line; }
545
+ set.push(m[1]);
546
+ return `${m[1]}=${v}`;
547
+ });
548
+ fs.writeFileSync(file, lines.join('\n'));
549
+ return { file, set, missing };
550
+ }
551
+
552
+ function envLines(env, game) {
553
+ if (!env) return [` · no ${ENV_FILE}(.example) here: not the web game template, so no .env was written (the client config is in docs/plaiful/client-config.md)`];
554
+ const out = [` ${ENV_FILE}: ${env.set.length} value(s) from your dev client config`];
555
+ if (env.missing.length) {
556
+ const why = game.analytics_ingest_key_note && env.missing.includes('VITE_PLAIFUL_ANALYTICS_KEY') ? ` (the analytics key: ${game.analytics_ingest_key_note})` : '';
557
+ out.push(` ! still empty: ${env.missing.join(', ')}${why}`);
558
+ }
559
+ return out;
560
+ }
561
+
562
+ async function envCmd(ctx) {
563
+ const r = repo(ctx);
564
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/game`);
565
+ const env = writeEnv(r.root, data);
566
+ if (!env) throw new UsageError(`no ${ENV_FILE} or ${ENV_FILE}.example in ${r.root}: this repo isn't the web game template`);
567
+ ctx.out([`${r.product} (dev):`, ...envLines(env, data)].join('\n'), { success: true, ...env });
568
+ return 0;
569
+ }
570
+
571
+ async function clone(ctx, [productArg, dirArg]) {
572
+ let product = productArg || ctx.flags.product;
573
+ if (!product) {
574
+ const { data } = await ctx.call('GET', '/partner/whoami');
575
+ if (data.products.length !== 1) throw new UsageError(`which game? ${data.products.length ? `yours: ${data.products.map((p) => p.product_id).join(', ')}` : 'you have none yet'} (plaiful clone <product>)`);
576
+ product = data.products[0].product_id;
577
+ }
578
+ const { data: game } = await ctx.call('GET', `/partner/${encodeURIComponent(product)}/game`);
579
+ if (!game.clone_url) throw new ApiError(409, { error: `${product} has no repo to clone yet: ${game.summary}`, code: 'no_repo' });
580
+ const repoLabel = (game.game_repo && game.game_repo.repo) || game.clone_url;
581
+ const repoName = String((game.game_repo && game.game_repo.repo) || product).split('/').pop().replace(/\.git$/, '');
582
+ const dir = path.resolve(ctx.io.cwd(), dirArg || repoName);
583
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length) throw new UsageError(`${dir} already exists and isn't empty; pass another folder: plaiful clone ${product} <dir>`);
584
+ ctx.io.stderr.write(`Cloning ${game.clone_url} into ${dir}...\n`);
585
+ const git = ctx.io.run('git', ['clone', game.clone_url, dir], { cwd: ctx.io.cwd() });
586
+ if (git.status !== 0) {
587
+ throw new ApiError(1, {
588
+ error: `git couldn't clone ${repoLabel}. You need access to it on GitHub (ask the product's owner, or Plaiful, to add your account) and git signed in to GitHub (gh auth login, or Git Credential Manager).`,
589
+ code: 'clone_failed',
590
+ });
591
+ }
592
+ const rel = path.relative(ctx.io.cwd(), dir) || '.';
593
+ const steps = [`Cloned ${repoLabel} into ${rel}.`];
594
+ const existing = config.findRepoConfig(dir);
595
+ const own = existing && existing.root === dir ? existing.config : null;
596
+ if (!own) config.writeRepoConfig(dir, { product, env: 'dev', docsDir: config.DEFAULT_DOCS_DIR });
597
+ const r = { product, root: dir, docsDir: path.resolve(dir, (own && own.docsDir) || config.DEFAULT_DOCS_DIR) };
598
+ steps.push(...envLines(writeEnv(dir, game), game));
599
+ await docsPull({ ...ctx, out: () => {} }, r);
600
+ steps.push(` ${path.relative(dir, r.docsDir).replace(/\\/g, '/')}: the onboarding docs and client-config.md`);
601
+ if (fs.existsSync(path.join(dir, 'package.json')) && !ctx.flags['no-install']) {
602
+ ctx.io.stderr.write('npm install...\n');
603
+ const npm = ctx.io.run('npm', ['install'], { cwd: dir });
604
+ steps.push(npm.status === 0 ? ' npm install: done'
605
+ : ' ! npm install failed. The @plaiful packages need npm access to the plaiful org (npm login; ask Plaiful), then run npm install there.');
606
+ }
607
+ if (!ctx.flags['no-open']) {
608
+ const zed = ctx.io.run('zed', [dir], { cwd: dir, detached: true });
609
+ steps.push(zed.status === 0 ? ' opened in Zed' : ' open it in your editor (Zed isn\'t installed)');
610
+ }
611
+ steps.push(`Next: cd ${rel}, npm run dev. docs/plaiful/README.md is the guide.`);
612
+ ctx.out(steps.join('\n'), { success: true, product, dir, clone_url: game.clone_url, game_repo: game.game_repo });
613
+ return 0;
614
+ }
615
+
616
+ const COMMANDS = {
617
+ login: (ctx) => login(ctx),
618
+ logout: (ctx) => logout(ctx),
619
+ whoami: (ctx) => whoami(ctx),
620
+ init: (ctx, rest) => init(ctx, rest),
621
+ 'docs pull': (ctx) => docsPull(ctx),
622
+ 'ovid check': (ctx, rest) => ovidCheck(ctx, rest),
623
+ 'ovid publish': (ctx, rest) => ovidPublish(ctx, rest),
624
+ 'ovid show': (ctx) => ovidShow(ctx),
625
+ seed: (ctx, [store, ...paths]) => seedStore(ctx, store, paths),
626
+ status: (ctx) => status(ctx),
627
+ lists: (ctx, rest) => lists(ctx, rest),
628
+ agents: (ctx, rest) => agents(ctx, rest),
629
+ upload: (ctx, files) => upload(ctx, files),
630
+ clone: (ctx, rest) => clone(ctx, rest),
631
+ env: (ctx) => envCmd(ctx),
632
+ };
633
+
634
+ function defaultIo() {
635
+ return {
636
+ fetch: (...a) => fetch(...a),
637
+ stdout: process.stdout,
638
+ stderr: process.stderr,
639
+ cwd: () => process.cwd(),
640
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
641
+ // git, npm and zed for `plaiful clone`, attached to the terminal so their output and prompts show. → { status }
642
+ run: (cmd, args, { cwd, detached = false } = {}) => {
643
+ const shell = process.platform === 'win32'; // npm and zed are .cmd shims on Windows
644
+ try {
645
+ if (detached) {
646
+ const probe = spawnSync(cmd, ['--version'], { shell, stdio: 'ignore' });
647
+ if (probe.status !== 0) return { status: probe.status === null ? 1 : probe.status };
648
+ spawn(cmd, args, { cwd, shell, stdio: 'ignore', detached: true }).on('error', () => {}).unref();
649
+ return { status: 0 };
650
+ }
651
+ const r = spawnSync(cmd, args, { cwd, shell, stdio: 'inherit' });
652
+ return { status: r.status === null ? 1 : r.status };
653
+ } catch { return { status: 1 }; }
654
+ },
655
+ openUrl: (url) => {
656
+ const [cmd, args] = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
657
+ : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
658
+ try { spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref(); } catch { /* print-only */ }
659
+ },
660
+ };
661
+ }
662
+
663
+ async function main(argv, io = defaultIo()) {
664
+ let flags = {};
665
+ try {
666
+ const parsed = parse(argv);
667
+ flags = parsed.flags;
668
+ if (flags.version) { io.stdout.write(`${version}\n`); return 0; }
669
+ const [a, b, ...rest] = parsed.args;
670
+ if (flags.help || !a || a === 'help') { io.stdout.write(`${HELP}\n`); return 0; }
671
+ const two = COMMANDS[`${a} ${b}`];
672
+ const one = COMMANDS[a];
673
+ const ctx = makeContext(io, flags);
674
+ if (two) return await two(ctx, rest);
675
+ if (one && !['docs', 'ovid'].includes(a)) return await one(ctx, b === undefined ? rest : [b, ...rest]);
676
+ throw new UsageError(`unknown command "${parsed.args.join(' ')}"`);
677
+ } catch (e) {
678
+ if (e instanceof UsageError) {
679
+ io.stderr.write(`plaiful: ${e.message}\n(plaiful help lists the commands)\n`);
680
+ return 2;
681
+ }
682
+ if (e instanceof ApiError) {
683
+ if (flags.json) io.stdout.write(`${JSON.stringify({ success: false, status: e.status, ...(e.body || {}), error: e.message }, null, 2)}\n`);
684
+ else io.stderr.write(`plaiful: ${e.message}\n`);
685
+ return 1;
686
+ }
687
+ io.stderr.write(`plaiful: ${e.stack || e.message}\n`);
688
+ return 1;
689
+ }
690
+ }
691
+
692
+ module.exports = { main, parse };
package/src/config.js ADDED
@@ -0,0 +1,73 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Where the CLI keeps things:
5
+ * - the sign-in: ~/.plaiful/credentials (JSON { api_url, token, email, expires_at }), never in a repo. PLAIFUL_TOKEN
6
+ * overrides it (CI, and later product API keys);
7
+ * - the repo's settings: .plaiful.json at the repo root ({ product, env, docsDir }), found from the current folder
8
+ * upward. No secrets in it, so it's safe to commit.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+
15
+ const DEFAULT_API_URL = 'https://p2rfkd5mn8.execute-api.us-west-1.amazonaws.com';
16
+ const REPO_FILE = '.plaiful.json';
17
+ const DEFAULT_DOCS_DIR = 'docs/plaiful';
18
+
19
+ const home = () => process.env.PLAIFUL_HOME || path.join(os.homedir(), '.plaiful');
20
+ const credentialsPath = () => path.join(home(), 'credentials');
21
+
22
+ function apiUrl(flags = {}) {
23
+ return String(flags.api || process.env.PLAIFUL_API_URL || DEFAULT_API_URL).replace(/\/+$/, '');
24
+ }
25
+
26
+ function readCredentials() {
27
+ try { return JSON.parse(fs.readFileSync(credentialsPath(), 'utf8')); } catch { return null; }
28
+ }
29
+
30
+ function writeCredentials(creds) {
31
+ fs.mkdirSync(home(), { recursive: true });
32
+ fs.writeFileSync(credentialsPath(), `${JSON.stringify(creds, null, 2)}\n`, { mode: 0o600 });
33
+ try { fs.chmodSync(credentialsPath(), 0o600); } catch { /* Windows: the user profile folder is already private */ }
34
+ }
35
+
36
+ function clearCredentials() {
37
+ try { fs.unlinkSync(credentialsPath()); } catch { /* not signed in */ }
38
+ }
39
+
40
+ /** The token to send for this API, or null. */
41
+ function tokenFor(url) {
42
+ if (process.env.PLAIFUL_TOKEN) return process.env.PLAIFUL_TOKEN;
43
+ const c = readCredentials();
44
+ if (!c || !c.token || c.api_url !== url) return null;
45
+ if (c.expires_at && Date.parse(c.expires_at) <= Date.now()) return null;
46
+ return c.token;
47
+ }
48
+
49
+ /** The nearest .plaiful.json from `start` upward → { file, root, config } or null. */
50
+ function findRepoConfig(start = process.cwd()) {
51
+ let dir = path.resolve(start);
52
+ for (;;) {
53
+ const file = path.join(dir, REPO_FILE);
54
+ if (fs.existsSync(file)) {
55
+ const config = JSON.parse(fs.readFileSync(file, 'utf8'));
56
+ return { file, root: dir, config: { env: 'dev', docsDir: DEFAULT_DOCS_DIR, ...config } };
57
+ }
58
+ const up = path.dirname(dir);
59
+ if (up === dir) return null;
60
+ dir = up;
61
+ }
62
+ }
63
+
64
+ function writeRepoConfig(root, config) {
65
+ const file = path.join(root, REPO_FILE);
66
+ fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
67
+ return file;
68
+ }
69
+
70
+ module.exports = {
71
+ DEFAULT_API_URL, DEFAULT_DOCS_DIR, REPO_FILE, apiUrl, credentialsPath, readCredentials, writeCredentials,
72
+ clearCredentials, tokenFor, findRepoConfig, writeRepoConfig,
73
+ };