@clickminded/coauthor-cli 0.0.6 → 0.0.8

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
@@ -118,8 +118,10 @@ Chat and workflow:
118
118
  coauthor chat <project-id> --message "..." --json
119
119
  coauthor workflow status <project-id> --json
120
120
  coauthor workflow run <project-id> --target draft --wait --json
121
+ coauthor workflow resume <project-id> --target draft --wait --json
121
122
  coauthor workflow rewind <project-id> --stage outline --reason "..." --json
122
123
  coauthor workflow approve <project-id> --stage research_plan --json
124
+ coauthor credits <project-id> --json
123
125
  ```
124
126
 
125
127
  Artifacts:
@@ -182,9 +184,11 @@ Agents should:
182
184
  - Prefer `coauthor` over browser automation, `curl` to session APIs, or direct database access.
183
185
  - Use `--json` on every command they need to parse.
184
186
  - Use `--wait` when starting long-running research or draft jobs and the user expects completion.
187
+ - Treat `status: "requires_key"` as a recoverable pause, not a failed workflow. Tell the user to add keys in AI settings, then resume with `coauthor workflow resume <project-id> --wait --json`.
188
+ - Use `coauthor credits <project-id> --json` to inspect credit allowance, pending holds, and remaining credits.
185
189
  - Avoid retrying publish/export after uncertain network failures.
186
190
  - Use `coauthor operation status <operation-key>` after uncertainty.
187
- - Never print tokens, cookies, service-role keys, or authorization headers.
191
+ - Never print tokens, cookies, service-role keys, provider API keys, or authorization headers.
188
192
 
189
193
  ## Security
190
194
 
@@ -211,6 +215,8 @@ The CLI talks to `/api/agent/v1/*`. Treat this as a public beta API surface:
211
215
 
212
216
  `authorization_pending` during login is normal while the browser approval page is waiting for browser approval.
213
217
 
218
+ `requires_key` means included credits are exhausted and no usable provider key is configured for the requested capability. The task is paused when possible. Open AI settings in the web app, add the required key, then run `coauthor workflow resume <project-id> --wait --json`.
219
+
214
220
  If `npx @clickminded/coauthor-cli help` fails while you are inside the CLI package source directory, run it from another directory or use:
215
221
 
216
222
  ```sh
package/dist/commands.js CHANGED
@@ -18,7 +18,7 @@ export async function runCommand(input, context) {
18
18
  if (scope === 'workspace')
19
19
  return runWorkspaceCommand(action, input, context.client);
20
20
  if (scope === 'chat')
21
- return runChatCommand(input, context.client);
21
+ return runChatCommand(action, input, context.client);
22
22
  if (scope === 'contract')
23
23
  return runArtifactCommand('contract', action, input, context.client);
24
24
  if (scope === 'outline')
@@ -31,6 +31,8 @@ export async function runCommand(input, context) {
31
31
  return runDraftCommand(action, input, context.client);
32
32
  if (scope === 'workflow')
33
33
  return runWorkflowCommand(action, input, context.client);
34
+ if (scope === 'credits')
35
+ return runCreditsCommand(input, context.client);
34
36
  if (scope === 'image')
35
37
  return runResourceCommand('images', action, input, context.client);
36
38
  if (scope === 'thread')
@@ -162,19 +164,37 @@ async function runWorkspaceCommand(action, input, client) {
162
164
  const data = await client.request({ path: `projects/${encodeURIComponent(projectId)}/workspace` });
163
165
  return { ok: true, data };
164
166
  }
165
- async function runChatCommand(input, client) {
167
+ async function runChatCommand(action, input, client) {
168
+ if (action === 'show' || action === 'list') {
169
+ const projectId = requireProjectId(input);
170
+ const data = await client.request({ path: `projects/${encodeURIComponent(projectId)}/workspace` });
171
+ return {
172
+ ok: true,
173
+ data: {
174
+ project_id: projectId,
175
+ workspace_chat_id: extractNestedString(data, ['workspaceChatId']) ?? null,
176
+ messages: extractNestedValue(data, ['messages']) ?? [],
177
+ },
178
+ };
179
+ }
166
180
  const projectId = requireProjectId(input);
167
181
  const message = getString(input.values, 'message') ?? input.positionals.slice(1).join(' ');
168
182
  if (!message)
169
183
  throw new Error('Usage: coauthor chat <projectId> --message "..."');
170
184
  const body = withNamedOptions(parseJsonOption(input.values), input.values, ['stage', 'execution-token']);
185
+ const stage = getString(input.values, 'stage');
186
+ if (stage)
187
+ body.activeArtifact = stage;
171
188
  body.message = message;
172
189
  const data = await client.request({
173
190
  method: 'POST',
174
191
  path: `projects/${encodeURIComponent(projectId)}/chat`,
175
192
  body,
176
193
  });
177
- return { ok: true, data };
194
+ return {
195
+ ok: true,
196
+ data: enrichChatResult(data, projectId, stage),
197
+ };
178
198
  }
179
199
  async function runWorkflowCommand(action, input, client) {
180
200
  const projectId = requireProjectId(input);
@@ -183,6 +203,25 @@ async function runWorkflowCommand(action, input, client) {
183
203
  const data = await client.request({ path: projectPath });
184
204
  return { ok: true, data };
185
205
  }
206
+ if (action === 'resume') {
207
+ const target = normalizeWorkflowWaitTarget(getString(input.values, 'target') ?? getString(input.values, 'stage')) ?? 'draft';
208
+ if (target === 'research') {
209
+ const data = await client.request({ method: 'POST', path: `projects/${encodeURIComponent(projectId)}/research/run`, body: {} });
210
+ return getBoolean(input.values, 'wait') ? waitForResearch(client, projectId, data) : { ok: true, data };
211
+ }
212
+ const researchStatus = await client.request({ path: `projects/${encodeURIComponent(projectId)}/research/status` });
213
+ if (extractNestedString(researchStatus, ['run', 'status']) === 'paused_requires_key') {
214
+ const data = await client.request({ method: 'POST', path: `projects/${encodeURIComponent(projectId)}/research/run`, body: {} });
215
+ return getBoolean(input.values, 'wait') ? waitForWorkflowDraft(client, projectId, data) : { ok: true, data };
216
+ }
217
+ const draftStatus = await client.request({ path: `projects/${encodeURIComponent(projectId)}/draft/status` });
218
+ if (getResponseString(draftStatus, 'phase') === 'paused_requires_key') {
219
+ const data = await client.request({ method: 'POST', path: `projects/${encodeURIComponent(projectId)}/draft/generate`, body: {} });
220
+ return getBoolean(input.values, 'wait') ? waitForDraft(client, projectId, data) : { ok: true, data };
221
+ }
222
+ const data = await client.request({ method: 'POST', path: `${projectPath}/run`, body: { target } });
223
+ return getBoolean(input.values, 'wait') ? waitForWorkflowDraft(client, projectId, data) : { ok: true, data };
224
+ }
186
225
  if (action === 'advance' || action === 'run' || action === 'rewind' || action === 'approve') {
187
226
  const body = withNamedOptions(parseJsonOption(input.values), input.values, [
188
227
  'stage',
@@ -213,7 +252,12 @@ async function runWorkflowCommand(action, input, client) {
213
252
  }
214
253
  return { ok: true, data };
215
254
  }
216
- throw new Error('Usage: coauthor workflow <show|status|advance|run|rewind|approve> <projectId>');
255
+ throw new Error('Usage: coauthor workflow <show|status|advance|run|rewind|approve|resume> <projectId>');
256
+ }
257
+ async function runCreditsCommand(input, client) {
258
+ const projectId = requireProjectId(input);
259
+ const data = await client.request({ path: `projects/${encodeURIComponent(projectId)}/credits` });
260
+ return { ok: true, data };
217
261
  }
218
262
  async function runArtifactCommand(artifact, action, input, client) {
219
263
  const projectId = requireProjectId(input);
@@ -223,7 +267,9 @@ async function runArtifactCommand(artifact, action, input, client) {
223
267
  return { ok: true, data };
224
268
  }
225
269
  if (action === 'generate' || action === 'save' || action === 'approve') {
226
- const body = withNamedOptions(parseJsonOption(input.values), input.values, ['execution-token']);
270
+ const body = action === 'approve'
271
+ ? await buildArtifactApproveBody(artifact, input, client, basePath)
272
+ : withNamedOptions(parseJsonOption(input.values), input.values, ['execution-token']);
227
273
  const path = action === 'save' ? basePath : `${basePath}/${action}`;
228
274
  const data = await client.request({ method: 'POST', path, body });
229
275
  return { ok: true, data };
@@ -242,7 +288,7 @@ async function runResearchCommand(action, input, client) {
242
288
  return { ok: true, data };
243
289
  }
244
290
  if (action === 'status') {
245
- return { ok: true, data: await client.request({ path: `${basePath}/status` }) };
291
+ return { ok: true, data: enrichResearchStatus(await client.request({ path: `${basePath}/status` })) };
246
292
  }
247
293
  if (action === 'structured') {
248
294
  return { ok: true, data: await client.request({ path: `${basePath}/structured` }) };
@@ -332,6 +378,9 @@ async function runResourceCommand(resource, action, input, client) {
332
378
  'id',
333
379
  'placeholder-id',
334
380
  'execution-token',
381
+ 'grounding-mode',
382
+ 'image-generation-model',
383
+ 'edit-prompt',
335
384
  ]);
336
385
  const path = action === 'create' && resource !== 'threads' ? basePath : `${basePath}/${action}`;
337
386
  const data = await client.request({ method: 'POST', path, body });
@@ -520,6 +569,9 @@ async function waitForResearch(client, projectId, initialData) {
520
569
  return { ok: true, message: 'Research completed', data: latest };
521
570
  if (status === 'failed')
522
571
  throw new Error(extractNestedString(latest, ['run', 'error_message']) ?? 'Research failed');
572
+ if (status === 'paused_requires_key') {
573
+ return requiresKeyPauseResult(projectId, 'research', extractNestedString(latest, ['run', 'error_message']) ?? 'Research paused: add the required API key to continue.', latest);
574
+ }
523
575
  }
524
576
  return { ok: true, message: 'Timed out waiting for research; check status with coauthor research status', data: latest };
525
577
  }
@@ -534,6 +586,8 @@ async function waitForDraft(client, projectId, initialData) {
534
586
  if (state === 'draft_generated' || state === 'editing' || phase === 'complete') {
535
587
  return { ok: true, message: 'Draft completed', data: latest };
536
588
  }
589
+ if (phase === 'paused_requires_key')
590
+ return requiresKeyPauseResult(projectId, 'draft', getResponseString(latest, 'message') ?? 'Draft paused: add the required API key to continue.', latest);
537
591
  if (phase === 'failed')
538
592
  throw new Error(getResponseString(latest, 'message') ?? 'Draft generation failed');
539
593
  }
@@ -545,6 +599,9 @@ async function waitForWorkflowDraft(client, projectId, initialData) {
545
599
  let latestResearch = null;
546
600
  let draftGenerate = null;
547
601
  let attemptedDraftStart = false;
602
+ if (workflowIndicatesBackgroundResearch(initialData)) {
603
+ return researchRunningWorkflowResult(projectId, initialData, null, null);
604
+ }
548
605
  while (Date.now() < deadline) {
549
606
  await sleep(3000);
550
607
  latestDraft = await client.request({ path: `projects/${encodeURIComponent(projectId)}/draft/status` });
@@ -564,11 +621,25 @@ async function waitForWorkflowDraft(client, projectId, initialData) {
564
621
  }
565
622
  if (draftPhase === 'failed')
566
623
  throw new Error(getResponseString(latestDraft, 'message') ?? 'Draft generation failed');
624
+ if (draftPhase === 'paused_requires_key') {
625
+ return requiresKeyPauseResult(projectId, 'draft', getResponseString(latestDraft, 'message') ?? 'Draft paused: add the required API key to continue.', {
626
+ workflow: initialData,
627
+ research_status: latestResearch,
628
+ draft_status: latestDraft,
629
+ });
630
+ }
567
631
  latestResearch = await client.request({ path: `projects/${encodeURIComponent(projectId)}/research/status` });
568
632
  const researchStatus = extractNestedString(latestResearch, ['run', 'status']);
569
633
  if (researchStatus === 'failed') {
570
634
  throw new Error(extractNestedString(latestResearch, ['run', 'error_message']) ?? 'Research failed');
571
635
  }
636
+ if (researchStatus === 'paused_requires_key') {
637
+ return requiresKeyPauseResult(projectId, 'research', extractNestedString(latestResearch, ['run', 'error_message']) ?? 'Research paused: add the required API key to continue.', {
638
+ workflow: initialData,
639
+ research_status: latestResearch,
640
+ draft_status: latestDraft,
641
+ });
642
+ }
572
643
  if (!attemptedDraftStart
573
644
  && (researchStatus === 'succeeded' || isResearchReadyForDraft(draftState))
574
645
  && draftPhase !== 'queued'
@@ -597,14 +668,117 @@ async function waitForWorkflowDraft(client, projectId, initialData) {
597
668
  },
598
669
  };
599
670
  }
671
+ async function buildArtifactApproveBody(artifact, input, client, basePath) {
672
+ const explicitBody = parseJsonOption(input.values);
673
+ const body = withNamedOptions(explicitBody, input.values, ['execution-token']);
674
+ if (getString(input.values, 'data') !== undefined)
675
+ return body;
676
+ const current = await client.request({ path: basePath });
677
+ const payloadHash = extractNestedString(current, ['metadata', 'payload_hash']);
678
+ if (payloadHash)
679
+ body.expectedPayloadHash = payloadHash;
680
+ if (artifact === 'contract') {
681
+ const contract = extractNestedValue(current, ['artifact']);
682
+ if (contract && typeof contract === 'object' && !Array.isArray(contract)) {
683
+ body.contract = contract;
684
+ }
685
+ return body;
686
+ }
687
+ if (artifact === 'outline') {
688
+ const sections = extractNestedValue(current, ['artifact']);
689
+ if (!Array.isArray(sections) || sections.length === 0) {
690
+ throw new Error('Generate or save an outline before approving it.');
691
+ }
692
+ body.sections = sections;
693
+ return body;
694
+ }
695
+ const researchTasks = extractNestedValue(current, ['artifact']);
696
+ if (!Array.isArray(researchTasks) || researchTasks.length === 0) {
697
+ throw new Error('Generate or save a research plan before approving it.');
698
+ }
699
+ body.researchTasks = researchTasks;
700
+ return body;
701
+ }
702
+ function enrichChatResult(data, projectId, stage) {
703
+ if (!data || typeof data !== 'object' || Array.isArray(data))
704
+ return data;
705
+ const result = {
706
+ ...data,
707
+ transcript_command: `coauthor chat show ${projectId} --json`,
708
+ };
709
+ if (stage?.trim().toLowerCase() === 'draft') {
710
+ result.draft_saved = false;
711
+ result.draft_note = 'Draft-stage chat responses are saved to the workspace chat transcript, not to the draft document. Use transcript_command to retrieve the response.';
712
+ }
713
+ return result;
714
+ }
715
+ function enrichResearchStatus(data) {
716
+ if (!data || typeof data !== 'object' || Array.isArray(data))
717
+ return data;
718
+ const runStatus = extractNestedString(data, ['run', 'status']);
719
+ const projectState = getResponseString(data, 'project_state');
720
+ if (runStatus !== 'running' || projectState === 'research_running')
721
+ return data;
722
+ return {
723
+ ...data,
724
+ diagnostic: {
725
+ code: 'research_run_state_mismatch',
726
+ message: `Latest research run is still running while project_state is "${projectState ?? 'unknown'}".`,
727
+ recovery_commands: [
728
+ 'coauthor research status <project-id> --json',
729
+ 'coauthor workflow resume <project-id> --target research --wait --json',
730
+ 'coauthor workflow rewind <project-id> --target research --json',
731
+ ],
732
+ },
733
+ };
734
+ }
735
+ function workflowIndicatesBackgroundResearch(data) {
736
+ if (!data || typeof data !== 'object' || Array.isArray(data))
737
+ return false;
738
+ return getResponseString(data, 'project_state') === 'research_running'
739
+ || getResponseString(data, 'status') === 'research_running';
740
+ }
741
+ function researchRunningWorkflowResult(projectId, workflow, researchStatus, draftStatus) {
742
+ return {
743
+ ok: true,
744
+ status: 'research_running',
745
+ message: 'Research is running in the background. Draft generation has not started yet.',
746
+ data: {
747
+ workflow,
748
+ research_status: researchStatus,
749
+ draft_status: draftStatus,
750
+ next_commands: [
751
+ `coauthor research status ${projectId} --json`,
752
+ `coauthor workflow resume ${projectId} --target draft --wait --json`,
753
+ `coauthor workflow rewind ${projectId} --target research --json`,
754
+ ],
755
+ },
756
+ };
757
+ }
758
+ function requiresKeyPauseResult(projectId, target, message, data) {
759
+ const resumeCommand = `coauthor workflow resume ${projectId} --target ${target} --wait --json`;
760
+ return {
761
+ ok: false,
762
+ status: 'requires_key',
763
+ exitCode: 2,
764
+ message: `${message}\nOpen AI settings: /settings/ai\nResume: ${resumeCommand}`,
765
+ settings_url: '/settings/ai',
766
+ resume_command: resumeCommand,
767
+ data,
768
+ };
769
+ }
600
770
  function extractNestedString(value, path) {
771
+ const current = extractNestedValue(value, path);
772
+ return typeof current === 'string' ? current : undefined;
773
+ }
774
+ function extractNestedValue(value, path) {
601
775
  let current = value;
602
776
  for (const key of path) {
603
777
  if (!current || typeof current !== 'object' || Array.isArray(current))
604
778
  return undefined;
605
779
  current = current[key];
606
780
  }
607
- return typeof current === 'string' ? current : undefined;
781
+ return current;
608
782
  }
609
783
  function normalizeWorkflowWaitTarget(value) {
610
784
  if (!value)
@@ -658,20 +832,21 @@ export function helpResult() {
658
832
  ' auth login|status|logout',
659
833
  ' project create|list|show',
660
834
  ' workspace show',
661
- ' chat',
835
+ ' chat [show|list]',
662
836
  ' contract show|save|approve',
663
837
  ' outline show|generate|save|approve',
664
838
  ' research-plan show|generate|save|approve',
665
839
  ' research run|status|structured',
666
840
  ' draft generate|status|get|save',
667
841
  ' draft get supports --format json|markdown|html|text',
668
- ' workflow show|status|advance|run|rewind|approve',
842
+ ' workflow show|status|advance|run|rewind|approve|resume',
669
843
  ' workflow run/advance supports --briefing-mode auto|strict|off and --require-brief-review',
670
844
  ' image list|status|show|generate|edit',
671
845
  ' thread list|show|create|generate|save',
672
846
  ' publish thread',
673
847
  ' export blog|clickminded',
674
848
  ' operation list|show|status',
849
+ ' credits',
675
850
  ' skills list|install',
676
851
  ].join('\n'),
677
852
  };
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { helpResult, runCommand } from './commands.js';
7
7
  import { renderError, renderResult } from './output.js';
8
8
  import { parseCliArgs } from './parser.js';
9
9
  export async function main(argv = process.argv.slice(2)) {
10
+ let resolvedBaseUrl = resolveBaseUrlFromArgv(argv);
10
11
  try {
11
12
  const parsed = parseCliArgs(argv);
12
13
  if (parsed.globals.help) {
@@ -17,6 +18,7 @@ export async function main(argv = process.argv.slice(2)) {
17
18
  baseUrlOverride: parsed.globals.baseUrl,
18
19
  tokenOverride: parsed.globals.token,
19
20
  });
21
+ resolvedBaseUrl = runtimeConfig.baseUrl;
20
22
  const client = new AgentClient(runtimeConfig);
21
23
  const result = await runCommand(parsed, {
22
24
  client,
@@ -24,20 +26,89 @@ export async function main(argv = process.argv.slice(2)) {
24
26
  token: runtimeConfig.token,
25
27
  });
26
28
  process.stdout.write(renderResult(result, parsed.globals.json));
27
- return 0;
29
+ return result.exitCode ?? (result.ok ? 0 : 1);
28
30
  }
29
31
  catch (error) {
30
32
  const wantsJson = argv.includes('--json');
31
- process.stderr.write(renderError(formatCliError(error), wantsJson));
32
- return 1;
33
+ const formatted = formatCliError(error, resolvedBaseUrl, argv);
34
+ process.stderr.write(renderError(formatted.result ?? formatted.error, wantsJson));
35
+ return formatted.exitCode;
33
36
  }
34
37
  }
35
- function formatCliError(error) {
38
+ function formatCliError(error, baseUrl, argv = []) {
36
39
  if (error instanceof AgentHttpError) {
40
+ const requiresKey = formatRequiresKeyResult(error.responseBody, baseUrl);
41
+ if (requiresKey)
42
+ return { error: new Error(requiresKey.message), result: requiresKey, exitCode: 2 };
37
43
  const message = extractErrorMessage(error.responseBody) ?? error.message;
38
- return new Error(message);
44
+ const researchBlock = formatResearchRunningDraftBlock(message, argv);
45
+ if (researchBlock)
46
+ return { error: new Error(researchBlock.message), result: researchBlock, exitCode: 2 };
47
+ return { error: new Error(message), exitCode: 1 };
39
48
  }
40
- return error instanceof Error ? error : new Error(String(error));
49
+ return { error: error instanceof Error ? error : new Error(String(error)), exitCode: 1 };
50
+ }
51
+ function formatResearchRunningDraftBlock(message, argv) {
52
+ if (!/Cannot generate draft in state "research_running"/i.test(message))
53
+ return null;
54
+ const projectId = resolveProjectIdFromArgv(argv);
55
+ const recoveryCommands = projectId
56
+ ? [
57
+ `coauthor research status ${projectId} --json`,
58
+ `coauthor workflow resume ${projectId} --target draft --wait --json`,
59
+ `coauthor workflow rewind ${projectId} --target research --json`,
60
+ ]
61
+ : [
62
+ 'coauthor research status <project-id> --json',
63
+ 'coauthor workflow resume <project-id> --target draft --wait --json',
64
+ 'coauthor workflow rewind <project-id> --target research --json',
65
+ ];
66
+ return {
67
+ ok: false,
68
+ status: 'blocked_by_research',
69
+ message: `${message}\nResearch is still marked running. Check status, resume, or rewind the research stage before generating a draft.`,
70
+ recovery_commands: recoveryCommands,
71
+ exitCode: 2,
72
+ };
73
+ }
74
+ function resolveProjectIdFromArgv(argv) {
75
+ const projectFlagIndex = argv.indexOf('--project');
76
+ if (projectFlagIndex >= 0 && argv[projectFlagIndex + 1])
77
+ return argv[projectFlagIndex + 1];
78
+ const commandWords = new Set([
79
+ 'auth',
80
+ 'login',
81
+ 'status',
82
+ 'logout',
83
+ 'project',
84
+ 'create',
85
+ 'list',
86
+ 'show',
87
+ 'workspace',
88
+ 'chat',
89
+ 'contract',
90
+ 'outline',
91
+ 'research-plan',
92
+ 'research',
93
+ 'run',
94
+ 'draft',
95
+ 'generate',
96
+ 'get',
97
+ 'save',
98
+ 'workflow',
99
+ 'advance',
100
+ 'rewind',
101
+ 'approve',
102
+ 'resume',
103
+ 'image',
104
+ 'thread',
105
+ 'publish',
106
+ 'export',
107
+ 'operation',
108
+ 'credits',
109
+ 'skills',
110
+ ]);
111
+ return argv.find((arg) => !arg.startsWith('-') && !commandWords.has(arg));
41
112
  }
42
113
  function extractErrorMessage(body) {
43
114
  if (!body || typeof body !== 'object' || Array.isArray(body) || !('error' in body))
@@ -50,6 +121,50 @@ function extractErrorMessage(body) {
50
121
  const message = error.message;
51
122
  return typeof message === 'string' ? message : null;
52
123
  }
124
+ function formatRequiresKeyResult(body, baseUrl) {
125
+ const envelopeError = extractEnvelopeError(body);
126
+ if (!envelopeError || envelopeError.code !== 'requires_key')
127
+ return null;
128
+ const details = envelopeError.details && typeof envelopeError.details === 'object' && !Array.isArray(envelopeError.details)
129
+ ? envelopeError.details
130
+ : {};
131
+ const settingsUrl = typeof details.settings_url === 'string' ? details.settings_url : new URL('/settings/ai', baseUrl).toString();
132
+ const resumeCommand = typeof details.resume_command === 'string' ? details.resume_command : undefined;
133
+ return {
134
+ ok: false,
135
+ status: 'requires_key',
136
+ message: [
137
+ envelopeError.message,
138
+ `Open AI settings: ${settingsUrl}`,
139
+ resumeCommand ? `Resume: ${resumeCommand}` : null,
140
+ ].filter(Boolean).join('\n'),
141
+ settings_url: settingsUrl,
142
+ resume_command: resumeCommand,
143
+ data: details,
144
+ exitCode: 2,
145
+ };
146
+ }
147
+ function extractEnvelopeError(body) {
148
+ if (!body || typeof body !== 'object' || Array.isArray(body) || !('error' in body))
149
+ return null;
150
+ const error = body.error;
151
+ if (!error || typeof error !== 'object' || Array.isArray(error))
152
+ return null;
153
+ const message = error.message;
154
+ if (typeof message !== 'string')
155
+ return null;
156
+ const code = error.code;
157
+ return {
158
+ code: typeof code === 'string' ? code : undefined,
159
+ message,
160
+ details: error.details,
161
+ };
162
+ }
163
+ function resolveBaseUrlFromArgv(argv) {
164
+ const index = argv.indexOf('--base-url');
165
+ const value = index >= 0 ? argv[index + 1] : undefined;
166
+ return value || process.env.COAUTHOR_BASE_URL || 'http://localhost:3000';
167
+ }
53
168
  function isCliEntrypoint() {
54
169
  const argvPath = process.argv[1];
55
170
  if (!argvPath)
package/dist/output.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import type { JsonValue } from './client.js';
2
2
  export type CommandResult = {
3
3
  ok: boolean;
4
+ status?: string;
4
5
  message?: string;
5
6
  data?: JsonValue;
7
+ exitCode?: number;
8
+ settings_url?: string;
9
+ resume_command?: string;
6
10
  };
7
11
  export declare function renderResult(result: CommandResult, json: boolean): string;
8
12
  export declare function renderError(error: unknown, json: boolean): string;
package/dist/output.js CHANGED
@@ -8,7 +8,14 @@ export function renderResult(result, json) {
8
8
  return `${JSON.stringify(result.data, null, 2)}\n`;
9
9
  }
10
10
  export function renderError(error, json) {
11
- const message = error instanceof Error ? error.message : String(error);
11
+ if (json && error && typeof error === 'object' && !Array.isArray(error) && 'ok' in error) {
12
+ return `${JSON.stringify(error, null, 2)}\n`;
13
+ }
14
+ const message = error instanceof Error
15
+ ? error.message
16
+ : error && typeof error === 'object' && !Array.isArray(error) && typeof error.message === 'string'
17
+ ? error.message
18
+ : String(error);
12
19
  if (json)
13
20
  return `${JSON.stringify({ ok: false, error: message }, null, 2)}\n`;
14
21
  return `Error: ${message}\n`;
package/dist/parser.js CHANGED
@@ -100,10 +100,14 @@ function commandLength(positionals) {
100
100
  return second && ['create', 'list', 'show'].includes(second) ? 2 : 1;
101
101
  if (first === 'workspace')
102
102
  return second === 'show' ? 2 : 1;
103
+ if (first === 'chat')
104
+ return second && ['show', 'list'].includes(second) ? 2 : 1;
103
105
  if (first === 'skills')
104
106
  return second && ['list', 'install'].includes(second) ? 2 : 1;
105
107
  if (first === 'workflow')
106
108
  return second ? 2 : 1;
109
+ if (first === 'credits')
110
+ return 1;
107
111
  if (['contract', 'outline', 'research-plan', 'research', 'draft', 'image', 'thread', 'publish', 'export', 'operation'].includes(first ?? ''))
108
112
  return second ? 2 : 1;
109
113
  return 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clickminded/coauthor-cli",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "coauthor": "dist/index.js",
@@ -14,11 +14,14 @@ This skill guides agent use of the CoAuthor CLI.
14
14
  - Use `--json` for machine-readable output and parse fields from that output.
15
15
  - Use `--wait` for commands that start asynchronous work when the user expects the operation to finish.
16
16
  - Let the default bounded briefing review run before outline/draft generation. Use `--briefing-mode strict` when the user explicitly wants a stronger brief gate, and answer or relay `data.clarification_questions` if the CLI returns `status: "needs_clarification"`.
17
+ - Treat `status: "requires_key"` or `paused_requires_key` as a saved, recoverable pause. Do not retry in a loop; tell the user to add the required provider key in AI settings, then resume with `coauthor workflow resume <project-id> --wait --json`.
18
+ - Use `coauthor credits <project-id> --json` to check credit allowance, pending credits, and remaining credits.
17
19
  - After a timeout, interruption, network error, or unclear result, check operation status before retrying.
18
20
 
19
21
  ## Safety
20
22
 
21
23
  - Never print access tokens, publish tokens, service-role keys, cookies, or authorization headers.
24
+ - Never ask the user to paste Anthropic, OpenAI, or Gemini provider API keys into chat or the terminal; key entry belongs in CoAuthor AI settings.
22
25
  - Pass tokens through environment variables or secret-backed CLI options only; do not paste them into prompts, logs, or shell history.
23
26
  - Treat publish/export operations as live side effects.
24
27
  - Require explicit user intent before live publish/export.
@@ -14,11 +14,14 @@ This skill guides agent use of the CoAuthor CLI.
14
14
  - Use `--json` for machine-readable output and parse fields from that output.
15
15
  - Use `--wait` for commands that start asynchronous work when the user expects the operation to finish.
16
16
  - Let the default bounded briefing review run before outline/draft generation. Use `--briefing-mode strict` when the user explicitly wants a stronger brief gate, and answer or relay `data.clarification_questions` if the CLI returns `status: "needs_clarification"`.
17
+ - Treat `status: "requires_key"` or `paused_requires_key` as a saved, recoverable pause. Do not retry in a loop; tell the user to add the required provider key in AI settings, then resume with `coauthor workflow resume <project-id> --wait --json`.
18
+ - Use `coauthor credits <project-id> --json` to check credit allowance, pending credits, and remaining credits.
17
19
  - After a timeout, interruption, network error, or unclear result, check operation status before retrying.
18
20
 
19
21
  ## Safety
20
22
 
21
23
  - Never print access tokens, publish tokens, service-role keys, cookies, or authorization headers.
24
+ - Never ask the user to paste Anthropic, OpenAI, or Gemini provider API keys into chat or the terminal; key entry belongs in CoAuthor AI settings.
22
25
  - Pass tokens through environment variables or secret-backed CLI options only; do not paste them into prompts, logs, or shell history.
23
26
  - Treat publish/export operations as live side effects.
24
27
  - Require explicit user intent before live publish/export.
@@ -11,8 +11,11 @@ alwaysApply: true
11
11
  - Use `--json` for agent-readable command output.
12
12
  - Use `--wait` when starting asynchronous work and the user expects a completed result.
13
13
  - Let the default bounded briefing review run before outline/draft generation. Use `--briefing-mode strict` for a stronger brief gate, and answer or relay `data.clarification_questions` if the CLI returns `status: "needs_clarification"`.
14
+ - Treat `status: "requires_key"` or `paused_requires_key` as a saved, recoverable pause. Do not retry in a loop; tell the user to add the required provider key in AI settings, then resume with `coauthor workflow resume <project-id> --wait --json`.
15
+ - Use `coauthor credits <project-id> --json` to check credit allowance, pending credits, and remaining credits.
14
16
  - After timeout, interruption, network error, or ambiguous output, check operation status before retrying or reporting success.
15
17
  - Never print tokens, service-role keys, cookies, or authorization headers.
18
+ - Never ask the user to paste Anthropic, OpenAI, or Gemini provider API keys into chat or the terminal; key entry belongs in CoAuthor AI settings.
16
19
  - Pass tokens through environment variables or secret-backed CLI options only.
17
20
  - Treat publish/export commands as live side effects.
18
21
  - Require explicit user intent before live publish/export.