@clickminded/coauthor-cli 0.0.32 → 0.0.34

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
@@ -69,7 +69,7 @@ Images, social, and export:
69
69
 
70
70
  ```sh
71
71
  coauthor image list <id> --json
72
- coauthor image generate <id> --placeholder-id <placeholder id> --json
72
+ coauthor image generate <id> --placeholder-id <id or placeholder_id> --json
73
73
  coauthor image status <id> --json
74
74
  coauthor repurpose generate <id> --format all --json # X thread and post, LinkedIn, Facebook, email newsletter
75
75
  coauthor repurpose download <id> --out ./social # copy-ready files plus the article
package/dist/client.d.ts CHANGED
@@ -5,23 +5,48 @@ export type AgentClientOptions = {
5
5
  baseUrl: string;
6
6
  token?: string;
7
7
  fetchImpl?: typeof fetch;
8
+ /** Overrides every request and download timeout (else COAUTHOR_CLI_REQUEST_TIMEOUT_MS, else the defaults below). */
9
+ timeoutMs?: number;
8
10
  };
9
11
  export type RequestOptions = {
10
12
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
11
13
  path: string;
12
14
  body?: JsonValue;
13
15
  idempotencyKey?: string;
16
+ timeoutMs?: number;
14
17
  };
18
+ export declare const DEFAULT_READ_TIMEOUT_MS = 120000;
19
+ export declare const DEFAULT_WRITE_TIMEOUT_MS = 330000;
20
+ export declare const DEFAULT_DOWNLOAD_TIMEOUT_MS = 300000;
15
21
  export declare class AgentHttpError extends Error {
16
22
  readonly status: number;
17
23
  readonly responseBody: unknown;
18
- constructor(status: number, responseBody: unknown);
24
+ readonly idempotencyKey?: string;
25
+ constructor(status: number, responseBody: unknown, idempotencyKey?: string);
19
26
  }
27
+ /** A request that never got an HTTP response: it timed out or the network failed. */
28
+ export declare class AgentRequestError extends Error {
29
+ readonly code: 'request_timeout' | 'network_error';
30
+ readonly idempotencyKey?: string;
31
+ constructor(code: 'request_timeout' | 'network_error', message: string, idempotencyKey?: string);
32
+ }
33
+ export declare function requestTimeoutOverrideMs(env?: NodeJS.ProcessEnv): number | undefined;
20
34
  export declare class AgentClient {
21
35
  private readonly baseUrl;
22
36
  private readonly token;
23
37
  private readonly fetchImpl;
24
- constructor(options: AgentClientOptions);
38
+ private readonly options;
39
+ private readonly sent;
40
+ constructor(options: AgentClientOptions, sent?: {
41
+ count: number;
42
+ });
43
+ /** Same transport and timeouts, different credentials (used to verify a token before saving it). */
44
+ withCredentials(params: {
45
+ baseUrl?: string;
46
+ token: string;
47
+ }): AgentClient;
48
+ /** Requests and downloads started so far, across derived clients. */
49
+ get requestsSent(): number;
25
50
  request(options: RequestOptions): Promise<JsonValue>;
26
51
  /**
27
52
  * Fetches a public file (a rendered MP4 or slide PNG on the CDN) as bytes.
package/dist/client.js CHANGED
@@ -8,45 +8,94 @@ const jsonValueSchema = z.lazy(() => z.union([
8
8
  z.array(jsonValueSchema),
9
9
  z.record(z.string(), jsonValueSchema),
10
10
  ]));
11
+ // Reads are quick status/list calls. Writes can run synchronous AI work
12
+ // (repurpose generate ~20-90s, outline/plan generation, workflow run, exports)
13
+ // and the server caps a request at 300s (maxDuration), so writes get a bit
14
+ // more than that. Downloads fetch MP4s and PNGs from the CDN.
15
+ export const DEFAULT_READ_TIMEOUT_MS = 120_000;
16
+ export const DEFAULT_WRITE_TIMEOUT_MS = 330_000;
17
+ export const DEFAULT_DOWNLOAD_TIMEOUT_MS = 300_000;
11
18
  export class AgentHttpError extends Error {
12
19
  status;
13
20
  responseBody;
14
- constructor(status, responseBody) {
21
+ idempotencyKey;
22
+ constructor(status, responseBody, idempotencyKey) {
15
23
  super(`Request failed with HTTP ${status}`);
16
24
  this.name = 'AgentHttpError';
17
25
  this.status = status;
18
26
  this.responseBody = responseBody;
27
+ this.idempotencyKey = idempotencyKey;
19
28
  }
20
29
  }
30
+ /** A request that never got an HTTP response: it timed out or the network failed. */
31
+ export class AgentRequestError extends Error {
32
+ code;
33
+ idempotencyKey;
34
+ constructor(code, message, idempotencyKey) {
35
+ super(message);
36
+ this.name = 'AgentRequestError';
37
+ this.code = code;
38
+ this.idempotencyKey = idempotencyKey;
39
+ }
40
+ }
41
+ export function requestTimeoutOverrideMs(env = process.env) {
42
+ const raw = Number(env.COAUTHOR_CLI_REQUEST_TIMEOUT_MS);
43
+ return Number.isFinite(raw) && raw > 0 ? raw : undefined;
44
+ }
21
45
  export class AgentClient {
22
46
  baseUrl;
23
47
  token;
24
48
  fetchImpl;
25
- constructor(options) {
49
+ options;
50
+ // Shared with clients derived by withCredentials, so the CLI can tell a
51
+ // command rejected before anything was sent (a usage error) from one that
52
+ // failed while talking to CoAuthor.
53
+ sent;
54
+ constructor(options, sent = { count: 0 }) {
55
+ this.options = options;
56
+ this.sent = sent;
26
57
  this.baseUrl = new URL('api/agent/v1/', normalizeBaseUrl(options.baseUrl));
27
58
  this.token = options.token ?? '';
28
59
  this.fetchImpl = options.fetchImpl ?? fetch;
29
60
  }
61
+ /** Same transport and timeouts, different credentials (used to verify a token before saving it). */
62
+ withCredentials(params) {
63
+ return new AgentClient({ ...this.options, baseUrl: params.baseUrl ?? this.options.baseUrl, token: params.token }, this.sent);
64
+ }
65
+ /** Requests and downloads started so far, across derived clients. */
66
+ get requestsSent() {
67
+ return this.sent.count;
68
+ }
30
69
  async request(options) {
70
+ this.sent.count += 1;
31
71
  const method = options.method ?? 'GET';
32
72
  const url = new URL(trimLeadingSlash(options.path), this.baseUrl);
33
73
  const headers = new Headers({
34
74
  Accept: 'application/json',
35
75
  });
76
+ const idempotencyKey = isLiveAction(method) ? options.idempotencyKey ?? randomUUID() : undefined;
36
77
  if (this.token)
37
78
  headers.set('Authorization', `Bearer ${this.token}`);
38
79
  if (options.body !== undefined)
39
80
  headers.set('Content-Type', 'application/json');
40
- if (isLiveAction(method))
41
- headers.set('Idempotency-Key', options.idempotencyKey ?? randomUUID());
42
- const response = await this.fetchImpl(url, {
43
- method,
44
- headers,
45
- body: options.body === undefined ? undefined : JSON.stringify(jsonValueSchema.parse(options.body)),
81
+ if (idempotencyKey)
82
+ headers.set('Idempotency-Key', idempotencyKey);
83
+ const timeoutMs = options.timeoutMs
84
+ ?? this.options.timeoutMs
85
+ ?? requestTimeoutOverrideMs()
86
+ ?? (isLiveAction(method) ? DEFAULT_WRITE_TIMEOUT_MS : DEFAULT_READ_TIMEOUT_MS);
87
+ const target = `${method} ${trimLeadingSlash(options.path).split('?')[0]}`;
88
+ const { response, responseBody } = await withTimeout(timeoutMs, target, idempotencyKey, async (signal) => {
89
+ const response = await this.fetchImpl(url, {
90
+ method,
91
+ headers,
92
+ body: options.body === undefined ? undefined : JSON.stringify(jsonValueSchema.parse(options.body)),
93
+ signal,
94
+ });
95
+ return { response, responseBody: await readResponseBody(response) };
46
96
  });
47
- const responseBody = await readResponseBody(response);
48
97
  if (!response.ok)
49
- throw new AgentHttpError(response.status, responseBody);
98
+ throw new AgentHttpError(response.status, responseBody, idempotencyKey);
50
99
  const parsedBody = jsonValueSchema.parse(responseBody ?? null);
51
100
  if (parsedBody
52
101
  && typeof parsedBody === 'object'
@@ -65,12 +114,44 @@ export class AgentClient {
65
114
  const target = new URL(url);
66
115
  if (target.protocol !== 'https:' && target.protocol !== 'http:')
67
116
  throw new Error(`Refusing to download a non-http URL: ${url}`);
68
- const response = await this.fetchImpl(target, { method: 'GET' });
69
- if (!response.ok)
70
- throw new Error(`Download failed with HTTP ${response.status}: ${url}`);
71
- return new Uint8Array(await response.arrayBuffer());
117
+ this.sent.count += 1;
118
+ const timeoutMs = this.options.timeoutMs ?? requestTimeoutOverrideMs() ?? DEFAULT_DOWNLOAD_TIMEOUT_MS;
119
+ return withTimeout(timeoutMs, `download ${url}`, undefined, async (signal) => {
120
+ const response = await this.fetchImpl(target, { method: 'GET', signal });
121
+ if (!response.ok)
122
+ throw new Error(`Download failed with HTTP ${response.status}: ${url}`);
123
+ return new Uint8Array(await response.arrayBuffer());
124
+ });
72
125
  }
73
126
  }
127
+ // Bounds the whole exchange (headers and body) so a hung connection can't
128
+ // block past a --wait deadline.
129
+ async function withTimeout(timeoutMs, target, idempotencyKey, run) {
130
+ // A ref'd timer (unlike AbortSignal.timeout) keeps the process alive until
131
+ // the deadline, and is cleared as soon as the exchange settles.
132
+ const controller = new AbortController();
133
+ const timer = setTimeout(() => controller.abort(new DOMException('The request timed out.', 'TimeoutError')), timeoutMs);
134
+ const signal = controller.signal;
135
+ try {
136
+ return await run(signal);
137
+ }
138
+ catch (error) {
139
+ if (signal.aborted || isAbortError(error)) {
140
+ throw new AgentRequestError('request_timeout', `Request timed out after ${Math.round(timeoutMs / 1000)}s (${target}). The server may still finish the work: check its status before retrying. Raise the limit with COAUTHOR_CLI_REQUEST_TIMEOUT_MS.`, idempotencyKey);
141
+ }
142
+ if (error instanceof TypeError && /fetch failed|network|ECONN|ENOTFOUND|EAI_AGAIN|socket/i.test(`${error.message} ${String(error.cause ?? '')}`)) {
143
+ throw new AgentRequestError('network_error', `Network error (${target}): ${error.message}`, idempotencyKey);
144
+ }
145
+ throw error;
146
+ }
147
+ finally {
148
+ clearTimeout(timer);
149
+ }
150
+ }
151
+ function isAbortError(error) {
152
+ const name = error?.name;
153
+ return name === 'TimeoutError' || name === 'AbortError';
154
+ }
74
155
  export function isLiveAction(method) {
75
156
  return !['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase());
76
157
  }
@@ -1,3 +1,4 @@
1
+ import { spawn } from 'node:child_process';
1
2
  import { AgentClient, type JsonValue } from './client.js';
2
3
  import { type ConfigPaths } from './config.js';
3
4
  import type { CommandResult } from './output.js';
@@ -9,6 +10,7 @@ export type CommandContext = {
9
10
  token: string;
10
11
  };
11
12
  export declare function runCommand(input: ParsedCommand, context: CommandContext): Promise<CommandResult>;
13
+ export declare function openBrowser(url: string, spawnImpl?: typeof spawn, warn?: (line: string) => void): void;
12
14
  /**
13
15
  * `--cta save,follow,custom:Join the webinar` -> the web app's cta_variants
14
16
  * list (at most 4 endings, at most one custom).
package/dist/commands.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { setTimeout as sleep } from 'node:timers/promises';
2
2
  import { spawn } from 'node:child_process';
3
- import { createHash } from 'node:crypto';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
4
  import { existsSync } from 'node:fs';
5
5
  import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
6
6
  import { homedir } from 'node:os';
7
7
  import { basename, dirname, join, resolve } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
- import { AgentHttpError, normalizeBaseUrl } from './client.js';
9
+ import { AgentHttpError, AgentRequestError, normalizeBaseUrl } from './client.js';
10
10
  import { clearConfig, loadConfig, saveConfig } from './config.js';
11
11
  import { getBoolean, getString, parseJsonOption, readJsonOptionText } from './parser.js';
12
12
  export async function runCommand(input, context) {
@@ -74,8 +74,32 @@ async function runAuthCommand(action, input, context) {
74
74
  const token = getString(input.values, 'token');
75
75
  const baseUrl = getString(input.values, 'base-url') ?? context.baseUrl;
76
76
  if (token) {
77
- await saveConfig({ ...(await loadConfig(context.paths)), baseUrl, token }, context.paths);
78
- return { ok: true, message: `Logged in to ${baseUrl}`, data: { baseUrl, authenticated: true } };
77
+ // Check the token before saving it, so a typo or a revoked token fails
78
+ // here instead of on the next command.
79
+ if (!AGENT_TOKEN_PATTERN.test(token.trim())) {
80
+ throw new Error('Invalid token format: CoAuthor tokens look like coa_<16 hex characters>_<secret>. Copy the whole token, or run `coauthor auth login` without --token to sign in in the browser.');
81
+ }
82
+ let status;
83
+ try {
84
+ status = await context.client.withCredentials({ baseUrl, token: token.trim() }).request({ path: 'auth/status' });
85
+ }
86
+ catch (error) {
87
+ if (error instanceof AgentHttpError && error.status === 401) {
88
+ throw new Error(`The server rejected this token (${extractErrorMessage(error)}). Nothing was saved. Create a new token, or run \`coauthor auth login\` without --token.`);
89
+ }
90
+ throw error;
91
+ }
92
+ await saveConfig({ ...(await loadConfig(context.paths)), baseUrl, token: token.trim() }, context.paths);
93
+ return {
94
+ ok: true,
95
+ message: `Logged in to ${baseUrl}`,
96
+ data: {
97
+ baseUrl,
98
+ authenticated: true,
99
+ tokenPrefix: getResponseString(status, 'token_prefix') ?? null,
100
+ scopes: getResponseValue(status, 'scopes') ?? [],
101
+ },
102
+ };
79
103
  }
