coaiajs 0.1.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 (162) hide show
  1. package/CLAUDE.md +56 -0
  2. package/KINSHIP.md +63 -0
  3. package/README.md +148 -0
  4. package/articles/academic/creative-orientation-vs-problem-solving.md +177 -0
  5. package/articles/academic/jsonl-knowledge-graphs-agent-memory.md +142 -0
  6. package/articles/academic/langfuse-observability-llm-pipelines.md +144 -0
  7. package/articles/academic/medicine-wheel-software-architecture.md +163 -0
  8. package/articles/academic/mmot-autonomous-agents.md +156 -0
  9. package/articles/academic/model-context-protocol-interagent.md +161 -0
  10. package/articles/academic/pde-prompt-decomposition.md +186 -0
  11. package/articles/academic/structural-tension-in-ai-agents.md +134 -0
  12. package/articles/reviews/mcp-protocol-design-review.md +170 -0
  13. package/articles/reviews/observability-ai-systems-review.md +176 -0
  14. package/articles/reviews/prompt-engineering-decomposition-review.md +184 -0
  15. package/articles/surveys/agent-orchestration-survey.md +186 -0
  16. package/articles/surveys/knowledge-graph-storage-survey.md +204 -0
  17. package/articles/surveys/structural-tension-methodology-survey.md +154 -0
  18. package/articles/technical/aws-sdk-v3-polly.md +270 -0
  19. package/articles/technical/commander-cli-framework.md +262 -0
  20. package/articles/technical/dotenv-config-patterns.md +360 -0
  21. package/articles/technical/ioredis-vs-redis.md +142 -0
  22. package/articles/technical/langfuse-js-sdk-vs-rest.md +191 -0
  23. package/articles/technical/mcp-sdk-typescript.md +291 -0
  24. package/articles/technical/octokit-github-api.md +293 -0
  25. package/articles/technical/openai-sdk-modern.md +231 -0
  26. package/articles/technical/yaml-parsing-node.md +266 -0
  27. package/articles/technical/zod-runtime-validation.md +212 -0
  28. package/dist/mcp/config.d.ts +14 -0
  29. package/dist/mcp/config.js +185 -0
  30. package/dist/mcp/server.d.ts +3 -0
  31. package/dist/mcp/server.js +324 -0
  32. package/dist/mcp/tools/coaiapy-tools.d.ts +8 -0
  33. package/dist/mcp/tools/coaiapy-tools.js +326 -0
  34. package/dist/mcp/tools/index.d.ts +3 -0
  35. package/dist/mcp/tools/index.js +3 -0
  36. package/dist/src/audio.d.ts +12 -0
  37. package/dist/src/audio.js +57 -0
  38. package/dist/src/cli-helpers.d.ts +9 -0
  39. package/dist/src/cli-helpers.js +78 -0
  40. package/dist/src/cli.d.ts +3 -0
  41. package/dist/src/cli.js +1086 -0
  42. package/dist/src/config.d.ts +15 -0
  43. package/dist/src/config.js +145 -0
  44. package/dist/src/environment.d.ts +44 -0
  45. package/dist/src/environment.js +146 -0
  46. package/dist/src/github.d.ts +47 -0
  47. package/dist/src/github.js +79 -0
  48. package/dist/src/langfuse/client.d.ts +30 -0
  49. package/dist/src/langfuse/client.js +75 -0
  50. package/dist/src/langfuse/comments.d.ts +16 -0
  51. package/dist/src/langfuse/comments.js +36 -0
  52. package/dist/src/langfuse/datasets.d.ts +19 -0
  53. package/dist/src/langfuse/datasets.js +140 -0
  54. package/dist/src/langfuse/index.d.ts +13 -0
  55. package/dist/src/langfuse/index.js +10 -0
  56. package/dist/src/langfuse/media.d.ts +11 -0
  57. package/dist/src/langfuse/media.js +167 -0
  58. package/dist/src/langfuse/observations.d.ts +18 -0
  59. package/dist/src/langfuse/observations.js +113 -0
  60. package/dist/src/langfuse/prompts.d.ts +14 -0
  61. package/dist/src/langfuse/prompts.js +127 -0
  62. package/dist/src/langfuse/scores.d.ts +54 -0
  63. package/dist/src/langfuse/scores.js +366 -0
  64. package/dist/src/langfuse/traces.d.ts +29 -0
  65. package/dist/src/langfuse/traces.js +225 -0
  66. package/dist/src/llm.d.ts +23 -0
  67. package/dist/src/llm.js +76 -0
  68. package/dist/src/narrative/graph-manager.d.ts +106 -0
  69. package/dist/src/narrative/graph-manager.js +915 -0
  70. package/dist/src/narrative/index.d.ts +9 -0
  71. package/dist/src/narrative/index.js +7 -0
  72. package/dist/src/narrative/markdown-export.d.ts +21 -0
  73. package/dist/src/narrative/markdown-export.js +383 -0
  74. package/dist/src/narrative/tool-definitions.d.ts +21 -0
  75. package/dist/src/narrative/tool-definitions.js +588 -0
  76. package/dist/src/narrative/tool-handlers.d.ts +11 -0
  77. package/dist/src/narrative/tool-handlers.js +462 -0
  78. package/dist/src/narrative/types.d.ts +2 -0
  79. package/dist/src/narrative/types.js +2 -0
  80. package/dist/src/narrative/validation.d.ts +29 -0
  81. package/dist/src/narrative/validation.js +144 -0
  82. package/dist/src/pde/index.d.ts +8 -0
  83. package/dist/src/pde/index.js +8 -0
  84. package/dist/src/pde/mcp-handlers.d.ts +7 -0
  85. package/dist/src/pde/mcp-handlers.js +300 -0
  86. package/dist/src/pde/mcp-tools.d.ts +15 -0
  87. package/dist/src/pde/mcp-tools.js +191 -0
  88. package/dist/src/pde/session-manager.d.ts +32 -0
  89. package/dist/src/pde/session-manager.js +205 -0
  90. package/dist/src/pde/stc-mapper.d.ts +26 -0
  91. package/dist/src/pde/stc-mapper.js +234 -0
  92. package/dist/src/pipeline/index.d.ts +2 -0
  93. package/dist/src/pipeline/index.js +3 -0
  94. package/dist/src/pipeline/template-engine.d.ts +20 -0
  95. package/dist/src/pipeline/template-engine.js +361 -0
  96. package/dist/src/planning/index.d.ts +7 -0
  97. package/dist/src/planning/index.js +7 -0
  98. package/dist/src/planning/mcp-handlers.d.ts +7 -0
  99. package/dist/src/planning/mcp-handlers.js +310 -0
  100. package/dist/src/planning/mcp-tools.d.ts +15 -0
  101. package/dist/src/planning/mcp-tools.js +145 -0
  102. package/dist/src/planning/plan-parser.d.ts +35 -0
  103. package/dist/src/planning/plan-parser.js +506 -0
  104. package/dist/src/redis.d.ts +21 -0
  105. package/dist/src/redis.js +78 -0
  106. package/dist/src/types.d.ts +244 -0
  107. package/dist/src/types.js +8 -0
  108. package/mcp/config.ts +196 -0
  109. package/mcp/server.ts +402 -0
  110. package/mcp/tools/coaiapy-tools.ts +364 -0
  111. package/mcp/tools/index.ts +4 -0
  112. package/package.json +52 -0
  113. package/rispecs/00-coaiajs-platform.spec.md +102 -0
  114. package/rispecs/01-core-config.spec.md +89 -0
  115. package/rispecs/02-redis-module.spec.md +62 -0
  116. package/rispecs/03-langfuse-module.spec.md +101 -0
  117. package/rispecs/04-narrative-engine.spec.md +185 -0
  118. package/rispecs/05-pde-engine.spec.md +112 -0
  119. package/rispecs/06-planning-engine.spec.md +128 -0
  120. package/rispecs/07-pipeline-templates.spec.md +97 -0
  121. package/rispecs/08-cli-interface.spec.md +134 -0
  122. package/rispecs/09-mcp-server.spec.md +140 -0
  123. package/rispecs/10-audio-module.spec.md +63 -0
  124. package/rispecs/KINSHIP.md +56 -0
  125. package/rispecs/README.md +100 -0
  126. package/src/audio.ts +76 -0
  127. package/src/cli-helpers.ts +86 -0
  128. package/src/cli.ts +1223 -0
  129. package/src/config.ts +172 -0
  130. package/src/environment.ts +171 -0
  131. package/src/github.ts +143 -0
  132. package/src/langfuse/client.ts +105 -0
  133. package/src/langfuse/comments.ts +52 -0
  134. package/src/langfuse/datasets.ts +178 -0
  135. package/src/langfuse/index.ts +33 -0
  136. package/src/langfuse/media.ts +193 -0
  137. package/src/langfuse/observations.ts +131 -0
  138. package/src/langfuse/prompts.ts +157 -0
  139. package/src/langfuse/scores.ts +456 -0
  140. package/src/langfuse/traces.ts +276 -0
  141. package/src/llm.ts +106 -0
  142. package/src/narrative/graph-manager.ts +1358 -0
  143. package/src/narrative/index.ts +32 -0
  144. package/src/narrative/markdown-export.ts +535 -0
  145. package/src/narrative/tool-definitions.ts +635 -0
  146. package/src/narrative/tool-handlers.ts +528 -0
  147. package/src/narrative/types.ts +9 -0
  148. package/src/narrative/validation.ts +179 -0
  149. package/src/pde/index.ts +8 -0
  150. package/src/pde/mcp-handlers.ts +359 -0
  151. package/src/pde/mcp-tools.ts +201 -0
  152. package/src/pde/session-manager.ts +248 -0
  153. package/src/pde/stc-mapper.ts +298 -0
  154. package/src/pipeline/index.ts +7 -0
  155. package/src/pipeline/template-engine.ts +398 -0
  156. package/src/planning/index.ts +13 -0
  157. package/src/planning/mcp-handlers.ts +369 -0
  158. package/src/planning/mcp-tools.ts +155 -0
  159. package/src/planning/plan-parser.ts +587 -0
  160. package/src/redis.ts +97 -0
  161. package/src/types.ts +280 -0
  162. package/tsconfig.json +26 -0
