coaiajs 0.1.2 → 0.2.0

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.
Files changed (169) hide show
  1. package/.claude/settings.local.json +16 -0
  2. package/README.md +2 -0
  3. package/articles/academic/NOTES.md +1 -0
  4. package/articles/academic/README.md +1 -0
  5. package/articles/academic/creative-orientation-vs-problem-solving.md +177 -0
  6. package/articles/academic/jsonl-knowledge-graphs-agent-memory.md +142 -0
  7. package/articles/academic/langfuse-observability-llm-pipelines.md +144 -0
  8. package/articles/academic/medicine-wheel-software-architecture.md +163 -0
  9. package/articles/academic/mmot-autonomous-agents.md +156 -0
  10. package/articles/academic/model-context-protocol-interagent.md +161 -0
  11. package/articles/academic/pde-prompt-decomposition.md +186 -0
  12. package/articles/academic/structural-tension-in-ai-agents.md +134 -0
  13. package/articles/reviews/mcp-protocol-design-review.md +170 -0
  14. package/articles/reviews/observability-ai-systems-review.md +176 -0
  15. package/articles/reviews/prompt-engineering-decomposition-review.md +184 -0
  16. package/articles/surveys/agent-orchestration-survey.md +186 -0
  17. package/articles/surveys/knowledge-graph-storage-survey.md +204 -0
  18. package/articles/surveys/structural-tension-methodology-survey.md +154 -0
  19. package/articles/technical/aws-sdk-v3-polly.md +270 -0
  20. package/articles/technical/commander-cli-framework.md +262 -0
  21. package/articles/technical/dotenv-config-patterns.md +360 -0
  22. package/articles/technical/ioredis-vs-redis.md +142 -0
  23. package/articles/technical/langfuse-js-sdk-vs-rest.md +191 -0
  24. package/articles/technical/mcp-sdk-typescript.md +291 -0
  25. package/articles/technical/octokit-github-api.md +293 -0
  26. package/articles/technical/openai-sdk-modern.md +231 -0
  27. package/articles/technical/yaml-parsing-node.md +266 -0
  28. package/articles/technical/zod-runtime-validation.md +212 -0
  29. package/dist/mcp/server.js +5 -3
  30. package/dist/mcp/tools/coaiapy-tools.js +1 -0
  31. package/dist/src/cli.js +41 -5
  32. package/dist/src/langfuse/index.d.ts +1 -1
  33. package/dist/src/langfuse/index.js +1 -1
  34. package/dist/src/langfuse/traces.d.ts +1 -0
  35. package/dist/src/langfuse/traces.js +24 -0
  36. package/dist/src/redis.d.ts +1 -1
  37. package/dist/src/redis.js +2 -2
  38. package/mcp/config.ts +225 -0
  39. package/mcp/prompts.ts +131 -0
  40. package/mcp/resources.ts +84 -0
  41. package/mcp/server.ts +518 -0
  42. package/mcp/tools/coaiapy-tools.ts +366 -0
  43. package/mcp/tools/index.ts +4 -0
  44. package/package.json +2 -67
  45. package/src/audio.ts +76 -0
  46. package/src/cli-helpers.ts +86 -0
  47. package/src/cli.ts +1260 -0
  48. package/src/config.ts +207 -0
  49. package/src/environment.ts +171 -0
  50. package/src/github.ts +143 -0
  51. package/src/index.ts +82 -0
  52. package/src/langfuse/client.ts +105 -0
  53. package/src/langfuse/comments.ts +52 -0
  54. package/src/langfuse/datasets.ts +178 -0
  55. package/src/langfuse/index.ts +33 -0
  56. package/src/langfuse/media.ts +193 -0
  57. package/src/langfuse/observations.ts +131 -0
  58. package/src/langfuse/prompts.ts +157 -0
  59. package/src/langfuse/scores.ts +456 -0
  60. package/src/langfuse/traces.ts +302 -0
  61. package/src/llm.ts +106 -0
  62. package/src/narrative/graph-manager.ts +1358 -0
  63. package/src/narrative/index.ts +188 -0
  64. package/src/narrative/markdown-export.ts +535 -0
  65. package/src/narrative/tool-definitions.ts +635 -0
  66. package/src/narrative/tool-handlers.ts +528 -0
  67. package/src/narrative/types.ts +9 -0
  68. package/src/narrative/validation.ts +179 -0
  69. package/src/pde/index.ts +34 -0
  70. package/src/pde/mcp-handlers.ts +359 -0
  71. package/src/pde/mcp-tools.ts +201 -0
  72. package/src/pde/session-manager.ts +248 -0
  73. package/src/pde/stc-mapper.ts +298 -0
  74. package/src/pipeline/index.ts +7 -0
  75. package/src/pipeline/template-engine.ts +398 -0
  76. package/src/planning/index.ts +32 -0
  77. package/src/planning/mcp-handlers.ts +369 -0
  78. package/src/planning/mcp-tools.ts +155 -0
  79. package/src/planning/plan-parser.ts +587 -0
  80. package/src/redis.ts +111 -0
  81. package/src/types.ts +281 -0
  82. package/test/config.test.mjs +93 -0
  83. package/tsconfig.json +26 -0
  84. package/dist/mcp/config.d.ts.map +0 -1
  85. package/dist/mcp/config.js.map +0 -1
  86. package/dist/mcp/prompts.d.ts.map +0 -1
  87. package/dist/mcp/prompts.js.map +0 -1
  88. package/dist/mcp/resources.d.ts.map +0 -1
  89. package/dist/mcp/resources.js.map +0 -1
  90. package/dist/mcp/server.d.ts.map +0 -1
  91. package/dist/mcp/server.js.map +0 -1
  92. package/dist/mcp/tools/coaiapy-tools.d.ts.map +0 -1
  93. package/dist/mcp/tools/coaiapy-tools.js.map +0 -1
  94. package/dist/mcp/tools/index.d.ts.map +0 -1
  95. package/dist/mcp/tools/index.js.map +0 -1
  96. package/dist/src/audio.d.ts.map +0 -1
  97. package/dist/src/audio.js.map +0 -1
  98. package/dist/src/cli-helpers.d.ts.map +0 -1
  99. package/dist/src/cli-helpers.js.map +0 -1
  100. package/dist/src/cli.d.ts.map +0 -1
  101. package/dist/src/cli.js.map +0 -1
  102. package/dist/src/config.d.ts.map +0 -1
  103. package/dist/src/config.js.map +0 -1
  104. package/dist/src/environment.d.ts.map +0 -1
  105. package/dist/src/environment.js.map +0 -1
  106. package/dist/src/github.d.ts.map +0 -1
  107. package/dist/src/github.js.map +0 -1
  108. package/dist/src/index.d.ts.map +0 -1
  109. package/dist/src/index.js.map +0 -1
  110. package/dist/src/langfuse/client.d.ts.map +0 -1
  111. package/dist/src/langfuse/client.js.map +0 -1
  112. package/dist/src/langfuse/comments.d.ts.map +0 -1
  113. package/dist/src/langfuse/comments.js.map +0 -1
  114. package/dist/src/langfuse/datasets.d.ts.map +0 -1
  115. package/dist/src/langfuse/datasets.js.map +0 -1
  116. package/dist/src/langfuse/index.d.ts.map +0 -1
  117. package/dist/src/langfuse/index.js.map +0 -1
  118. package/dist/src/langfuse/media.d.ts.map +0 -1
  119. package/dist/src/langfuse/media.js.map +0 -1
  120. package/dist/src/langfuse/observations.d.ts.map +0 -1
  121. package/dist/src/langfuse/observations.js.map +0 -1
  122. package/dist/src/langfuse/prompts.d.ts.map +0 -1
  123. package/dist/src/langfuse/prompts.js.map +0 -1
  124. package/dist/src/langfuse/scores.d.ts.map +0 -1
  125. package/dist/src/langfuse/scores.js.map +0 -1
  126. package/dist/src/langfuse/traces.d.ts.map +0 -1
  127. package/dist/src/langfuse/traces.js.map +0 -1
  128. package/dist/src/llm.d.ts.map +0 -1
  129. package/dist/src/llm.js.map +0 -1
  130. package/dist/src/narrative/graph-manager.d.ts.map +0 -1
  131. package/dist/src/narrative/graph-manager.js.map +0 -1
  132. package/dist/src/narrative/index.d.ts.map +0 -1
  133. package/dist/src/narrative/index.js.map +0 -1
  134. package/dist/src/narrative/markdown-export.d.ts.map +0 -1
  135. package/dist/src/narrative/markdown-export.js.map +0 -1
  136. package/dist/src/narrative/tool-definitions.d.ts.map +0 -1
  137. package/dist/src/narrative/tool-definitions.js.map +0 -1
  138. package/dist/src/narrative/tool-handlers.d.ts.map +0 -1
  139. package/dist/src/narrative/tool-handlers.js.map +0 -1
  140. package/dist/src/narrative/types.d.ts.map +0 -1
  141. package/dist/src/narrative/types.js.map +0 -1
  142. package/dist/src/narrative/validation.d.ts.map +0 -1
  143. package/dist/src/narrative/validation.js.map +0 -1
  144. package/dist/src/pde/index.d.ts.map +0 -1
  145. package/dist/src/pde/index.js.map +0 -1
  146. package/dist/src/pde/mcp-handlers.d.ts.map +0 -1
  147. package/dist/src/pde/mcp-handlers.js.map +0 -1
  148. package/dist/src/pde/mcp-tools.d.ts.map +0 -1
  149. package/dist/src/pde/mcp-tools.js.map +0 -1
  150. package/dist/src/pde/session-manager.d.ts.map +0 -1
  151. package/dist/src/pde/session-manager.js.map +0 -1
  152. package/dist/src/pde/stc-mapper.d.ts.map +0 -1
  153. package/dist/src/pde/stc-mapper.js.map +0 -1
  154. package/dist/src/pipeline/index.d.ts.map +0 -1
  155. package/dist/src/pipeline/index.js.map +0 -1
  156. package/dist/src/pipeline/template-engine.d.ts.map +0 -1
  157. package/dist/src/pipeline/template-engine.js.map +0 -1
  158. package/dist/src/planning/index.d.ts.map +0 -1
  159. package/dist/src/planning/index.js.map +0 -1
  160. package/dist/src/planning/mcp-handlers.d.ts.map +0 -1
  161. package/dist/src/planning/mcp-handlers.js.map +0 -1
  162. package/dist/src/planning/mcp-tools.d.ts.map +0 -1
  163. package/dist/src/planning/mcp-tools.js.map +0 -1
  164. package/dist/src/planning/plan-parser.d.ts.map +0 -1
  165. package/dist/src/planning/plan-parser.js.map +0 -1
  166. package/dist/src/redis.d.ts.map +0 -1
  167. package/dist/src/redis.js.map +0 -1
  168. package/dist/src/types.d.ts.map +0 -1
  169. package/dist/src/types.js.map +0 -1