80
104
  const start = await context.client.request({
81
105
  method: 'POST',
@@ -98,8 +122,9 @@ async function runAuthCommand(action, input, context) {
98
122
  ].join('\n'));
99
123
  const deadline = Date.now() + expiresInSeconds * 1000;
100
124
  let tokenResponse = null;
125
+ let delayMs = intervalSeconds * 1000;
101
126
  while (Date.now() < deadline) {
102
- await sleep(intervalSeconds * 1000);
127
+ await sleep(Math.max(0, Math.min(delayMs, deadline - Date.now())));
103
128
  try {
104
129
  tokenResponse = await context.client.request({
105
130
  method: 'POST',
@@ -109,8 +134,16 @@ async function runAuthCommand(action, input, context) {
109
134
  break;
110
135
  }
111
136
  catch (error) {
112
- if (isAuthorizationPending(error))
137
+ if (isAuthorizationPending(error)) {
138
+ delayMs = intervalSeconds * 1000;
139
+ continue;
140
+ }
141
+ // A deploy or a network blip must not abort the sign-in: back off and
142
+ // keep polling until the code expires.
143
+ if (isTransientPollError(error)) {
144
+ delayMs = Math.min(Math.max(delayMs, intervalSeconds * 1000) * 2, 30_000);
113
145
  continue;
146
+ }
114
147
  throw error;
115
148
  }
116
149
  }
@@ -156,16 +189,32 @@ async function runAuthCommand(action, input, context) {
156
189
  data: { authenticated: false, remoteRevoked: null, localOnly },
157
190
  };
158
191
  }
159
- if (localOnly) {
192
+ // The token in use can come from --token or COAUTHOR_TOKEN rather than
193
+ // the saved config. Only remove the saved config when it holds that same
194
+ // token; a different saved login stays.
195
+ const storedToken = (await loadConfig(context.paths)).token;
196
+ const clearStoredIfSame = async () => {
197
+ if (storedToken !== context.token)
198
+ return false;
160
199
  await clearConfig(context.paths);
200
+ return true;
201
+ };
202
+ const keptNote = (removed) => removed || !storedToken
203
+ ? ''
204
+ : ' The token came from --token or COAUTHOR_TOKEN, so the different token saved in the local config was kept.';
205
+ if (localOnly) {
206
+ const removed = await clearStoredIfSame();
161
207
  return {
162
208
  ok: true,
163
- message: 'Local credentials removed without revoking the remote token.',
209
+ message: removed
210
+ ? 'Local credentials removed without revoking the remote token.'
211
+ : `Did not revoke the remote token. No saved login holds this token (it came from --token or COAUTHOR_TOKEN), so nothing local was removed${storedToken ? ' and the different saved login was kept' : ''}.`,
164
212
  data: {
165
213
  authenticated: false,
166
214
  remoteRevoked: false,
167
215
  localOnly: true,
168
216
  remoteTokenMayRemainActive: true,
217
+ ...(removed ? {} : { localConfigCleared: false }),
169
218
  },
170
219
  };
171
220
  }
@@ -177,25 +226,27 @@ async function runAuthCommand(action, input, context) {
177
226
  if (!inactiveCode) {
178
227
  throw new Error('Could not confirm remote token revocation. Local credentials were kept so you can retry `coauthor auth logout`. Use `coauthor auth logout --local-only` only to remove the local token without revoking it remotely.');
179
228
  }
180
- await clearConfig(context.paths);
229
+ const removed = await clearStoredIfSame();
181
230
  return {
182
231
  ok: true,
183
- message: inactiveCode === 'token_revoked'
184
- ? 'Logged out; the remote token was already revoked and local credentials were removed.'
185
- : 'Logged out; the remote token was already expired and local credentials were removed.',
232
+ message: (inactiveCode === 'token_revoked'
233
+ ? 'Logged out; the remote token was already revoked'
234
+ : 'Logged out; the remote token was already expired')
235
+ + (removed ? ' and local credentials were removed.' : '.') + keptNote(removed),
186
236
  data: {
187
237
  authenticated: false,
188
238
  remoteRevoked: true,
189
239
  localOnly: false,
190
240
  alreadyInactive: true,
241
+ ...(removed ? {} : { localConfigCleared: false }),
191
242
  },
192
243
  };
193
244
  }
194
- await clearConfig(context.paths);
245
+ const removed = await clearStoredIfSame();
195
246
  return {
196
247
  ok: true,
197
- message: 'Logged out; remote token revoked and local credentials removed.',
198
- data: { authenticated: false, remoteRevoked: true, localOnly: false },
248
+ message: `Logged out; remote token revoked${removed ? ' and local credentials removed.' : '.'}${keptNote(removed)}`,
249
+ data: { authenticated: false, remoteRevoked: true, localOnly: false, ...(removed ? {} : { localConfigCleared: false }) },
199
250
  };
200
251
  }
201
252
  throw new Error('Usage: coauthor auth <login|status|logout>');
@@ -225,11 +276,17 @@ async function runProjectCommand(action, input, client) {
225
276
  body.contract = parseJsonOption(input.values, 'contract');
226
277
  }
227
278
  const data = await client.request({ method: 'POST', path: 'projects', body });
228
- return { ok: true, message: 'Project created', data };
279
+ const projectId = extractNestedString(data, ['project', 'id']);
280
+ return { ok: true, message: projectId ? `Project created: ${projectId}` : 'Project created', data };
229
281
  }
230
282
  if (action === 'list') {
231
- const data = await client.request({ path: withQuery('projects', input.values, ['limit', 'cursor']) });
232
- return { ok: true, data };
283
+ const status = getString(input.values, 'status');
284
+ if (status !== undefined && !PROJECT_LIST_STATUSES.includes(status)) {
285
+ throw new Error(`Unknown --status "${status}". Use one of: ${PROJECT_LIST_STATUSES.join(', ')}.`);
286
+ }
287
+ const data = await client.request({ path: withQuery('projects', input.values, ['limit', 'cursor', 'status']) });
288
+ const nextCursor = getResponseString(data, 'next_cursor');
289
+ return { ok: true, message: nextCursor ? `More projects: coauthor project list --cursor ${nextCursor}` : undefined, data };
233
290
  }
234
291
  if (action === 'show') {
235
292
  const projectId = requireProjectId(input);
@@ -265,6 +322,21 @@ async function runProjectCommand(action, input, client) {
265
322
  }
266
323
  throw new Error('Usage: coauthor project <create|list|show|rename|delete|duplicate>');
267
324
  }
325
+ // The project's workflow state (project_state) or its publication status.
326
+ const PROJECT_LIST_STATUSES = [
327
+ 'topic_discussion',
328
+ 'topic_committed',
329
+ 'outline_discussion',
330
+ 'outline_locked',
331
+ 'research_planning',
332
+ 'research_running',
333
+ 'research_complete',
334
+ 'research_structured',
335
+ 'draft_generated',
336
+ 'editing',
337
+ 'submitted',
338
+ 'published',
339
+ ];
268
340
  async function runWorkspaceCommand(action, input, client) {
269
341
  if (action !== 'show')
270
342
  throw new Error('Usage: coauthor workspace show <projectId>');
@@ -391,7 +463,7 @@ async function runShareCommand(input, client) {
391
463
  async function runModelsCommand(action, input, client) {
392
464
  if (!action || action === 'list') {
393
465
  const data = await client.request({ path: 'models' });
394
- return { ok: true, message: formatModelsList(data), data };
466
+ return { ok: true, message: formatModelsList(data), messageIncludesData: true, data };
395
467
  }
396
468
  if (action === 'preferences') {
397
469
  const subaction = input.command[2] ?? 'show';
@@ -647,18 +719,43 @@ async function waitForRevision(client, projectId, revisionId) {
647
719
  return null;
648
720
  }
649
721
  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`.';
722
+ // The actions each resource supports on the Agent API. Anything else used to
723
+ // reach the server and come back as "Agent API route not found".
724
+ const RESOURCE_ACTIONS = {
725
+ images: ['list', 'status', 'show', 'generate', 'edit', 'metadata'],
726
+ threads: ['list', 'show', 'status', 'generate', 'save', 'create'],
727
+ slideshows: ['list', 'show', 'status', 'generate', 'save'],
728
+ publish: ['thread'],
729
+ exports: ['list', 'blog', 'clickminded', 'wordpress'],
730
+ };
731
+ function resourceUsage(resource) {
732
+ const name = resourceCommandName(resource);
733
+ return `Usage: coauthor ${name} <${RESOURCE_ACTIONS[resource]?.join('|') ?? 'list'}> <project-id> [...]. Run \`coauthor ${name} --help\` for details.`;
734
+ }
650
735
  async function runResourceCommand(resource, action, input, client) {
651
736
  const projectId = getString(input.values, 'project') ?? input.positionals[0];
652
737
  const resourceId = getString(input.values, 'id') ?? input.positionals[1];
653
- const basePath = projectId
654
- ? `projects/${encodeURIComponent(projectId)}/${resource}`
655
- : resource;
656
- if (!action || action === 'list') {
657
- const data = await client.request({ path: withQuery(basePath, input.values, ['limit', 'cursor', 'status']) });
738
+ const name = resourceCommandName(resource);
739
+ const resolvedAction = action ?? (resource === 'publish' ? undefined : 'list');
740
+ if (!resolvedAction || !RESOURCE_ACTIONS[resource]?.includes(resolvedAction)) {
741
+ throw new Error(action ? `Unknown ${name} command: ${action}. ${resourceUsage(resource)}` : resourceUsage(resource));
742
+ }
743
+ if (!projectId)
744
+ throw new Error(`Missing project id. Usage: coauthor ${name} ${resolvedAction} <project-id> [...]`);
745
+ const basePath = `projects/${encodeURIComponent(projectId)}/${resource}`;
746
+ if (resolvedAction === 'list') {
747
+ // These lists return everything for the project; the server has no
748
+ // filters or pages for them, so don't pretend to send any.
749
+ for (const flag of ['status', 'cursor', 'limit']) {
750
+ if (getString(input.values, flag) !== undefined) {
751
+ throw new Error(`${name} list does not support --${flag}; it always returns every ${name === 'export' ? 'export' : 'item'} for the project.`);
752
+ }
753
+ }
754
+ const data = await client.request({ path: basePath });
658
755
  return { ok: true, data };
659
756
  }
660
- if (action === 'show' || action === 'status') {
661
- if (resource === 'images' && action === 'status') {
757
+ if (resolvedAction === 'show' || resolvedAction === 'status') {
758
+ if (resource === 'images' && resolvedAction === 'status') {
662
759
  const data = await client.request({ path: `${basePath}/status` });
663
760
  return { ok: true, data };
664
761
  }
@@ -667,45 +764,24 @@ async function runResourceCommand(resource, action, input, client) {
667
764
  return { ok: true, data };
668
765
  }
669
766
  if (!resourceId)
670
- throw new Error(`Usage: coauthor ${resourceCommandName(resource)} ${action} <projectId> <id>`);
767
+ throw new Error(`Usage: coauthor ${name} ${resolvedAction} <projectId> <id>`);
671
768
  const data = await client.request({ path: `${basePath}/${encodeURIComponent(resourceId)}` });
672
769
  return { ok: true, data };
673
770
  }
674
- if (resource === 'publish' && action === 'thread') {
675
- if (!projectId)
676
- throw new Error('Missing project id for publish thread');
771
+ if (resource === 'publish' && resolvedAction === 'thread') {
677
772
  if (!getBoolean(input.values, 'yes'))
678
773
  throw new Error('Live publish requires --yes');
679
- const data = await client.request({ method: 'POST', path: `${basePath}/thread`, body: parseJsonOption(input.values) });
680
- return { ok: true, data };
774
+ return liveOperationRequest(client, input, `${basePath}/thread`, parseJsonOption(input.values));
681
775
  }
682
- if (resource === 'exports' && (action === 'blog' || action === 'clickminded' || action === 'wordpress')) {
683
- if (!projectId)
684
- throw new Error(`Missing project id for export ${action}`);
776
+ if (resource === 'exports') {
685
777
  if (!getBoolean(input.values, 'yes'))
686
778
  throw new Error('Live export requires --yes');
687
- const body = withNamedOptions(parseJsonOption(input.values), input.values, [
688
- 'slug',
689
- 'status',
690
- 'permalink',
691
- 'connection-id',
692
- 'format',
693
- ]);
694
- if (typeof body.connectionId === 'string') {
695
- body.integration_id = body.connectionId;
696
- delete body.connectionId;
697
- }
698
- const data = await client.request({ method: 'POST', path: `${basePath}/${action}`, body });
699
- return { ok: true, data };
779
+ return liveOperationRequest(client, input, `${basePath}/${resolvedAction}`, exportRequestBody(resolvedAction, input));
700
780
  }
701
- if (resource === 'images' && action === 'generate' && getBoolean(input.values, 'all')) {
702
- if (!projectId)
703
- throw new Error('Usage: coauthor image generate <project-id> --all [--wait]');
781
+ if (resource === 'images' && resolvedAction === 'generate' && getBoolean(input.values, 'all')) {
704
782
  return generateAllImages(client, projectId, getBoolean(input.values, 'wait'));
705
783
  }
706
- if (resource === 'images' && action === 'metadata') {
707
- if (!projectId)
708
- throw new Error('Missing project id for image metadata');
784
+ if (resource === 'images' && resolvedAction === 'metadata') {
709
785
  if (!resourceId) {
710
786
  throw new Error('Usage: coauthor image metadata <projectId> <placeholderId> [--alt-text <text>] [--description <text>] [--file-slug <slug>]');
711
787
  }
@@ -728,28 +804,81 @@ async function runResourceCommand(resource, action, input, client) {
728
804
  });
729
805
  return { ok: true, data };
730
806
  }
731
- if (['create', 'generate', 'save', 'edit', 'publish', 'export', 'cancel', 'retry'].includes(action)) {
732
- if (!projectId)
733
- throw new Error(`Missing project id for ${resourceCommandName(resource)} ${action}`);
734
- const body = withNamedOptions(parseJsonOption(input.values), input.values, [
735
- 'prompt',
736
- 'format',
737
- 'target',
738
- 'thread',
739
- 'image',
740
- 'id',
741
- 'placeholder-id',
742
- 'execution-token',
743
- 'grounding-mode',
744
- 'image-generation-model',
745
- ...(resource === 'threads' && action === 'generate' ? ['writing-model'] : []),
746
- 'edit-prompt',
747
- ]);
748
- const path = action === 'create' && resource !== 'threads' ? basePath : `${basePath}/${action}`;
749
- const data = await client.request({ method: 'POST', path, body });
750
- return { ok: true, data };
807
+ if (getString(input.values, 'prompt') !== undefined) {
808
+ // No resource endpoint reads a free-form prompt (images are built from the
809
+ // placeholder's planned brief), so --prompt used to be silently dropped.
810
+ throw new Error(resource === 'images'
811
+ ? `image ${resolvedAction} does not take --prompt. Generate the image first, then direct changes with \`coauthor image edit <project-id> --placeholder-id <id> --edit-prompt "..."\`.`
812
+ : `${name} ${resolvedAction} does not take --prompt.`);
813
+ }
814
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, [
815
+ 'format',
816
+ 'target',
817
+ 'thread',
818
+ 'image',
819
+ 'id',
820
+ 'placeholder-id',
821
+ 'execution-token',
822
+ 'grounding-mode',
823
+ 'image-generation-model',
824
+ ...(resource === 'threads' && resolvedAction === 'generate' ? ['writing-model'] : []),
825
+ 'edit-prompt',
826
+ ]);
827
+ const path = resolvedAction === 'create' && resource !== 'threads' ? basePath : `${basePath}/${resolvedAction}`;
828
+ const data = await client.request({ method: 'POST', path, body });
829
+ return { ok: true, data };
830
+ }
831
+ // Publish and export run as recorded operations keyed by the Idempotency-Key.
832
+ // Print the key so the caller can look the outcome up (`operation status`) or
833
+ // replay the same request safely with --idempotency-key.
834
+ async function liveOperationRequest(client, input, path, body) {
835
+ const idempotencyKey = getString(input.values, 'idempotency-key')?.trim() || randomUUID();
836
+ const data = await client.request({ method: 'POST', path, body, idempotencyKey });
837
+ const replayed = getResponseValue(data, 'replayed') === true;
838
+ return {
839
+ ok: true,
840
+ message: `${replayed ? 'Replayed recorded operation' : 'Done'}. Operation key: ${idempotencyKey} (coauthor operation status ${idempotencyKey} --json).`,
841
+ idempotency_key: idempotencyKey,
842
+ data,
843
+ };
844
+ }
845
+ const EXPORT_STATUSES = ['draft', 'published'];
846
+ function exportRequestBody(action, input) {
847
+ const body = parseJsonOption(input.values);
848
+ const status = getString(input.values, 'status');
849
+ if (status !== undefined && !EXPORT_STATUSES.includes(status)) {
850
+ throw new Error(`--status must be draft or published (got "${status}").`);
851
+ }
852
+ const slug = getString(input.values, 'slug');
853
+ const description = getString(input.values, 'description');
854
+ if (action === 'wordpress') {
855
+ if (status !== undefined)
856
+ throw new Error('export wordpress always creates a WordPress draft; it does not take --status.');
857
+ if (slug !== undefined)
858
+ body.slug = slug;
859
+ const connectionId = getString(input.values, 'connection-id');
860
+ if (connectionId !== undefined)
861
+ body.integration_id = connectionId;
862
+ return body;
863
+ }
864
+ if (action === 'clickminded') {
865
+ const permalink = getString(input.values, 'permalink') ?? slug;
866
+ if (permalink !== undefined)
867
+ body.permalink = permalink;
868
+ if (status !== undefined)
869
+ body.published = status === 'published';
870
+ if (description !== undefined)
871
+ body.seoDescription = description;
872
+ return body;
751
873
  }
752
- throw new Error(`Unknown ${resourceCommandName(resource)} command: ${action}`);
874
+ // blog
875
+ if (slug !== undefined)
876
+ body.slug = slug;
877
+ if (status !== undefined)
878
+ body.status = status;
879
+ if (description !== undefined)
880
+ body.description = description;
881
+ return body;
753
882
  }
754
883
  async function runOperationCommand(action, input, client) {
755
884
  const key = getString(input.values, 'id') ?? input.positionals[0];
@@ -799,6 +928,7 @@ async function runSkillsCommand(action, input) {
799
928
  return {
800
929
  ok: true,
801
930
  message: formatSkillInstallMessage(results, warnings, dryRun),
931
+ messageIncludesData: true,
802
932
  data: { results, ...(warnings.length > 0 ? { warnings } : {}) },
803
933
  };
804
934
  }
@@ -1079,18 +1209,37 @@ function isAuthorizationPending(error) {
1079
1209
  return false;
1080
1210
  return envelopeError.code === 'authorization_pending';
1081
1211
  }
1082
- function openBrowser(url) {
1212
+ const AGENT_TOKEN_PATTERN = /^coa_[0-9a-f]{16}_[A-Za-z0-9_-]+$/;
1213
+ function isTransientPollError(error) {
1214
+ if (error instanceof AgentRequestError)
1215
+ return true;
1216
+ if (error instanceof AgentHttpError)
1217
+ return error.status >= 500 || error.status === 429;
1218
+ return false;
1219
+ }
1220
+ // A missing opener (headless Linux without xdg-open) emits 'error' on the
1221
+ // child; without a listener that crashed the CLI. The URL is printed anyway.
1222
+ export function openBrowser(url, spawnImpl = spawn, warn = (line) => process.stderr.write(line)) {
1083
1223
  const command = process.platform === 'darwin'
1084
1224
  ? 'open'
1085
1225
  : process.platform === 'win32'
1086
1226
  ? 'cmd'
1087
1227
  : 'xdg-open';
1088
1228
  const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
1089
- const child = spawn(command, args, {
1090
- detached: true,
1091
- stdio: 'ignore',
1092
- });
1093
- child.unref();
1229
+ const fallback = (error) => {
1230
+ warn(`Could not open a browser (${error instanceof Error ? error.message : String(error)}). Open this URL yourself: ${url}\n`);
1231
+ };
1232
+ try {
1233
+ const child = spawnImpl(command, args, {
1234
+ detached: true,
1235
+ stdio: 'ignore',
1236
+ });
1237
+ child.on('error', fallback);
1238
+ child.unref();
1239
+ }
1240
+ catch (error) {
1241
+ fallback(error);
1242
+ }
1094
1243
  }
1095
1244
  async function waitForResearch(client, projectId, initialData, baseUrl) {
1096
1245
  const deadline = Date.now() + waitTimeoutMs(20 * 60_000);
@@ -2190,6 +2339,7 @@ export function helpResult(command = []) {
2190
2339
  'Usage: coauthor <command> [options]',
2191
2340
  '',
2192
2341
  'Global options: --json, --help, --version, --base-url <url>, --token <token>',
2342
+ 'Requests time out after 120s (reads) or 330s (writes); override with COAUTHOR_CLI_REQUEST_TIMEOUT_MS.',
2193
2343
  'JSON options (--data, --contract) also accept @file.json, or @- to read stdin.',
2194
2344
  '',
2195
2345
  'Commands:',
@@ -2215,8 +2365,8 @@ export function helpResult(command = []) {
2215
2365
  ' image list|status|show|generate|edit|metadata',
2216
2366
  ' thread list|show|create|generate|save',
2217
2367
  ' slideshow show|save',
2218
- ' publish thread',
2219
- ' export list|wordpress',
2368
+ ' publish thread (supports --idempotency-key)',
2369
+ ' export list|wordpress (supports --idempotency-key)',
2220
2370
  ' operation list|show|status',
2221
2371
  ' credits',
2222
2372
  ' share <project-id>',
@@ -2229,6 +2379,12 @@ export function helpResult(command = []) {
2229
2379
  function commandHelp(command) {
2230
2380
  const key = command.join(' ');
2231
2381
  const help = {
2382
+ 'auth login': [
2383
+ 'Usage: coauthor auth login [--with-publish] [--no-browser] [--token <coa_...>] [--base-url <url>] [--json]',
2384
+ '',
2385
+ 'Signs in through the browser (device code). Without a browser, the URL is printed to open elsewhere.',
2386
+ '--token saves an existing token after checking its format and verifying it with the server.',
2387
+ ].join('\n'),
2232
2388
  'auth logout': [
2233
2389
  'Usage: coauthor auth logout [--local-only] [--json]',
2234
2390
  '',
@@ -2286,7 +2442,8 @@ function commandHelp(command) {
2286
2442
  project: [
2287
2443
  'Usage: coauthor project <create|list|show|rename|delete|duplicate> [<project-id>] [--title "..."] [--yes] [--json]',
2288
2444
  '',
2289
- 'create: --title, --topic, --audience, --contract <json|@file>. list: --limit. show: one project.',
2445
+ 'create: --title, --topic, --audience, --contract <json|@file>. show: one project.',
2446
+ 'list: --limit <n> (1-100), --cursor <next_cursor from the previous page>, --status <state> (a project_state such as research_running or editing, or the publication status submitted|published).',
2290
2447
  'duplicate <project-id> [--title "..."]: copies the brief, outline, research, chats, draft, images and repurposed posts into a new project that keeps the same profile (default title is "<title> (Copy)"). Prints the new project id.',
2291
2448
  ].join('\n'),
2292
2449
  profile: [
@@ -2378,7 +2535,7 @@ function commandHelp(command) {
2378
2535
  'Usage: coauthor image <list|status|show|generate|edit|metadata> <project-id> [...] [--json]',
2379
2536
  ' coauthor image generate <project-id> --all [--wait] [--json] (every planned image; --wait until they finish)',
2380
2537
  '',
2381
- 'list: planned placeholders (use each id). generate/edit: --placeholder-id <id> [--edit-prompt "..."]. status: generation progress.',
2538
+ 'list: planned placeholders. generate/edit: --placeholder-id <id or placeholder_id> [--edit-prompt "..."]. status: generation progress.',
2382
2539
  'metadata <project-id> <placeholder id>: --alt-text, --description, --file-slug.',
2383
2540
  ].join('\n'),
2384
2541
  thread: [
@@ -2388,15 +2545,17 @@ function commandHelp(command) {
2388
2545
  'save takes {"posts":[...], "destination_url"?, "selected_social_account_id"?}. Publish with: coauthor publish thread <project-id> --yes',
2389
2546
  ].join('\n'),
2390
2547
  publish: [
2391
- 'Usage: coauthor publish thread <project-id> --yes [--json]',
2548
+ 'Usage: coauthor publish thread <project-id> --yes [--idempotency-key <key>] [--json]',
2392
2549
  '',
2393
2550
  'Posts the X thread now. Needs a login with publish permission: coauthor auth login --with-publish',
2551
+ 'Prints the operation key (data.idempotency_key in --json). If the command is interrupted, check it with coauthor operation status <key>, or rerun with --idempotency-key <key> to replay instead of posting twice.',
2394
2552
  ].join('\n'),
2395
2553
  export: [
2396
2554
  'Usage: coauthor export list <project-id> [--json]',
2397
- ' coauthor export wordpress <project-id> --yes --slug <slug> [--connection-id <id>] [--json]',
2555
+ ' coauthor export wordpress <project-id> --yes --slug <slug> [--connection-id <id>] [--idempotency-key <key>] [--json]',
2398
2556
  '',
2399
2557
  'wordpress creates a draft post on the connected WordPress site and returns wordpress_edit_url.',
2558
+ 'The export prints its operation key; check it with coauthor operation status <key>, or rerun with --idempotency-key <key> to replay safely.',
2400
2559
  'Needs a login with publish permission (coauthor auth login --with-publish). With several sites connected, the error lists their ids for --connection-id.',
2401
2560
  ].join('\n'),
2402
2561
  share: [
@@ -2437,7 +2596,8 @@ function commandHelp(command) {
2437
2596
  'image generate': [
2438
2597
  'Usage: coauthor image generate <project-id> --placeholder-id <id> [--grounding-mode <mode>] [--image-generation-model <id>] [--json]',
2439
2598
  '',
2440
- 'Pass the placeholder `id` from coauthor image list. Draft generation creates placeholders.',
2599
+ 'Pass the placeholder `id` (UUID) or its `placeholder_id` from coauthor image list. Draft generation creates placeholders.',
2600
+ 'Images are drawn from the planned brief; to steer one, generate it and then use coauthor image edit --edit-prompt.',
2441
2601
  'Generation is asynchronous: poll coauthor image status <project-id> --json until it is done.',
2442
2602
  ].join('\n'),
2443
2603
  'image edit': [
package/dist/index.d.ts CHANGED
@@ -1,2 +1,15 @@
1
1
  #!/usr/bin/env node
2
- export declare function main(argv?: string[]): Promise<number>;
2
+ import { type JsonValue } from './client.js';
3
+ export type CliIo = {
4
+ stdout: (text: string) => void;
5
+ stderr: (text: string) => void;
6
+ };
7
+ export declare function main(argv?: string[], io?: CliIo): Promise<number>;
8
+ export declare function formatCliError(error: unknown, baseUrl: string, argv?: string[], context?: {
9
+ requestsSent?: number;
10
+ }): {
11
+ error: Error;
12
+ result?: JsonValue;
13
+ exitCode: number;
14
+ };
15
+ export declare function resolveProjectIdFromArgv(argv: string[]): string | undefined;
package/dist/index.js CHANGED
@@ -1,21 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync, realpathSync } from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { AgentHttpError, AgentClient, normalizeBaseUrl } from './client.js';
4
+ import { AgentHttpError, AgentClient, AgentRequestError, normalizeBaseUrl } from './client.js';
5
5
  import { DEFAULT_BASE_URL, resolveRuntimeConfig } from './config.js';
6
6
  import { helpResult, runCommand } from './commands.js';
7
7
  import { renderError, renderResult } from './output.js';
8
- import { parseCliArgs } from './parser.js';
9
- export async function main(argv = process.argv.slice(2)) {
8
+ import { getString, optionTakesValue, parseCliArgs } from './parser.js';
9
+ const processIo = {
10
+ stdout: (text) => { process.stdout.write(text); },
11
+ stderr: (text) => { process.stderr.write(text); },
12
+ };
13
+ export async function main(argv = process.argv.slice(2), io = processIo) {
10
14
  let resolvedBaseUrl = resolveBaseUrlFromArgv(argv);
15
+ let client;
11
16
  try {
12
17
  const parsed = parseCliArgs(argv);
13
18
  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`);
19
+ io.stdout(parsed.globals.json ? `${JSON.stringify({ ok: true, version: cliVersion() })}\n` : `${cliVersion()}\n`);
15
20
  return 0;
16
21
  }
17
22
  if (parsed.globals.help) {
18
- process.stdout.write(renderResult(helpResult(parsed.command), parsed.globals.json));
23
+ io.stdout(renderResult(helpResult(parsed.command), parsed.globals.json));
19
24
  return 0;
20
25
  }
21
26
  const runtimeConfig = await resolveRuntimeConfig({
@@ -23,57 +28,107 @@ export async function main(argv = process.argv.slice(2)) {
23
28
  tokenOverride: parsed.globals.token,
24
29
  });
25
30
  resolvedBaseUrl = runtimeConfig.baseUrl;
26
- const client = new AgentClient(runtimeConfig);
31
+ client = new AgentClient(runtimeConfig);
27
32
  const result = await runCommand(parsed, {
28
33
  client,
29
34
  baseUrl: runtimeConfig.baseUrl,
30
35
  token: runtimeConfig.token,
31
36
  });
32
- process.stdout.write(renderResult(result, parsed.globals.json));
37
+ // Failures and pauses (ok: false) go to stderr whether they came from a
38
+ // thrown HTTP error or a --wait loop, so callers read one stream for them.
39
+ const output = renderResult(result, parsed.globals.json);
40
+ if (result.ok)
41
+ io.stdout(output);
42
+ else
43
+ io.stderr(output);
33
44
  return result.exitCode ?? (result.ok ? 0 : 1);
34
45
  }
35
46
  catch (error) {
36
47
  const wantsJson = argv.includes('--json');
37
- const formatted = formatCliError(error, resolvedBaseUrl, argv);
38
- process.stderr.write(renderError(formatted.result ?? formatted.error, wantsJson));
48
+ const formatted = formatCliError(error, resolvedBaseUrl, argv, { requestsSent: client?.requestsSent ?? 0 });
49
+ io.stderr(wantsJson
50
+ ? renderError(formatted.result ?? formatted.error, true)
51
+ : renderError(formatted.error, false));
39
52
  return formatted.exitCode;
40
53
  }
41
54
  }
42
- function formatCliError(error, baseUrl, argv = []) {
55
+ export function formatCliError(error, baseUrl, argv = [], context = {}) {
43
56
  if (error instanceof AgentHttpError) {
57
+ // Keep the server's error code and details (e.g. the current draft version
58
+ // on a 409) on every --json error so agents can recover without guessing.
59
+ const envelope = extractEnvelopeError(error.responseBody);
60
+ const errorFields = {
61
+ ...(envelope?.code ? { code: envelope.code } : {}),
62
+ http_status: error.status,
63
+ ...(envelope?.details !== undefined ? { details: envelope.details } : {}),
64
+ ...(error.idempotencyKey ? { idempotency_key: error.idempotencyKey } : {}),
65
+ };
66
+ const operationHint = operationLookupHint(envelope?.details, error.idempotencyKey);
44
67
  const entitlement = formatEntitlementResult(error.responseBody);
45
68
  if (entitlement)
46
- return { error: new Error(entitlement.message), result: entitlement, exitCode: 2 };
69
+ return { error: new Error(entitlement.message), result: { ...entitlement, ...errorFields }, exitCode: 2 };
47
70
  const requiresKey = formatRequiresKeyResult(error.responseBody, baseUrl);
48
71
  if (requiresKey)
49
- return { error: new Error(requiresKey.message), result: requiresKey, exitCode: 2 };
72
+ return { error: new Error(requiresKey.message), result: { ...requiresKey, ...errorFields }, exitCode: 2 };
50
73
  const serverMessage = extractErrorMessage(error.responseBody) ?? error.message;
51
74
  const message = error.status === 401
52
75
  ? `${serverMessage}\nSign in with \`coauthor auth login\` (or set COAUTHOR_TOKEN).`
53
76
  : serverMessage;
54
77
  const researchBlock = formatResearchDraftBlock(message, argv);
55
78
  if (researchBlock)
56
- return { error: new Error(researchBlock.message), result: researchBlock, exitCode: 2 };
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);
79
+ return { error: new Error(researchBlock.message), result: { ...researchBlock, code: researchBlock.status, ...errorFields }, exitCode: 2 };
60
80
  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;
81
+ const humanMessage = [
82
+ current
83
+ ? `${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.`
84
+ : message,
85
+ operationHint,
86
+ ].filter(Boolean).join('\n');
64
87
  return {
65
88
  error: new Error(humanMessage),
66
89
  result: {
67
90
  ok: false,
68
91
  error: humanMessage,
69
- ...(envelope?.code ? { code: envelope.code } : {}),
70
- http_status: error.status,
71
- ...(envelope?.details !== undefined ? { details: envelope.details } : {}),
92
+ code: envelope?.code ?? `http_${error.status}`,
93
+ ...errorFields,
72
94
  },
73
95
  exitCode: 1,
74
96
  };
75
97
  }
76
- return { error: error instanceof Error ? error : new Error(String(error)), exitCode: 1 };
98
+ if (error instanceof AgentRequestError) {
99
+ return {
100
+ error,
101
+ result: {
102
+ ok: false,
103
+ error: error.message,
104
+ code: error.code,
105
+ http_status: null,
106
+ ...(error.idempotencyKey ? { idempotency_key: error.idempotencyKey } : {}),
107
+ },
108
+ exitCode: 1,
109
+ };
110
+ }
111
+ const normalized = error instanceof Error ? error : new Error(String(error));
112
+ return {
113
+ error: normalized,
114
+ // Anything rejected before the first request is the command's own fault
115
+ // (bad flag, missing argument, invalid value): a usage error.
116
+ result: { ok: false, error: normalized.message, code: context.requestsSent === 0 || isUsageMessage(normalized.message) ? 'usage_error' : 'cli_error', http_status: null },
117
+ exitCode: 1,
118
+ };
119
+ }
120
+ function isUsageMessage(message) {
121
+ return /^(Usage:|Unknown option|Unknown command|Missing |Unknown \w+ command)/.test(message) || /Run `coauthor [^`]*--help`/.test(message);
122
+ }
123
+ // Live actions (publish, export) are recorded as operations under the
124
+ // Idempotency-Key the CLI sent. Point at it so a caller can check the outcome
125
+ // instead of retrying blind.
126
+ function operationLookupHint(details, idempotencyKey) {
127
+ if (!idempotencyKey)
128
+ return null;
129
+ if (!details || typeof details !== 'object' || Array.isArray(details) || !('operation' in details))
130
+ return null;
131
+ return `Operation key: ${idempotencyKey} (check it with \`coauthor operation status ${idempotencyKey} --json\`; retry with --idempotency-key ${idempotencyKey} to replay safely).`;
77
132
  }
78
133
  function formatEntitlementResult(body) {
79
134
  const envelopeError = extractEnvelopeError(body);
@@ -144,44 +199,30 @@ function formatResearchDraftBlock(message, argv) {
144
199
  exitCode: 2,
145
200
  };
146
201
  }
147
- function resolveProjectIdFromArgv(argv) {
148
- const projectFlagIndex = argv.indexOf('--project');
149
- if (projectFlagIndex >= 0 && argv[projectFlagIndex + 1])
150
- return argv[projectFlagIndex + 1];
151
- const commandWords = new Set([
152
- 'auth',
153
- 'login',
154
- 'status',
155
- 'logout',
156
- 'project',
157
- 'create',
158
- 'list',
159
- 'show',
160
- 'workspace',
161
- 'chat',
162
- 'contract',
163
- 'outline',
164
- 'research-plan',
165
- 'research',
166
- 'run',
167
- 'draft',
168
- 'generate',
169
- 'get',
170
- 'save',
171
- 'workflow',
172
- 'advance',
173
- 'rewind',
174
- 'approve',
175
- 'resume',
176
- 'image',
177
- 'thread',
178
- 'publish',
179
- 'export',
180
- 'operation',
181
- 'credits',
182
- 'skills',
183
- ]);
184
- return argv.find((arg) => !arg.startsWith('-') && !commandWords.has(arg));
202
+ export function resolveProjectIdFromArgv(argv) {
203
+ try {
204
+ const parsed = parseCliArgs(argv);
205
+ return getString(parsed.values, 'project') ?? parsed.positionals[0];
206
+ }
207
+ catch {
208
+ // Unparseable argv: walk it, skipping the values of flags that take one.
209
+ }
210
+ const words = [];
211
+ for (let index = 0; index < argv.length; index += 1) {
212
+ const arg = argv[index] ?? '';
213
+ if (arg === '--project' && argv[index + 1])
214
+ return argv[index + 1];
215
+ if (arg.startsWith('--project='))
216
+ return arg.slice('--project='.length);
217
+ if (arg.startsWith('-')) {
218
+ if (optionTakesValue(arg))
219
+ index += 1;
220
+ continue;
221
+ }
222
+ words.push(arg);
223
+ }
224
+ const commandWords = new Set(['auth', 'login', 'status', 'logout', 'project', 'create', 'list', 'show', 'workspace', 'chat', 'contract', 'outline', 'research-plan', 'research', 'run', 'draft', 'generate', 'get', 'save', 'workflow', 'advance', 'rewind', 'approve', 'resume', 'image', 'thread', 'publish', 'export', 'operation', 'credits', 'skills']);
225
+ return words.find((word) => !commandWords.has(word));
185
226
  }
186
227
  function extractErrorMessage(body) {
187
228
  if (!body || typeof body !== 'object' || Array.isArray(body) || !('error' in body))
package/dist/output.d.ts CHANGED
@@ -7,6 +7,14 @@ export type CommandResult = {
7
7
  exitCode?: number;
8
8
  settings_url?: string;
9
9
  resume_command?: string;
10
+ /** The Idempotency-Key sent with the command's live request; look it up with `coauthor operation status <key>`. */
11
+ idempotency_key?: string;
12
+ /** Set when `message` already shows everything in `data`, so plain output doesn't print it twice. Never rendered. */
13
+ messageIncludesData?: boolean;
10
14
  };
11
15
  export declare function renderResult(result: CommandResult, json: boolean): string;
12
16
  export declare function renderError(error: unknown, json: boolean): string;
17
+ export declare function withErrorFields<T extends Record<string, unknown>>(value: T): T & {
18
+ code: unknown;
19
+ http_status: unknown;
20
+ };
package/dist/output.js CHANGED
@@ -1,22 +1,40 @@
1
1
  export function renderResult(result, json) {
2
+ const { messageIncludesData, ...printable } = result;
2
3
  if (json)
3
- return `${JSON.stringify(result, null, 2)}\n`;
4
+ return `${JSON.stringify(result.ok ? printable : withErrorFields(printable), null, 2)}\n`;
5
+ // Plain output used to stop at the message, hiding ids and clarification
6
+ // questions. Print the message, then the data behind it.
7
+ const parts = [];
4
8
  if (result.message)
5
- return `${result.message}\n`;
6
- if (result.data === undefined)
7
- return '';
8
- return `${JSON.stringify(result.data, null, 2)}\n`;
9
+ parts.push(result.message);
10
+ if (result.data !== undefined && result.data !== null && !(result.message && messageIncludesData)) {
11
+ parts.push(JSON.stringify(result.data, null, 2));
12
+ }
13
+ return parts.length > 0 ? `${parts.join('\n')}\n` : '';
9
14
  }
10
15
  export function renderError(error, json) {
11
16
  if (json && error && typeof error === 'object' && !Array.isArray(error) && 'ok' in error) {
12
- return `${JSON.stringify(error, null, 2)}\n`;
17
+ return `${JSON.stringify(withErrorFields(error), null, 2)}\n`;
13
18
  }
19
+ const record = error && typeof error === 'object' && !Array.isArray(error) ? error : null;
14
20
  const message = error instanceof Error
15
21
  ? error.message
16
- : error && typeof error === 'object' && !Array.isArray(error) && typeof error.message === 'string'
17
- ? error.message
18
- : String(error);
22
+ : typeof record?.message === 'string'
23
+ ? record.message
24
+ : typeof record?.error === 'string'
25
+ ? record.error
26
+ : String(error);
19
27
  if (json)
20
- return `${JSON.stringify({ ok: false, error: message }, null, 2)}\n`;
28
+ return `${JSON.stringify({ ok: false, error: message, code: 'cli_error', http_status: null }, null, 2)}\n`;
21
29
  return `Error: ${message}\n`;
22
30
  }
31
+ // Every --json failure carries `code` and `http_status` (null when no HTTP
32
+ // response caused it: a pause seen while polling, a usage error, a timeout).
33
+ export function withErrorFields(value) {
34
+ const status = typeof value.status === 'string' ? value.status : undefined;
35
+ return {
36
+ ...value,
37
+ code: value.code ?? status ?? 'failed',
38
+ http_status: value.http_status ?? null,
39
+ };
40
+ }
package/dist/parser.d.ts CHANGED
@@ -25,6 +25,8 @@ export declare const commandInputSchema: z.ZodObject<{
25
25
  }, z.core.$strip>;
26
26
  values: z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodBoolean, z.ZodArray<z.ZodString>]>>>;
27
27
  }, z.core.$strip>;
28
+ /** True when `--name` (or its short alias) consumes the next argv entry as its value. */
29
+ export declare function optionTakesValue(flag: string): boolean;
28
30
  export declare function parseCliArgs(argv: string[]): ParsedCommand;
29
31
  export declare function getString(values: ParsedCommand['values'], name: string): string | undefined;
30
32
  export declare function requireString(values: ParsedCommand['values'], name: string): string;
package/dist/parser.js CHANGED
@@ -76,7 +76,19 @@ const OPTIONS = {
76
76
  apply: { type: 'boolean', default: false },
77
77
  accept: { type: 'string' },
78
78
  reject: { type: 'string' },
79
+ 'idempotency-key': { type: 'string' },
79
80
  };
81
+ /** True when `--name` (or its short alias) consumes the next argv entry as its value. */
82
+ export function optionTakesValue(flag) {
83
+ const name = flag.replace(/^--?/, '').split('=')[0] ?? '';
84
+ if (flag.includes('='))
85
+ return false;
86
+ const entries = Object.entries(OPTIONS);
87
+ const option = flag.startsWith('--')
88
+ ? entries.find(([key]) => key === name)?.[1]
89
+ : entries.find(([, value]) => value.short === name)?.[1];
90
+ return option?.type === 'string';
91
+ }
80
92
  export function parseCliArgs(argv) {
81
93
  let parsed;
82
94
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clickminded/coauthor-cli",
3
- "version": "0.0.32",
3
+ "version": "0.0.34",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "coauthor": "dist/index.js",
@@ -6,7 +6,7 @@ Draft generation plans image placeholders, including a featured image (`is_featu
6
6
 
7
7
  1. `coauthor image list <id> --json` returns `data.placeholders`. Each has an `id` (UUID), a `purpose`, an `image_type`, and the planned brief.
8
8
  2. Generate them all and wait: `coauthor image generate <id> --all --wait --json`. It skips images that are already done, and reports `done`, `failed`, and `still_running` (check again with `coauthor image status <id> --json`). Each image takes about 20 seconds.
9
- 3. To generate one: `coauthor image generate <id> --placeholder-id <id UUID> --json` (the `id` UUID; the descriptive `placeholder_id` string is not accepted; optional `--grounding-mode <mode>`, `--image-generation-model <id>`), then poll `coauthor image status <id> --json`.
9
+ 3. To generate one: `coauthor image generate <id> --placeholder-id <id UUID> --json` (the `id` UUID or the descriptive `placeholder_id`; optional `--grounding-mode <mode>`, `--image-generation-model <id>`), then poll `coauthor image status <id> --json`.
10
10
  4. Check every finished image (the URLs are in `image status` and in `draft get --format markdown`):
11
11
  - Charts and tables must match the article's numbers, and must not state figures the article deliberately leaves open.
12
12
  - Screens of real products (for example a Google or Meta interface) must not be presented as genuine.
@@ -34,4 +34,4 @@ See `references/images-and-social.md`. Publishing a thread posts immediately and
34
34
 
35
35
  ## If a live action's result is unclear
36
36
 
37
- After a network error or an unclear result on an export or publish, do not run it again straight away. Check `coauthor operation list --json` for the operation and its status first, then decide.
37
+ After a network error or an unclear result on an export or publish, do not run it again straight away. Every export and publish prints its `idempotency_key`; check `coauthor operation status <idempotency_key> --json` (or `coauthor operation list --json`) first. To retry safely, pass the same key back with `--idempotency-key <key>`, so CoAuthor won't run it twice.
@@ -30,6 +30,8 @@ Every failure prints JSON on stderr with `ok: false`, `error` (a readable messag
30
30
  | `workflow_token_mismatch`, `conflict` | The project moved on since you read it (for example someone used the web app). | Re-read the state with `coauthor workflow status <id> --json` and continue from there. |
31
31
  | `insufficient_scope` | The token can't publish. | `coauthor auth login --with-publish`. |
32
32
  | `wordpress_connection_required` | Several WordPress sites are connected. | Ask which one from `details.connections`, add `--connection-id`. |
33
+ | `usage_error` | The command or its flags are wrong; nothing was sent. | Check `coauthor help <command>` and fix the command. |
34
+ | `request_timeout`, `network_error` | No answer from CoAuthor in time, or the connection failed. | For reads, retry. For exports and publishes, check `coauthor operation status <idempotency_key>` before retrying. |
33
35
 
34
36
  ## Sign-in
35
37
 
@@ -335,7 +335,7 @@ Draft generation plans image placeholders, including a featured image (`is_featu
335
335
 
336
336
  1. `coauthor image list <id> --json` returns `data.placeholders`. Each has an `id` (UUID), a `purpose`, an `image_type`, and the planned brief.
337
337
  2. Generate them all and wait: `coauthor image generate <id> --all --wait --json`. It skips images that are already done, and reports `done`, `failed`, and `still_running` (check again with `coauthor image status <id> --json`). Each image takes about 20 seconds.
338
- 3. To generate one: `coauthor image generate <id> --placeholder-id <id UUID> --json` (the `id` UUID; the descriptive `placeholder_id` string is not accepted; optional `--grounding-mode <mode>`, `--image-generation-model <id>`), then poll `coauthor image status <id> --json`.
338
+ 3. To generate one: `coauthor image generate <id> --placeholder-id <id UUID> --json` (the `id` UUID or the descriptive `placeholder_id`; optional `--grounding-mode <mode>`, `--image-generation-model <id>`), then poll `coauthor image status <id> --json`.
339
339
  4. Check every finished image (the URLs are in `image status` and in `draft get --format markdown`):
340
340
  - Charts and tables must match the article's numbers, and must not state figures the article deliberately leaves open.
341
341
  - Screens of real products (for example a Google or Meta interface) must not be presented as genuine.
@@ -394,7 +394,7 @@ See `references/images-and-social.md`. Publishing a thread posts immediately and
394
394
 
395
395
  ### If a live action's result is unclear
396
396
 
397
- After a network error or an unclear result on an export or publish, do not run it again straight away. Check `coauthor operation list --json` for the operation and its status first, then decide.
397
+ After a network error or an unclear result on an export or publish, do not run it again straight away. Every export and publish prints its `idempotency_key`; check `coauthor operation status <idempotency_key> --json` (or `coauthor operation list --json`) first. To retry safely, pass the same key back with `--idempotency-key <key>`, so CoAuthor won't run it twice.
398
398
 
399
399
  ## references/repurposing.md
400
400
 
@@ -508,6 +508,8 @@ Every failure prints JSON on stderr with `ok: false`, `error` (a readable messag
508
508
  | `workflow_token_mismatch`, `conflict` | The project moved on since you read it (for example someone used the web app). | Re-read the state with `coauthor workflow status <id> --json` and continue from there. |
509
509
  | `insufficient_scope` | The token can't publish. | `coauthor auth login --with-publish`. |
510
510
  | `wordpress_connection_required` | Several WordPress sites are connected. | Ask which one from `details.connections`, add `--connection-id`. |
511
+ | `usage_error` | The command or its flags are wrong; nothing was sent. | Check `coauthor help <command>` and fix the command. |
512
+ | `request_timeout`, `network_error` | No answer from CoAuthor in time, or the connection failed. | For reads, retry. For exports and publishes, check `coauthor operation status <idempotency_key>` before retrying. |
511
513
 
512
514
  ### Sign-in
513
515