@clickminded/coauthor-cli 0.0.31 → 0.0.33

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,27 +5,47 @@ 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;
38
+ private readonly options;
24
39
  constructor(options: AgentClientOptions);
40
+ /** Same transport and timeouts, different credentials (used to verify a token before saving it). */
41
+ withCredentials(params: {
42
+ baseUrl?: string;
43
+ token: string;
44
+ }): AgentClient;
25
45
  request(options: RequestOptions): Promise<JsonValue>;
26
46
  /**
27
- * Fetches a public file (for example a rendered MP4 on the CDN) as bytes.
28
- * Sends no Authorization header: the URL is not an agent API endpoint.
47
+ * Fetches a public file (a rendered MP4 or slide PNG on the CDN) as bytes.
48
+ * Sends no Authorization header: these URLs are not on the CoAuthor API.
29
49
  */
30
50
  download(url: string): Promise<Uint8Array>;
31
51
  }
package/dist/client.js CHANGED
@@ -8,45 +8,84 @@ 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;
49
+ options;
25
50
  constructor(options) {
51
+ this.options = options;
26
52
  this.baseUrl = new URL('api/agent/v1/', normalizeBaseUrl(options.baseUrl));
27
53
  this.token = options.token ?? '';
28
54
  this.fetchImpl = options.fetchImpl ?? fetch;
29
55
  }
56
+ /** Same transport and timeouts, different credentials (used to verify a token before saving it). */
57
+ withCredentials(params) {
58
+ return new AgentClient({ ...this.options, baseUrl: params.baseUrl ?? this.options.baseUrl, token: params.token });
59
+ }
30
60
  async request(options) {
31
61
  const method = options.method ?? 'GET';
32
62
  const url = new URL(trimLeadingSlash(options.path), this.baseUrl);
33
63
  const headers = new Headers({
34
64
  Accept: 'application/json',
35
65
  });
66
+ const idempotencyKey = isLiveAction(method) ? options.idempotencyKey ?? randomUUID() : undefined;
36
67
  if (this.token)
37
68
  headers.set('Authorization', `Bearer ${this.token}`);
38
69
  if (options.body !== undefined)
39
70
  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)),
71
+ if (idempotencyKey)
72
+ headers.set('Idempotency-Key', idempotencyKey);
73
+ const timeoutMs = options.timeoutMs
74
+ ?? this.options.timeoutMs
75
+ ?? requestTimeoutOverrideMs()
76
+ ?? (isLiveAction(method) ? DEFAULT_WRITE_TIMEOUT_MS : DEFAULT_READ_TIMEOUT_MS);
77
+ const target = `${method} ${trimLeadingSlash(options.path).split('?')[0]}`;
78
+ const { response, responseBody } = await withTimeout(timeoutMs, target, idempotencyKey, async (signal) => {
79
+ const response = await this.fetchImpl(url, {
80
+ method,
81
+ headers,
82
+ body: options.body === undefined ? undefined : JSON.stringify(jsonValueSchema.parse(options.body)),
83
+ signal,
84
+ });
85
+ return { response, responseBody: await readResponseBody(response) };
46
86
  });
47
- const responseBody = await readResponseBody(response);
48
87
  if (!response.ok)
49
- throw new AgentHttpError(response.status, responseBody);
88
+ throw new AgentHttpError(response.status, responseBody, idempotencyKey);
50
89
  const parsedBody = jsonValueSchema.parse(responseBody ?? null);
51
90
  if (parsedBody
52
91
  && typeof parsedBody === 'object'
@@ -58,15 +97,49 @@ export class AgentClient {
58
97
  return parsedBody;
59
98
  }
60
99
  /**
61
- * Fetches a public file (for example a rendered MP4 on the CDN) as bytes.
62
- * Sends no Authorization header: the URL is not an agent API endpoint.
100
+ * Fetches a public file (a rendered MP4 or slide PNG on the CDN) as bytes.
101
+ * Sends no Authorization header: these URLs are not on the CoAuthor API.
63
102
  */
64
103
  async download(url) {
65
- const response = await this.fetchImpl(url, { method: 'GET' });
66
- if (!response.ok)
67
- throw new Error(`Download failed with HTTP ${response.status} for ${url}`);
68
- return new Uint8Array(await response.arrayBuffer());
104
+ const target = new URL(url);
105
+ if (target.protocol !== 'https:' && target.protocol !== 'http:')
106
+ throw new Error(`Refusing to download a non-http URL: ${url}`);
107
+ const timeoutMs = this.options.timeoutMs ?? requestTimeoutOverrideMs() ?? DEFAULT_DOWNLOAD_TIMEOUT_MS;
108
+ return withTimeout(timeoutMs, `download ${url}`, undefined, async (signal) => {
109
+ const response = await this.fetchImpl(target, { method: 'GET', signal });
110
+ if (!response.ok)
111
+ throw new Error(`Download failed with HTTP ${response.status}: ${url}`);
112
+ return new Uint8Array(await response.arrayBuffer());
113
+ });
114
+ }
115
+ }
116
+ // Bounds the whole exchange (headers and body) so a hung connection can't
117
+ // block past a --wait deadline.
118
+ async function withTimeout(timeoutMs, target, idempotencyKey, run) {
119
+ // A ref'd timer (unlike AbortSignal.timeout) keeps the process alive until
120
+ // the deadline, and is cleared as soon as the exchange settles.
121
+ const controller = new AbortController();
122
+ const timer = setTimeout(() => controller.abort(new DOMException('The request timed out.', 'TimeoutError')), timeoutMs);
123
+ const signal = controller.signal;
124
+ try {
125
+ return await run(signal);
69
126
  }
127
+ catch (error) {
128
+ if (signal.aborted || isAbortError(error)) {
129
+ 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);
130
+ }
131
+ if (error instanceof TypeError && /fetch failed|network|ECONN|ENOTFOUND|EAI_AGAIN|socket/i.test(`${error.message} ${String(error.cause ?? '')}`)) {
132
+ throw new AgentRequestError('network_error', `Network error (${target}): ${error.message}`, idempotencyKey);
133
+ }
134
+ throw error;
135
+ }
136
+ finally {
137
+ clearTimeout(timer);
138
+ }
139
+ }
140
+ function isAbortError(error) {
141
+ const name = error?.name;
142
+ return name === 'TimeoutError' || name === 'AbortError';
70
143
  }
71
144
  export function isLiveAction(method) {
72
145
  return !['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase());
@@ -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,5 +10,11 @@ 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;
14
+ /**
15
+ * `--cta save,follow,custom:Join the webinar` -> the web app's cta_variants
16
+ * list (at most 4 endings, at most one custom).
17
+ */
18
+ export declare function parseSlideshowCtaOption(raw: string): JsonValue[];
12
19
  export declare function creditsExhaustedPauseResult(projectId: string, target: 'research' | 'draft', message: string, data: JsonValue): CommandResult;
13
20
  export declare function helpResult(command?: string[]): CommandResult;