@@ -0,0 +1,140 @@
1
+ // coaiajs/src/langfuse/datasets.ts — Dataset operations
2
+ // Port of cofuse.py dataset functions
3
+ import { getClient } from './client.js';
4
+ export async function listDatasets() {
5
+ const client = getClient();
6
+ const result = await client.request('GET', '/api/public/v2/datasets');
7
+ return JSON.stringify(result, null, 2);
8
+ }
9
+ export async function getDataset(name) {
10
+ const client = getClient();
11
+ const result = await client.request('GET', `/api/public/v2/datasets/${encodeURIComponent(name)}`);
12
+ return JSON.stringify(result, null, 2);
13
+ }
14
+ export async function createDataset(params) {
15
+ const client = getClient();
16
+ const data = { name: params.name };
17
+ if (params.description)
18
+ data.description = params.description;
19
+ if (params.metadata) {
20
+ data.metadata = typeof params.metadata === 'string'
21
+ ? safeParseJSON(params.metadata)
22
+ : params.metadata;
23
+ }
24
+ const result = await client.request('POST', '/api/public/v2/datasets', data);
25
+ return JSON.stringify(result, null, 2);
26
+ }
27
+ export async function listDatasetItems(name) {
28
+ const client = getClient();
29
+ const allItems = [];
30
+ let page = 1;
31
+ while (true) {
32
+ const data = await client.request('GET', `/api/public/dataset-items?name=${encodeURIComponent(name)}&page=${page}`);
33
+ const items = data.data;
34
+ if (!items || !Array.isArray(items) || items.length === 0)
35
+ break;
36
+ allItems.push(...items);
37
+ const meta = data.meta;
38
+ if (!meta || (meta.page ?? page) >= (meta.totalPages ?? 1))
39
+ break;
40
+ page++;
41
+ }
42
+ return JSON.stringify(allItems, null, 2);
43
+ }
44
+ export async function createDatasetItem(params) {
45
+ const client = getClient();
46
+ const data = {
47
+ datasetName: params.datasetName,
48
+ input: params.input,
49
+ };
50
+ if (params.expectedOutput !== undefined)
51
+ data.expectedOutput = params.expectedOutput;
52
+ if (params.metadata)
53
+ data.metadata = params.metadata;
54
+ if (params.sourceTraceId)
55
+ data.sourceTraceId = params.sourceTraceId;
56
+ if (params.sourceObservationId)
57
+ data.sourceObservationId = params.sourceObservationId;
58
+ const result = await client.request('POST', '/api/public/dataset-items', data);
59
+ return JSON.stringify(result, null, 2);
60
+ }
61
+ // ─── Formatters ─────────────────────────────────────────────────────
62
+ export function formatDatasetsTable(json) {
63
+ try {
64
+ const raw = typeof json === 'string' ? JSON.parse(json) : json;
65
+ const datasets = Array.isArray(raw)
66
+ ? raw
67
+ : raw.data ?? [];
68
+ if (!datasets.length)
69
+ return 'No datasets found.';
70
+ const headers = ['Name', 'Description', 'Items', 'Created'];
71
+ const rows = datasets.map((d) => [
72
+ trunc(String(d.name ?? 'N/A'), 25),
73
+ trunc(String(d.description ?? 'N/A'), 30),
74
+ String(d.items?.toString() ?? 'N/A'),
75
+ String(d.createdAt ?? 'N/A').slice(0, 10),
76
+ ]);
77
+ return formatTable(headers, rows) + `\nTotal datasets: ${datasets.length}`;
78
+ }
79
+ catch (e) {
80
+ return `Error formatting datasets: ${e}`;
81
+ }
82
+ }
83
+ export function formatDatasetForFinetuning(items, format, systemInstruction) {
84
+ try {
85
+ const parsed = (typeof items === 'string' ? JSON.parse(items) : items);
86
+ const sysInstr = systemInstruction ?? 'You are a helpful assistant.';
87
+ const lines = [];
88
+ for (const item of parsed) {
89
+ const input = item.input;
90
+ const output = item.expectedOutput;
91
+ if (!input || !output)
92
+ continue;
93
+ if (format === 'openai') {
94
+ lines.push(JSON.stringify({
95
+ messages: [
96
+ { role: 'system', content: sysInstr },
97
+ { role: 'user', content: input },
98
+ { role: 'assistant', content: output },
99
+ ],
100
+ }));
101
+ }
102
+ else {
103
+ lines.push(JSON.stringify({
104
+ systemInstruction: {
105
+ role: 'system',
106
+ parts: [{ text: sysInstr }],
107
+ },
108
+ contents: [
109
+ { role: 'user', parts: [{ text: input }] },
110
+ { role: 'model', parts: [{ text: output }] },
111
+ ],
112
+ }));
113
+ }
114
+ }
115
+ return lines.join('\n');
116
+ }
117
+ catch (e) {
118
+ return `Error formatting for fine-tuning: ${e}`;
119
+ }
120
+ }
121
+ // ─── Helpers ────────────────────────────────────────────────────────
122
+ function trunc(s, len) {
123
+ return s.length > len ? s.slice(0, len - 3) + '...' : s;
124
+ }
125
+ function safeParseJSON(s) {
126
+ try {
127
+ return JSON.parse(s);
128
+ }
129
+ catch {
130
+ return { note: s };
131
+ }
132
+ }
133
+ function formatTable(headers, rows) {
134
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));
135
+ const sep = '+' + widths.map((w) => '-'.repeat(w + 2)).join('+') + '+';
136
+ const hdr = '| ' + headers.map((h, i) => h.padEnd(widths[i])).join(' | ') + ' |';
137
+ const body = rows.map((r) => '| ' + r.map((c, i) => (c ?? '').padEnd(widths[i])).join(' | ') + ' |');
138
+ return [sep, hdr, sep, ...body, sep].join('\n');
139
+ }
140
+ //# sourceMappingURL=datasets.js.map
@@ -0,0 +1,13 @@
1
+ export { LangfuseClient, LangfuseApiError, getClient, resetClient, nowISO } from './client.js';
2
+ export type { IngestionEvent, LangfuseClientConfig } from './client.js';
3
+ export { addTrace, patchTraceOutput, listTraces, getTrace, formatTracesTable, formatTraceTree } from './traces.js';
4
+ export type { TraceFilters } from './traces.js';
5
+ export { addObservation, getObservation, formatObservationDisplay } from './observations.js';
6
+ export { listPrompts, getPrompt, createPrompt, formatPromptsTable, formatPromptDisplay } from './prompts.js';
7
+ export { listDatasets, getDataset, createDataset, listDatasetItems, createDatasetItem, formatDatasetsTable, formatDatasetForFinetuning, } from './datasets.js';
8
+ export { createScore, applyScoreToTrace, createScoreForTarget, listScores, listScoreConfigs, getScoreConfig, createScoreConfig, exportScoreConfigs, importScoreConfigs, applyScoreConfig, getBuiltInPresets, installPreset, formatScoresTable, formatScoreConfigsTable, } from './scores.js';
9
+ export type { ScoreFilters } from './scores.js';
10
+ export { listComments, getComment, createComment } from './comments.js';
11
+ export type { CommentFilters } from './comments.js';
12
+ export { uploadAndAttachMedia, getMedia, detectContentType, formatMediaDisplay, } from './media.js';
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,10 @@
1
+ // coaiajs/src/langfuse/index.ts — Barrel export
2
+ export { LangfuseClient, LangfuseApiError, getClient, resetClient, nowISO } from './client.js';
3
+ export { addTrace, patchTraceOutput, listTraces, getTrace, formatTracesTable, formatTraceTree } from './traces.js';
4
+ export { addObservation, getObservation, formatObservationDisplay } from './observations.js';
5
+ export { listPrompts, getPrompt, createPrompt, formatPromptsTable, formatPromptDisplay } from './prompts.js';
6
+ export { listDatasets, getDataset, createDataset, listDatasetItems, createDatasetItem, formatDatasetsTable, formatDatasetForFinetuning, } from './datasets.js';
7
+ export { createScore, applyScoreToTrace, createScoreForTarget, listScores, listScoreConfigs, getScoreConfig, createScoreConfig, exportScoreConfigs, importScoreConfigs, applyScoreConfig, getBuiltInPresets, installPreset, formatScoresTable, formatScoreConfigsTable, } from './scores.js';
8
+ export { listComments, getComment, createComment } from './comments.js';
9
+ export { uploadAndAttachMedia, getMedia, detectContentType, formatMediaDisplay, } from './media.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ export declare function uploadAndAttachMedia(params: {
2
+ filePath: string;
3
+ traceId: string;
4
+ field?: string;
5
+ observationId?: string;
6
+ contentType?: string;
7
+ }): Promise<string>;
8
+ export declare function getMedia(mediaId: string): Promise<string>;
9
+ export declare function detectContentType(filePath: string): string;
10
+ export declare function formatMediaDisplay(json: unknown): string;
11
+ //# sourceMappingURL=media.d.ts.map
@@ -0,0 +1,167 @@
1
+ // coaiajs/src/langfuse/media.ts — Media upload operations
2
+ // Port of cofuse.py media functions
3
+ import { readFileSync, statSync } from 'node:fs';
4
+ import { createHash } from 'node:crypto';
5
+ import { basename, extname } from 'node:path';
6
+ import { getClient } from './client.js';
7
+ const SUPPORTED_CONTENT_TYPES = new Set([
8
+ 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
9
+ 'image/tiff', 'image/bmp', 'image/avif',
10
+ 'audio/mpeg', 'audio/mp4', 'audio/wav', 'audio/ogg', 'audio/webm', 'audio/flac',
11
+ 'video/mp4', 'video/webm', 'video/ogg', 'video/quicktime',
12
+ 'application/pdf',
13
+ 'text/plain', 'text/html', 'text/css', 'text/csv',
14
+ 'application/json', 'application/xml',
15
+ ]);
16
+ const EXTENSION_MAP = {
17
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
18
+ '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
19
+ '.tiff': 'image/tiff', '.tif': 'image/tiff', '.bmp': 'image/bmp',
20
+ '.avif': 'image/avif',
21
+ '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.wav': 'audio/wav',
22
+ '.ogg': 'audio/ogg', '.flac': 'audio/flac', '.weba': 'audio/webm',
23
+ '.mp4': 'video/mp4', '.webm': 'video/webm', '.ogv': 'video/ogg',
24
+ '.mov': 'video/quicktime',
25
+ '.pdf': 'application/pdf',
26
+ '.txt': 'text/plain', '.html': 'text/html', '.htm': 'text/html',
27
+ '.css': 'text/css', '.csv': 'text/csv',
28
+ '.json': 'application/json', '.xml': 'application/xml',
29
+ };
30
+ const TRUSTED_DOMAINS = [
31
+ 'amazonaws.com',
32
+ 's3.amazonaws.com',
33
+ 'storage.googleapis.com',
34
+ 'blob.core.windows.net',
35
+ 'r2.cloudflarestorage.com',
36
+ ];
37
+ export async function uploadAndAttachMedia(params) {
38
+ const { filePath, traceId, observationId } = params;
39
+ const field = params.field ?? 'input';
40
+ // Detect content type
41
+ const contentType = params.contentType ?? detectContentType(filePath);
42
+ if (!SUPPORTED_CONTENT_TYPES.has(contentType)) {
43
+ return JSON.stringify({ error: `Unsupported content type: ${contentType}` });
44
+ }
45
+ // Calculate file info
46
+ const stat = statSync(filePath);
47
+ const fileData = readFileSync(filePath);
48
+ const sha256 = createHash('sha256').update(fileData).digest('base64');
49
+ const client = getClient();
50
+ // Step 1: Get presigned upload URL
51
+ const uploadReqData = {
52
+ traceId,
53
+ contentType,
54
+ contentLength: stat.size,
55
+ sha256Hash: sha256,
56
+ field,
57
+ };
58
+ if (observationId)
59
+ uploadReqData.observationId = observationId;
60
+ const uploadInfo = await client.request('POST', '/api/public/media', uploadReqData);
61
+ const uploadUrl = uploadInfo.uploadUrl;
62
+ const mediaId = uploadInfo.mediaId;
63
+ if (!uploadUrl || !mediaId) {
64
+ return JSON.stringify({ error: 'Failed to get upload URL', detail: uploadInfo });
65
+ }
66
+ // Step 2: Validate upload URL domain
67
+ const url = new URL(uploadUrl);
68
+ if (!isTrustedDomain(url.hostname)) {
69
+ return JSON.stringify({
70
+ error: `Security: Upload URL domain '${url.hostname}' is not trusted`,
71
+ });
72
+ }
73
+ // Step 3: Upload to presigned URL
74
+ const startTime = Date.now();
75
+ const uploadResponse = await fetch(uploadUrl, {
76
+ method: 'PUT',
77
+ headers: {
78
+ 'Content-Type': contentType,
79
+ 'x-amz-checksum-sha256': sha256,
80
+ },
81
+ body: fileData,
82
+ });
83
+ const uploadTimeMs = Date.now() - startTime;
84
+ // Step 4: Patch status
85
+ await client.request('PATCH', `/api/public/media/${mediaId}`, {
86
+ uploadHttpStatus: uploadResponse.status,
87
+ uploadTimeMs,
88
+ uploadedAt: new Date().toISOString(),
89
+ });
90
+ if (!uploadResponse.ok) {
91
+ return JSON.stringify({
92
+ error: `Upload failed: ${uploadResponse.status}`,
93
+ mediaId,
94
+ });
95
+ }
96
+ // Build media token
97
+ const token = `@@@langfuseMedia:type=${contentType}|id=${mediaId}|source=file@@@`;
98
+ return JSON.stringify({
99
+ success: true,
100
+ mediaId,
101
+ fileName: basename(filePath),
102
+ contentType,
103
+ contentLength: stat.size,
104
+ traceId,
105
+ field,
106
+ observationId: observationId ?? null,
107
+ uploadTimeMs,
108
+ mediaToken: token,
109
+ }, null, 2);
110
+ }
111
+ export async function getMedia(mediaId) {
112
+ const client = getClient();
113
+ const result = await client.request('GET', `/api/public/media/${mediaId}`);
114
+ return JSON.stringify(result, null, 2);
115
+ }
116
+ export function detectContentType(filePath) {
117
+ const ext = extname(filePath).toLowerCase();
118
+ return EXTENSION_MAP[ext] ?? 'application/octet-stream';
119
+ }
120
+ export function formatMediaDisplay(json) {
121
+ try {
122
+ const media = (typeof json === 'string' ? JSON.parse(json) : json);
123
+ if ('error' in media)
124
+ return `Error: ${media.error}`;
125
+ const contentType = String(media.contentType ?? 'unknown');
126
+ let glyph = '📎';
127
+ if (contentType.startsWith('image/'))
128
+ glyph = '🖼️';
129
+ else if (contentType.startsWith('video/'))
130
+ glyph = '🎥';
131
+ else if (contentType.startsWith('audio/'))
132
+ glyph = '🎵';
133
+ else if (contentType === 'application/pdf')
134
+ glyph = '📄';
135
+ const lines = [];
136
+ lines.push(`${glyph} Media: ${media.fileName ?? 'Unnamed'}`);
137
+ lines.push(`├── 🆔 ID: ${media.id ?? media.mediaId ?? 'N/A'}`);
138
+ lines.push(`├── 📝 Content Type: ${contentType}`);
139
+ lines.push(`├── 📏 Size: ${media.contentLength ?? 0} bytes`);
140
+ lines.push(`├── 🔗 Trace ID: ${media.traceId ?? 'N/A'}`);
141
+ if (media.observationId)
142
+ lines.push(`├── 👁️ Observation ID: ${media.observationId}`);
143
+ if (media.field)
144
+ lines.push(`├── 🏷️ Field: ${media.field}`);
145
+ if (media.uploadedAt)
146
+ lines.push(`├── ⏰ Uploaded: ${String(media.uploadedAt).slice(0, 19)}`);
147
+ // Fix last line to └──
148
+ if (lines.length > 1) {
149
+ const last = lines[lines.length - 1];
150
+ lines[lines.length - 1] = last.replace('├── ', '└── ');
151
+ }
152
+ return lines.join('\n');
153
+ }
154
+ catch (e) {
155
+ return `Error formatting media: ${e}`;
156
+ }
157
+ }
158
+ // ─── Helpers ────────────────────────────────────────────────────────
159
+ function isTrustedDomain(hostname) {
160
+ const lower = hostname.toLowerCase();
161
+ for (const domain of TRUSTED_DOMAINS) {
162
+ if (lower === domain || lower.endsWith(`.${domain}`))
163
+ return true;
164
+ }
165
+ return false;
166
+ }
167
+ //# sourceMappingURL=media.js.map
@@ -0,0 +1,18 @@
1
+ export declare function addObservation(params: {
2
+ observationId?: string;
3
+ traceId: string;
4
+ type?: string;
5
+ name: string;
6
+ parentId?: string;
7
+ inputData?: unknown;
8
+ outputData?: unknown;
9
+ metadata?: unknown;
10
+ startTime?: string;
11
+ endTime?: string;
12
+ level?: string;
13
+ model?: string;
14
+ usage?: unknown;
15
+ }): Promise<string>;
16
+ export declare function getObservation(observationId: string): Promise<string>;
17
+ export declare function formatObservationDisplay(json: unknown): string;
18
+ //# sourceMappingURL=observations.d.ts.map
@@ -0,0 +1,113 @@
1
+ // coaiajs/src/langfuse/observations.ts — Observation operations
2
+ // Port of cofuse.py observation functions
3
+ import { v4 as uuidv4 } from 'uuid';
4
+ import { getClient, nowISO } from './client.js';
5
+ export async function addObservation(params) {
6
+ const client = getClient();
7
+ const now = nowISO();
8
+ const obsId = params.observationId ?? uuidv4();
9
+ const body = {
10
+ id: obsId,
11
+ traceId: params.traceId,
12
+ type: params.type ?? 'EVENT',
13
+ startTime: params.startTime ?? now,
14
+ level: params.level ?? 'DEFAULT',
15
+ };
16
+ if (params.name)
17
+ body.name = params.name;
18
+ if (params.inputData)
19
+ body.input = params.inputData;
20
+ if (params.outputData)
21
+ body.output = params.outputData;
22
+ if (params.metadata)
23
+ body.metadata = params.metadata;
24
+ if (params.parentId)
25
+ body.parentObservationId = params.parentId;
26
+ if (params.endTime)
27
+ body.endTime = params.endTime;
28
+ if (params.model)
29
+ body.model = params.model;
30
+ if (params.usage)
31
+ body.usage = params.usage;
32
+ const event = {
33
+ id: `${obsId}-event`,
34
+ timestamp: now,
35
+ type: 'observation-create',
36
+ body,
37
+ };
38
+ await client.ingest([event]);
39
+ return JSON.stringify({
40
+ success: true,
41
+ observationId: obsId,
42
+ traceId: params.traceId,
43
+ name: params.name,
44
+ type: params.type ?? 'EVENT',
45
+ }, null, 2);
46
+ }
47
+ export async function getObservation(observationId) {
48
+ const client = getClient();
49
+ const result = await client.request('GET', `/api/public/observations/${observationId}`);
50
+ return JSON.stringify(result, null, 2);
51
+ }
52
+ // ─── Formatters ─────────────────────────────────────────────────────
53
+ const TYPE_GLYPHS = {
54
+ SPAN: '🔗',
55
+ GENERATION: '🤖',
56
+ EVENT: '⚡',
57
+ DEFAULT: '📦',
58
+ };
59
+ export function formatObservationDisplay(json) {
60
+ try {
61
+ const obs = (typeof json === 'string' ? JSON.parse(json) : json);
62
+ if ('error' in obs)
63
+ return `Error: ${obs.error}`;
64
+ const obsType = String(obs.type ?? 'UNKNOWN').toUpperCase();
65
+ const glyph = TYPE_GLYPHS[obsType] ?? TYPE_GLYPHS.DEFAULT;
66
+ const lines = [];
67
+ lines.push(`${glyph} Observation: ${obs.name ?? 'Unnamed'}`);
68
+ lines.push(`├── 🆔 ID: ${obs.id ?? 'N/A'}`);
69
+ lines.push(`├── 📋 Type: ${obsType}`);
70
+ lines.push(`├── 🔗 Trace: ${obs.traceId ?? 'N/A'}`);
71
+ lines.push(`├── ⏰ Start: ${String(obs.startTime ?? 'N/A').slice(0, 19)}`);
72
+ if (obs.endTime)
73
+ lines.push(`├── ⏰ End: ${String(obs.endTime).slice(0, 19)}`);
74
+ if (obs.level && obs.level !== 'DEFAULT')
75
+ lines.push(`├── 📊 Level: ${obs.level}`);
76
+ if (obs.model)
77
+ lines.push(`├── 🤖 Model: ${obs.model}`);
78
+ if (obs.parentObservationId) {
79
+ lines.push(`├── 👆 Parent: ${obs.parentObservationId}`);
80
+ }
81
+ if (obs.input) {
82
+ const txt = String(obs.input).replace(/\n/g, ' ');
83
+ lines.push(`├── 📥 Input: ${txt.length > 100 ? txt.slice(0, 100) + '...' : txt}`);
84
+ }
85
+ if (obs.output) {
86
+ const txt = String(obs.output).replace(/\n/g, ' ');
87
+ lines.push(`├── 📤 Output: ${txt.length > 100 ? txt.slice(0, 100) + '...' : txt}`);
88
+ }
89
+ const metadata = obs.metadata;
90
+ if (metadata && typeof metadata === 'object' && Object.keys(metadata).length) {
91
+ lines.push(`└── 📋 Metadata:`);
92
+ const entries = Object.entries(metadata);
93
+ entries.forEach(([k, v], i) => {
94
+ const pre = i === entries.length - 1 ? '└── ' : '├── ';
95
+ lines.push(` ${pre}${k}: ${JSON.stringify(v)}`);
96
+ });
97
+ }
98
+ else {
99
+ // Fix last ├── to └──
100
+ if (lines.length > 0) {
101
+ const last = lines[lines.length - 1];
102
+ if (last.startsWith('├── ')) {
103
+ lines[lines.length - 1] = last.replace('├── ', '└── ');
104
+ }
105
+ }
106
+ }
107
+ return lines.join('\n');
108
+ }
109
+ catch (e) {
110
+ return `Error formatting observation: ${e}`;
111
+ }
112
+ }
113
+ //# sourceMappingURL=observations.js.map
@@ -0,0 +1,14 @@
1
+ export declare function listPrompts(): Promise<string>;
2
+ export declare function getPrompt(name: string, label?: string): Promise<string>;
3
+ export declare function createPrompt(params: {
4
+ name: string;
5
+ content: string | unknown[];
6
+ commitMessage?: string;
7
+ labels?: string[];
8
+ tags?: string[];
9
+ promptType?: 'text' | 'chat';
10
+ config?: Record<string, unknown>;
11
+ }): Promise<string>;
12
+ export declare function formatPromptsTable(json: unknown): string;
13
+ export declare function formatPromptDisplay(json: unknown): string;
14
+ //# sourceMappingURL=prompts.d.ts.map
@@ -0,0 +1,127 @@
1
+ // coaiajs/src/langfuse/prompts.ts — Prompt operations
2
+ // Port of cofuse.py prompt functions
3
+ import { getClient } from './client.js';
4
+ export async function listPrompts() {
5
+ const client = getClient();
6
+ const allPrompts = [];
7
+ let page = 1;
8
+ while (true) {
9
+ const data = await client.request('GET', `/api/public/v2/prompts?page=${page}`);
10
+ const prompts = data.data;
11
+ if (!prompts || !Array.isArray(prompts) || prompts.length === 0)
12
+ break;
13
+ allPrompts.push(...prompts);
14
+ const meta = data.meta;
15
+ if (meta?.totalPages && (meta.page ?? page) >= meta.totalPages)
16
+ break;
17
+ if (!data.hasNextPage && !meta?.totalPages)
18
+ break;
19
+ page++;
20
+ }
21
+ return JSON.stringify(allPrompts, null, 2);
22
+ }
23
+ export async function getPrompt(name, label) {
24
+ const client = getClient();
25
+ const params = label ? `?label=${encodeURIComponent(label)}` : '';
26
+ const result = await client.request('GET', `/api/public/v2/prompts/${encodeURIComponent(name)}${params}`);
27
+ return JSON.stringify(result, null, 2);
28
+ }
29
+ export async function createPrompt(params) {
30
+ const client = getClient();
31
+ const data = {
32
+ type: params.promptType ?? 'text',
33
+ name: params.name,
34
+ prompt: params.content,
35
+ };
36
+ if (params.commitMessage)
37
+ data.commitMessage = params.commitMessage;
38
+ if (params.labels)
39
+ data.labels = params.labels;
40
+ if (params.tags)
41
+ data.tags = params.tags;
42
+ if (params.config)
43
+ data.config = params.config;
44
+ const result = await client.request('POST', '/api/public/v2/prompts', data);
45
+ return JSON.stringify(result, null, 2);
46
+ }
47
+ // ─── Formatters ─────────────────────────────────────────────────────
48
+ export function formatPromptsTable(json) {
49
+ try {
50
+ const raw = typeof json === 'string' ? JSON.parse(json) : json;
51
+ const prompts = Array.isArray(raw)
52
+ ? raw
53
+ : raw.data ?? [];
54
+ if (!prompts.length)
55
+ return 'No prompts found.';
56
+ const headers = ['Name', 'Version', 'Created', 'Tags/Labels'];
57
+ const rows = prompts.map((p) => [
58
+ trunc(String(p.name ?? 'N/A'), 30),
59
+ String(p.version ?? 'N/A'),
60
+ String(p.createdAt ?? 'N/A').slice(0, 10),
61
+ (p.labels ?? []).join(', ') || 'None',
62
+ ]);
63
+ return formatTable(headers, rows) + `\nTotal prompts: ${prompts.length}`;
64
+ }
65
+ catch (e) {
66
+ return `Error formatting prompts: ${e}`;
67
+ }
68
+ }
69
+ export function formatPromptDisplay(json) {
70
+ try {
71
+ const prompt = (typeof json === 'string' ? JSON.parse(json) : json);
72
+ if ('error' in prompt)
73
+ return `Error: ${prompt.error}`;
74
+ const name = String(prompt.name ?? 'Unnamed');
75
+ const version = String(prompt.version ?? 'N/A');
76
+ const type = String(prompt.type ?? 'text');
77
+ const isActive = Boolean(prompt.isActive);
78
+ const created = String(prompt.createdAt ?? 'N/A').slice(0, 19);
79
+ const updated = String(prompt.updatedAt ?? 'N/A').slice(0, 19);
80
+ const labels = prompt.labels ?? [];
81
+ const tags = prompt.tags ?? [];
82
+ const commitMsg = String(prompt.commitMessage ?? '');
83
+ const config = prompt.config;
84
+ const content = String(prompt.prompt ?? '');
85
+ const header = `🎯 PROMPT: ${name}${version !== 'N/A' ? ` (v${version})` : ''}`;
86
+ const sep = '='.repeat(header.length);
87
+ const lines = [sep, header, sep, ''];
88
+ lines.push('📋 METADATA:');
89
+ lines.push(` Type: ${type}`);
90
+ lines.push(` Active: ${isActive ? '✅ Yes' : '❌ No'}`);
91
+ lines.push(` Created: ${created}`);
92
+ lines.push(` Updated: ${updated}`);
93
+ lines.push(` Labels: ${labels.length ? labels.join(', ') : 'None'}`);
94
+ if (tags.length)
95
+ lines.push(` Tags: ${tags.join(', ')}`);
96
+ if (commitMsg)
97
+ lines.push(` Commit: ${commitMsg}`);
98
+ lines.push('');
99
+ if (config && Object.keys(config).length) {
100
+ lines.push('⚙️ CONFIGURATION:');
101
+ for (const [k, v] of Object.entries(config)) {
102
+ lines.push(` ${k}: ${v}`);
103
+ }
104
+ lines.push('');
105
+ }
106
+ lines.push('📝 PROMPT CONTENT:');
107
+ lines.push('-'.repeat(50));
108
+ lines.push(content || '(No content)');
109
+ lines.push('-'.repeat(50));
110
+ return lines.join('\n');
111
+ }
112
+ catch (e) {
113
+ return `Error formatting prompt: ${e}`;
114
+ }
115
+ }
116
+ // ─── Helpers ────────────────────────────────────────────────────────
117
+ function trunc(s, len) {
118
+ return s.length > len ? s.slice(0, len - 3) + '...' : s;
119
+ }
120
+ function formatTable(headers, rows) {
121
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));
122
+ const sep = '+' + widths.map((w) => '-'.repeat(w + 2)).join('+') + '+';
123
+ const hdr = '| ' + headers.map((h, i) => h.padEnd(widths[i])).join(' | ') + ' |';
124
+ const body = rows.map((r) => '| ' + r.map((c, i) => (c ?? '').padEnd(widths[i])).join(' | ') + ' |');
125
+ return [sep, hdr, sep, ...body, sep].join('\n');
126
+ }
127
+ //# sourceMappingURL=prompts.js.map
@@ -0,0 +1,54 @@
1
+ import type { ScoreConfig } from '../types.js';
2
+ export interface ScoreFilters {
3
+ userId?: string;
4
+ name?: string;
5
+ fromTimestamp?: string;
6
+ toTimestamp?: string;
7
+ configId?: string;
8
+ page?: number;
9
+ }
10
+ export declare function createScore(params: {
11
+ id?: string;
12
+ name?: string;
13
+ value: number;
14
+ traceId?: string;
15
+ observationId?: string;
16
+ configId?: string;
17
+ comment?: string;
18
+ }): Promise<string>;
19
+ export declare function applyScoreToTrace(traceId: string, scoreId: string, value: number): Promise<string>;
20
+ export declare function createScoreForTarget(params: {
21
+ targetType: 'trace' | 'session';
22
+ targetId: string;
23
+ scoreId?: string;
24
+ value: number;
25
+ scoreName?: string;
26
+ observationId?: string;
27
+ configId?: string;
28
+ comment?: string;
29
+ }): Promise<string>;
30
+ export declare function listScores(filters: ScoreFilters): Promise<string>;
31
+ export declare function listScoreConfigs(): Promise<string>;
32
+ export declare function getScoreConfig(configId: string): Promise<string>;
33
+ export declare function createScoreConfig(params: {
34
+ name: string;
35
+ dataType: 'NUMERIC' | 'CATEGORICAL' | 'BOOLEAN';
36
+ description?: string;
37
+ categories?: Array<{
38
+ label: string;
39
+ value: number;
40
+ }>;
41
+ minValue?: number;
42
+ maxValue?: number;
43
+ }): Promise<string>;
44
+ export declare function exportScoreConfigs(outputFile: string): Promise<string>;
45
+ export declare function importScoreConfigs(importFile: string, options?: {
46
+ allowDuplicates?: boolean;
47
+ selectedConfigs?: string[];
48
+ }): Promise<string>;
49
+ export declare function applyScoreConfig(configNameOrId: string, targetType: string, targetId: string, value: number, observationId?: string, comment?: string): Promise<string>;
50
+ export declare function getBuiltInPresets(): ScoreConfig[];
51
+ export declare function installPreset(name: string, checkDuplicates?: boolean): Promise<string>;
52
+ export declare function formatScoresTable(json: unknown): string;
53
+ export declare function formatScoreConfigsTable(json: unknown): string;
54
+ //# sourceMappingURL=scores.d.ts.map