@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,21 @@
1
+ import { z } from 'zod';
2
+ export declare const DEFAULT_BASE_URL = "http://localhost:3000";
3
+ declare const configSchema: z.ZodObject<{
4
+ baseUrl: z.ZodOptional<z.ZodString>;
5
+ token: z.ZodOptional<z.ZodString>;
6
+ }, z.core.$strip>;
7
+ export type CoauthorConfig = z.infer<typeof configSchema>;
8
+ export type ConfigPaths = {
9
+ configFile: string;
10
+ };
11
+ export declare function getDefaultConfigPaths(): ConfigPaths;
12
+ export declare function loadConfig(paths?: ConfigPaths): Promise<CoauthorConfig>;
13
+ export declare function saveConfig(config: CoauthorConfig, paths?: ConfigPaths): Promise<void>;
14
+ export declare function clearConfig(paths?: ConfigPaths): Promise<void>;
15
+ export declare function resolveRuntimeConfig(params?: {
16
+ env?: NodeJS.ProcessEnv;
17
+ paths?: ConfigPaths;
18
+ baseUrlOverride?: string;
19
+ tokenOverride?: string;
20
+ }): Promise<Required<CoauthorConfig>>;
21
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,64 @@
1
+ import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { z } from 'zod';
5
+ export const DEFAULT_BASE_URL = 'http://localhost:3000';
6
+ const configSchema = z.object({
7
+ baseUrl: z.string().url().optional(),
8
+ token: z.string().min(1).optional(),
9
+ });
10
+ export function getDefaultConfigPaths() {
11
+ return {
12
+ configFile: join(homedir(), '.coauthor', 'config.json'),
13
+ };
14
+ }
15
+ export async function loadConfig(paths = getDefaultConfigPaths()) {
16
+ try {
17
+ const raw = await readFile(paths.configFile, 'utf8');
18
+ return configSchema.parse(JSON.parse(raw));
19
+ }
20
+ catch (error) {
21
+ if (isMissingFileError(error))
22
+ return {};
23
+ throw new Error(`Failed to read ${paths.configFile}: ${formatError(error)}`);
24
+ }
25
+ }
26
+ export async function saveConfig(config, paths = getDefaultConfigPaths()) {
27
+ const parsed = configSchema.parse(config);
28
+ await mkdir(dirname(paths.configFile), { recursive: true, mode: 0o700 });
29
+ await writeFile(paths.configFile, `${JSON.stringify(parsed, null, 2)}\n`, { mode: 0o600 });
30
+ try {
31
+ await chmod(paths.configFile, 0o600);
32
+ }
33
+ catch {
34
+ // Best effort: some filesystems do not support POSIX permissions.
35
+ }
36
+ }
37
+ export async function clearConfig(paths = getDefaultConfigPaths()) {
38
+ try {
39
+ await rm(paths.configFile);
40
+ }
41
+ catch (error) {
42
+ if (!isMissingFileError(error))
43
+ throw error;
44
+ }
45
+ }
46
+ export async function resolveRuntimeConfig(params = {}) {
47
+ const env = params.env ?? process.env;
48
+ const fileConfig = await loadConfig(params.paths);
49
+ const baseUrl = params.baseUrlOverride ?? env.COAUTHOR_BASE_URL ?? fileConfig.baseUrl ?? DEFAULT_BASE_URL;
50
+ const token = params.tokenOverride ?? env.COAUTHOR_TOKEN ?? fileConfig.token ?? '';
51
+ configSchema.pick({ baseUrl: true }).required({ baseUrl: true }).parse({ baseUrl });
52
+ if (token)
53
+ configSchema.pick({ token: true }).required({ token: true }).parse({ token });
54
+ return { baseUrl, token };
55
+ }
56
+ function isMissingFileError(error) {
57
+ return typeof error === 'object'
58
+ && error !== null
59
+ && 'code' in error
60
+ && error.code === 'ENOENT';
61
+ }
62
+ function formatError(error) {
63
+ return error instanceof Error ? error.message : String(error);
64
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export declare function main(argv?: string[]): Promise<number>;
package/dist/index.js ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ import { AgentHttpError, AgentClient } from './client.js';
3
+ import { resolveRuntimeConfig } from './config.js';
4
+ import { runCommand } from './commands.js';
5
+ import { renderError, renderResult } from './output.js';
6
+ import { parseCliArgs } from './parser.js';
7
+ export async function main(argv = process.argv.slice(2)) {
8
+ try {
9
+ const parsed = parseCliArgs(argv);
10
+ const runtimeConfig = await resolveRuntimeConfig({
11
+ baseUrlOverride: parsed.globals.baseUrl,
12
+ tokenOverride: parsed.globals.token,
13
+ });
14
+ const client = new AgentClient(runtimeConfig);
15
+ const result = await runCommand(parsed, {
16
+ client,
17
+ baseUrl: runtimeConfig.baseUrl,
18
+ token: runtimeConfig.token,
19
+ });
20
+ process.stdout.write(renderResult(result, parsed.globals.json));
21
+ return 0;
22
+ }
23
+ catch (error) {
24
+ const wantsJson = argv.includes('--json');
25
+ process.stderr.write(renderError(formatCliError(error), wantsJson));
26
+ return 1;
27
+ }
28
+ }
29
+ function formatCliError(error) {
30
+ if (error instanceof AgentHttpError) {
31
+ const message = extractErrorMessage(error.responseBody) ?? error.message;
32
+ return new Error(message);
33
+ }
34
+ return error instanceof Error ? error : new Error(String(error));
35
+ }
36
+ function extractErrorMessage(body) {
37
+ if (!body || typeof body !== 'object' || Array.isArray(body) || !('error' in body))
38
+ return null;
39
+ const error = body.error;
40
+ if (typeof error === 'string')
41
+ return error;
42
+ if (!error || typeof error !== 'object' || Array.isArray(error))
43
+ return null;
44
+ const message = error.message;
45
+ return typeof message === 'string' ? message : null;
46
+ }
47
+ if (import.meta.url === `file://${process.argv[1]}`) {
48
+ main().then((code) => {
49
+ process.exitCode = code;
50
+ });
51
+ }
@@ -0,0 +1,8 @@
1
+ import type { JsonValue } from './client.js';
2
+ export type CommandResult = {
3
+ ok: boolean;
4
+ message?: string;
5
+ data?: JsonValue;
6
+ };
7
+ export declare function renderResult(result: CommandResult, json: boolean): string;
8
+ export declare function renderError(error: unknown, json: boolean): string;
package/dist/output.js ADDED
@@ -0,0 +1,15 @@
1
+ export function renderResult(result, json) {
2
+ if (json)
3
+ return `${JSON.stringify(result, null, 2)}\n`;
4
+ 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
+ }
10
+ export function renderError(error, json) {
11
+ const message = error instanceof Error ? error.message : String(error);
12
+ if (json)
13
+ return `${JSON.stringify({ ok: false, error: message }, null, 2)}\n`;
14
+ return `Error: ${message}\n`;
15
+ }
@@ -0,0 +1,28 @@
1
+ import { z } from 'zod';
2
+ import type { JsonValue } from './client.js';
3
+ export type GlobalOptions = {
4
+ json: boolean;
5
+ baseUrl?: string;
6
+ token?: string;
7
+ };
8
+ export type ParsedCommand = {
9
+ command: string[];
10
+ positionals: string[];
11
+ globals: GlobalOptions;
12
+ values: Record<string, string | boolean | string[] | undefined>;
13
+ };
14
+ export declare const commandInputSchema: z.ZodObject<{
15
+ command: z.ZodArray<z.ZodString>;
16
+ positionals: z.ZodArray<z.ZodString>;
17
+ globals: z.ZodObject<{
18
+ json: z.ZodBoolean;
19
+ baseUrl: z.ZodOptional<z.ZodString>;
20
+ token: z.ZodOptional<z.ZodString>;
21
+ }, z.core.$strip>;
22
+ values: z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodBoolean, z.ZodArray<z.ZodString>]>>>;
23
+ }, z.core.$strip>;
24
+ export declare function parseCliArgs(argv: string[]): ParsedCommand;
25
+ export declare function getString(values: ParsedCommand['values'], name: string): string | undefined;
26
+ export declare function requireString(values: ParsedCommand['values'], name: string): string;
27
+ export declare function getBoolean(values: ParsedCommand['values'], name: string): boolean;
28
+ export declare function parseJsonOption(values: ParsedCommand['values'], name?: string): Record<string, JsonValue>;
package/dist/parser.js ADDED
@@ -0,0 +1,114 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { z } from 'zod';
3
+ export const commandInputSchema = z.object({
4
+ command: z.array(z.string().min(1)),
5
+ positionals: z.array(z.string()),
6
+ globals: z.object({
7
+ json: z.boolean(),
8
+ baseUrl: z.string().url().optional(),
9
+ token: z.string().min(1).optional(),
10
+ }),
11
+ values: z.record(z.string(), z.union([z.string(), z.boolean(), z.array(z.string())]).optional()),
12
+ });
13
+ export function parseCliArgs(argv) {
14
+ const parsed = parseArgs({
15
+ args: argv,
16
+ allowPositionals: true,
17
+ strict: false,
18
+ options: {
19
+ json: { type: 'boolean', default: false },
20
+ 'base-url': { type: 'string' },
21
+ token: { type: 'string' },
22
+ email: { type: 'string' },
23
+ password: { type: 'string' },
24
+ 'with-publish': { type: 'boolean', default: false },
25
+ 'no-browser': { type: 'boolean', default: false },
26
+ yes: { type: 'boolean', default: false },
27
+ wait: { type: 'boolean', default: false },
28
+ force: { type: 'boolean', default: false },
29
+ 'dry-run': { type: 'boolean', default: false },
30
+ data: { type: 'string' },
31
+ cwd: { type: 'string' },
32
+ title: { type: 'string' },
33
+ topic: { type: 'string' },
34
+ audience: { type: 'string' },
35
+ project: { type: 'string' },
36
+ id: { type: 'string' },
37
+ 'placeholder-id': { type: 'string' },
38
+ message: { type: 'string' },
39
+ stage: { type: 'string' },
40
+ target: { type: 'string' },
41
+ reason: { type: 'string' },
42
+ 'briefing-mode': { type: 'string' },
43
+ 'require-brief-review': { type: 'boolean', default: false },
44
+ 'max-brief-questions': { type: 'string' },
45
+ prompt: { type: 'string' },
46
+ format: { type: 'string' },
47
+ thread: { type: 'string' },
48
+ image: { type: 'string' },
49
+ slug: { type: 'string' },
50
+ permalink: { type: 'string' },
51
+ status: { type: 'string' },
52
+ limit: { type: 'string' },
53
+ cursor: { type: 'string' },
54
+ 'execution-token': { type: 'string' },
55
+ },
56
+ });
57
+ const positionals = parsed.positionals;
58
+ const command = positionals.slice(0, commandLength(positionals));
59
+ return commandInputSchema.parse({
60
+ command,
61
+ positionals: positionals.slice(command.length),
62
+ globals: {
63
+ json: Boolean(parsed.values.json),
64
+ baseUrl: stringValue(parsed.values['base-url']),
65
+ token: stringValue(parsed.values.token),
66
+ },
67
+ values: parsed.values,
68
+ });
69
+ }
70
+ export function getString(values, name) {
71
+ return stringValue(values[name]);
72
+ }
73
+ export function requireString(values, name) {
74
+ const value = getString(values, name);
75
+ if (!value)
76
+ throw new Error(`Missing required option --${name}`);
77
+ return value;
78
+ }
79
+ export function getBoolean(values, name) {
80
+ return values[name] === true;
81
+ }
82
+ export function parseJsonOption(values, name = 'data') {
83
+ const raw = getString(values, name);
84
+ if (!raw)
85
+ return {};
86
+ const parsed = JSON.parse(raw);
87
+ return z.record(z.string(), z.unknown()).transform((value) => value).parse(parsed);
88
+ }
89
+ function commandLength(positionals) {
90
+ if (positionals.length === 0)
91
+ return 0;
92
+ const first = positionals[0];
93
+ const second = positionals[1];
94
+ if (first === 'auth')
95
+ return second && ['login', 'status', 'logout'].includes(second) ? 2 : 1;
96
+ if (first === 'project')
97
+ return second && ['create', 'list', 'show'].includes(second) ? 2 : 1;
98
+ if (first === 'workspace')
99
+ return second === 'show' ? 2 : 1;
100
+ if (first === 'skills')
101
+ return second && ['list', 'install'].includes(second) ? 2 : 1;
102
+ if (first === 'workflow')
103
+ return second ? 2 : 1;
104
+ if (['contract', 'outline', 'research-plan', 'research', 'draft', 'image', 'thread', 'publish', 'export', 'operation'].includes(first ?? ''))
105
+ return second ? 2 : 1;
106
+ return 1;
107
+ }
108
+ function stringValue(value) {
109
+ if (typeof value === 'string')
110
+ return value;
111
+ if (Array.isArray(value))
112
+ return value.at(-1);
113
+ return undefined;
114
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@clickminded/coauthor-cli",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "bin": {
6
+ "coauthor": "dist/index.js"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/eduardoyi/coauthor.git",
11
+ "directory": "packages/cli"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "skills",
22
+ "README.md"
23
+ ],
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "test": "node --import tsx --test test/*.test.ts",
27
+ "typecheck": "tsc --noEmit"
28
+ },
29
+ "dependencies": {
30
+ "zod": "^4.1.8"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^22.10.6",
37
+ "tsx": "^4.19.2",
38
+ "typescript": "^5.6.3"
39
+ },
40
+ "engines": {
41
+ "node": ">=20"
42
+ }
43
+ }
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: coauthor
3
+ description: Use the CoAuthor Agent CLI for project/workflow operations instead of browser routes, curl, or direct database access. Applies when inspecting or advancing CoAuthor projects, operations, exports, publishing, tokens, or workflow status.
4
+ ---
5
+
6
+ This skill guides agent use of the CoAuthor CLI.
7
+
8
+ ## CLI First
9
+
10
+ - Prefer `coauthor` CLI commands for CoAuthor project and workflow work.
11
+ - Do not drive browser routes, hand-written `curl`, or direct database edits when a CLI command covers the task.
12
+ - Use `--json` for machine-readable output and parse fields from that output.
13
+ - Use `--wait` for commands that start asynchronous work when the user expects the operation to finish.
14
+ - Let the default bounded briefing review run before outline/draft generation. Use `--briefing-mode strict` when the user explicitly wants a stronger brief gate, and answer or relay `data.clarification_questions` if the CLI returns `status: "needs_clarification"`.
15
+ - After a timeout, interruption, network error, or unclear result, check operation status before retrying.
16
+
17
+ ## Safety
18
+
19
+ - Never print access tokens, publish tokens, service-role keys, cookies, or authorization headers.
20
+ - Pass tokens through environment variables or secret-backed CLI options only; do not paste them into prompts, logs, or shell history.
21
+ - Treat publish/export operations as live side effects.
22
+ - Require explicit user intent before live publish/export.
23
+ - Include `--yes` only when the user has clearly approved the live publish/export action.
24
+
25
+ ## Workflow
26
+
27
+ 1. Identify the project, operation, or export target.
28
+ 2. Run the relevant `coauthor` command with `--json`.
29
+ 3. Add `--wait` when starting or advancing asynchronous work.
30
+ 4. If anything is uncertain, query operation status and report the current state.
31
+ 5. For live publish/export, confirm explicit user intent, then run with `--yes`.
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: coauthor
3
+ description: Use the CoAuthor Agent CLI for project/workflow operations instead of browser routes, curl, or direct database access. Applies when inspecting or advancing CoAuthor projects, operations, exports, publishing, tokens, or workflow status.
4
+ ---
5
+
6
+ This skill guides agent use of the CoAuthor CLI.
7
+
8
+ ## CLI First
9
+
10
+ - Prefer `coauthor` CLI commands for CoAuthor project and workflow work.
11
+ - Do not drive browser routes, hand-written `curl`, or direct database edits when a CLI command covers the task.
12
+ - Use `--json` for machine-readable output and parse fields from that output.
13
+ - Use `--wait` for commands that start asynchronous work when the user expects the operation to finish.
14
+ - Let the default bounded briefing review run before outline/draft generation. Use `--briefing-mode strict` when the user explicitly wants a stronger brief gate, and answer or relay `data.clarification_questions` if the CLI returns `status: "needs_clarification"`.
15
+ - After a timeout, interruption, network error, or unclear result, check operation status before retrying.
16
+
17
+ ## Safety
18
+
19
+ - Never print access tokens, publish tokens, service-role keys, cookies, or authorization headers.
20
+ - Pass tokens through environment variables or secret-backed CLI options only; do not paste them into prompts, logs, or shell history.
21
+ - Treat publish/export operations as live side effects.
22
+ - Require explicit user intent before live publish/export.
23
+ - Include `--yes` only when the user has clearly approved the live publish/export action.
24
+
25
+ ## Workflow
26
+
27
+ 1. Identify the project, operation, or export target.
28
+ 2. Run the relevant `coauthor` command with `--json`.
29
+ 3. Add `--wait` when starting or advancing asynchronous work.
30
+ 4. If anything is uncertain, query operation status and report the current state.
31
+ 5. For live publish/export, confirm explicit user intent, then run with `--yes`.
@@ -0,0 +1,17 @@
1
+ ---
2
+ description: Agent-facing rules for using the CoAuthor CLI safely
3
+ alwaysApply: true
4
+ ---
5
+
6
+ # CoAuthor CLI
7
+
8
+ - Prefer the `coauthor` CLI for CoAuthor project/workflow operations instead of browser routes, hand-written `curl`, or direct database access.
9
+ - Use `--json` for agent-readable command output.
10
+ - Use `--wait` when starting asynchronous work and the user expects a completed result.
11
+ - Let the default bounded briefing review run before outline/draft generation. Use `--briefing-mode strict` for a stronger brief gate, and answer or relay `data.clarification_questions` if the CLI returns `status: "needs_clarification"`.
12
+ - After timeout, interruption, network error, or ambiguous output, check operation status before retrying or reporting success.
13
+ - Never print tokens, service-role keys, cookies, or authorization headers.
14
+ - Pass tokens through environment variables or secret-backed CLI options only.
15
+ - Treat publish/export commands as live side effects.
16
+ - Require explicit user intent before live publish/export.
17
+ - Use `--yes` only after the user has clearly approved the live publish/export action.