package/src/cli.ts ADDED
@@ -0,0 +1,1260 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import chalk from 'chalk';
4
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
5
+ import { resolve } from 'node:path';
6
+
7
+ import { tash, fetch as redisFetch, keys as redisKeys, disconnect as redisDisconnect } from './redis.js';
8
+ import { readConfig, getConfig } from './config.js';
9
+ import { llm as llmCall, transcribeAudio, abstractProcess } from './llm.js';
10
+ import { listIssues, getIssue } from './github.js';
11
+ import { createEnvironment, findEnvironment } from './environment.js';
12
+ import {
13
+ formatTable, formatJson, formatError, formatSuccess,
14
+ truncate, formatDate, formatProgress, setColorEnabled,
15
+ } from './cli-helpers.js';
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Types
19
+ // ---------------------------------------------------------------------------
20
+
21
+ interface GlobalOpts {
22
+ env?: string;
23
+ memoryPath?: string;
24
+ color: boolean;
25
+ json: boolean;
26
+ }
27
+
28
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
+ type AnyModule = Record<string, (...args: any[]) => any>;
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Helpers
33
+ // ---------------------------------------------------------------------------
34
+
35
+ async function loadModule(name: string): Promise<AnyModule> {
36
+ const paths: Record<string, string> = {
37
+ langfuse: './langfuse/index.js',
38
+ narrative: './narrative/index.js',
39
+ pde: './pde/index.js',
40
+ planning: './planning/index.js',
41
+ pipeline: './pipeline/index.js',
42
+ };
43
+ const p = paths[name];
44
+ if (!p) throw new Error(`Unknown module: ${name}`);
45
+ try {
46
+ return (await import(p)) as AnyModule;
47
+ } catch {
48
+ throw new Error(`Module '${name}' is not yet implemented. Expected at ${p}`);
49
+ }
50
+ }
51
+
52
+ async function callModule(moduleName: string, funcName: string, ...args: unknown[]): Promise<unknown> {
53
+ const mod = await loadModule(moduleName);
54
+ const fn = mod[funcName];
55
+ if (typeof fn !== 'function') {
56
+ throw new Error(`${moduleName}.${funcName} is not available`);
57
+ }
58
+ return fn(...args);
59
+ }
60
+
61
+ function globals(cmd: Command): GlobalOpts {
62
+ return cmd.optsWithGlobals() as GlobalOpts;
63
+ }
64
+
65
+ function output(data: unknown, cmd: Command): void {
66
+ if (globals(cmd).json) {
67
+ console.log(formatJson(data));
68
+ } else if (typeof data === 'string') {
69
+ console.log(data);
70
+ } else {
71
+ console.log(formatJson(data));
72
+ }
73
+ }
74
+
75
+ async function readStdin(): Promise<string> {
76
+ if (process.stdin.isTTY) return '';
77
+ const chunks: string[] = [];
78
+ for await (const chunk of process.stdin) {
79
+ chunks.push(String(chunk));
80
+ }
81
+ return chunks.join('');
82
+ }
83
+
84
+ function parseInteger(value: string): number {
85
+ return parseInt(value, 10);
86
+ }
87
+
88
+ function resolveText(
89
+ positional: string | undefined,
90
+ opts: { file?: string },
91
+ ): string | undefined {
92
+ if (opts.file) return readFileSync(resolve(opts.file), 'utf-8');
93
+ return positional;
94
+ }
95
+
96
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
+ function actionHandler(
98
+ fn: (...args: any[]) => Promise<void>,
99
+ ): (...args: any[]) => Promise<void> {
100
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
101
+ return async (...args: any[]) => {
102
+ try {
103
+ await fn(...args);
104
+ } catch (err) {
105
+ console.error(formatError(err instanceof Error ? err.message : String(err)));
106
+ process.exit(1);
107
+ }
108
+ };
109
+ }
110
+
111
+ // ---------------------------------------------------------------------------
112
+ // Root commands
113
+ // ---------------------------------------------------------------------------
114
+
115
+ function registerRootCommands(program: Command): void {
116
+ // ── tash ─────────────────────────────────────────────────────────────
117
+ program
118
+ .command('tash')
119
+ .alias('m')
120
+ .description('Store a key-value pair in Redis')
121
+ .argument('<key>', 'Redis key')
122
+ .argument('[value]', 'Value to store')
123
+ .option('-F, --file <path>', 'Read value from file')
124
+ .option('-T, --ttl <minutes>', 'Time to live in minutes', parseInteger, 5555)
125
+ .option('-v, --verbose', 'Verbose output')
126
+ .action(
127
+ actionHandler(async (key: string, value: string | undefined, opts: { file?: string; ttl?: number; verbose?: boolean }, cmd: Command) => {
128
+ const val = resolveText(value, opts);
129
+ if (!val) {
130
+ console.error(formatError('Value required — provide as argument or with --file'));
131
+ process.exit(1);
132
+ }
133
+ await tash(key, val, opts.ttl);
134
+ if (opts.verbose) {
135
+ console.log(formatSuccess(`Stored ${key} (${val.length} bytes${opts.ttl ? `, ttl=${opts.ttl}m` : ''})`));
136
+ } else {
137
+ console.log(formatSuccess(`Stored ${key}`));
138
+ }
139
+ }),
140
+ );
141
+
142
+ // ── fetch ────────────────────────────────────────────────────────────
143
+ program
144
+ .command('fetch')
145
+ .description('Get a value from Redis')
146
+ .argument('<key>', 'Redis key')
147
+ .option('-O, --output <path>', 'Write result to file')
148
+ .option('-v, --verbose', 'Verbose output')
149
+ .action(
150
+ actionHandler(async (key: string, opts: { output?: string; verbose?: boolean }, cmd: Command) => {
151
+ const result = await redisFetch(key);
152
+ if (result === null) {
153
+ console.error(formatError(`Key not found: ${key}`));
154
+ process.exit(1);
155
+ }
156
+ if (opts.output) {
157
+ writeFileSync(resolve(opts.output), result);
158
+ console.log(formatSuccess(`Written to ${opts.output}`));
159
+ } else {
160
+ output(result, cmd);
161
+ }
162
+ }),
163
+ );
164
+
165
+ // ── transcribe ───────────────────────────────────────────────────────
166
+ program
167
+ .command('transcribe')
168
+ .alias('t')
169
+ .description('Transcribe audio via Whisper')
170
+ .argument('<file>', 'Audio file path')
171
+ .option('--output <path>', 'Write transcript to file')
172
+ .action(
173
+ actionHandler(async (file: string, opts: { output?: string }, cmd: Command) => {
174
+ const result = await transcribeAudio(resolve(file));
175
+ if (opts.output) {
176
+ writeFileSync(resolve(opts.output), result);
177
+ console.log(formatSuccess(`Transcript written to ${opts.output}`));
178
+ } else {
179
+ output(result, cmd);
180
+ }
181
+ }),
182
+ );
183
+
184
+ // ── summarize ────────────────────────────────────────────────────────
185
+ program
186
+ .command('summarize')
187
+ .alias('s')
188
+ .description('Summarize text')
189
+ .argument('[text]', 'Text to summarize')
190
+ .option('--output <path>', 'Write summary to file')
191
+ .option('--file <path>', 'Read text from file')
192
+ .action(
193
+ actionHandler(async (text: string | undefined, opts: { output?: string; file?: string }, cmd: Command) => {
194
+ let input = resolveText(text, opts);
195
+ if (!input) input = await readStdin();
196
+ if (!input) {
197
+ console.error(formatError('Text required — provide as argument, --file, or pipe via stdin'));
198
+ process.exit(1);
199
+ }
200
+ const result = await abstractProcess('summarize', input);
201
+ if (opts.output) {
202
+ writeFileSync(resolve(opts.output), result);
203
+ console.log(formatSuccess(`Summary written to ${opts.output}`));
204
+ } else {
205
+ output(result, cmd);
206
+ }
207
+ }),
208
+ );
209
+
210
+ // ── p (process) ──────────────────────────────────────────────────────
211
+ program
212
+ .command('p')
213
+ .description('Process text with a custom tag')
214
+ .argument('<tag>', 'Processing tag')
215
+ .argument('[text]', 'Text to process')
216
+ .option('--output <path>', 'Write result to file')
217
+ .option('--file <path>', 'Read text from file')
218
+ .action(
219
+ actionHandler(async (tag: string, text: string | undefined, opts: { output?: string; file?: string }, cmd: Command) => {
220
+ let input = resolveText(text, opts);
221
+ if (!input) input = await readStdin();
222
+ if (!input) {
223
+ console.error(formatError('Text required — provide as argument, --file, or pipe via stdin'));
224
+ process.exit(1);
225
+ }
226
+ const result = await abstractProcess(tag, input);
227
+ if (opts.output) {
228
+ writeFileSync(resolve(opts.output), result);
229
+ console.log(formatSuccess(`Result written to ${opts.output}`));
230
+ } else {
231
+ output(result, cmd);
232
+ }
233
+ }),
234
+ );
235
+
236
+ // ── init ─────────────────────────────────────────────────────────────
237
+ program
238
+ .command('init')
239
+ .description('Create a sample coaia.json config')
240
+ .action(
241
+ actionHandler(async () => {
242
+ const target = resolve('coaia.json');
243
+ if (existsSync(target)) {
244
+ console.error(formatError('coaia.json already exists'));
245
+ process.exit(1);
246
+ }
247
+ const sample = {
248
+ redis: { url: 'redis://localhost:6379' },
249
+ langfuse: { publicKey: '', secretKey: '', baseUrl: 'https://cloud.langfuse.com' },
250
+ openai: { apiKey: '', model: 'gpt-4o-mini' },
251
+ github: { token: '' },
252
+ };
253
+ writeFileSync(target, JSON.stringify(sample, null, 2) + '\n');
254
+ console.log(formatSuccess('Created coaia.json'));
255
+ }),
256
+ );
257
+
258
+ // ── llm ──────────────────────────────────────────────────────────────
259
+ program
260
+ .command('llm')
261
+ .description('Make a raw LLM call')
262
+ .argument('<user>', 'User message')
263
+ .argument('[system]', 'System message')
264
+ .option('--temperature <n>', 'Temperature (0-2)', parseFloat)
265
+ .action(
266
+ actionHandler(async (user: string, system: string | undefined, opts: { temperature?: number }, cmd: Command) => {
267
+ const result = await llmCall(user, system, opts.temperature);
268
+ output(result, cmd);
269
+ }),
270
+ );
271
+ }
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // Fuse (Langfuse) commands
275
+ // ---------------------------------------------------------------------------
276
+
277
+ function registerFuseCommands(program: Command): void {
278
+ const fuse = program
279
+ .command('fuse')
280
+ .description('Langfuse operations');
281
+
282
+ // ── comments ─────────────────────────────────────────────────────────
283
+ const comments = fuse.command('comments').description('Comment operations');
284
+
285
+ comments
286
+ .command('list')
287
+ .description('List comments')
288
+ .option('--trace-id <id>', 'Filter by trace ID')
289
+ .option('--page <n>', 'Page number', parseInt)
290
+ .option('--limit <n>', 'Results per page', parseInt)
291
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
292
+ const result = await callModule('langfuse', 'listComments', opts);
293
+ output(result, cmd);
294
+ }));
295
+
296
+ comments
297
+ .command('post')
298
+ .description('Post a comment')
299
+ .option('--trace-id <id>', 'Trace ID')
300
+ .option('--content <text>', 'Comment content')
301
+ .option('--author <name>', 'Author name')
302
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
303
+ const result = await callModule('langfuse', 'postComment', opts);
304
+ output(result, cmd);
305
+ }));
306
+
307
+ // ── prompts ──────────────────────────────────────────────────────────
308
+ const prompts = fuse.command('prompts').description('Prompt management');
309
+
310
+ prompts
311
+ .command('list')
312
+ .description('List prompts')
313
+ .option('--page <n>', 'Page number', parseInt)
314
+ .option('--limit <n>', 'Results per page', parseInt)
315
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
316
+ const result = await callModule('langfuse', 'listPrompts', opts);
317
+ output(result, cmd);
318
+ }));
319
+
320
+ prompts
321
+ .command('get')
322
+ .description('Get a prompt')
323
+ .argument('<name>', 'Prompt name')
324
+ .option('--version <n>', 'Prompt version', parseInt)
325
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
326
+ const result = await callModule('langfuse', 'getPrompt', name, opts);
327
+ output(result, cmd);
328
+ }));
329
+
330
+ prompts
331
+ .command('create')
332
+ .description('Create a prompt')
333
+ .option('--name <name>', 'Prompt name')
334
+ .option('--prompt <text>', 'Prompt text')
335
+ .option('--model <model>', 'Model name')
336
+ .option('--config <json>', 'Config JSON')
337
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
338
+ const result = await callModule('langfuse', 'createPrompt', opts);
339
+ output(result, cmd);
340
+ }));
341
+
342
+ // ── datasets ─────────────────────────────────────────────────────────
343
+ const datasets = fuse.command('datasets').description('Dataset management');
344
+
345
+ datasets
346
+ .command('list')
347
+ .description('List datasets')
348
+ .option('--page <n>', 'Page number', parseInt)
349
+ .option('--limit <n>', 'Results per page', parseInt)
350
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
351
+ const result = await callModule('langfuse', 'listDatasets', opts);
352
+ output(result, cmd);
353
+ }));
354
+
355
+ datasets
356
+ .command('get')
357
+ .description('Get a dataset')
358
+ .argument('<name>', 'Dataset name')
359
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
360
+ const result = await callModule('langfuse', 'getDataset', name);
361
+ output(result, cmd);
362
+ }));
363
+
364
+ datasets
365
+ .command('create')
366
+ .description('Create a dataset')
367
+ .option('--name <name>', 'Dataset name')
368
+ .option('--description <text>', 'Description')
369
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
370
+ const result = await callModule('langfuse', 'createDataset', opts);
371
+ output(result, cmd);
372
+ }));
373
+
374
+ // ── sessions ─────────────────────────────────────────────────────────
375
+ const sessions = fuse.command('sessions').description('Session management');
376
+
377
+ sessions
378
+ .command('create')
379
+ .description('Create a session')
380
+ .option('--id <id>', 'Session ID')
381
+ .option('--project-id <id>', 'Project ID')
382
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
383
+ const result = await callModule('langfuse', 'createSession', opts);
384
+ output(result, cmd);
385
+ }));
386
+
387
+ sessions
388
+ .command('addnode')
389
+ .description('Add a node to a session')
390
+ .option('--session-id <id>', 'Session ID')
391
+ .option('--trace-id <id>', 'Trace ID')
392
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
393
+ const result = await callModule('langfuse', 'addSessionNode', opts);
394
+ output(result, cmd);
395
+ }));
396
+
397
+ sessions
398
+ .command('view')
399
+ .description('View a session')
400
+ .argument('<sessionId>', 'Session ID')
401
+ .action(actionHandler(async (sessionId: string, opts: Record<string, unknown>, cmd: Command) => {
402
+ const result = await callModule('langfuse', 'viewSession', sessionId);
403
+ output(result, cmd);
404
+ }));
405
+
406
+ // ── scores ───────────────────────────────────────────────────────────
407
+ const scores = fuse.command('scores').alias('sc').description('Score management');
408
+
409
+ scores
410
+ .command('create')
411
+ .description('Create a score')
412
+ .option('--name <name>', 'Score name')
413
+ .option('--trace-id <id>', 'Trace ID')
414
+ .option('--observation-id <id>', 'Observation ID')
415
+ .option('--value <n>', 'Score value', parseFloat)
416
+ .option('--data-type <type>', 'Data type (NUMERIC|CATEGORICAL|BOOLEAN)')
417
+ .option('--comment <text>', 'Comment')
418
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
419
+ const result = await callModule('langfuse', 'createScore', opts);
420
+ output(result, cmd);
421
+ }));
422
+
423
+ scores
424
+ .command('apply')
425
+ .description('Apply a score config')
426
+ .option('--config <name>', 'Score config name')
427
+ .option('--trace-id <id>', 'Trace ID')
428
+ .option('--value <n>', 'Score value', parseFloat)
429
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
430
+ const result = await callModule('langfuse', 'applyScore', opts);
431
+ output(result, cmd);
432
+ }));
433
+
434
+ scores
435
+ .command('list')
436
+ .description('List scores')
437
+ .option('--trace-id <id>', 'Filter by trace ID')
438
+ .option('--name <name>', 'Filter by name')
439
+ .option('--page <n>', 'Page number', parseInt)
440
+ .option('--limit <n>', 'Results per page', parseInt)
441
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
442
+ const result = await callModule('langfuse', 'listScores', opts);
443
+ output(result, cmd);
444
+ }));
445
+
446
+ // ── score-configs ────────────────────────────────────────────────────
447
+ const scc = fuse.command('score-configs').alias('scc').description('Score config management');
448
+
449
+ scc
450
+ .command('list')
451
+ .description('List score configs')
452
+ .option('--page <n>', 'Page number', parseInt)
453
+ .option('--limit <n>', 'Results per page', parseInt)
454
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
455
+ const result = await callModule('langfuse', 'listScoreConfigs', opts);
456
+ output(result, cmd);
457
+ }));
458
+
459
+ scc
460
+ .command('get')
461
+ .description('Get a score config')
462
+ .argument('<name>', 'Config name')
463
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
464
+ const result = await callModule('langfuse', 'getScoreConfig', name);
465
+ output(result, cmd);
466
+ }));
467
+
468
+ scc
469
+ .command('create')
470
+ .description('Create a score config')
471
+ .option('--name <name>', 'Config name')
472
+ .option('--data-type <type>', 'NUMERIC | CATEGORICAL | BOOLEAN')
473
+ .option('--description <text>', 'Description')
474
+ .option('--min <n>', 'Min value (NUMERIC)', parseFloat)
475
+ .option('--max <n>', 'Max value (NUMERIC)', parseFloat)
476
+ .option('--categories <json>', 'Categories JSON (CATEGORICAL)')
477
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
478
+ const result = await callModule('langfuse', 'createScoreConfig', opts);
479
+ output(result, cmd);
480
+ }));
481
+
482
+ scc
483
+ .command('export')
484
+ .description('Export score configs')
485
+ .option('--output <path>', 'Output file path')
486
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
487
+ const result = await callModule('langfuse', 'exportScoreConfigs', opts);
488
+ output(result, cmd);
489
+ }));
490
+
491
+ scc
492
+ .command('import')
493
+ .description('Import score configs')
494
+ .argument('<path>', 'Config file path')
495
+ .action(actionHandler(async (path: string, opts: Record<string, unknown>, cmd: Command) => {
496
+ const result = await callModule('langfuse', 'importScoreConfigs', resolve(path));
497
+ output(result, cmd);
498
+ }));
499
+
500
+ scc
501
+ .command('presets')
502
+ .description('List available presets')
503
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
504
+ const result = await callModule('langfuse', 'listScoreConfigPresets');
505
+ output(result, cmd);
506
+ }));
507
+
508
+ scc
509
+ .command('apply')
510
+ .description('Apply a preset')
511
+ .argument('<preset>', 'Preset name')
512
+ .action(actionHandler(async (preset: string, opts: Record<string, unknown>, cmd: Command) => {
513
+ const result = await callModule('langfuse', 'applyScoreConfigPreset', preset);
514
+ output(result, cmd);
515
+ }));
516
+
517
+ scc
518
+ .command('available')
519
+ .description('Show available score types')
520
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
521
+ const result = await callModule('langfuse', 'availableScoreTypes');
522
+ output(result, cmd);
523
+ }));
524
+
525
+ scc
526
+ .command('show')
527
+ .description('Show a score config in detail')
528
+ .argument('<name>', 'Config name')
529
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
530
+ const result = await callModule('langfuse', 'showScoreConfig', name);
531
+ output(result, cmd);
532
+ }));
533
+
534
+ // ── traces ───────────────────────────────────────────────────────────
535
+ const traces = fuse.command('traces').description('Trace operations');
536
+
537
+ traces
538
+ .command('list')
539
+ .description('List traces with optional filters')
540
+ .option('--session-id <id>', 'Filter by session ID')
541
+ .option('--user-id <id>', 'Filter by user ID')
542
+ .option('--name <name>', 'Filter by trace name')
543
+ .option('--tags <tags>', 'Comma-separated tags to filter by')
544
+ .option('--from <timestamp>', 'From timestamp (ISO 8601)')
545
+ .option('--to <timestamp>', 'To timestamp (ISO 8601)')
546
+ .option('--order-by <field>', 'Order by field')
547
+ .option('--page <n>', 'Page number', parseInt)
548
+ .option('--limit <n>', 'Items per page (default 50)', parseInt)
549
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
550
+ const filters = {
551
+ sessionId: opts.sessionId as string | undefined,
552
+ userId: opts.userId as string | undefined,
553
+ name: opts.name as string | undefined,
554
+ tags: opts.tags ? (opts.tags as string).split(',').map((t: string) => t.trim()) : undefined,
555
+ fromTimestamp: opts.from as string | undefined,
556
+ toTimestamp: opts.to as string | undefined,
557
+ orderBy: opts.orderBy as string | undefined,
558
+ page: opts.page as number | undefined,
559
+ limit: opts.limit as number | undefined,
560
+ };
561
+ const raw = await callModule('langfuse', 'listTraces', filters) as string;
562
+ if (globals(cmd).json) {
563
+ console.log(raw);
564
+ } else {
565
+ const formatted = await callModule('langfuse', 'formatTracesMarkdown', raw);
566
+ console.log(formatted);
567
+ }
568
+ }));
569
+
570
+ traces
571
+ .command('create')
572
+ .description('Create a trace')
573
+ .option('--name <name>', 'Trace name')
574
+ .option('--session-id <id>', 'Session ID')
575
+ .option('--input <json>', 'Input JSON')
576
+ .option('--metadata <json>', 'Metadata JSON')
577
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
578
+ const result = await callModule('langfuse', 'createTrace', opts);
579
+ output(result, cmd);
580
+ }));
581
+
582
+ traces
583
+ .command('add-observation')
584
+ .description('Add an observation to a trace')
585
+ .option('--trace-id <id>', 'Trace ID')
586
+ .option('--name <name>', 'Observation name')
587
+ .option('--type <type>', 'Type: generation | span | event')
588
+ .option('--input <json>', 'Input JSON')
589
+ .option('--output <json>', 'Output JSON')
590
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
591
+ const result = await callModule('langfuse', 'addObservation', opts);
592
+ output(result, cmd);
593
+ }));
594
+
595
+ traces
596
+ .command('add-observations')
597
+ .description('Add multiple observations from a file')
598
+ .option('--trace-id <id>', 'Trace ID')
599
+ .option('--file <path>', 'JSON file with observations')
600
+ .action(actionHandler(async (opts: { traceId?: string; file?: string }, cmd: Command) => {
601
+ let data: unknown = opts;
602
+ if (opts.file) {
603
+ const raw = readFileSync(resolve(opts.file), 'utf-8');
604
+ data = { traceId: opts.traceId, observations: JSON.parse(raw) };
605
+ }
606
+ const result = await callModule('langfuse', 'addObservations', data);
607
+ output(result, cmd);
608
+ }));
609
+
610
+ traces
611
+ .command('patch-output')
612
+ .description('Patch trace output')
613
+ .option('--trace-id <id>', 'Trace ID')
614
+ .option('--output <json>', 'Output JSON')
615
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
616
+ const result = await callModule('langfuse', 'patchTraceOutput', opts);
617
+ output(result, cmd);
618
+ }));
619
+
620
+ traces
621
+ .command('session-view')
622
+ .description('View traces by session')
623
+ .argument('<sessionId>', 'Session ID')
624
+ .action(actionHandler(async (sessionId: string, opts: Record<string, unknown>, cmd: Command) => {
625
+ const result = await callModule('langfuse', 'sessionView', sessionId);
626
+ output(result, cmd);
627
+ }));
628
+
629
+ traces
630
+ .command('trace-view')
631
+ .description('View a specific trace')
632
+ .argument('<traceId>', 'Trace ID')
633
+ .action(actionHandler(async (traceId: string, opts: Record<string, unknown>, cmd: Command) => {
634
+ const result = await callModule('langfuse', 'traceView', traceId);
635
+ output(result, cmd);
636
+ }));
637
+
638
+ traces
639
+ .command('get-observation')
640
+ .description('Get an observation')
641
+ .argument('<observationId>', 'Observation ID')
642
+ .action(actionHandler(async (observationId: string, opts: Record<string, unknown>, cmd: Command) => {
643
+ const result = await callModule('langfuse', 'getObservation', observationId);
644
+ output(result, cmd);
645
+ }));
646
+
647
+ // ── projects ─────────────────────────────────────────────────────────
648
+ fuse
649
+ .command('projects')
650
+ .description('List projects')
651
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
652
+ const result = await callModule('langfuse', 'listProjects');
653
+ output(result, cmd);
654
+ }));
655
+
656
+ // ── media ────────────────────────────────────────────────────────────
657
+ const media = fuse.command('media').description('Media operations');
658
+
659
+ media
660
+ .command('upload')
661
+ .description('Upload a media file')
662
+ .argument('<file>', 'File path')
663
+ .option('--trace-id <id>', 'Associate with trace')
664
+ .action(actionHandler(async (file: string, opts: Record<string, unknown>, cmd: Command) => {
665
+ const result = await callModule('langfuse', 'uploadMedia', resolve(file), opts);
666
+ output(result, cmd);
667
+ }));
668
+
669
+ media
670
+ .command('get')
671
+ .description('Get media details')
672
+ .argument('<mediaId>', 'Media ID')
673
+ .action(actionHandler(async (mediaId: string, opts: Record<string, unknown>, cmd: Command) => {
674
+ const result = await callModule('langfuse', 'getMedia', mediaId);
675
+ output(result, cmd);
676
+ }));
677
+
678
+ // ── dataset-items ────────────────────────────────────────────────────
679
+ const datasetItems = fuse.command('dataset-items').description('Dataset item operations');
680
+
681
+ datasetItems
682
+ .command('create')
683
+ .description('Create a dataset item')
684
+ .option('--dataset <name>', 'Dataset name')
685
+ .option('--input <json>', 'Input JSON')
686
+ .option('--expected <json>', 'Expected output JSON')
687
+ .option('--metadata <json>', 'Metadata JSON')
688
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
689
+ const result = await callModule('langfuse', 'createDatasetItem', opts);
690
+ output(result, cmd);
691
+ }));
692
+ }
693
+
694
+ // ---------------------------------------------------------------------------
695
+ // Pipeline commands
696
+ // ---------------------------------------------------------------------------
697
+
698
+ function registerPipelineCommands(program: Command): void {
699
+ const pipeline = program
700
+ .command('pipeline')
701
+ .description('Pipeline template operations');
702
+
703
+ pipeline
704
+ .command('list')
705
+ .description('List pipeline templates')
706
+ .option('--path <dir>', 'Templates directory')
707
+ .option('--json', 'JSON output')
708
+ .action(actionHandler(async (opts: { path?: string; json?: boolean }, cmd: Command) => {
709
+ const result = await callModule('pipeline', 'listTemplates', opts);
710
+ output(result, cmd);
711
+ }));
712
+
713
+ pipeline
714
+ .command('show')
715
+ .description('Show a pipeline template')
716
+ .argument('<name>', 'Template name')
717
+ .option('--preview', 'Preview rendered template')
718
+ .action(actionHandler(async (name: string, opts: { preview?: boolean }, cmd: Command) => {
719
+ const result = await callModule('pipeline', 'showTemplate', name, opts);
720
+ output(result, cmd);
721
+ }));
722
+
723
+ pipeline
724
+ .command('create')
725
+ .description('Create a run from template')
726
+ .argument('<name>', 'Template name')
727
+ .option(
728
+ '--var <pair>',
729
+ 'Template variable (KEY=value), repeatable',
730
+ (val: string, list: string[]) => { list.push(val); return list; },
731
+ [] as string[],
732
+ )
733
+ .option('--trace-id <id>', 'Trace ID')
734
+ .option('--session-id <id>', 'Session ID')
735
+ .option('--dry-run', 'Preview without executing')
736
+ .action(actionHandler(async (name: string, opts: { var: string[]; traceId?: string; sessionId?: string; dryRun?: boolean }, cmd: Command) => {
737
+ const vars: Record<string, string> = {};
738
+ for (const pair of opts.var) {
739
+ const eq = pair.indexOf('=');
740
+ if (eq === -1) { console.error(formatError(`Invalid --var format: ${pair} (expected KEY=value)`)); process.exit(1); }
741
+ vars[pair.slice(0, eq)] = pair.slice(eq + 1);
742
+ }
743
+ const result = await callModule('pipeline', 'createFromTemplate', name, {
744
+ variables: vars,
745
+ traceId: opts.traceId,
746
+ sessionId: opts.sessionId,
747
+ dryRun: opts.dryRun,
748
+ });
749
+ output(result, cmd);
750
+ }));
751
+
752
+ pipeline
753
+ .command('init')
754
+ .description('Create a new pipeline template')
755
+ .argument('<name>', 'Template name')
756
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
757
+ const result = await callModule('pipeline', 'initTemplate', name);
758
+ output(result, cmd);
759
+ }));
760
+ }
761
+
762
+ // ---------------------------------------------------------------------------
763
+ // Environment commands
764
+ // ---------------------------------------------------------------------------
765
+
766
+ function registerEnvCommands(program: Command): void {
767
+ const env = program
768
+ .command('env')
769
+ .description('Environment variable management');
770
+
771
+ env
772
+ .command('init')
773
+ .description('Initialize environment file')
774
+ .action(actionHandler(async () => {
775
+ const mgr = createEnvironment();
776
+ mgr.init();
777
+ console.log(formatSuccess(`Initialized ${mgr.getFilePath()}`));
778
+ }));
779
+
780
+ env
781
+ .command('list')
782
+ .description('List environment variables')
783
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
784
+ const mgr = findEnvironment();
785
+ const vars = mgr.list();
786
+ if (globals(cmd).json) {
787
+ console.log(formatJson(vars));
788
+ } else {
789
+ const entries = Object.entries(vars);
790
+ if (entries.length === 0) {
791
+ console.log('(no variables set)');
792
+ } else {
793
+ console.log(formatTable(
794
+ ['Key', 'Value'],
795
+ entries.map(([k, v]) => [k, truncate(v, 60)]),
796
+ ));
797
+ }
798
+ }
799
+ }));
800
+
801
+ env
802
+ .command('source')
803
+ .description('Load env vars into process')
804
+ .action(actionHandler(async () => {
805
+ const mgr = findEnvironment();
806
+ mgr.source();
807
+ console.log(formatSuccess('Environment loaded'));
808
+ }));
809
+
810
+ env
811
+ .command('set')
812
+ .description('Set an environment variable')
813
+ .argument('<key>', 'Variable name')
814
+ .argument('<value>', 'Variable value')
815
+ .action(actionHandler(async (key: string, value: string) => {
816
+ const mgr = findEnvironment();
817
+ mgr.set(key, value);
818
+ console.log(formatSuccess(`Set ${key}`));
819
+ }));
820
+
821
+ env
822
+ .command('get')
823
+ .description('Get an environment variable')
824
+ .argument('<key>', 'Variable name')
825
+ .action(actionHandler(async (key: string, opts: Record<string, unknown>, cmd: Command) => {
826
+ const mgr = findEnvironment();
827
+ const value = mgr.get(key);
828
+ if (value === undefined) {
829
+ console.error(formatError(`Variable not set: ${key}`));
830
+ process.exit(1);
831
+ }
832
+ output(value, cmd);
833
+ }));
834
+
835
+ env
836
+ .command('unset')
837
+ .description('Remove an environment variable')
838
+ .argument('<key>', 'Variable name')
839
+ .action(actionHandler(async (key: string) => {
840
+ const mgr = findEnvironment();
841
+ mgr.unset(key);
842
+ console.log(formatSuccess(`Unset ${key}`));
843
+ }));
844
+
845
+ env
846
+ .command('clear')
847
+ .description('Remove environment file')
848
+ .action(actionHandler(async () => {
849
+ const mgr = findEnvironment();
850
+ mgr.clear();
851
+ console.log(formatSuccess('Environment cleared'));
852
+ }));
853
+
854
+ env
855
+ .command('save')
856
+ .description('Save current context')
857
+ .action(actionHandler(async () => {
858
+ const mgr = findEnvironment();
859
+ mgr.save();
860
+ console.log(formatSuccess(`Saved to ${mgr.getFilePath()}`));
861
+ }));
862
+ }
863
+
864
+ // ---------------------------------------------------------------------------
865
+ // GitHub commands
866
+ // ---------------------------------------------------------------------------
867
+
868
+ function registerGhCommands(program: Command): void {
869
+ const gh = program
870
+ .command('gh')
871
+ .description('GitHub operations');
872
+
873
+ const issues = gh.command('issues').description('Issue operations');
874
+
875
+ issues
876
+ .command('list')
877
+ .description('List issues')
878
+ .requiredOption('--owner <owner>', 'Repository owner')
879
+ .requiredOption('--repo <repo>', 'Repository name')
880
+ .option('--state <state>', 'Filter: open | closed | all', 'open')
881
+ .option('--labels <labels>', 'Comma-separated labels')
882
+ .option('--per-page <n>', 'Results per page', parseInt)
883
+ .action(actionHandler(async (opts: { owner: string; repo: string; state?: string; labels?: string; perPage?: number }, cmd: Command) => {
884
+ const result = await listIssues(opts.owner, opts.repo, {
885
+ state: opts.state as 'open' | 'closed' | 'all' | undefined,
886
+ labels: opts.labels,
887
+ per_page: opts.perPage,
888
+ });
889
+ if (globals(cmd).json) {
890
+ console.log(formatJson(result));
891
+ } else {
892
+ console.log(formatTable(
893
+ ['#', 'State', 'Title', 'Labels', 'Updated'],
894
+ result.map(i => [
895
+ String(i.number),
896
+ i.state,
897
+ truncate(i.title, 50),
898
+ i.labels.map(l => l.name).join(', '),
899
+ formatDate(i.updated_at),
900
+ ]),
901
+ ));
902
+ }
903
+ }));
904
+
905
+ issues
906
+ .command('get')
907
+ .description('Get an issue (owner/repo#123 or number with --owner/--repo)')
908
+ .argument('<spec>', 'Issue spec: owner/repo#123 or issue number')
909
+ .option('--owner <owner>', 'Repository owner')
910
+ .option('--repo <repo>', 'Repository name')
911
+ .action(actionHandler(async (spec: string, opts: { owner?: string; repo?: string }, cmd: Command) => {
912
+ let owner = opts.owner;
913
+ let repo = opts.repo;
914
+ let num: number;
915
+
916
+ const match = spec.match(/^([^/]+)\/([^#]+)#(\d+)$/);
917
+ if (match) {
918
+ owner = match[1];
919
+ repo = match[2];
920
+ num = parseInt(match[3]!, 10);
921
+ } else {
922
+ num = parseInt(spec, 10);
923
+ if (isNaN(num) || !owner || !repo) {
924
+ console.error(formatError('Provide owner/repo#number or a number with --owner and --repo'));
925
+ process.exit(1);
926
+ }
927
+ }
928
+
929
+ const issue = await getIssue(owner!, repo!, num);
930
+ if (globals(cmd).json) {
931
+ console.log(formatJson(issue));
932
+ } else {
933
+ console.log([
934
+ `${chalk.bold(`#${issue.number}`)} ${issue.title}`,
935
+ `State: ${issue.state} Author: ${issue.user?.login ?? '?'}`,
936
+ `Labels: ${issue.labels.map(l => l.name).join(', ') || '(none)'}`,
937
+ `URL: ${issue.html_url}`,
938
+ '',
939
+ issue.body ?? '(no body)',
940
+ ].join('\n'));
941
+ }
942
+ }));
943
+ }
944
+
945
+ // ---------------------------------------------------------------------------
946
+ // Narrative commands
947
+ // ---------------------------------------------------------------------------
948
+
949
+ function registerNarrativeCommands(program: Command): void {
950
+ const narr = program
951
+ .command('narrative')
952
+ .alias('n')
953
+ .description('Structural tension narrative operations');
954
+
955
+ narr
956
+ .command('list')
957
+ .alias('ls')
958
+ .description('List active charts')
959
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
960
+ const result = await callModule('narrative', 'listCharts', globals(cmd));
961
+ output(result, cmd);
962
+ }));
963
+
964
+ narr
965
+ .command('view')
966
+ .alias('v')
967
+ .description('View chart details')
968
+ .argument('<chartId>', 'Chart ID')
969
+ .action(actionHandler(async (chartId: string, opts: Record<string, unknown>, cmd: Command) => {
970
+ const result = await callModule('narrative', 'viewChart', chartId, globals(cmd));
971
+ output(result, cmd);
972
+ }));
973
+
974
+ narr
975
+ .command('current')
976
+ .alias('cur')
977
+ .description('Show or set the current chart')
978
+ .argument('[chartId]', 'Chart ID to set as current')
979
+ .action(actionHandler(async (chartId: string | undefined, opts: Record<string, unknown>, cmd: Command) => {
980
+ if (chartId) {
981
+ await callModule('narrative', 'setCurrentChart', chartId);
982
+ console.log(formatSuccess(`Current chart set to ${chartId}`));
983
+ } else {
984
+ const result = await callModule('narrative', 'getCurrentChart');
985
+ output(result, cmd);
986
+ }
987
+ }));
988
+
989
+ narr
990
+ .command('update')
991
+ .alias('up')
992
+ .description('Update a chart')
993
+ .argument('<chartId>', 'Chart ID')
994
+ .option('--desired-outcome <text>', 'New desired outcome')
995
+ .option('--current-reality <text>', 'New current reality observation')
996
+ .action(actionHandler(async (chartId: string, opts: { desiredOutcome?: string; currentReality?: string }, cmd: Command) => {
997
+ const result = await callModule('narrative', 'updateChart', chartId, opts);
998
+ output(result, cmd);
999
+ }));
1000
+
1001
+ narr
1002
+ .command('add-action')
1003
+ .alias('aa')
1004
+ .description('Add an action step to a chart')
1005
+ .argument('<chartId>', 'Chart ID')
1006
+ .option('--title <text>', 'Action step title')
1007
+ .option('--current-reality <text>', 'Current reality for this step')
1008
+ .option('--due <date>', 'Due date (ISO)')
1009
+ .action(actionHandler(async (chartId: string, opts: { title?: string; currentReality?: string; due?: string }, cmd: Command) => {
1010
+ const result = await callModule('narrative', 'addAction', chartId, opts);
1011
+ output(result, cmd);
1012
+ }));
1013
+
1014
+ narr
1015
+ .command('add-obs')
1016
+ .alias('ao')
1017
+ .description('Add an observation to a chart')
1018
+ .argument('<chartId>', 'Chart ID')
1019
+ .argument('[text...]', 'Observation text')
1020
+ .action(actionHandler(async (chartId: string, text: string[], opts: Record<string, unknown>, cmd: Command) => {
1021
+ const observation = text.join(' ');
1022
+ if (!observation) {
1023
+ console.error(formatError('Observation text required'));
1024
+ process.exit(1);
1025
+ }
1026
+ const result = await callModule('narrative', 'addObservation', chartId, observation);
1027
+ output(result, cmd);
1028
+ }));
1029
+
1030
+ narr
1031
+ .command('complete')
1032
+ .alias('done')
1033
+ .description('Mark an action step complete')
1034
+ .argument('<actionName>', 'Action step name')
1035
+ .action(actionHandler(async (actionName: string, opts: Record<string, unknown>, cmd: Command) => {
1036
+ const result = await callModule('narrative', 'completeAction', actionName);
1037
+ if (typeof result === 'string') console.log(formatSuccess(result));
1038
+ else output(result, cmd);
1039
+ }));
1040
+
1041
+ narr
1042
+ .command('export')
1043
+ .alias('exp')
1044
+ .description('Export a chart to markdown')
1045
+ .argument('<chartId>', 'Chart ID')
1046
+ .option('--output <path>', 'Output file path')
1047
+ .action(actionHandler(async (chartId: string, opts: { output?: string }, cmd: Command) => {
1048
+ const result = await callModule('narrative', 'exportChart', chartId) as string;
1049
+ if (opts.output) {
1050
+ writeFileSync(resolve(opts.output), result);
1051
+ console.log(formatSuccess(`Exported to ${opts.output}`));
1052
+ } else {
1053
+ console.log(result);
1054
+ }
1055
+ }));
1056
+
1057
+ narr
1058
+ .command('export-all')
1059
+ .description('Export all charts to markdown')
1060
+ .option('--output <dir>', 'Output directory')
1061
+ .action(actionHandler(async (opts: { output?: string }, cmd: Command) => {
1062
+ const result = await callModule('narrative', 'exportAllCharts', opts);
1063
+ output(result, cmd);
1064
+ }));
1065
+
1066
+ narr
1067
+ .command('stats')
1068
+ .alias('st')
1069
+ .description('Show chart statistics')
1070
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
1071
+ const result = await callModule('narrative', 'getStats', globals(cmd));
1072
+ output(result, cmd);
1073
+ }));
1074
+
1075
+ narr
1076
+ .command('progress')
1077
+ .alias('pg')
1078
+ .description('Progress report for a chart')
1079
+ .argument('<chartId>', 'Chart ID')
1080
+ .action(actionHandler(async (chartId: string, opts: Record<string, unknown>, cmd: Command) => {
1081
+ const result = await callModule('narrative', 'getProgress', chartId) as {
1082
+ completed: number; total: number; chartId: string;
1083
+ } | unknown;
1084
+ if (globals(cmd).json) {
1085
+ console.log(formatJson(result));
1086
+ } else if (
1087
+ result &&
1088
+ typeof result === 'object' &&
1089
+ 'completed' in result &&
1090
+ 'total' in result
1091
+ ) {
1092
+ const r = result as { completed: number; total: number; chartId: string };
1093
+ console.log(`${chalk.bold(r.chartId)} ${formatProgress(r.completed, r.total)}`);
1094
+ } else {
1095
+ output(result, cmd);
1096
+ }
1097
+ }));
1098
+
1099
+ narr
1100
+ .command('mmot')
1101
+ .description('Run MMOT evaluation on a chart')
1102
+ .argument('<chartId>', 'Chart ID')
1103
+ .option('--assessment <text>', 'Assessment text')
1104
+ .option('--direction <dir>', 'Direction: South | East | West | North')
1105
+ .action(actionHandler(async (chartId: string, opts: { assessment?: string; direction?: string }, cmd: Command) => {
1106
+ const result = await callModule('narrative', 'performMmot', chartId, opts);
1107
+ output(result, cmd);
1108
+ }));
1109
+
1110
+ narr
1111
+ .command('set-date')
1112
+ .alias('sd')
1113
+ .description('Set due date on a chart')
1114
+ .argument('<chartId>', 'Chart ID')
1115
+ .argument('<date>', 'Due date (ISO)')
1116
+ .action(actionHandler(async (chartId: string, date: string, opts: Record<string, unknown>, cmd: Command) => {
1117
+ const result = await callModule('narrative', 'setDueDate', chartId, date);
1118
+ if (typeof result === 'string') console.log(formatSuccess(result));
1119
+ else output(result, cmd);
1120
+ }));
1121
+ }
1122
+
1123
+ // ---------------------------------------------------------------------------
1124
+ // PDE commands
1125
+ // ---------------------------------------------------------------------------
1126
+
1127
+ function registerPdeCommands(program: Command): void {
1128
+ const pde = program
1129
+ .command('pde')
1130
+ .description('Prompt Decomposition Engine');
1131
+
1132
+ pde
1133
+ .command('import')
1134
+ .description('Import a PDE decomposition into narrative')
1135
+ .argument('<pdeId>', 'Decomposition ID')
1136
+ .action(actionHandler(async (pdeId: string, opts: Record<string, unknown>, cmd: Command) => {
1137
+ const result = await callModule('pde', 'importDecomposition', pdeId);
1138
+ output(result, cmd);
1139
+ }));
1140
+
1141
+ pde
1142
+ .command('list')
1143
+ .description('List decompositions')
1144
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
1145
+ const result = await callModule('pde', 'listDecompositions');
1146
+ output(result, cmd);
1147
+ }));
1148
+
1149
+ pde
1150
+ .command('sessions')
1151
+ .description('List PDE sessions')
1152
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
1153
+ const result = await callModule('pde', 'listSessions');
1154
+ output(result, cmd);
1155
+ }));
1156
+
1157
+ pde
1158
+ .command('show')
1159
+ .description('Show session details')
1160
+ .argument('<sessionId>', 'Session ID')
1161
+ .action(actionHandler(async (sessionId: string, opts: Record<string, unknown>, cmd: Command) => {
1162
+ const result = await callModule('pde', 'showSession', sessionId);
1163
+ output(result, cmd);
1164
+ }));
1165
+ }
1166
+
1167
+ // ---------------------------------------------------------------------------
1168
+ // Planning commands
1169
+ // ---------------------------------------------------------------------------
1170
+
1171
+ function registerPlanCommands(program: Command): void {
1172
+ const plan = program
1173
+ .command('plan')
1174
+ .description('Structural tension plan operations');
1175
+
1176
+ plan
1177
+ .command('parse')
1178
+ .description('Parse a plan file structurally')
1179
+ .argument('<planPath>', 'Path to plan file')
1180
+ .action(actionHandler(async (planPath: string, opts: Record<string, unknown>, cmd: Command) => {
1181
+ const result = await callModule('planning', 'parsePlan', resolve(planPath));
1182
+ output(result, cmd);
1183
+ }));
1184
+
1185
+ plan
1186
+ .command('convert')
1187
+ .description('Convert a plan to a structural tension chart')
1188
+ .argument('<planPath>', 'Path to plan file')
1189
+ .action(actionHandler(async (planPath: string, opts: Record<string, unknown>, cmd: Command) => {
1190
+ const result = await callModule('planning', 'convertToChart', resolve(planPath));
1191
+ output(result, cmd);
1192
+ }));
1193
+
1194
+ plan
1195
+ .command('sync-to-chart')
1196
+ .description('Sync a plan file into charts')
1197
+ .argument('<planPath>', 'Path to plan file')
1198
+ .argument('<chartsPath>', 'Path to charts JSONL')
1199
+ .action(actionHandler(async (planPath: string, chartsPath: string, opts: Record<string, unknown>, cmd: Command) => {
1200
+ const result = await callModule('planning', 'syncToChart', resolve(planPath), resolve(chartsPath));
1201
+ output(result, cmd);
1202
+ }));
1203
+
1204
+ plan
1205
+ .command('sync-to-plan')
1206
+ .description('Sync chart data back to a plan file')
1207
+ .argument('<chartsPath>', 'Path to charts JSONL')
1208
+ .argument('<planPath>', 'Path to plan file')
1209
+ .action(actionHandler(async (chartsPath: string, planPath: string, opts: Record<string, unknown>, cmd: Command) => {
1210
+ const result = await callModule('planning', 'syncToPlan', resolve(chartsPath), resolve(planPath));
1211
+ output(result, cmd);
1212
+ }));
1213
+ }
1214
+
1215
+ // ---------------------------------------------------------------------------
1216
+ // Main
1217
+ // ---------------------------------------------------------------------------
1218
+
1219
+ async function main(): Promise<void> {
1220
+ const program = new Command();
1221
+
1222
+ program
1223
+ .name('coaia')
1224
+ .version('0.1.3', '-V, --version')
1225
+ .description('CoAIA unified CLI — structural tension, narrative, and DevOps tooling')
1226
+ .option('--env <path>', 'Load environment file')
1227
+ .option('-M, --memory-path <path>', 'JSONL memory file path')
1228
+ .option('--no-color', 'Disable colors')
1229
+ .option('--json', 'JSON output', false);
1230
+
1231
+ program.hook('preAction', (_thisCmd, actionCmd) => {
1232
+ const opts = actionCmd.optsWithGlobals();
1233
+ if (opts.color === false) {
1234
+ setColorEnabled(false);
1235
+ }
1236
+ if (opts.env) {
1237
+ readConfig(opts.env as string);
1238
+ }
1239
+ });
1240
+
1241
+ registerRootCommands(program);
1242
+ registerFuseCommands(program);
1243
+ registerPipelineCommands(program);
1244
+ registerEnvCommands(program);
1245
+ registerGhCommands(program);
1246
+ registerNarrativeCommands(program);
1247
+ registerPdeCommands(program);
1248
+ registerPlanCommands(program);
1249
+
1250
+ program.hook('postAction', async () => {
1251
+ try { await redisDisconnect(); } catch { /* client may not have been initialized */ }
1252
+ });
1253
+
1254
+ await program.parseAsync(process.argv);
1255
+ }
1256
+
1257
+ main().catch((err: unknown) => {
1258
+ console.error(formatError(err instanceof Error ? err.message : String(err)));
1259
+ process.exit(1);
1260
+ });