@clickminded/coauthor-cli 0.0.18 → 0.0.20

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
@@ -134,7 +134,9 @@ Images and social content:
134
134
 
135
135
  ```sh
136
136
  coauthor image list <project-id> --json
137
- coauthor image generate <project-id> --placeholder-id <placeholder-id> --prompt "Image direction" --json
137
+ coauthor image generate <project-id> --placeholder-id <placeholder-id> --json
138
+ coauthor image status <project-id> --json
139
+ coauthor image edit <project-id> --placeholder-id <placeholder-id> --edit-prompt "Make the sky overcast" --json
138
140
  coauthor thread generate <project-id> --writing-model gpt-5.6-terra --json
139
141
  ```
140
142
 
@@ -166,7 +168,7 @@ Then run live actions only when you mean to publish or export:
166
168
  ```sh
167
169
  coauthor publish thread <project-id> --yes --json
168
170
  coauthor export blog <project-id> --yes --slug "post-slug" --json
169
- coauthor export clickminded <project-id> --yes --json
171
+ coauthor export clickminded <project-id> --yes --permalink <permalink> --json
170
172
  coauthor export wordpress <project-id> --yes --slug "post-slug" --json
171
173
  coauthor operation status <operation-key> --json
172
174
  ```
package/dist/commands.js CHANGED
@@ -7,7 +7,7 @@ import { dirname, join, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { AgentHttpError, normalizeBaseUrl } from './client.js';
9
9
  import { clearConfig, loadConfig, saveConfig } from './config.js';
10
- import { getBoolean, getString, parseJsonOption } from './parser.js';
10
+ import { getBoolean, getString, parseJsonOption, readJsonOptionText } from './parser.js';
11
11
  export async function runCommand(input, context) {
12
12
  const [scope, action] = input.command;
13
13
  if (!scope)
@@ -270,7 +270,13 @@ async function runWorkflowCommand(action, input, context) {
270
270
  return { ok: true, data };
271
271
  }
272
272
  if (action === 'resume') {
273
- const target = normalizeWorkflowWaitTarget(getString(input.values, 'target') ?? getString(input.values, 'stage')) ?? 'draft';
273
+ const requestedTarget = getString(input.values, 'target') ?? getString(input.values, 'stage');
274
+ const target = normalizeWorkflowWaitTarget(requestedTarget);
275
+ // An unsupported target used to fall back to 'draft' and run the whole
276
+ // pipeline (research + draft credits) when the caller meant an earlier stage.
277
+ if (!target) {
278
+ throw new Error(`workflow resume supports --target research or draft (got "${requestedTarget}"). To advance to an earlier stage, use \`coauthor workflow run ${projectId} --target <contract|outline|research-plan>\`.`);
279
+ }
274
280
  if (target === 'research' && (getString(input.values, 'planning-model') || getString(input.values, 'writing-model'))) {
275
281
  throw new Error('workflow resume --target research does not support --planning-model or --writing-model.');
276
282
  }
@@ -405,6 +411,12 @@ async function runArtifactCommand(artifact, action, input, client) {
405
411
  const data = await client.request({ path: basePath });
406
412
  return { ok: true, data };
407
413
  }
414
+ if (artifact === 'contract' && action === 'generate') {
415
+ throw new Error('contract generate is not supported. The brief comes from `coauthor project create`; refine it with `coauthor chat <project-id> --stage contract --message "..."` or replace it with `coauthor contract save <project-id> --data @contract.json`.');
416
+ }
417
+ if (action === 'save' && readJsonOptionText(input.values) === undefined) {
418
+ throw new Error(`Usage: coauthor ${artifact} save <projectId> --data '<json>' (or --data @file.json). ${artifactSaveShape(artifact)}`);
419
+ }
408
420
  if (action === 'generate' || action === 'save' || action === 'approve') {
409
421
  const body = action === 'approve'
410
422
  ? await buildArtifactApproveBody(artifact, input, client, basePath)
@@ -416,7 +428,14 @@ async function runArtifactCommand(artifact, action, input, client) {
416
428
  const data = await client.request({ method: 'POST', path, body });
417
429
  return { ok: true, data };
418
430
  }
419
- throw new Error(`Usage: coauthor ${artifact} <show|generate|save|approve> <projectId>`);
431
+ throw new Error(`Usage: coauthor ${artifact} <${artifact === 'contract' ? 'show|save|approve' : 'show|generate|save|approve'}> <projectId>`);
432
+ }
433
+ function artifactSaveShape(artifact) {
434
+ if (artifact === 'contract')
435
+ return 'Send the contract fields, e.g. {"contract":{"topic":"...","target_audience":"..."}}.';
436
+ if (artifact === 'outline')
437
+ return 'Send the complete outline in order, e.g. {"sections":[...]} from `coauthor outline show`; sections you omit are removed.';
438
+ return 'Send the complete plan, e.g. {"research_tasks":[...]} from `coauthor research-plan show`.';
420
439
  }
421
440
  async function runResearchCommand(action, input, context) {
422
441
  const { client } = context;
@@ -459,11 +478,20 @@ async function runDraftCommand(action, input, context) {
459
478
  return { ok: true, data };
460
479
  }
461
480
  if (action === 'save') {
462
- const data = await client.request({ method: 'POST', path: `${basePath}/save`, body: parseJsonOption(input.values) });
481
+ if (readJsonOptionText(input.values) === undefined) {
482
+ throw new Error(`Usage: coauthor draft save <projectId> --data @payload.json. ${DRAFT_SAVE_SHAPE}`);
483
+ }
484
+ const body = parseJsonOption(input.values);
485
+ const content = body.content;
486
+ if (!content || typeof content !== 'object' || Array.isArray(content) || content.type !== 'doc') {
487
+ throw new Error(`draft save content must be a ProseMirror document, not markdown or text. ${DRAFT_SAVE_SHAPE}`);
488
+ }
489
+ const data = await client.request({ method: 'POST', path: `${basePath}/save`, body });
463
490
  return { ok: true, data };
464
491
  }
465
492
  throw new Error('Usage: coauthor draft <generate|status|get|save> <projectId>');
466
493
  }
494
+ const DRAFT_SAVE_SHAPE = 'Payload: {"document_id":"<from draft get>","expected_base_version":<version_number>,"content":{"type":"doc","content":[...]}}, where content is the edited `data.content` from `coauthor draft get <project-id> --format json --json`.';
467
495
  async function runResourceCommand(resource, action, input, client) {
468
496
  const projectId = getString(input.values, 'project') ?? input.positionals[0];
469
497
  const resourceId = getString(input.values, 'id') ?? input.positionals[1];
@@ -515,6 +543,31 @@ async function runResourceCommand(resource, action, input, client) {
515
543
  const data = await client.request({ method: 'POST', path: `${basePath}/${action}`, body });
516
544
  return { ok: true, data };
517
545
  }
546
+ if (resource === 'images' && action === 'metadata') {
547
+ if (!projectId)
548
+ throw new Error('Missing project id for image metadata');
549
+ if (!resourceId) {
550
+ throw new Error('Usage: coauthor image metadata <projectId> <placeholderId> [--alt-text <text>] [--description <text>] [--file-slug <slug>]');
551
+ }
552
+ // Server keys (alt_text/description/file_slug) are snake_case, unlike
553
+ // the camelCase withNamedOptions produces, so they are set directly.
554
+ const body = parseJsonOption(input.values);
555
+ const altText = getString(input.values, 'alt-text');
556
+ if (altText !== undefined)
557
+ body.alt_text = altText;
558
+ const description = getString(input.values, 'description');
559
+ if (description !== undefined)
560
+ body.description = description;
561
+ const fileSlug = getString(input.values, 'file-slug');
562
+ if (fileSlug !== undefined)
563
+ body.file_slug = fileSlug;
564
+ const data = await client.request({
565
+ method: 'POST',
566
+ path: `${basePath}/${encodeURIComponent(resourceId)}/metadata`,
567
+ body,
568
+ });
569
+ return { ok: true, data };
570
+ }
518
571
  if (['create', 'generate', 'save', 'edit', 'publish', 'export', 'cancel', 'retry'].includes(action)) {
519
572
  if (!projectId)
520
573
  throw new Error(`Missing project id for ${resourceCommandName(resource)} ${action}`);
@@ -784,9 +837,11 @@ async function waitForResearch(client, projectId, initialData, baseUrl) {
784
837
  const deadline = Date.now() + waitTimeoutMs(20 * 60_000);
785
838
  const pollMs = waitPollMs();
786
839
  let latest = initialData;
840
+ let liveness = null;
787
841
  while (Date.now() < deadline) {
788
842
  await sleep(pollMs);
789
843
  latest = await client.request({ path: `projects/${encodeURIComponent(projectId)}/research/status` });
844
+ liveness = observeResearchLiveness(liveness, latest);
790
845
  const status = extractNestedString(latest, ['run', 'status']);
791
846
  if (status === 'succeeded')
792
847
  return { ok: true, message: 'Research completed', data: latest };
@@ -798,7 +853,7 @@ async function waitForResearch(client, projectId, initialData, baseUrl) {
798
853
  if (status === 'paused_credits_exhausted') {
799
854
  return creditsExhaustedPauseResult(projectId, 'research', extractNestedString(latest, ['run', 'error_message']) ?? 'Research paused until included credits reset.', latest);
800
855
  }
801
- const stale = researchRunningStaleResult(projectId, latest, null, initialData);
856
+ const stale = researchRunningStaleResult(projectId, latest, null, initialData, liveness);
802
857
  if (stale)
803
858
  return stale;
804
859
  }
@@ -832,6 +887,7 @@ async function waitForWorkflowDraft(client, projectId, initialData, baseUrl, mod
832
887
  let latestResearch = null;
833
888
  let draftGenerate = null;
834
889
  let attemptedDraftStart = false;
890
+ let liveness = null;
835
891
  while (Date.now() < deadline) {
836
892
  await sleep(pollMs);
837
893
  latestDraft = await client.request({ path: `projects/${encodeURIComponent(projectId)}/draft/status` });
@@ -866,6 +922,7 @@ async function waitForWorkflowDraft(client, projectId, initialData, baseUrl, mod
866
922
  });
867
923
  }
868
924
  latestResearch = await client.request({ path: `projects/${encodeURIComponent(projectId)}/research/status` });
925
+ liveness = observeResearchLiveness(liveness, latestResearch);
869
926
  const researchStatus = extractNestedString(latestResearch, ['run', 'status']);
870
927
  if (researchStatus === 'failed') {
871
928
  throw new Error(extractNestedString(latestResearch, ['run', 'error_message']) ?? 'Research failed');
@@ -884,11 +941,14 @@ async function waitForWorkflowDraft(client, projectId, initialData, baseUrl, mod
884
941
  draft_status: latestDraft,
885
942
  });
886
943
  }
887
- const stale = researchRunningStaleResult(projectId, latestResearch, latestDraft, initialData);
944
+ const stale = researchRunningStaleResult(projectId, latestResearch, latestDraft, initialData, liveness);
888
945
  if (stale)
889
946
  return stale;
947
+ // Only start the draft once the project reaches research_structured. The
948
+ // research run is marked succeeded before structuring finishes, and a draft
949
+ // request in that window is rejected with state "research_complete".
890
950
  if (!attemptedDraftStart
891
- && (researchStatus === 'succeeded' || isResearchReadyForDraft(draftState))
951
+ && isResearchReadyForDraft(draftState)
892
952
  && draftPhase !== 'queued'
893
953
  && draftPhase !== 'running') {
894
954
  attemptedDraftStart = true;
@@ -915,9 +975,30 @@ function waitTimeoutMs(defaultMs) {
915
975
  const raw = Number(process.env.COAUTHOR_CLI_WAIT_TIMEOUT_MS);
916
976
  return Number.isFinite(raw) && raw > 0 ? raw : defaultMs;
917
977
  }
978
+ // While waiting, research is stale only when its progress (sections done, run
979
+ // status, project state) stops changing for this long. A long deep-research
980
+ // section can legitimately run for well over ten minutes.
918
981
  function researchStaleMs() {
919
982
  const raw = Number(process.env.COAUTHOR_CLI_RESEARCH_STALE_MS);
920
- return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60_000;
983
+ return Number.isFinite(raw) && raw > 0 ? raw : 30 * 60_000;
984
+ }
985
+ // A one-off `research status` has no progress history, so it can only judge by
986
+ // the run's age.
987
+ function researchStatusStaleMs() {
988
+ const raw = Number(process.env.COAUTHOR_CLI_RESEARCH_STALE_MS);
989
+ return Number.isFinite(raw) && raw > 0 ? raw : 60 * 60_000;
990
+ }
991
+ function observeResearchLiveness(previous, data) {
992
+ const signature = JSON.stringify([
993
+ extractNestedString(data, ['run', 'id']) ?? null,
994
+ extractNestedString(data, ['run', 'status']) ?? null,
995
+ getResponseString(data, 'project_state') ?? null,
996
+ extractNestedValue(data, ['run', 'progress', 'completed_sections']) ?? null,
997
+ extractNestedValue(data, ['run', 'progress', 'in_progress_section_ids']) ?? null,
998
+ ]);
999
+ if (previous && previous.signature === signature)
1000
+ return previous;
1001
+ return { signature, changedAt: Date.now() };
921
1002
  }
922
1003
  function researchRunAgeMs(data) {
923
1004
  const timestamp = extractNestedString(data, ['run', 'updated_at'])
@@ -929,22 +1010,24 @@ function researchRunAgeMs(data) {
929
1010
  return null;
930
1011
  return Date.now() - time;
931
1012
  }
932
- function isResearchRunningStale(data) {
1013
+ function isResearchRunningStale(data, liveness = null) {
933
1014
  if (extractNestedString(data, ['run', 'status']) !== 'running')
934
1015
  return false;
935
1016
  if (getResponseString(data, 'project_state') !== 'research_running')
936
1017
  return false;
1018
+ if (liveness)
1019
+ return Date.now() - liveness.changedAt >= researchStaleMs();
937
1020
  const ageMs = researchRunAgeMs(data);
938
- return typeof ageMs === 'number' && ageMs >= researchStaleMs();
1021
+ return typeof ageMs === 'number' && ageMs >= researchStatusStaleMs();
939
1022
  }
940
- function researchRunningStaleResult(projectId, researchStatus, draftStatus, workflow) {
941
- if (!isResearchRunningStale(researchStatus))
1023
+ function researchRunningStaleResult(projectId, researchStatus, draftStatus, workflow, liveness) {
1024
+ if (!isResearchRunningStale(researchStatus, liveness))
942
1025
  return null;
943
1026
  return {
944
1027
  ok: false,
945
1028
  status: 'research_running_stale',
946
1029
  exitCode: 2,
947
- message: 'Research is still marked running and has not reported a terminal state within the expected window.',
1030
+ message: `Research is still marked running and its progress has not changed for ${Math.round(researchStaleMs() / 60_000)} minutes.`,
948
1031
  data: {
949
1032
  workflow,
950
1033
  research_status: enrichResearchStatus(researchStatus),
@@ -1031,7 +1114,7 @@ function enrichResearchStatus(data) {
1031
1114
  ...data,
1032
1115
  diagnostic: {
1033
1116
  code: 'research_running_stale',
1034
- message: 'Research is still marked running and has not reported a terminal state within the expected window. Inspect structured output before deciding whether to rewind.',
1117
+ message: `Research has been running for over ${Math.round(researchStatusStaleMs() / 60_000)} minutes. Check status again a few minutes apart; rewind only if run.progress has stopped changing, because rewinding discards the research already done.`,
1035
1118
  next_commands: [
1036
1119
  'coauthor research status <project-id> --json',
1037
1120
  'coauthor research structured <project-id> --json',
@@ -1155,7 +1238,7 @@ function isAlreadyStartedOrComplete(error) {
1155
1238
  if (!(error instanceof AgentHttpError))
1156
1239
  return false;
1157
1240
  const message = extractErrorMessage(error);
1158
- return /already|state "draft_generated"|state "editing"|state "draft_running"|draft.*running/i.test(message);
1241
+ return /already|state "draft_generated"|state "editing"/i.test(message);
1159
1242
  }
1160
1243
  function extractErrorMessage(error) {
1161
1244
  const body = error.responseBody;
@@ -1189,6 +1272,9 @@ export function helpResult(command = []) {
1189
1272
  message: scoped ?? [
1190
1273
  'Usage: coauthor <command> [options]',
1191
1274
  '',
1275
+ 'Global options: --json, --help, --version, --base-url <url>, --token <token>',
1276
+ 'JSON options (--data, --contract) also accept @file.json, or @- to read stdin.',
1277
+ '',
1192
1278
  'Commands:',
1193
1279
  ' auth login|status|logout (logout supports --local-only)',
1194
1280
  ' project create|list|show',
@@ -1202,11 +1288,11 @@ export function helpResult(command = []) {
1202
1288
  ' draft get supports --format json|markdown|html|text',
1203
1289
  ' workflow show|status|advance|run|rewind|approve|resume',
1204
1290
  ' workflow run/advance supports --briefing-mode auto|strict|off and --require-brief-review',
1205
- ' image list|status|show|generate|edit',
1291
+ ' image list|status|show|generate|edit|metadata',
1206
1292
  ' thread list|show|create|generate|save',
1207
1293
  ' slideshow show|save',
1208
1294
  ' publish thread',
1209
- ' export blog|clickminded|wordpress',
1295
+ ' export list|blog|clickminded|wordpress',
1210
1296
  ' operation list|show|status',
1211
1297
  ' credits',
1212
1298
  ' share <project-id>',
@@ -1262,14 +1348,31 @@ function commandHelp(command) {
1262
1348
  'Retrieves a saved generated draft. Chat responses are available through coauthor chat show.',
1263
1349
  ].join('\n'),
1264
1350
  'draft save': [
1265
- 'Usage: coauthor draft save <project-id> --data \'<json>\' [--json]',
1351
+ 'Usage: coauthor draft save <project-id> --data @payload.json [--json]',
1266
1352
  '',
1267
- 'Saves a draft document payload through the agent API.',
1353
+ 'Replaces the draft with an edited ProseMirror document. Markdown is not accepted.',
1354
+ DRAFT_SAVE_SHAPE,
1268
1355
  ].join('\n'),
1269
1356
  'image generate': [
1270
- 'Usage: coauthor image generate <project-id> --placeholder-id <placeholder-id> [--prompt "..."] [--json]',
1357
+ 'Usage: coauthor image generate <project-id> --placeholder-id <id> [--grounding-mode <mode>] [--image-generation-model <id>] [--json]',
1358
+ '',
1359
+ 'Pass the placeholder `id` from coauthor image list. Draft generation creates placeholders.',
1360
+ 'Generation is asynchronous: poll coauthor image status <project-id> --json until it is done.',
1361
+ ].join('\n'),
1362
+ 'image edit': [
1363
+ 'Usage: coauthor image edit <project-id> --placeholder-id <id> --edit-prompt "..." [--json]',
1364
+ '',
1365
+ 'Edits the current image for a placeholder. Poll coauthor image status <project-id> --json for the result.',
1366
+ ].join('\n'),
1367
+ 'contract save': [
1368
+ 'Usage: coauthor contract save <project-id> --data @contract.json [--json]',
1369
+ '',
1370
+ 'Send the contract fields, e.g. {"contract":{"topic":"...","target_audience":"..."}}.',
1371
+ ].join('\n'),
1372
+ 'outline save': [
1373
+ 'Usage: coauthor outline save <project-id> --data @outline.json [--json]',
1271
1374
  '',
1272
- 'Image generation requires an image placeholder from coauthor image list. Draft generation creates placeholders.',
1375
+ 'Send the complete outline in order as {"sections":[...]}. Sections you omit are removed.',
1273
1376
  ].join('\n'),
1274
1377
  'thread generate': [
1275
1378
  'Usage: coauthor thread generate <project-id> [--writing-model <id>] [--json]',
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { realpathSync } from 'node:fs';
2
+ import { readFileSync, realpathSync } from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { AgentHttpError, AgentClient, normalizeBaseUrl } from './client.js';
5
5
  import { DEFAULT_BASE_URL, resolveRuntimeConfig } from './config.js';
@@ -10,6 +10,10 @@ export async function main(argv = process.argv.slice(2)) {
10
10
  let resolvedBaseUrl = resolveBaseUrlFromArgv(argv);
11
11
  try {
12
12
  const parsed = parseCliArgs(argv);
13
+ if (parsed.globals.version || (parsed.command.length === 1 && parsed.command[0] === 'version')) {
14
+ process.stdout.write(parsed.globals.json ? `${JSON.stringify({ ok: true, version: cliVersion() })}\n` : `${cliVersion()}\n`);
15
+ return 0;
16
+ }
13
17
  if (parsed.globals.help) {
14
18
  process.stdout.write(renderResult(helpResult(parsed.command), parsed.globals.json));
15
19
  return 0;
@@ -43,7 +47,10 @@ function formatCliError(error, baseUrl, argv = []) {
43
47
  const requiresKey = formatRequiresKeyResult(error.responseBody, baseUrl);
44
48
  if (requiresKey)
45
49
  return { error: new Error(requiresKey.message), result: requiresKey, exitCode: 2 };
46
- const message = extractErrorMessage(error.responseBody) ?? error.message;
50
+ const serverMessage = extractErrorMessage(error.responseBody) ?? error.message;
51
+ const message = error.status === 401
52
+ ? `${serverMessage}\nSign in with \`coauthor auth login\` (or set COAUTHOR_TOKEN).`
53
+ : serverMessage;
47
54
  const researchBlock = formatResearchDraftBlock(message, argv);
48
55
  if (researchBlock)
49
56
  return { error: new Error(researchBlock.message), result: researchBlock, exitCode: 2 };
@@ -211,6 +218,15 @@ function extractEnvelopeError(body) {
211
218
  details: error.details,
212
219
  };
213
220
  }
221
+ function cliVersion() {
222
+ try {
223
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
224
+ return typeof pkg.version === 'string' ? pkg.version : 'unknown';
225
+ }
226
+ catch {
227
+ return 'unknown';
228
+ }
229
+ }
214
230
  function resolveBaseUrlFromArgv(argv) {
215
231
  const index = argv.indexOf('--base-url');
216
232
  const value = index >= 0 ? argv[index + 1] : undefined;
package/dist/parser.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { JsonValue } from './client.js';
3
3
  export type GlobalOptions = {
4
4
  json: boolean;
5
5
  help: boolean;
6
+ version: boolean;
6
7
  baseUrl?: string;
7
8
  token?: string;
8
9
  };
@@ -18,6 +19,7 @@ export declare const commandInputSchema: z.ZodObject<{
18
19
  globals: z.ZodObject<{
19
20
  json: z.ZodBoolean;
20
21
  help: z.ZodBoolean;
22
+ version: z.ZodBoolean;
21
23
  baseUrl: z.ZodOptional<z.ZodString>;
22
24
  token: z.ZodOptional<z.ZodString>;
23
25
  }, z.core.$strip>;
@@ -27,4 +29,5 @@ export declare function parseCliArgs(argv: string[]): ParsedCommand;
27
29
  export declare function getString(values: ParsedCommand['values'], name: string): string | undefined;
28
30
  export declare function requireString(values: ParsedCommand['values'], name: string): string;
29
31
  export declare function getBoolean(values: ParsedCommand['values'], name: string): boolean;
32
+ export declare function readJsonOptionText(values: ParsedCommand['values'], name?: string): string | undefined;
30
33
  export declare function parseJsonOption(values: ParsedCommand['values'], name?: string): Record<string, JsonValue>;
package/dist/parser.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { parseArgs } from 'node:util';
2
3
  import { z } from 'zod';
3
4
  export const commandInputSchema = z.object({
@@ -6,61 +7,72 @@ export const commandInputSchema = z.object({
6
7
  globals: z.object({
7
8
  json: z.boolean(),
8
9
  help: z.boolean(),
10
+ version: z.boolean(),
9
11
  baseUrl: z.string().url().optional(),
10
12
  token: z.string().min(1).optional(),
11
13
  }),
12
14
  values: z.record(z.string(), z.union([z.string(), z.boolean(), z.array(z.string())]).optional()),
13
15
  });
16
+ // Every flag any command reads must be declared here. Parsing is strict: an
17
+ // undeclared flag used to parse as `true` and push its value into the
18
+ // positionals, silently dropping it (and sometimes misreading it as an id).
19
+ const OPTIONS = {
20
+ json: { type: 'boolean', default: false },
21
+ help: { type: 'boolean', short: 'h', default: false },
22
+ version: { type: 'boolean', short: 'v', default: false },
23
+ 'base-url': { type: 'string' },
24
+ token: { type: 'string' },
25
+ 'with-publish': { type: 'boolean', default: false },
26
+ 'no-browser': { type: 'boolean', default: false },
27
+ 'local-only': { type: 'boolean', default: false },
28
+ yes: { type: 'boolean', default: false },
29
+ wait: { type: 'boolean', default: false },
30
+ force: { type: 'boolean', default: false },
31
+ 'dry-run': { type: 'boolean', default: false },
32
+ data: { type: 'string' },
33
+ cwd: { type: 'string' },
34
+ title: { type: 'string' },
35
+ topic: { type: 'string' },
36
+ audience: { type: 'string' },
37
+ contract: { type: 'string' },
38
+ project: { type: 'string' },
39
+ id: { type: 'string' },
40
+ 'placeholder-id': { type: 'string' },
41
+ message: { type: 'string' },
42
+ stage: { type: 'string' },
43
+ target: { type: 'string' },
44
+ reason: { type: 'string' },
45
+ 'briefing-mode': { type: 'string' },
46
+ 'require-brief-review': { type: 'boolean', default: false },
47
+ 'max-brief-questions': { type: 'string' },
48
+ prompt: { type: 'string' },
49
+ format: { type: 'string' },
50
+ thread: { type: 'string' },
51
+ image: { type: 'string' },
52
+ slug: { type: 'string' },
53
+ permalink: { type: 'string' },
54
+ 'connection-id': { type: 'string' },
55
+ status: { type: 'string' },
56
+ limit: { type: 'string' },
57
+ cursor: { type: 'string' },
58
+ 'execution-token': { type: 'string' },
59
+ 'planning-model': { type: 'string' },
60
+ 'writing-model': { type: 'string' },
61
+ 'alt-text': { type: 'string' },
62
+ description: { type: 'string' },
63
+ 'file-slug': { type: 'string' },
64
+ 'edit-prompt': { type: 'string' },
65
+ 'grounding-mode': { type: 'string' },
66
+ 'image-generation-model': { type: 'string' },
67
+ };
14
68
  export function parseCliArgs(argv) {
15
- const parsed = parseArgs({
16
- args: argv,
17
- allowPositionals: true,
18
- strict: false,
19
- options: {
20
- json: { type: 'boolean', default: false },
21
- help: { type: 'boolean', short: 'h', default: false },
22
- 'base-url': { type: 'string' },
23
- token: { type: 'string' },
24
- email: { type: 'string' },
25
- password: { type: 'string' },
26
- 'with-publish': { type: 'boolean', default: false },
27
- 'no-browser': { type: 'boolean', default: false },
28
- 'local-only': { type: 'boolean', default: false },
29
- yes: { type: 'boolean', default: false },
30
- wait: { type: 'boolean', default: false },
31
- force: { type: 'boolean', default: false },
32
- 'dry-run': { type: 'boolean', default: false },
33
- data: { type: 'string' },
34
- cwd: { type: 'string' },
35
- title: { type: 'string' },
36
- topic: { type: 'string' },
37
- audience: { type: 'string' },
38
- contract: { type: 'string' },
39
- project: { type: 'string' },
40
- id: { type: 'string' },
41
- 'placeholder-id': { type: 'string' },
42
- message: { type: 'string' },
43
- stage: { type: 'string' },
44
- target: { type: 'string' },
45
- reason: { type: 'string' },
46
- 'briefing-mode': { type: 'string' },
47
- 'require-brief-review': { type: 'boolean', default: false },
48
- 'max-brief-questions': { type: 'string' },
49
- prompt: { type: 'string' },
50
- format: { type: 'string' },
51
- thread: { type: 'string' },
52
- image: { type: 'string' },
53
- slug: { type: 'string' },
54
- permalink: { type: 'string' },
55
- 'connection-id': { type: 'string' },
56
- status: { type: 'string' },
57
- limit: { type: 'string' },
58
- cursor: { type: 'string' },
59
- 'execution-token': { type: 'string' },
60
- 'planning-model': { type: 'string' },
61
- 'writing-model': { type: 'string' },
62
- },
63
- });
69
+ let parsed;
70
+ try {
71
+ parsed = parseArgs({ args: argv, allowPositionals: true, strict: true, options: OPTIONS });
72
+ }
73
+ catch (error) {
74
+ throw new Error(formatParseError(error, argv));
75
+ }
64
76
  const positionals = parsed.positionals;
65
77
  const command = positionals.slice(0, commandLength(positionals));
66
78
  return commandInputSchema.parse({
@@ -69,6 +81,7 @@ export function parseCliArgs(argv) {
69
81
  globals: {
70
82
  json: Boolean(parsed.values.json),
71
83
  help: Boolean(parsed.values.help),
84
+ version: Boolean(parsed.values.version),
72
85
  baseUrl: stringValue(parsed.values['base-url']),
73
86
  token: stringValue(parsed.values.token),
74
87
  },
@@ -87,11 +100,28 @@ export function requireString(values, name) {
87
100
  export function getBoolean(values, name) {
88
101
  return values[name] === true;
89
102
  }
90
- export function parseJsonOption(values, name = 'data') {
103
+ // `--data @payload.json` reads a file and `--data @-` reads stdin, so large
104
+ // payloads (draft documents, contracts) never go through shell quoting.
105
+ export function readJsonOptionText(values, name = 'data') {
91
106
  const raw = getString(values, name);
107
+ if (raw === undefined || !raw.startsWith('@'))
108
+ return raw;
109
+ const source = raw.slice(1);
110
+ if (!source)
111
+ throw new Error(`--${name} @<file> needs a file path (or @- for stdin)`);
112
+ return readFileSync(source === '-' ? 0 : source, 'utf8');
113
+ }
114
+ export function parseJsonOption(values, name = 'data') {
115
+ const raw = readJsonOptionText(values, name);
92
116
  if (!raw)
93
117
  return {};
94
- const parsed = JSON.parse(raw);
118
+ let parsed;
119
+ try {
120
+ parsed = JSON.parse(raw);
121
+ }
122
+ catch (error) {
123
+ throw new Error(`--${name} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
124
+ }
95
125
  return z.record(z.string(), z.unknown()).transform((value) => value).parse(parsed);
96
126
  }
97
127
  function commandLength(positionals) {
@@ -121,6 +151,17 @@ function commandLength(positionals) {
121
151
  return second ? 2 : 1;
122
152
  return 1;
123
153
  }
154
+ function formatParseError(error, argv) {
155
+ const message = error instanceof Error ? error.message : String(error);
156
+ const code = error?.code;
157
+ const command = argv.filter((arg) => !arg.startsWith('-')).slice(0, 2).join(' ');
158
+ const help = command ? `coauthor ${command} --help` : 'coauthor --help';
159
+ if (code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
160
+ const option = /'(--?[^']+)'/.exec(message)?.[1] ?? 'option';
161
+ return `Unknown option ${option}. Run \`${help}\` for supported options.`;
162
+ }
163
+ return `${message.split('\n')[0]} Run \`${help}\` for usage.`;
164
+ }
124
165
  function stringValue(value) {
125
166
  if (typeof value === 'string')
126
167
  return value;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clickminded/coauthor-cli",
3
- "version": "0.0.18",
3
+ "version": "0.0.20",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "coauthor": "dist/index.js",
@@ -32,6 +32,16 @@ This skill guides agent use of the CoAuthor CLI.
32
32
  - After a timeout, interruption, network error, or unclear result, check operation status before retrying.
33
33
  - `contract approve`, `outline approve`, and `research-plan approve` approve the saved artifact when `--data` is omitted. Pass `--data` only when intentionally approving a replacement payload.
34
34
 
35
+ ## Draft-Stage Mutation Guard
36
+
37
+ CoAuthor artifacts form a dependency chain: contract/brief -> outline -> research plan -> research -> draft. Saving or approving an upstream artifact after a draft exists can deliberately rewind the project and mark every downstream artifact stale, even though the saved draft version still exists.
38
+
39
+ - Before any `contract save|approve`, `outline save|generate|approve`, or `research-plan save|generate|approve` on an existing project, inspect `coauthor workflow status <project-id> --json`. Also inspect `coauthor draft status <project-id> --json` when the project may already have reached drafting.
40
+ - Treat `draft_generated` and `editing` as an upstream-artifact lock. While in either state, make requested prose or document changes with `coauthor draft save`; do not mirror draft changes back into the contract, outline, or research plan as a cleanup, bookkeeping, or finalization step.
41
+ - Do not run an upstream `save`, `generate`, or `approve` command after `draft save` merely to record constraints discovered during editing. That command order can hide the draft in the web app by rewinding the project to an earlier stage.
42
+ - Change an upstream artifact after drafting only when the user explicitly asks to revise the premise, structure, or research inputs and understands that CoAuthor must regenerate the downstream chain. Before the change, preserve the current document with `coauthor draft get <project-id> --format json --json`. Then complete the regeneration with `coauthor workflow run <project-id> --target draft --wait --json`; do not leave the project at an intermediate stale checkpoint.
43
+ - After ordinary draft editing, finish with read-only verification such as `coauthor draft get`, `coauthor draft status`, or `coauthor workflow status`.
44
+
35
45
  ## Plans, Models, And Credits
36
46
 
37
47
  - Starter includes 2,500 credits per monthly subscription-anniversary period. It supports the full user-visible model list, but it cannot store or use customer provider keys. When its credits reach zero, work pauses until the next reset.
@@ -32,6 +32,16 @@ This skill guides agent use of the CoAuthor CLI.
32
32
  - After a timeout, interruption, network error, or unclear result, check operation status before retrying.
33
33
  - `contract approve`, `outline approve`, and `research-plan approve` approve the saved artifact when `--data` is omitted. Pass `--data` only when intentionally approving a replacement payload.
34
34
 
35
+ ## Draft-Stage Mutation Guard
36
+
37
+ CoAuthor artifacts form a dependency chain: contract/brief -> outline -> research plan -> research -> draft. Saving or approving an upstream artifact after a draft exists can deliberately rewind the project and mark every downstream artifact stale, even though the saved draft version still exists.
38
+
39
+ - Before any `contract save|approve`, `outline save|generate|approve`, or `research-plan save|generate|approve` on an existing project, inspect `coauthor workflow status <project-id> --json`. Also inspect `coauthor draft status <project-id> --json` when the project may already have reached drafting.
40
+ - Treat `draft_generated` and `editing` as an upstream-artifact lock. While in either state, make requested prose or document changes with `coauthor draft save`; do not mirror draft changes back into the contract, outline, or research plan as a cleanup, bookkeeping, or finalization step.
41
+ - Do not run an upstream `save`, `generate`, or `approve` command after `draft save` merely to record constraints discovered during editing. That command order can hide the draft in the web app by rewinding the project to an earlier stage.
42
+ - Change an upstream artifact after drafting only when the user explicitly asks to revise the premise, structure, or research inputs and understands that CoAuthor must regenerate the downstream chain. Before the change, preserve the current document with `coauthor draft get <project-id> --format json --json`. Then complete the regeneration with `coauthor workflow run <project-id> --target draft --wait --json`; do not leave the project at an intermediate stale checkpoint.
43
+ - After ordinary draft editing, finish with read-only verification such as `coauthor draft get`, `coauthor draft status`, or `coauthor workflow status`.
44
+
35
45
  ## Plans, Models, And Credits
36
46
 
37
47
  - Starter includes 2,500 credits per monthly subscription-anniversary period. It supports the full user-visible model list, but it cannot store or use customer provider keys. When its credits reach zero, work pauses until the next reset.
@@ -32,6 +32,16 @@ This skill guides agent use of the CoAuthor CLI.
32
32
  - After a timeout, interruption, network error, or unclear result, check operation status before retrying.
33
33
  - `contract approve`, `outline approve`, and `research-plan approve` approve the saved artifact when `--data` is omitted. Pass `--data` only when intentionally approving a replacement payload.
34
34
 
35
+ ## Draft-Stage Mutation Guard
36
+
37
+ CoAuthor artifacts form a dependency chain: contract/brief -> outline -> research plan -> research -> draft. Saving or approving an upstream artifact after a draft exists can deliberately rewind the project and mark every downstream artifact stale, even though the saved draft version still exists.
38
+
39
+ - Before any `contract save|approve`, `outline save|generate|approve`, or `research-plan save|generate|approve` on an existing project, inspect `coauthor workflow status <project-id> --json`. Also inspect `coauthor draft status <project-id> --json` when the project may already have reached drafting.
40
+ - Treat `draft_generated` and `editing` as an upstream-artifact lock. While in either state, make requested prose or document changes with `coauthor draft save`; do not mirror draft changes back into the contract, outline, or research plan as a cleanup, bookkeeping, or finalization step.
41
+ - Do not run an upstream `save`, `generate`, or `approve` command after `draft save` merely to record constraints discovered during editing. That command order can hide the draft in the web app by rewinding the project to an earlier stage.
42
+ - Change an upstream artifact after drafting only when the user explicitly asks to revise the premise, structure, or research inputs and understands that CoAuthor must regenerate the downstream chain. Before the change, preserve the current document with `coauthor draft get <project-id> --format json --json`. Then complete the regeneration with `coauthor workflow run <project-id> --target draft --wait --json`; do not leave the project at an intermediate stale checkpoint.
43
+ - After ordinary draft editing, finish with read-only verification such as `coauthor draft get`, `coauthor draft status`, or `coauthor workflow status`.
44
+
35
45
  ## Plans, Models, And Credits
36
46
 
37
47
  - Starter includes 2,500 credits per monthly subscription-anniversary period. It supports the full user-visible model list, but it cannot store or use customer provider keys. When its credits reach zero, work pauses until the next reset.
@@ -35,6 +35,17 @@ alwaysApply: true
35
35
  - The Supabase `admins` table is the canonical admin source and grants the cross-surface access/quota bypass.
36
36
  - After timeout, interruption, network error, or ambiguous output, check operation status before retrying or reporting success.
37
37
  - `contract approve`, `outline approve`, and `research-plan approve` approve the saved artifact when `--data` is omitted. Pass `--data` only when intentionally approving a replacement payload.
38
+
39
+ ## Draft-Stage Mutation Guard
40
+
41
+ CoAuthor artifacts form a dependency chain: contract/brief -> outline -> research plan -> research -> draft. Saving or approving an upstream artifact after a draft exists can deliberately rewind the project and mark every downstream artifact stale, even though the saved draft version still exists.
42
+
43
+ - Before any `contract save|approve`, `outline save|generate|approve`, or `research-plan save|generate|approve` on an existing project, inspect `coauthor workflow status <project-id> --json`. Also inspect `coauthor draft status <project-id> --json` when the project may already have reached drafting.
44
+ - Treat `draft_generated` and `editing` as an upstream-artifact lock. While in either state, make requested prose or document changes with `coauthor draft save`; do not mirror draft changes back into the contract, outline, or research plan as a cleanup, bookkeeping, or finalization step.
45
+ - Do not run an upstream `save`, `generate`, or `approve` command after `draft save` merely to record constraints discovered during editing. That command order can hide the draft in the web app by rewinding the project to an earlier stage.
46
+ - Change an upstream artifact after drafting only when the user explicitly asks to revise the premise, structure, or research inputs and understands that CoAuthor must regenerate the downstream chain. Before the change, preserve the current document with `coauthor draft get <project-id> --format json --json`. Then complete the regeneration with `coauthor workflow run <project-id> --target draft --wait --json`; do not leave the project at an intermediate stale checkpoint.
47
+ - After ordinary draft editing, finish with read-only verification such as `coauthor draft get`, `coauthor draft status`, or `coauthor workflow status`.
48
+
38
49
  - For simple starts, use `coauthor project create --title "..." --topic "prose brief" --audience "target reader" --json`.
39
50
  - When you know the editorial contract fields, prefer `coauthor project create --contract '<json>' --json` instead of cramming structured data into `--topic`.
40
51
  - Keep `--topic` as a plain prose brief. Do not pass JSON through `--topic`.