@clickminded/coauthor-cli 0.0.1

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.
@@ -0,0 +1,677 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { spawn } from 'node:child_process';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { AgentHttpError } from './client.js';
8
+ import { clearConfig, loadConfig, saveConfig } from './config.js';
9
+ import { getBoolean, getString, parseJsonOption } from './parser.js';
10
+ export async function runCommand(input, context) {
11
+ const [scope, action] = input.command;
12
+ if (!scope)
13
+ return helpResult();
14
+ if (scope === 'auth')
15
+ return runAuthCommand(action, input, context);
16
+ if (scope === 'project')
17
+ return runProjectCommand(action, input, context.client);
18
+ if (scope === 'workspace')
19
+ return runWorkspaceCommand(action, input, context.client);
20
+ if (scope === 'chat')
21
+ return runChatCommand(input, context.client);
22
+ if (scope === 'contract')
23
+ return runArtifactCommand('contract', action, input, context.client);
24
+ if (scope === 'outline')
25
+ return runArtifactCommand('outline', action, input, context.client);
26
+ if (scope === 'research-plan')
27
+ return runArtifactCommand('research-plan', action, input, context.client);
28
+ if (scope === 'research')
29
+ return runResearchCommand(action, input, context.client);
30
+ if (scope === 'draft')
31
+ return runDraftCommand(action, input, context.client);
32
+ if (scope === 'workflow')
33
+ return runWorkflowCommand(action, input, context.client);
34
+ if (scope === 'image')
35
+ return runResourceCommand('images', action, input, context.client);
36
+ if (scope === 'thread')
37
+ return runResourceCommand('threads', action, input, context.client);
38
+ if (scope === 'publish')
39
+ return runResourceCommand('publish', action, input, context.client);
40
+ if (scope === 'export')
41
+ return runResourceCommand('exports', action, input, context.client);
42
+ if (scope === 'operation')
43
+ return runOperationCommand(action, input, context.client);
44
+ if (scope === 'skills')
45
+ return runSkillsCommand(action, input);
46
+ if (scope === 'help')
47
+ return helpResult();
48
+ throw new Error(`Unknown command: ${input.command.join(' ')}`);
49
+ }
50
+ async function runAuthCommand(action, input, context) {
51
+ if (action === 'login') {
52
+ const token = getString(input.values, 'token');
53
+ const baseUrl = getString(input.values, 'base-url') ?? context.baseUrl;
54
+ if (token) {
55
+ await saveConfig({ ...(await loadConfig(context.paths)), baseUrl, token }, context.paths);
56
+ return { ok: true, message: `Logged in to ${baseUrl}`, data: { baseUrl, authenticated: true } };
57
+ }
58
+ const start = await context.client.request({
59
+ method: 'POST',
60
+ path: 'auth/device/start',
61
+ body: { withPublish: getBoolean(input.values, 'with-publish') },
62
+ });
63
+ const deviceCode = requireResponseString(start, 'device_code');
64
+ const verificationUrl = requireResponseString(start, 'verification_uri_complete');
65
+ const intervalSeconds = getResponseNumber(start, 'interval') ?? 3;
66
+ const expiresInSeconds = getResponseNumber(start, 'expires_in') ?? 600;
67
+ const userCode = requireResponseString(start, 'user_code');
68
+ if (!getBoolean(input.values, 'no-browser')) {
69
+ openBrowser(verificationUrl);
70
+ }
71
+ process.stderr.write([
72
+ `Open this URL to authorize CoAuthor CLI: ${verificationUrl}`,
73
+ `Code: ${userCode}`,
74
+ 'Waiting for approval...',
75
+ '',
76
+ ].join('\n'));
77
+ const deadline = Date.now() + expiresInSeconds * 1000;
78
+ let tokenResponse = null;
79
+ while (Date.now() < deadline) {
80
+ await sleep(intervalSeconds * 1000);
81
+ try {
82
+ tokenResponse = await context.client.request({
83
+ method: 'POST',
84
+ path: 'auth/device/poll',
85
+ body: { device_code: deviceCode },
86
+ });
87
+ break;
88
+ }
89
+ catch (error) {
90
+ if (isAuthorizationPending(error))
91
+ continue;
92
+ throw error;
93
+ }
94
+ }
95
+ if (!tokenResponse) {
96
+ throw new Error(`Timed out waiting for browser authorization. Start again with code ${userCode}.`);
97
+ }
98
+ const nextToken = requireResponseString(tokenResponse, 'access_token');
99
+ await saveConfig({ ...(await loadConfig(context.paths)), baseUrl, token: nextToken }, context.paths);
100
+ return {
101
+ ok: true,
102
+ message: `Logged in to ${baseUrl}`,
103
+ data: {
104
+ baseUrl,
105
+ authenticated: true,
106
+ tokenPrefix: getResponseString(tokenResponse, 'token_prefix') ?? null,
107
+ scopes: getResponseValue(tokenResponse, 'scopes') ?? [],
108
+ },
109
+ };
110
+ }
111
+ if (action === 'status') {
112
+ const config = await loadConfig(context.paths);
113
+ const data = context.token
114
+ ? await context.client.request({ path: 'auth/status' })
115
+ : null;
116
+ return {
117
+ ok: true,
118
+ message: context.token ? `Authenticated against ${context.baseUrl}` : `No token configured for ${context.baseUrl}`,
119
+ data: {
120
+ baseUrl: context.baseUrl,
121
+ configBaseUrl: config.baseUrl ?? null,
122
+ hasToken: Boolean(context.token),
123
+ server: data,
124
+ },
125
+ };
126
+ }
127
+ if (action === 'logout') {
128
+ if (context.token) {
129
+ try {
130
+ await context.client.request({ method: 'POST', path: 'auth/logout', body: {} });
131
+ }
132
+ catch {
133
+ // Local logout should still clear credentials if the server is unavailable.
134
+ }
135
+ }
136
+ await clearConfig(context.paths);
137
+ return { ok: true, message: 'Logged out', data: { authenticated: false } };
138
+ }
139
+ throw new Error('Usage: coauthor auth <login|status|logout>');
140
+ }
141
+ async function runProjectCommand(action, input, client) {
142
+ if (action === 'create') {
143
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, ['title', 'topic', 'audience']);
144
+ const data = await client.request({ method: 'POST', path: 'projects', body });
145
+ return { ok: true, message: 'Project created', data };
146
+ }
147
+ if (action === 'list') {
148
+ const data = await client.request({ path: withQuery('projects', input.values, ['limit', 'cursor']) });
149
+ return { ok: true, data };
150
+ }
151
+ if (action === 'show') {
152
+ const projectId = requireProjectId(input);
153
+ const data = await client.request({ path: `projects/${encodeURIComponent(projectId)}` });
154
+ return { ok: true, data };
155
+ }
156
+ throw new Error('Usage: coauthor project <create|list|show>');
157
+ }
158
+ async function runWorkspaceCommand(action, input, client) {
159
+ if (action !== 'show')
160
+ throw new Error('Usage: coauthor workspace show <projectId>');
161
+ const projectId = requireProjectId(input);
162
+ const data = await client.request({ path: `projects/${encodeURIComponent(projectId)}/workspace` });
163
+ return { ok: true, data };
164
+ }
165
+ async function runChatCommand(input, client) {
166
+ const projectId = requireProjectId(input);
167
+ const message = getString(input.values, 'message') ?? input.positionals.slice(1).join(' ');
168
+ if (!message)
169
+ throw new Error('Usage: coauthor chat <projectId> --message "..."');
170
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, ['stage', 'execution-token']);
171
+ body.message = message;
172
+ const data = await client.request({
173
+ method: 'POST',
174
+ path: `projects/${encodeURIComponent(projectId)}/chat`,
175
+ body,
176
+ });
177
+ return { ok: true, data };
178
+ }
179
+ async function runWorkflowCommand(action, input, client) {
180
+ const projectId = requireProjectId(input);
181
+ const projectPath = `projects/${encodeURIComponent(projectId)}/workflow`;
182
+ if (action === 'show' || action === 'status') {
183
+ const data = await client.request({ path: projectPath });
184
+ return { ok: true, data };
185
+ }
186
+ if (action === 'advance' || action === 'run' || action === 'rewind' || action === 'approve') {
187
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, [
188
+ 'stage',
189
+ 'target',
190
+ 'execution-token',
191
+ 'reason',
192
+ 'briefing-mode',
193
+ 'max-brief-questions',
194
+ ]);
195
+ if (getBoolean(input.values, 'require-brief-review'))
196
+ body.requireBriefReview = true;
197
+ const data = await client.request({
198
+ method: 'POST',
199
+ path: `${projectPath}/${action}`,
200
+ body,
201
+ });
202
+ if (getResponseString(data, 'status') === 'needs_clarification') {
203
+ return { ok: true, message: 'Workflow needs brief clarification before continuing', data };
204
+ }
205
+ if (getBoolean(input.values, 'wait') && (action === 'advance' || action === 'run')) {
206
+ const target = normalizeWorkflowWaitTarget(getString(input.values, 'target')
207
+ ?? getString(input.values, 'stage')
208
+ ?? getResponseString(data, 'target'));
209
+ if (target === 'research')
210
+ return waitForResearch(client, projectId, data);
211
+ if (target === 'draft')
212
+ return waitForWorkflowDraft(client, projectId, data);
213
+ }
214
+ return { ok: true, data };
215
+ }
216
+ throw new Error('Usage: coauthor workflow <show|status|advance|run|rewind|approve> <projectId>');
217
+ }
218
+ async function runArtifactCommand(artifact, action, input, client) {
219
+ const projectId = requireProjectId(input);
220
+ const basePath = `projects/${encodeURIComponent(projectId)}/${artifact}`;
221
+ if (!action || action === 'show') {
222
+ const data = await client.request({ path: basePath });
223
+ return { ok: true, data };
224
+ }
225
+ if (action === 'generate' || action === 'save' || action === 'approve') {
226
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, ['execution-token']);
227
+ const path = action === 'save' ? basePath : `${basePath}/${action}`;
228
+ const data = await client.request({ method: 'POST', path, body });
229
+ return { ok: true, data };
230
+ }
231
+ throw new Error(`Usage: coauthor ${artifact} <show|generate|save|approve> <projectId>`);
232
+ }
233
+ async function runResearchCommand(action, input, client) {
234
+ const projectId = requireProjectId(input);
235
+ const basePath = `projects/${encodeURIComponent(projectId)}/research`;
236
+ if (action === 'run') {
237
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, ['execution-token']);
238
+ const data = await client.request({ method: 'POST', path: `${basePath}/run`, body });
239
+ if (getBoolean(input.values, 'wait')) {
240
+ return waitForResearch(client, projectId, data);
241
+ }
242
+ return { ok: true, data };
243
+ }
244
+ if (action === 'status') {
245
+ return { ok: true, data: await client.request({ path: `${basePath}/status` }) };
246
+ }
247
+ if (action === 'structured') {
248
+ return { ok: true, data: await client.request({ path: `${basePath}/structured` }) };
249
+ }
250
+ throw new Error('Usage: coauthor research <run|status|structured> <projectId>');
251
+ }
252
+ async function runDraftCommand(action, input, client) {
253
+ const projectId = requireProjectId(input);
254
+ const basePath = `projects/${encodeURIComponent(projectId)}/draft`;
255
+ if (action === 'generate') {
256
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, ['execution-token']);
257
+ const data = await client.request({ method: 'POST', path: `${basePath}/generate`, body });
258
+ if (getBoolean(input.values, 'wait')) {
259
+ return waitForDraft(client, projectId, data);
260
+ }
261
+ return { ok: true, data };
262
+ }
263
+ if (action === 'status') {
264
+ return { ok: true, data: await client.request({ path: `${basePath}/status` }) };
265
+ }
266
+ if (action === 'get') {
267
+ const format = getString(input.values, 'format');
268
+ const data = await client.request({ path: format ? `${basePath}/get?format=${encodeURIComponent(format)}` : `${basePath}/get` });
269
+ return { ok: true, data };
270
+ }
271
+ if (action === 'save') {
272
+ const data = await client.request({ method: 'POST', path: `${basePath}/save`, body: parseJsonOption(input.values) });
273
+ return { ok: true, data };
274
+ }
275
+ throw new Error('Usage: coauthor draft <generate|status|get|save> <projectId>');
276
+ }
277
+ async function runResourceCommand(resource, action, input, client) {
278
+ const projectId = getString(input.values, 'project') ?? input.positionals[0];
279
+ const resourceId = getString(input.values, 'id') ?? input.positionals[1];
280
+ const basePath = projectId
281
+ ? `projects/${encodeURIComponent(projectId)}/${resource}`
282
+ : resource;
283
+ if (!action || action === 'list') {
284
+ const data = await client.request({ path: withQuery(basePath, input.values, ['limit', 'cursor', 'status']) });
285
+ return { ok: true, data };
286
+ }
287
+ if (action === 'show' || action === 'status') {
288
+ if (resource === 'images' && action === 'status') {
289
+ const data = await client.request({ path: `${basePath}/status` });
290
+ return { ok: true, data };
291
+ }
292
+ if (resource === 'threads') {
293
+ const data = await client.request({ path: resourceId ? `${basePath}/${encodeURIComponent(resourceId)}` : basePath });
294
+ return { ok: true, data };
295
+ }
296
+ if (!resourceId)
297
+ throw new Error(`Usage: coauthor ${resourceCommandName(resource)} ${action} <projectId> <id>`);
298
+ const data = await client.request({ path: `${basePath}/${encodeURIComponent(resourceId)}` });
299
+ return { ok: true, data };
300
+ }
301
+ if (resource === 'publish' && action === 'thread') {
302
+ if (!projectId)
303
+ throw new Error('Missing project id for publish thread');
304
+ if (!getBoolean(input.values, 'yes'))
305
+ throw new Error('Live publish requires --yes');
306
+ const data = await client.request({ method: 'POST', path: `${basePath}/thread`, body: parseJsonOption(input.values) });
307
+ return { ok: true, data };
308
+ }
309
+ if (resource === 'exports' && (action === 'blog' || action === 'clickminded')) {
310
+ if (!projectId)
311
+ throw new Error(`Missing project id for export ${action}`);
312
+ if (!getBoolean(input.values, 'yes'))
313
+ throw new Error('Live export requires --yes');
314
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, [
315
+ 'slug',
316
+ 'status',
317
+ 'permalink',
318
+ 'format',
319
+ ]);
320
+ const data = await client.request({ method: 'POST', path: `${basePath}/${action}`, body });
321
+ return { ok: true, data };
322
+ }
323
+ if (['create', 'generate', 'save', 'edit', 'publish', 'export', 'cancel', 'retry'].includes(action)) {
324
+ if (!projectId)
325
+ throw new Error(`Missing project id for ${resourceCommandName(resource)} ${action}`);
326
+ const body = withNamedOptions(parseJsonOption(input.values), input.values, [
327
+ 'prompt',
328
+ 'format',
329
+ 'target',
330
+ 'thread',
331
+ 'image',
332
+ 'id',
333
+ 'placeholder-id',
334
+ 'execution-token',
335
+ ]);
336
+ const path = action === 'create' && resource !== 'threads' ? basePath : `${basePath}/${action}`;
337
+ const data = await client.request({ method: 'POST', path, body });
338
+ return { ok: true, data };
339
+ }
340
+ throw new Error(`Unknown ${resourceCommandName(resource)} command: ${action}`);
341
+ }
342
+ async function runOperationCommand(action, input, client) {
343
+ const key = getString(input.values, 'id') ?? input.positionals[0];
344
+ if (!action || action === 'list') {
345
+ return { ok: true, data: await client.request({ path: 'operations' }) };
346
+ }
347
+ if (action === 'show' || action === 'status') {
348
+ if (!key)
349
+ throw new Error('Usage: coauthor operation status <operationKey>');
350
+ return { ok: true, data: await client.request({ path: `operations/${encodeURIComponent(key)}` }) };
351
+ }
352
+ throw new Error('Usage: coauthor operation <list|show|status>');
353
+ }
354
+ const SKILL_NAMES = ['codex', 'claude', 'cursor'];
355
+ const SKILL_TEMPLATE_PATHS = {
356
+ codex: '../skills/codex/SKILL.md',
357
+ claude: '../skills/claude/SKILL.md',
358
+ cursor: '../skills/cursor/coauthor-cli.mdc',
359
+ };
360
+ async function runSkillsCommand(action, input) {
361
+ if (!action || action === 'list') {
362
+ const cwd = resolve(getString(input.values, 'cwd') ?? process.cwd());
363
+ return {
364
+ ok: true,
365
+ data: {
366
+ skills: SKILL_NAMES.map((skill) => ({
367
+ skill,
368
+ path: getSkillInstallPath(skill, cwd),
369
+ })),
370
+ },
371
+ };
372
+ }
373
+ if (action === 'install') {
374
+ const requested = input.positionals[0];
375
+ const skills = resolveRequestedSkills(requested);
376
+ const cwd = resolve(getString(input.values, 'cwd') ?? process.cwd());
377
+ const force = getBoolean(input.values, 'force');
378
+ const dryRun = getBoolean(input.values, 'dry-run');
379
+ const results = [];
380
+ for (const skill of skills) {
381
+ results.push(await installSkill({ skill, cwd, force, dryRun }));
382
+ }
383
+ return {
384
+ ok: true,
385
+ message: dryRun ? 'Skill install dry run complete' : 'Skill install complete',
386
+ data: { results },
387
+ };
388
+ }
389
+ throw new Error('Usage: coauthor skills <list|install> [codex|claude|cursor|all]');
390
+ }
391
+ function resolveRequestedSkills(value) {
392
+ if (!value || value === 'all')
393
+ return [...SKILL_NAMES];
394
+ if (isSkillName(value))
395
+ return [value];
396
+ throw new Error('Usage: coauthor skills install <codex|claude|cursor|all>');
397
+ }
398
+ function isSkillName(value) {
399
+ return SKILL_NAMES.includes(value);
400
+ }
401
+ async function installSkill(params) {
402
+ const targetPath = getSkillInstallPath(params.skill, params.cwd);
403
+ if (!params.force && await fileExists(targetPath)) {
404
+ return { skill: params.skill, status: 'skipped', path: targetPath };
405
+ }
406
+ if (params.dryRun) {
407
+ return { skill: params.skill, status: 'dry_run', path: targetPath };
408
+ }
409
+ const template = await readFile(getSkillTemplatePath(params.skill), 'utf8');
410
+ await mkdir(dirname(targetPath), { recursive: true });
411
+ await writeFile(targetPath, template, { mode: 0o644 });
412
+ return { skill: params.skill, status: 'installed', path: targetPath };
413
+ }
414
+ function getSkillTemplatePath(skill) {
415
+ return fileURLToPath(new URL(SKILL_TEMPLATE_PATHS[skill], import.meta.url));
416
+ }
417
+ function getSkillInstallPath(skill, cwd) {
418
+ if (skill === 'codex')
419
+ return join(homedir(), '.codex', 'skills', 'coauthor', 'SKILL.md');
420
+ if (skill === 'claude')
421
+ return join(cwd, '.claude', 'skills', 'coauthor', 'SKILL.md');
422
+ return join(cwd, '.cursor', 'rules', 'coauthor-cli.mdc');
423
+ }
424
+ async function fileExists(path) {
425
+ try {
426
+ await readFile(path);
427
+ return true;
428
+ }
429
+ catch (error) {
430
+ return isMissingFileError(error)
431
+ ? false
432
+ : Promise.reject(error);
433
+ }
434
+ }
435
+ function isMissingFileError(error) {
436
+ return typeof error === 'object'
437
+ && error !== null
438
+ && 'code' in error
439
+ && error.code === 'ENOENT';
440
+ }
441
+ function requireProjectId(input) {
442
+ const projectId = getString(input.values, 'project') ?? input.positionals[0];
443
+ if (!projectId)
444
+ throw new Error('Missing project id');
445
+ return projectId;
446
+ }
447
+ function withNamedOptions(body, values, names) {
448
+ for (const name of names) {
449
+ const value = getString(values, name);
450
+ if (value !== undefined)
451
+ body[toCamelCase(name)] = value;
452
+ }
453
+ return body;
454
+ }
455
+ function withQuery(path, values, names) {
456
+ const params = new URLSearchParams();
457
+ for (const name of names) {
458
+ const value = getString(values, name);
459
+ if (value !== undefined)
460
+ params.set(toCamelCase(name), value);
461
+ }
462
+ const query = params.toString();
463
+ return query ? `${path}?${query}` : path;
464
+ }
465
+ function toCamelCase(name) {
466
+ return name.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
467
+ }
468
+ function getResponseValue(data, key) {
469
+ if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
470
+ return data[key];
471
+ }
472
+ return undefined;
473
+ }
474
+ function getResponseString(data, key) {
475
+ const value = getResponseValue(data, key);
476
+ return typeof value === 'string' ? value : undefined;
477
+ }
478
+ function requireResponseString(data, key) {
479
+ const value = getResponseString(data, key);
480
+ if (!value)
481
+ throw new Error(`Response did not include ${key}`);
482
+ return value;
483
+ }
484
+ function getResponseNumber(data, key) {
485
+ const value = getResponseValue(data, key);
486
+ return typeof value === 'number' ? value : undefined;
487
+ }
488
+ function isAuthorizationPending(error) {
489
+ if (!(error instanceof AgentHttpError))
490
+ return false;
491
+ const body = error.responseBody;
492
+ if (!body || typeof body !== 'object' || Array.isArray(body))
493
+ return false;
494
+ const envelopeError = body.error;
495
+ if (!envelopeError || typeof envelopeError !== 'object' || Array.isArray(envelopeError))
496
+ return false;
497
+ return envelopeError.code === 'authorization_pending';
498
+ }
499
+ function openBrowser(url) {
500
+ const command = process.platform === 'darwin'
501
+ ? 'open'
502
+ : process.platform === 'win32'
503
+ ? 'cmd'
504
+ : 'xdg-open';
505
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
506
+ const child = spawn(command, args, {
507
+ detached: true,
508
+ stdio: 'ignore',
509
+ });
510
+ child.unref();
511
+ }
512
+ async function waitForResearch(client, projectId, initialData) {
513
+ const deadline = Date.now() + 20 * 60_000;
514
+ let latest = initialData;
515
+ while (Date.now() < deadline) {
516
+ await sleep(3000);
517
+ latest = await client.request({ path: `projects/${encodeURIComponent(projectId)}/research/status` });
518
+ const status = extractNestedString(latest, ['run', 'status']);
519
+ if (status === 'succeeded')
520
+ return { ok: true, message: 'Research completed', data: latest };
521
+ if (status === 'failed')
522
+ throw new Error(extractNestedString(latest, ['run', 'error_message']) ?? 'Research failed');
523
+ }
524
+ return { ok: true, message: 'Timed out waiting for research; check status with coauthor research status', data: latest };
525
+ }
526
+ async function waitForDraft(client, projectId, initialData) {
527
+ const deadline = Date.now() + 20 * 60_000;
528
+ let latest = initialData;
529
+ while (Date.now() < deadline) {
530
+ await sleep(3000);
531
+ latest = await client.request({ path: `projects/${encodeURIComponent(projectId)}/draft/status` });
532
+ const state = getResponseString(latest, 'project_state');
533
+ const phase = getResponseString(latest, 'phase');
534
+ if (state === 'draft_generated' || state === 'editing' || phase === 'complete') {
535
+ return { ok: true, message: 'Draft completed', data: latest };
536
+ }
537
+ if (phase === 'failed')
538
+ throw new Error(getResponseString(latest, 'message') ?? 'Draft generation failed');
539
+ }
540
+ return { ok: true, message: 'Timed out waiting for draft; check status with coauthor draft status', data: latest };
541
+ }
542
+ async function waitForWorkflowDraft(client, projectId, initialData) {
543
+ const deadline = Date.now() + 40 * 60_000;
544
+ let latestDraft = initialData;
545
+ let latestResearch = null;
546
+ let draftGenerate = null;
547
+ let attemptedDraftStart = false;
548
+ while (Date.now() < deadline) {
549
+ await sleep(3000);
550
+ latestDraft = await client.request({ path: `projects/${encodeURIComponent(projectId)}/draft/status` });
551
+ const draftState = getResponseString(latestDraft, 'project_state');
552
+ const draftPhase = getResponseString(latestDraft, 'phase');
553
+ if (draftState === 'draft_generated' || draftState === 'editing' || draftPhase === 'complete') {
554
+ return {
555
+ ok: true,
556
+ message: 'Workflow target draft completed',
557
+ data: {
558
+ workflow: initialData,
559
+ research_status: latestResearch,
560
+ draft_generate: draftGenerate,
561
+ draft_status: latestDraft,
562
+ },
563
+ };
564
+ }
565
+ if (draftPhase === 'failed')
566
+ throw new Error(getResponseString(latestDraft, 'message') ?? 'Draft generation failed');
567
+ latestResearch = await client.request({ path: `projects/${encodeURIComponent(projectId)}/research/status` });
568
+ const researchStatus = extractNestedString(latestResearch, ['run', 'status']);
569
+ if (researchStatus === 'failed') {
570
+ throw new Error(extractNestedString(latestResearch, ['run', 'error_message']) ?? 'Research failed');
571
+ }
572
+ if (!attemptedDraftStart
573
+ && (researchStatus === 'succeeded' || isResearchReadyForDraft(draftState))
574
+ && draftPhase !== 'queued'
575
+ && draftPhase !== 'running') {
576
+ attemptedDraftStart = true;
577
+ try {
578
+ draftGenerate = await client.request({
579
+ method: 'POST',
580
+ path: `projects/${encodeURIComponent(projectId)}/draft/generate`,
581
+ body: {},
582
+ });
583
+ }
584
+ catch (error) {
585
+ if (!isAlreadyStartedOrComplete(error))
586
+ throw error;
587
+ }
588
+ }
589
+ }
590
+ return {
591
+ ok: true,
592
+ message: 'Timed out waiting for workflow draft target; check status with coauthor draft status',
593
+ data: {
594
+ workflow: initialData,
595
+ research_status: latestResearch,
596
+ draft_status: latestDraft,
597
+ },
598
+ };
599
+ }
600
+ function extractNestedString(value, path) {
601
+ let current = value;
602
+ for (const key of path) {
603
+ if (!current || typeof current !== 'object' || Array.isArray(current))
604
+ return undefined;
605
+ current = current[key];
606
+ }
607
+ return typeof current === 'string' ? current : undefined;
608
+ }
609
+ function normalizeWorkflowWaitTarget(value) {
610
+ if (!value)
611
+ return 'draft';
612
+ const normalized = value.trim().toLowerCase().replace(/_/g, '-');
613
+ if (normalized === 'research' || normalized === 'research-run' || normalized === 'research-structured')
614
+ return 'research';
615
+ if (normalized === 'draft' || normalized === 'editor' || normalized === 'editing')
616
+ return 'draft';
617
+ return null;
618
+ }
619
+ function isResearchReadyForDraft(state) {
620
+ return state === 'research_structured';
621
+ }
622
+ function isAlreadyStartedOrComplete(error) {
623
+ if (!(error instanceof AgentHttpError))
624
+ return false;
625
+ const message = extractErrorMessage(error);
626
+ return /already|state "draft_generated"|state "editing"|state "draft_running"|draft.*running/i.test(message);
627
+ }
628
+ function extractErrorMessage(error) {
629
+ const body = error.responseBody;
630
+ if (!body || typeof body !== 'object' || Array.isArray(body))
631
+ return error.message;
632
+ const envelopeError = body.error;
633
+ if (envelopeError && typeof envelopeError === 'object' && !Array.isArray(envelopeError)) {
634
+ const message = envelopeError.message;
635
+ if (typeof message === 'string')
636
+ return message;
637
+ }
638
+ return error.message;
639
+ }
640
+ function resourceCommandName(resource) {
641
+ if (resource === 'images')
642
+ return 'image';
643
+ if (resource === 'threads')
644
+ return 'thread';
645
+ if (resource === 'exports')
646
+ return 'export';
647
+ if (resource === 'operations')
648
+ return 'operation';
649
+ return resource;
650
+ }
651
+ function helpResult() {
652
+ return {
653
+ ok: true,
654
+ message: [
655
+ 'Usage: coauthor <command> [options]',
656
+ '',
657
+ 'Commands:',
658
+ ' auth login|status|logout',
659
+ ' project create|list|show',
660
+ ' workspace show',
661
+ ' chat',
662
+ ' contract show|save|approve',
663
+ ' outline show|generate|save|approve',
664
+ ' research-plan show|generate|save|approve',
665
+ ' research run|status|structured',
666
+ ' draft generate|status|get|save',
667
+ ' workflow show|status|advance|run|rewind|approve',
668
+ ' workflow run/advance supports --briefing-mode auto|strict|off and --require-brief-review',
669
+ ' image list|status|show|generate|edit',
670
+ ' thread list|show|create|generate|save',
671
+ ' publish thread',
672
+ ' export blog|clickminded',
673
+ ' operation list|show|status',
674
+ ' skills list|install',
675
+ ].join('\n'),
676
+ };
677
+ }