@clickminded/coauthor-cli 0.0.20 → 0.0.21

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/dist/commands.js CHANGED
@@ -477,6 +477,10 @@ async function runDraftCommand(action, input, context) {
477
477
  const data = await client.request({ path: format ? `${basePath}/get?format=${encodeURIComponent(format)}` : `${basePath}/get` });
478
478
  return { ok: true, data };
479
479
  }
480
+ if (action === 'revise')
481
+ return runDraftReviseCommand(projectId, input, context);
482
+ if (action === 'revision')
483
+ return runDraftRevisionCommand(input.command[2], projectId, input, context);
480
484
  if (action === 'save') {
481
485
  if (readJsonOptionText(input.values) === undefined) {
482
486
  throw new Error(`Usage: coauthor draft save <projectId> --data @payload.json. ${DRAFT_SAVE_SHAPE}`);
@@ -486,12 +490,95 @@ async function runDraftCommand(action, input, context) {
486
490
  if (!content || typeof content !== 'object' || Array.isArray(content) || content.type !== 'doc') {
487
491
  throw new Error(`draft save content must be a ProseMirror document, not markdown or text. ${DRAFT_SAVE_SHAPE}`);
488
492
  }
493
+ const baseVersion = body.expected_base_version ?? body.expectedBaseVersion ?? body.expected_version ?? body.expectedVersion;
494
+ if (typeof baseVersion !== 'number') {
495
+ throw new Error(`draft save needs expected_base_version: the version_number you edited. ${DRAFT_SAVE_SHAPE}`);
496
+ }
497
+ if (getBoolean(input.values, 'force'))
498
+ body.allow_recent_user_edit = true;
489
499
  const data = await client.request({ method: 'POST', path: `${basePath}/save`, body });
490
500
  return { ok: true, data };
491
501
  }
492
- throw new Error('Usage: coauthor draft <generate|status|get|save> <projectId>');
502
+ throw new Error('Usage: coauthor draft <generate|status|get|save|revise|revision> <projectId>');
503
+ }
504
+ // Revise by instruction: CoAuthor's editor proposes the change, and the
505
+ // calling agent reviews the groups and applies or discards them.
506
+ async function runDraftReviseCommand(projectId, input, context) {
507
+ const instruction = getString(input.values, 'instruction') ?? input.positionals.slice(1).join(' ');
508
+ if (!instruction.trim())
509
+ throw new Error('Usage: coauthor draft revise <projectId> --instruction "..." [--wait] [--apply]');
510
+ const started = await context.client.request({
511
+ method: 'POST',
512
+ path: `projects/${encodeURIComponent(projectId)}/draft/revisions`,
513
+ body: { instruction },
514
+ });
515
+ const revisionId = getResponseString(started, 'revision_id');
516
+ if (!getBoolean(input.values, 'wait') || !revisionId) {
517
+ return { ok: true, message: revisionId ? `Revision ${revisionId} queued. Check it with: coauthor draft revision show ${projectId} ${revisionId}` : undefined, data: started };
518
+ }
519
+ const revision = await waitForRevision(context.client, projectId, revisionId);
520
+ if (!revision) {
521
+ return {
522
+ ok: false,
523
+ status: 'still_running',
524
+ exitCode: 2,
525
+ message: `Revision ${revisionId} is still running. Check again with: coauthor draft revision show ${projectId} ${revisionId} --json`,
526
+ data: started,
527
+ };
528
+ }
529
+ if (getResponseValue(revision, 'awaiting_review') !== true) {
530
+ return { ok: true, message: `Revision ${revisionId} finished as ${getResponseString(revision, 'state') ?? 'unknown'} with no changes to review.`, data: revision };
531
+ }
532
+ if (getBoolean(input.values, 'apply')) {
533
+ const applied = await applyRevision(context.client, projectId, revisionId, input);
534
+ return { ok: true, message: `Applied revision ${revisionId}.`, data: { revision, applied } };
535
+ }
536
+ return {
537
+ ok: true,
538
+ status: 'awaiting_review',
539
+ message: `Revision ${revisionId} is ready to review. Apply with: coauthor draft revision apply ${projectId} ${revisionId} (or --accept/--reject <group ids>), or discard it.`,
540
+ data: revision,
541
+ };
542
+ }
543
+ async function runDraftRevisionCommand(action, projectId, input, context) {
544
+ const revisionId = input.positionals[1];
545
+ if (!action || !revisionId)
546
+ throw new Error('Usage: coauthor draft revision <show|apply|discard> <projectId> <revisionId>');
547
+ const path = `projects/${encodeURIComponent(projectId)}/draft/revisions/${encodeURIComponent(revisionId)}`;
548
+ if (action === 'show')
549
+ return { ok: true, data: await context.client.request({ path }) };
550
+ if (action === 'apply')
551
+ return { ok: true, message: `Applied revision ${revisionId}.`, data: await applyRevision(context.client, projectId, revisionId, input) };
552
+ if (action === 'discard')
553
+ return { ok: true, data: await context.client.request({ method: 'POST', path: `${path}/discard`, body: {} }) };
554
+ throw new Error('Usage: coauthor draft revision <show|apply|discard> <projectId> <revisionId>');
555
+ }
556
+ function applyRevision(client, projectId, revisionId, input) {
557
+ const list = (name) => getString(input.values, name)?.split(',').map((id) => id.trim()).filter(Boolean);
558
+ const accept = list('accept');
559
+ const reject = list('reject');
560
+ if (accept && reject)
561
+ throw new Error('Pass --accept or --reject, not both.');
562
+ return client.request({
563
+ method: 'POST',
564
+ path: `projects/${encodeURIComponent(projectId)}/draft/revisions/${encodeURIComponent(revisionId)}/apply`,
565
+ body: { ...(accept ? { accept } : {}), ...(reject ? { reject } : {}) },
566
+ });
567
+ }
568
+ async function waitForRevision(client, projectId, revisionId) {
569
+ // Stay under the 10-minute foreground limit of agent shells; the caller
570
+ // gets a resumable still_running result instead of being killed.
571
+ const deadline = Date.now() + waitTimeoutMs(9 * 60_000);
572
+ const pollMs = Math.min(waitPollMs(), 2000);
573
+ while (Date.now() < deadline) {
574
+ const revision = await client.request({ path: `projects/${encodeURIComponent(projectId)}/draft/revisions/${encodeURIComponent(revisionId)}` });
575
+ if (getResponseValue(revision, 'running') !== true)
576
+ return revision;
577
+ await sleep(pollMs);
578
+ }
579
+ return null;
493
580
  }
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`.';
581
+ const DRAFT_SAVE_SHAPE = 'Payload: {"document_id":"<from draft get>","expected_base_version":<version_number>,"expected_content_hash":"<content_hash, if draft get returned one>","content":{"type":"doc","content":[...]}}, where content is the edited `data.content` from `coauthor draft get <project-id> --format json --json`.';
495
582
  async function runResourceCommand(resource, action, input, client) {
496
583
  const projectId = getString(input.values, 'project') ?? input.positionals[0];
497
584
  const resourceId = getString(input.values, 'id') ?? input.positionals[1];
@@ -1284,7 +1371,8 @@ export function helpResult(command = []) {
1284
1371
  ' outline show|generate|save|approve',
1285
1372
  ' research-plan show|generate|save|approve',
1286
1373
  ' research run|status|structured',
1287
- ' draft generate|status|get|save',
1374
+ ' draft generate|status|get|save|revise',
1375
+ ' draft revision show|apply|discard',
1288
1376
  ' draft get supports --format json|markdown|html|text',
1289
1377
  ' workflow show|status|advance|run|rewind|approve|resume',
1290
1378
  ' workflow run/advance supports --briefing-mode auto|strict|off and --require-brief-review',
@@ -1348,11 +1436,24 @@ function commandHelp(command) {
1348
1436
  'Retrieves a saved generated draft. Chat responses are available through coauthor chat show.',
1349
1437
  ].join('\n'),
1350
1438
  'draft save': [
1351
- 'Usage: coauthor draft save <project-id> --data @payload.json [--json]',
1439
+ 'Usage: coauthor draft save <project-id> --data @payload.json [--force] [--json]',
1352
1440
  '',
1353
1441
  'Replaces the draft with an edited ProseMirror document. Markdown is not accepted.',
1442
+ 'Fails with 409 if the draft changed since you read it (re-read and reapply), or if the user edited it in the browser in the last 90 seconds (--force overrides).',
1354
1443
  DRAFT_SAVE_SHAPE,
1355
1444
  ].join('\n'),
1445
+ 'draft revise': [
1446
+ 'Usage: coauthor draft revise <project-id> --instruction "..." [--wait] [--apply] [--accept <ids> | --reject <ids>] [--json]',
1447
+ '',
1448
+ "CoAuthor's editor rewrites the draft from your instruction. With --wait the command returns the proposed changes as groups (before/after markdown) for you to review.",
1449
+ 'Then: coauthor draft revision apply <project-id> <revision-id> [--accept g1,g2 | --reject g3], or coauthor draft revision discard <project-id> <revision-id>.',
1450
+ '--apply applies every group as soon as the revision is ready. Only one revision can be open on a draft at a time.',
1451
+ ].join('\n'),
1452
+ 'draft revision': [
1453
+ 'Usage: coauthor draft revision <show|apply|discard> <project-id> <revision-id> [--accept <ids> | --reject <ids>] [--json]',
1454
+ '',
1455
+ 'show: status and the proposed groups. apply: keep every group, or only --accept / all but --reject. discard: drop the revision (cancels it if still running).',
1456
+ ].join('\n'),
1356
1457
  'image generate': [
1357
1458
  'Usage: coauthor image generate <project-id> --placeholder-id <id> [--grounding-mode <mode>] [--image-generation-model <id>] [--json]',
1358
1459
  '',
@@ -1380,5 +1481,5 @@ function commandHelp(command) {
1380
1481
  'Generates a social thread from the saved draft.',
1381
1482
  ].join('\n'),
1382
1483
  };
1383
- return help[key] ?? null;
1484
+ return help[key] ?? help[command.slice(0, 2).join(' ')] ?? null;
1384
1485
  }
package/dist/index.js CHANGED
@@ -54,7 +54,24 @@ function formatCliError(error, baseUrl, argv = []) {
54
54
  const researchBlock = formatResearchDraftBlock(message, argv);
55
55
  if (researchBlock)
56
56
  return { error: new Error(researchBlock.message), result: researchBlock, exitCode: 2 };
57
- return { error: new Error(message), exitCode: 1 };
57
+ // Keep the server's error code and details (e.g. the current draft version
58
+ // on a 409) so agents can recover without guessing.
59
+ const envelope = extractEnvelopeError(error.responseBody);
60
+ const current = currentDraftDetails(envelope?.details);
61
+ const humanMessage = current
62
+ ? `${message}\nCurrent draft: version ${current.version_number ?? 'unknown'}${current.content_hash ? `, content_hash ${current.content_hash}` : ''}. Re-read it with \`${current.reread_command ?? 'coauthor draft get <project-id> --format json --json'}\` and save again.`
63
+ : message;
64
+ return {
65
+ error: new Error(humanMessage),
66
+ result: {
67
+ ok: false,
68
+ error: humanMessage,
69
+ ...(envelope?.code ? { code: envelope.code } : {}),
70
+ http_status: error.status,
71
+ ...(envelope?.details !== undefined ? { details: envelope.details } : {}),
72
+ },
73
+ exitCode: 1,
74
+ };
58
75
  }
