personify-cli 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.
@@ -0,0 +1,502 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFileSync, writeFileSync } from "node:fs";
3
+ import { stringFlag, UUID } from "./args.js";
4
+ import { clearCredentials, credentialsPath, getCredentials, setCredentials, } from "./config.js";
5
+ import { CliError, EXIT, usage } from "./errors.js";
6
+ import { callTool, listTools } from "./mcp.js";
7
+ import { authorizeUrl, DEFAULT_SCOPE, discover, exchange, listenForCode, parseCallback, pkce, randomState, register, RENDER_SCOPE, revoke, } from "./oauth.js";
8
+ import { resolveSession, withSession } from "./session.js";
9
+ const reviewUrl = (origin, id) => `${origin}/dashboard?view=videos&video=${id}`;
10
+ const sessionOptions = (ctx) => ({
11
+ origin: ctx.origin,
12
+ env: ctx.env,
13
+ fetchImpl: ctx.fetchImpl,
14
+ now: ctx.now,
15
+ });
16
+ const canRender = (session) => session.source === "env" || session.scope.split(" ").includes(RENDER_SCOPE);
17
+ function requireId(ctx, what = "video") {
18
+ const id = ctx.args.positionals[0];
19
+ if (!id || !UUID.test(id))
20
+ throw usage(`Give the ${what} id (a UUID).`);
21
+ return id;
22
+ }
23
+ /** `--script` takes the words, `@path` to read a file, or `-` for stdin. */
24
+ async function scriptFlag(ctx) {
25
+ const raw = stringFlag(ctx.args.flags, "script");
26
+ if (raw === undefined)
27
+ return undefined;
28
+ if (raw === "-")
29
+ return (await ctx.readStdin()).replace(/\r?\n$/, "");
30
+ if (raw.startsWith("@"))
31
+ return readFileSync(raw.slice(1), "utf8").trim();
32
+ return raw;
33
+ }
34
+ const summary = (v) => ({
35
+ id: v.id,
36
+ title: v.theme,
37
+ status: v.status,
38
+ generation: v.generation?.status ?? null,
39
+ format: v.format_payload?.format_remix?.id ?? null,
40
+ scheduled: v.is_scheduled ? v.scheduled_date : null,
41
+ updated_at: v.updated_at,
42
+ });
43
+ const login = {
44
+ name: "login",
45
+ summary: "Sign in through the browser (OAuth). One login covers the brand selected in Personify.",
46
+ usage: "personify login [--allow-render] [--no-browser] [--manual] [--api-url <origin>]",
47
+ run: async (ctx) => {
48
+ const { flags } = ctx.args;
49
+ const endpoints = await discover(ctx.origin, ctx.fetchImpl);
50
+ const existing = getCredentials(ctx.origin, ctx.env);
51
+ const clientId = existing?.client_id || (await register(endpoints, ctx.fetchImpl));
52
+ const scope = flags["allow-render"] === true
53
+ ? `${DEFAULT_SCOPE} ${RENDER_SCOPE}`
54
+ : DEFAULT_SCOPE;
55
+ const { verifier, challenge } = pkce();
56
+ const state = randomState();
57
+ const manual = flags.manual === true;
58
+ const listener = manual ? null : await listenForCode();
59
+ const redirectUri = listener
60
+ ? listener.redirectUri
61
+ : "http://127.0.0.1/callback";
62
+ const url = authorizeUrl({
63
+ endpoints,
64
+ clientId,
65
+ redirectUri,
66
+ challenge,
67
+ scope,
68
+ state,
69
+ });
70
+ let callback;
71
+ try {
72
+ const opened = !manual && flags.browser !== false ? ctx.openBrowser(url) : false;
73
+ ctx.log(opened
74
+ ? "Approve the connection in your browser. If it did not open, use this address:"
75
+ : "Open this address in a browser that is signed in to Personify:");
76
+ ctx.log(url);
77
+ if (listener) {
78
+ ctx.log("Waiting for the approval (up to 5 minutes)…");
79
+ callback = await listener.waitForCode();
80
+ }
81
+ else {
82
+ ctx.log("After approving, paste the full address the browser was sent to, then press Enter:");
83
+ callback = parseCallback(await ctx.readStdin());
84
+ }
85
+ }
86
+ finally {
87
+ listener?.close();
88
+ }
89
+ if (callback.state !== state)
90
+ throw new CliError("The approval did not match this login attempt. Run `personify login` again.", EXIT.AUTH, "state_mismatch");
91
+ if (callback.iss && callback.iss !== ctx.origin)
92
+ throw new CliError("The approval came from a different server. Run `personify login` again.", EXIT.AUTH, "issuer_mismatch");
93
+ const tokens = await exchange(endpoints, { code: callback.code, redirectUri, clientId, verifier }, ctx.fetchImpl);
94
+ const creds = {
95
+ client_id: clientId,
96
+ access_token: tokens.access_token,
97
+ refresh_token: tokens.refresh_token,
98
+ expires_at: ctx.now() + tokens.expires_in * 1000,
99
+ scope: tokens.scope || scope,
100
+ };
101
+ setCredentials(ctx.origin, creds, ctx.env);
102
+ const brand = await callTool({ origin: ctx.origin, token: creds.access_token }, "get_brand", {}, ctx.fetchImpl);
103
+ return {
104
+ data: {
105
+ origin: ctx.origin,
106
+ brand: { id: brand.id, company_name: brand.company_name },
107
+ scope: creds.scope,
108
+ can_render: creds.scope.split(" ").includes(RENDER_SCOPE),
109
+ credentials: credentialsPath(ctx.env),
110
+ },
111
+ text: `Signed in to ${ctx.origin} for ${brand.company_name}.`,
112
+ };
113
+ },
114
+ };
115
+ const logout = {
116
+ name: "logout",
117
+ summary: "Revoke this machine's login and delete the stored session.",
118
+ usage: "personify logout",
119
+ run: async (ctx) => {
120
+ const creds = getCredentials(ctx.origin, ctx.env);
121
+ if (creds) {
122
+ const endpoints = await discover(ctx.origin, ctx.fetchImpl);
123
+ await revoke(endpoints, { token: creds.access_token, clientId: creds.client_id }, ctx.fetchImpl);
124
+ clearCredentials(ctx.origin, ctx.env);
125
+ }
126
+ return {
127
+ data: { origin: ctx.origin, signed_out: Boolean(creds) },
128
+ text: creds ? "Signed out." : "No stored login for this origin.",
129
+ };
130
+ },
131
+ };
132
+ const whoami = {
133
+ name: "whoami",
134
+ summary: "Show the signed-in brand and what this login may do.",
135
+ usage: "personify whoami",
136
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
137
+ const brand = await callTool(session, "get_brand", {}, ctx.fetchImpl);
138
+ return {
139
+ data: {
140
+ origin: ctx.origin,
141
+ brand: { id: brand.id, company_name: brand.company_name },
142
+ scope: session.scope || null,
143
+ can_render: canRender(session),
144
+ token_source: session.source,
145
+ expires_at: session.expires_at
146
+ ? new Date(session.expires_at).toISOString()
147
+ : null,
148
+ },
149
+ };
150
+ }),
151
+ };
152
+ const brands = {
153
+ name: "brands",
154
+ summary: "List the brand this login can work on. A login covers one brand; select another brand in Personify and run `personify login` again to switch.",
155
+ usage: "personify brands",
156
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
157
+ const brand = await callTool(session, "get_brand", {}, ctx.fetchImpl);
158
+ return { data: [{ id: brand.id, company_name: brand.company_name }] };
159
+ }),
160
+ };
161
+ const brand = {
162
+ name: "brand",
163
+ summary: "Read the signed-in brand: offering, audience, tone and persona.",
164
+ usage: "personify brand",
165
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => ({
166
+ data: await callTool(session, "get_brand", {}, ctx.fetchImpl),
167
+ })),
168
+ };
169
+ const formatsList = {
170
+ name: "formats list",
171
+ summary: "List the Format Book reel formats with category, audio mode, length and the words a script may hold.",
172
+ usage: "personify formats list [--category <id>] [--audio text|speech|dialogue|ambient]",
173
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
174
+ const args = {};
175
+ const category = stringFlag(ctx.args.flags, "category");
176
+ const audio = stringFlag(ctx.args.flags, "audio");
177
+ if (category)
178
+ args.category = category;
179
+ if (audio)
180
+ args.audio = audio;
181
+ return {
182
+ data: await callTool(session, "list_formats", args, ctx.fetchImpl),
183
+ };
184
+ }),
185
+ };
186
+ const formatsGet = {
187
+ name: "formats get",
188
+ summary: "Show one format by id.",
189
+ usage: "personify formats get <format-id>",
190
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
191
+ const id = ctx.args.positionals[0];
192
+ if (!id)
193
+ throw usage("Give the format id, for example format-advice-01.");
194
+ const all = await callTool(session, "list_formats", {}, ctx.fetchImpl);
195
+ const found = all.find((f) => f.id === id);
196
+ if (!found)
197
+ throw new CliError(`Unknown format ${id}. Run \`personify formats list\`.`, EXIT.NOT_FOUND, "not_found");
198
+ return { data: found };
199
+ }),
200
+ };
201
+ const videoList = {
202
+ name: "video list",
203
+ summary: "List the latest 50 drafts and videos with their status.",
204
+ usage: "personify video list [--all]",
205
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
206
+ const videos = await callTool(session, "list_videos", {}, ctx.fetchImpl);
207
+ return {
208
+ data: ctx.args.flags.all === true ? videos : videos.map(summary),
209
+ };
210
+ }),
211
+ };
212
+ const videoGet = {
213
+ name: "video status",
214
+ summary: "Read one draft or video: script, format, generation status and review state.",
215
+ usage: "personify video status <video-id>",
216
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
217
+ const id = requireId(ctx);
218
+ const video = await callTool(session, "get_video", { id }, ctx.fetchImpl);
219
+ return {
220
+ data: { ...video, review_url: reviewUrl(ctx.origin, id) },
221
+ };
222
+ }),
223
+ };
224
+ const videoCreate = {
225
+ name: "video create",
226
+ summary: "Save a draft (nothing is generated or charged). Add --format to follow a Format Book format.",
227
+ usage: "personify video create --title <text> --script <text|@file|-> [--format <id>] [--caption <text>] [--request-id <uuid>] [--brand <id>]",
228
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
229
+ const title = stringFlag(ctx.args.flags, "title");
230
+ const script = await scriptFlag(ctx);
231
+ if (!title)
232
+ throw usage("Give --title.");
233
+ if (script === undefined)
234
+ throw usage("Give --script (text, @file or - for stdin).");
235
+ const requestId = stringFlag(ctx.args.flags, "request-id") || randomUUID();
236
+ if (!UUID.test(requestId))
237
+ throw usage("--request-id must be a UUID.");
238
+ const brandFlag = stringFlag(ctx.args.flags, "brand");
239
+ if (brandFlag) {
240
+ const current = await callTool(session, "get_brand", {}, ctx.fetchImpl);
241
+ if (brandFlag !== current.id && brandFlag !== current.company_name)
242
+ throw new CliError(`This login works on ${current.company_name} (${current.id}). Select ${brandFlag} in Personify and run \`personify login\` again.`, EXIT.PERMISSION, "wrong_brand");
243
+ }
244
+ const args = {
245
+ request_id: requestId,
246
+ title,
247
+ script,
248
+ };
249
+ const format = stringFlag(ctx.args.flags, "format");
250
+ const caption = stringFlag(ctx.args.flags, "caption");
251
+ if (format)
252
+ args.format = format;
253
+ if (caption)
254
+ args.caption = caption;
255
+ const video = await callTool(session, "create_draft", args, ctx.fetchImpl);
256
+ return {
257
+ data: {
258
+ ...video,
259
+ request_id: requestId,
260
+ review_url: reviewUrl(ctx.origin, video.id),
261
+ },
262
+ text: `Draft saved. Review it at ${reviewUrl(ctx.origin, video.id)}`,
263
+ };
264
+ }),
265
+ };
266
+ const videoEdit = {
267
+ name: "video edit",
268
+ summary: "Change a draft's title or script (unrendered drafts only).",
269
+ usage: "personify video edit <video-id> [--title <text>] [--script <text|@file|->]",
270
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
271
+ const id = requireId(ctx);
272
+ const title = stringFlag(ctx.args.flags, "title");
273
+ const script = await scriptFlag(ctx);
274
+ if (title === undefined && script === undefined)
275
+ throw usage("Give --title and/or --script.");
276
+ const current = await callTool(session, "get_video", { id }, ctx.fetchImpl);
277
+ const video = await callTool(session, "edit_draft", {
278
+ id,
279
+ updated_at: current.updated_at,
280
+ title: title ?? current.theme ?? "Untitled",
281
+ script: script ?? current.format_payload?.script ?? "",
282
+ }, ctx.fetchImpl);
283
+ return { data: { ...video, review_url: reviewUrl(ctx.origin, id) } };
284
+ }),
285
+ };
286
+ const videoReviewLink = {
287
+ name: "video review-link",
288
+ summary: "Get the link where the owner reviews and approves a draft.",
289
+ usage: "personify video review-link <video-id>",
290
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => ({
291
+ data: await callTool(session, "prepare_generation_approval", { id: requireId(ctx) }, ctx.fetchImpl),
292
+ })),
293
+ };
294
+ const videoDownload = {
295
+ name: "video download",
296
+ summary: "Get a one-hour download link for a finished, approved video; --out saves the mp4 to a file.",
297
+ usage: "personify video download <video-id> [--out <file.mp4>]",
298
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
299
+ const id = requireId(ctx);
300
+ const link = await callTool(session, "get_video_download", { id }, ctx.fetchImpl);
301
+ const out = stringFlag(ctx.args.flags, "out");
302
+ if (!out)
303
+ return { data: link };
304
+ if (link.requires_owner_session)
305
+ throw new CliError("This video can only be downloaded by the owner in Personify. Open the download_url in a signed-in browser.", EXIT.PERMISSION, "owner_session_required", link);
306
+ const res = await ctx.fetchImpl(link.download_url);
307
+ if (!res.ok)
308
+ throw new CliError(`The download failed (${res.status}). Ask for a new link.`, EXIT.UNAVAILABLE, "download_failed");
309
+ const bytes = Buffer.from(await res.arrayBuffer());
310
+ writeFileSync(out, bytes);
311
+ return {
312
+ data: { ...link, saved_to: out, bytes: bytes.length },
313
+ text: `Saved ${bytes.length} bytes to ${out}.`,
314
+ };
315
+ }),
316
+ };
317
+ function assertRenderAllowed(ctx, session, id) {
318
+ if (canRender(session))
319
+ return;
320
+ throw new CliError("This login cannot start paid renders. Run `personify login --allow-render` and approve the extra permission, or ask the owner to approve the draft at its review link.", EXIT.PERMISSION, "render_not_allowed", { review_url: reviewUrl(ctx.origin, id) });
321
+ }
322
+ const videoQuote = {
323
+ name: "video quote",
324
+ summary: "Price one render in credits without spending (needs a login with --allow-render).",
325
+ usage: "personify video quote <video-id>",
326
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
327
+ const id = requireId(ctx);
328
+ assertRenderAllowed(ctx, session, id);
329
+ return {
330
+ data: await callTool(session, "quote_video", { id }, ctx.fetchImpl),
331
+ };
332
+ }),
333
+ };
334
+ const FINAL = new Set(["completed", "failed"]);
335
+ const videoWait = {
336
+ name: "video wait",
337
+ summary: "Poll a rendering video until it finishes or fails.",
338
+ usage: "personify video wait <video-id> [--interval <seconds>] [--timeout <seconds>]",
339
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
340
+ const id = requireId(ctx);
341
+ const interval = Math.max(5, Number(stringFlag(ctx.args.flags, "interval")) || 15);
342
+ const timeout = Math.max(interval, Number(stringFlag(ctx.args.flags, "timeout")) || 1200);
343
+ const deadline = ctx.now() + timeout * 1000;
344
+ for (;;) {
345
+ const video = await callTool(session, "get_video", { id }, ctx.fetchImpl);
346
+ const status = video.generation?.status;
347
+ if ((status && FINAL.has(status)) ||
348
+ ["rendered", "failed", "published"].includes(video.status))
349
+ return {
350
+ data: { ...video, review_url: reviewUrl(ctx.origin, id) },
351
+ exit: status === "failed" || video.status === "failed"
352
+ ? EXIT.ERROR
353
+ : EXIT.OK,
354
+ };
355
+ if (ctx.now() >= deadline)
356
+ throw new CliError(`Still ${status || video.status} after ${timeout} seconds. Check again later with \`personify video status ${id}\`.`, EXIT.UNAVAILABLE, "timeout", { ...video });
357
+ ctx.log(`${status || video.status}${video.generation?.stage ? ` · ${video.generation.stage}` : ""}; checking again in ${interval}s`);
358
+ await ctx.sleep(interval * 1000);
359
+ }
360
+ }),
361
+ };
362
+ const render = {
363
+ name: "render",
364
+ summary: "Quote a draft, then start the paid render only with --confirm-paid. Without the flag nothing is spent (exit 3).",
365
+ usage: "personify render <video-id> [--confirm-paid]",
366
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
367
+ const id = requireId(ctx);
368
+ assertRenderAllowed(ctx, session, id);
369
+ const quote = await callTool(session, "quote_video", { id }, ctx.fetchImpl);
370
+ const review_url = reviewUrl(ctx.origin, id);
371
+ if (ctx.args.flags["confirm-paid"] !== true)
372
+ return {
373
+ data: {
374
+ confirmed: false,
375
+ spent: 0,
376
+ ...quote,
377
+ review_url,
378
+ next: `personify render ${id} --confirm-paid`,
379
+ },
380
+ text: `Nothing was spent. ${quote.message} To start the render from here, re-run with --confirm-paid.`,
381
+ exit: EXIT.CONFIRM,
382
+ };
383
+ const started = await callTool(session, "render_video", {
384
+ id,
385
+ updated_at: quote.updated_at,
386
+ ...(quote.quote_id ? { quote_id: quote.quote_id } : {}),
387
+ confirm: true,
388
+ }, ctx.fetchImpl);
389
+ return {
390
+ data: {
391
+ confirmed: true,
392
+ credits: quote.credits,
393
+ quote_id: quote.quote_id,
394
+ ...started,
395
+ },
396
+ text: `Render started. Follow it with \`personify video wait ${id}\`.`,
397
+ };
398
+ }),
399
+ };
400
+ const assetsList = {
401
+ name: "assets list",
402
+ summary: "List finished reels, their takes and clips, and brand photos; --references lists approved reusable media.",
403
+ usage: "personify assets list [--kind reels|clips|photos] [--references]",
404
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
405
+ if (ctx.args.flags.references === true)
406
+ return {
407
+ data: await callTool(session, "list_approved_assets", {}, ctx.fetchImpl),
408
+ };
409
+ const assets = await callTool(session, "list_assets", {}, ctx.fetchImpl);
410
+ const kind = stringFlag(ctx.args.flags, "kind");
411
+ if (kind) {
412
+ if (!(kind in assets))
413
+ throw usage("--kind must be reels, clips or photos.");
414
+ return { data: assets[kind] };
415
+ }
416
+ return { data: assets };
417
+ }),
418
+ };
419
+ const tools = {
420
+ name: "tools",
421
+ summary: "List the MCP tools this login can call, with their input schemas.",
422
+ usage: "personify tools",
423
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => ({
424
+ data: await listTools(session, ctx.fetchImpl),
425
+ })),
426
+ };
427
+ const call = {
428
+ name: "call",
429
+ summary: "Call any MCP tool directly with a JSON argument object.",
430
+ usage: "personify call <tool> [--args '<json>']",
431
+ run: (ctx) => withSession(sessionOptions(ctx), async (session) => {
432
+ const tool = ctx.args.positionals[0];
433
+ if (!tool)
434
+ throw usage("Give the tool name. See `personify tools`.");
435
+ const raw = stringFlag(ctx.args.flags, "args") || "{}";
436
+ let args;
437
+ try {
438
+ args = JSON.parse(raw);
439
+ if (!args || typeof args !== "object" || Array.isArray(args))
440
+ throw Error();
441
+ }
442
+ catch {
443
+ throw usage("--args must be a JSON object.");
444
+ }
445
+ return { data: await callTool(session, tool, args, ctx.fetchImpl) };
446
+ }),
447
+ };
448
+ const docs = {
449
+ name: "docs",
450
+ summary: "Where the agent and developer documentation lives.",
451
+ usage: "personify docs",
452
+ run: async (ctx) => ({
453
+ data: {
454
+ agents: `${ctx.origin}/docs/agents`,
455
+ mcp: `${ctx.origin}/docs/mcp`,
456
+ llms: `${ctx.origin}/llms.txt`,
457
+ llms_full: `${ctx.origin}/llms-full.txt`,
458
+ mcp_server: `${ctx.origin}/api/mcp`,
459
+ },
460
+ }),
461
+ };
462
+ export const COMMANDS = [
463
+ login,
464
+ logout,
465
+ whoami,
466
+ brands,
467
+ brand,
468
+ formatsList,
469
+ formatsGet,
470
+ videoList,
471
+ videoGet,
472
+ videoCreate,
473
+ videoEdit,
474
+ videoReviewLink,
475
+ videoDownload,
476
+ videoQuote,
477
+ videoWait,
478
+ render,
479
+ assetsList,
480
+ tools,
481
+ call,
482
+ docs,
483
+ ];
484
+ const ALIASES = {
485
+ "video get": "video status",
486
+ "video show": "video status",
487
+ formats: "formats list",
488
+ assets: "assets list",
489
+ videos: "video list",
490
+ };
491
+ /** Resolve the longest command name that prefixes the positionals. */
492
+ export function findCommand(positionals) {
493
+ for (const depth of [2, 1]) {
494
+ const key = positionals.slice(0, depth).join(" ");
495
+ const name = ALIASES[key] || key;
496
+ const command = COMMANDS.find((c) => c.name === name);
497
+ if (command)
498
+ return { command, depth };
499
+ }
500
+ return null;
501
+ }
502
+ export { resolveSession };
package/dist/config.js ADDED
@@ -0,0 +1,73 @@
1
+ import { chmodSync, closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ export function configDir(env = process.env) {
5
+ return (env.PERSONIFY_CONFIG_DIR ||
6
+ join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "personify"));
7
+ }
8
+ export const credentialsPath = (env) => join(configDir(env), "credentials.json");
9
+ export function readStore(env) {
10
+ try {
11
+ const parsed = JSON.parse(readFileSync(credentialsPath(env), "utf8"));
12
+ return parsed && typeof parsed === "object" ? parsed : {};
13
+ }
14
+ catch {
15
+ return {};
16
+ }
17
+ }
18
+ export function writeStore(store, env) {
19
+ mkdirSync(configDir(env), { recursive: true, mode: 0o700 });
20
+ const path = credentialsPath(env);
21
+ writeFileSync(path, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
22
+ chmodSync(path, 0o600);
23
+ }
24
+ export const getCredentials = (origin, env) => readStore(env)[origin];
25
+ export function setCredentials(origin, creds, env) {
26
+ writeStore({ ...readStore(env), [origin]: creds }, env);
27
+ }
28
+ export function clearCredentials(origin, env) {
29
+ const store = readStore(env);
30
+ const had = origin in store;
31
+ delete store[origin];
32
+ writeStore(store, env);
33
+ return had;
34
+ }
35
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
36
+ /**
37
+ * Serialize credential refreshes across concurrent CLI processes. A refresh
38
+ * token is single-use and a replay revokes the whole login, so two commands
39
+ * racing to refresh must not both try.
40
+ */
41
+ export async function withLock(fn, env) {
42
+ mkdirSync(configDir(env), { recursive: true, mode: 0o700 });
43
+ const lock = join(configDir(env), "credentials.lock");
44
+ for (let attempt = 0;; attempt++) {
45
+ try {
46
+ closeSync(openSync(lock, "wx"));
47
+ break;
48
+ }
49
+ catch {
50
+ try {
51
+ if (Date.now() - statSync(lock).mtimeMs > 30_000)
52
+ unlinkSync(lock);
53
+ }
54
+ catch {
55
+ // The lock vanished between the checks; try again.
56
+ }
57
+ if (attempt > 100)
58
+ throw new Error("Could not lock the credential store.");
59
+ await sleep(100);
60
+ }
61
+ }
62
+ try {
63
+ return await fn();
64
+ }
65
+ finally {
66
+ try {
67
+ unlinkSync(lock);
68
+ }
69
+ catch {
70
+ // Already removed.
71
+ }
72
+ }
73
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,44 @@
1
+ /** Exit codes an agent can branch on. */
2
+ export const EXIT = {
3
+ OK: 0,
4
+ ERROR: 1,
5
+ USAGE: 2,
6
+ /** A paid action needs an explicit flag; nothing was spent. */
7
+ CONFIRM: 3,
8
+ /** Not signed in, or the session expired and could not be refreshed. */
9
+ AUTH: 4,
10
+ NOT_FOUND: 5,
11
+ /** The record changed since it was read; read it again. */
12
+ CONFLICT: 6,
13
+ /** The login does not hold the permission the command needs. */
14
+ PERMISSION: 7,
15
+ /** Personify or the network is temporarily unavailable. */
16
+ UNAVAILABLE: 8,
17
+ };
18
+ export class CliError extends Error {
19
+ exit;
20
+ code;
21
+ details;
22
+ constructor(message, exit = EXIT.ERROR, code = "error", details) {
23
+ super(message);
24
+ this.exit = exit;
25
+ this.code = code;
26
+ this.details = details;
27
+ }
28
+ }
29
+ export const usage = (message) => new CliError(message, EXIT.USAGE, "usage");
30
+ /** Map a tool refusal to an exit code from its customer-facing message. */
31
+ export function exitForMessage(message) {
32
+ const m = message.toLowerCase();
33
+ if (/permission|not allowed|sign in|revoked|invalid_token/.test(m))
34
+ return /sign in|revoked|invalid_token/.test(m)
35
+ ? EXIT.AUTH
36
+ : EXIT.PERMISSION;
37
+ if (/not found|unknown format/.test(m))
38
+ return EXIT.NOT_FOUND;
39
+ if (/changed|read it again|already|locked|fresh/.test(m))
40
+ return EXIT.CONFLICT;
41
+ if (/unavailable|try again|too many/.test(m))
42
+ return EXIT.UNAVAILABLE;
43
+ return EXIT.ERROR;
44
+ }
package/dist/help.js ADDED
@@ -0,0 +1,34 @@
1
+ import { COMMANDS } from "./commands.js";
2
+ import { EXIT } from "./errors.js";
3
+ export function help(topic) {
4
+ if (topic) {
5
+ const matches = COMMANDS.filter((c) => c.name === topic || c.name.startsWith(`${topic} `));
6
+ if (matches.length)
7
+ return matches.map((c) => `${c.usage}\n ${c.summary}`).join("\n\n");
8
+ }
9
+ const width = Math.max(...COMMANDS.map((c) => c.name.length));
10
+ return [
11
+ "personify — the Personify (personify.gg) command line for people and AI agents.",
12
+ "",
13
+ "Usage: personify <command> [options]",
14
+ "",
15
+ "Commands:",
16
+ ...COMMANDS.map((c) => ` ${c.name.padEnd(width)} ${c.summary}`),
17
+ "",
18
+ "Options on every command:",
19
+ " --json Print the result as JSON (also PERSONIFY_JSON=1).",
20
+ " --api-url <origin> Another Personify origin (also PERSONIFY_API_URL).",
21
+ " --help Show this help, or `personify help <command>`.",
22
+ "",
23
+ "Environment:",
24
+ " PERSONIFY_TOKEN Use an existing MCP access token instead of the stored login.",
25
+ " PERSONIFY_CONFIG_DIR Where credentials.json lives (default ~/.config/personify).",
26
+ "",
27
+ "Exit codes:",
28
+ ` ${EXIT.OK} ok · ${EXIT.ERROR} error · ${EXIT.USAGE} usage · ${EXIT.CONFIRM} confirmation needed (nothing spent) · ${EXIT.AUTH} sign in`,
29
+ ` ${EXIT.NOT_FOUND} not found · ${EXIT.CONFLICT} changed, read again · ${EXIT.PERMISSION} permission · ${EXIT.UNAVAILABLE} unavailable`,
30
+ "",
31
+ "Paid renders only start with `personify render <id> --confirm-paid` on a login made with `--allow-render`.",
32
+ "Docs: https://personify.gg/docs/agents · https://personify.gg/llms.txt",
33
+ ].join("\n");
34
+ }