59
76
  return { error: error instanceof Error ? error : new Error(String(error)), exitCode: 1 };
60
77
  }
@@ -227,6 +244,14 @@ function cliVersion() {
227
244
  return 'unknown';
228
245
  }
229
246
  }
247
+ function currentDraftDetails(details) {
248
+ if (!details || typeof details !== 'object' || Array.isArray(details))
249
+ return null;
250
+ const current = details.current;
251
+ if (!current || typeof current !== 'object' || Array.isArray(current))
252
+ return null;
253
+ return current;
254
+ }
230
255
  function resolveBaseUrlFromArgv(argv) {
231
256
  const index = argv.indexOf('--base-url');
232
257
  const value = index >= 0 ? argv[index + 1] : undefined;
package/dist/parser.js CHANGED
@@ -64,6 +64,10 @@ const OPTIONS = {
64
64
  'edit-prompt': { type: 'string' },
65
65
  'grounding-mode': { type: 'string' },
66
66
  'image-generation-model': { type: 'string' },
67
+ instruction: { type: 'string' },
68
+ apply: { type: 'boolean', default: false },
69
+ accept: { type: 'string' },
70
+ reject: { type: 'string' },
67
71
  };
68
72
  export function parseCliArgs(argv) {
69
73
  let parsed;
@@ -145,6 +149,8 @@ function commandLength(positionals) {
145
149
  : 1;
146
150
  if (first === 'workflow')
147
151
  return second ? 2 : 1;
152
+ if (first === 'draft' && second === 'revision')
153
+ return positionals[2] && ['show', 'apply', 'discard'].includes(positionals[2]) ? 3 : 2;
148
154
  if (first === 'credits')
149
155
  return 1;
150
156
  if (['contract', 'outline', 'research-plan', 'research', 'draft', 'image', 'thread', 'slideshow', 'publish', 'export', 'operation'].includes(first ?? ''))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clickminded/coauthor-cli",
3
- "version": "0.0.20",
3
+ "version": "0.0.21",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "coauthor": "dist/index.js",
@@ -253,6 +253,14 @@ Use `coauthor chat show <project-id> --json` to retrieve the workspace chat tran
253
253
 
254
254
  When using `coauthor chat <project-id> --stage draft --json`, treat the returned text as a workspace chat response, not a saved draft document. The CLI returns `draft_saved: false` and `transcript_command` when applicable. Use `coauthor draft get <project-id> --format markdown --json` only for a saved generated draft.
255
255
 
256
+ ## Editing a Draft
257
+
258
+ Two ways to change a generated draft. Both work whichever editor the user has opened the draft in.
259
+
260
+ - **Revise by instruction (prose changes):** `coauthor draft revise <project-id> --instruction "Make the intro two sentences" --wait --json`. CoAuthor's own editor rewrites the draft in the project's voice and returns `data.groups`, each with `before_markdown` and `after_markdown`. Review every group against the brief before applying: `coauthor draft revision apply <project-id> <revision-id> --json`, keep only some with `--accept g1,g2` or `--reject g3`, or drop it with `coauthor draft revision discard <project-id> <revision-id> --json`. Only one revision can be open on a draft; an unresolved one blocks the user's browser saves, so always apply or discard it. If `--wait` returns `still_running`, run `coauthor draft revision show <project-id> <revision-id> --json` again. `revise_unavailable` means this account cannot revise by instruction yet; use a direct edit.
261
+ - **Direct edit (exact text you already have):** `coauthor draft get <project-id> --format json --json`, edit nodes inside `data.content` (keep node ids and `imagePlaceholder` nodes), write `{"document_id": ..., "expected_base_version": <data.version_number>, "expected_content_hash": <data.content_hash, if present>, "content": <edited doc>}` to a file, then `coauthor draft save <project-id> --data @payload.json --json`. Never send markdown as `content`.
262
+ - On `stale_draft`, re-read with `draft get` and reapply your edit; never retry the same payload. On `user_recently_editing`, the user is typing in the browser: wait or ask them, and pass `--force` only if they agree.
263
+
256
264
  ## Draft Export
257
265
 
258
266
  Use `coauthor draft get <project-id> --format markdown --json` when the user needs a finished draft in Markdown. Generated images are resolved into Markdown image URLs when available.
@@ -253,6 +253,14 @@ Use `coauthor chat show <project-id> --json` to retrieve the workspace chat tran
253
253
 
254
254
  When using `coauthor chat <project-id> --stage draft --json`, treat the returned text as a workspace chat response, not a saved draft document. The CLI returns `draft_saved: false` and `transcript_command` when applicable. Use `coauthor draft get <project-id> --format markdown --json` only for a saved generated draft.
255
255
 
256
+ ## Editing a Draft
257
+
258
+ Two ways to change a generated draft. Both work whichever editor the user has opened the draft in.
259
+
260
+ - **Revise by instruction (prose changes):** `coauthor draft revise <project-id> --instruction "Make the intro two sentences" --wait --json`. CoAuthor's own editor rewrites the draft in the project's voice and returns `data.groups`, each with `before_markdown` and `after_markdown`. Review every group against the brief before applying: `coauthor draft revision apply <project-id> <revision-id> --json`, keep only some with `--accept g1,g2` or `--reject g3`, or drop it with `coauthor draft revision discard <project-id> <revision-id> --json`. Only one revision can be open on a draft; an unresolved one blocks the user's browser saves, so always apply or discard it. If `--wait` returns `still_running`, run `coauthor draft revision show <project-id> <revision-id> --json` again. `revise_unavailable` means this account cannot revise by instruction yet; use a direct edit.
261
+ - **Direct edit (exact text you already have):** `coauthor draft get <project-id> --format json --json`, edit nodes inside `data.content` (keep node ids and `imagePlaceholder` nodes), write `{"document_id": ..., "expected_base_version": <data.version_number>, "expected_content_hash": <data.content_hash, if present>, "content": <edited doc>}` to a file, then `coauthor draft save <project-id> --data @payload.json --json`. Never send markdown as `content`.
262
+ - On `stale_draft`, re-read with `draft get` and reapply your edit; never retry the same payload. On `user_recently_editing`, the user is typing in the browser: wait or ask them, and pass `--force` only if they agree.
263
+
256
264
  ## Draft Export
257
265
 
258
266
  Use `coauthor draft get <project-id> --format markdown --json` when the user needs a finished draft in Markdown. Generated images are resolved into Markdown image URLs when available.
@@ -253,6 +253,14 @@ Use `coauthor chat show <project-id> --json` to retrieve the workspace chat tran
253
253
 
254
254
  When using `coauthor chat <project-id> --stage draft --json`, treat the returned text as a workspace chat response, not a saved draft document. The CLI returns `draft_saved: false` and `transcript_command` when applicable. Use `coauthor draft get <project-id> --format markdown --json` only for a saved generated draft.
255
255
 
256
+ ## Editing a Draft
257
+
258
+ Two ways to change a generated draft. Both work whichever editor the user has opened the draft in.
259
+
260
+ - **Revise by instruction (prose changes):** `coauthor draft revise <project-id> --instruction "Make the intro two sentences" --wait --json`. CoAuthor's own editor rewrites the draft in the project's voice and returns `data.groups`, each with `before_markdown` and `after_markdown`. Review every group against the brief before applying: `coauthor draft revision apply <project-id> <revision-id> --json`, keep only some with `--accept g1,g2` or `--reject g3`, or drop it with `coauthor draft revision discard <project-id> <revision-id> --json`. Only one revision can be open on a draft; an unresolved one blocks the user's browser saves, so always apply or discard it. If `--wait` returns `still_running`, run `coauthor draft revision show <project-id> <revision-id> --json` again. `revise_unavailable` means this account cannot revise by instruction yet; use a direct edit.
261
+ - **Direct edit (exact text you already have):** `coauthor draft get <project-id> --format json --json`, edit nodes inside `data.content` (keep node ids and `imagePlaceholder` nodes), write `{"document_id": ..., "expected_base_version": <data.version_number>, "expected_content_hash": <data.content_hash, if present>, "content": <edited doc>}` to a file, then `coauthor draft save <project-id> --data @payload.json --json`. Never send markdown as `content`.
262
+ - On `stale_draft`, re-read with `draft get` and reapply your edit; never retry the same payload. On `user_recently_editing`, the user is typing in the browser: wait or ask them, and pass `--force` only if they agree.
263
+
256
264
  ## Draft Export
257
265
 
258
266
  Use `coauthor draft get <project-id> --format markdown --json` when the user needs a finished draft in Markdown. Generated images are resolved into Markdown image URLs when available.
@@ -230,6 +230,14 @@ Persuasive opinion essay:
230
230
  - Require explicit user intent before live publish/export.
231
231
  - Use `--yes` only after the user has clearly approved the live publish/export action.
232
232
 
233
+ ## Editing a Draft
234
+
235
+ Two ways to change a generated draft. Both work whichever editor the user has opened the draft in.
236
+
237
+ - **Revise by instruction (prose changes):** `coauthor draft revise <project-id> --instruction "Make the intro two sentences" --wait --json`. CoAuthor's own editor rewrites the draft in the project's voice and returns `data.groups`, each with `before_markdown` and `after_markdown`. Review every group against the brief before applying: `coauthor draft revision apply <project-id> <revision-id> --json`, keep only some with `--accept g1,g2` or `--reject g3`, or drop it with `coauthor draft revision discard <project-id> <revision-id> --json`. Only one revision can be open on a draft; an unresolved one blocks the user's browser saves, so always apply or discard it. If `--wait` returns `still_running`, run `coauthor draft revision show <project-id> <revision-id> --json` again. `revise_unavailable` means this account cannot revise by instruction yet; use a direct edit.
238
+ - **Direct edit (exact text you already have):** `coauthor draft get <project-id> --format json --json`, edit nodes inside `data.content` (keep node ids and `imagePlaceholder` nodes), write `{"document_id": ..., "expected_base_version": <data.version_number>, "expected_content_hash": <data.content_hash, if present>, "content": <edited doc>}` to a file, then `coauthor draft save <project-id> --data @payload.json --json`. Never send markdown as `content`.
239
+ - On `stale_draft`, re-read with `draft get` and reapply your edit; never retry the same payload. On `user_recently_editing`, the user is typing in the browser: wait or ask them, and pass `--force` only if they agree.
240
+
233
241
  ## Draft Export
234
242
 
235
243
  - Use `coauthor chat show <project-id> --json` to retrieve workspace chat transcripts after long chat responses.