@useavalon/caelence-agent 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 (161) hide show
  1. package/README.md +201 -0
  2. package/bin/harness.ts +10 -0
  3. package/package.json +75 -0
  4. package/skills/copy-editor/SKILL.md +74 -0
  5. package/skills/copy-editor/references/anti-slop.md +62 -0
  6. package/skills/copy-editor/references/ui-states.md +46 -0
  7. package/skills/copy-editor/scripts/lint-copy.py +78 -0
  8. package/skills/copy-harry-dry/SKILL.md +120 -0
  9. package/skills/copy-rmbc/SKILL.md +97 -0
  10. package/skills/copywriting/SKILL.md +73 -0
  11. package/skills/impeccable/SKILL.md +133 -0
  12. package/skills/impeccable/references/visual-slop.md +36 -0
  13. package/src/cli/main.test.ts +36 -0
  14. package/src/cli/main.ts +384 -0
  15. package/src/cli/media-models.ts +82 -0
  16. package/src/cli/models.ts +43 -0
  17. package/src/cli/openrouter-live.test.ts +35 -0
  18. package/src/cli/openrouter-live.ts +72 -0
  19. package/src/cli/openrouter-modality.test.ts +25 -0
  20. package/src/cli/openrouter-modality.ts +83 -0
  21. package/src/cli/picker.test.ts +53 -0
  22. package/src/cli/picker.ts +48 -0
  23. package/src/cli/plain-text.ts +15 -0
  24. package/src/cli/slash-dispatch.test.ts +213 -0
  25. package/src/cli/slash-dispatch.ts +298 -0
  26. package/src/cli/slash.test.ts +113 -0
  27. package/src/cli/slash.ts +119 -0
  28. package/src/cli/theme.test.ts +10 -0
  29. package/src/cli/theme.ts +44 -0
  30. package/src/cli/tui-layout.test.ts +33 -0
  31. package/src/cli/tui-layout.ts +33 -0
  32. package/src/cli/tui-screen.test.ts +33 -0
  33. package/src/cli/tui-screen.ts +13 -0
  34. package/src/cli/tui.tsx +735 -0
  35. package/src/config.ts +86 -0
  36. package/src/core/approval.test.ts +60 -0
  37. package/src/core/approval.ts +83 -0
  38. package/src/core/auto-router.test.ts +31 -0
  39. package/src/core/auto-router.ts +66 -0
  40. package/src/core/errors.ts +67 -0
  41. package/src/core/events.ts +85 -0
  42. package/src/core/hooks.test.ts +66 -0
  43. package/src/core/hooks.ts +94 -0
  44. package/src/core/ids.ts +6 -0
  45. package/src/core/instructions.test.ts +49 -0
  46. package/src/core/instructions.ts +44 -0
  47. package/src/core/logger.ts +45 -0
  48. package/src/core/mcp.ts +191 -0
  49. package/src/core/mode.test.ts +63 -0
  50. package/src/core/mode.ts +60 -0
  51. package/src/core/run-turn.test.ts +339 -0
  52. package/src/core/run-turn.ts +487 -0
  53. package/src/core/session.test.ts +203 -0
  54. package/src/core/session.ts +349 -0
  55. package/src/core/stdio-mcp.ts +143 -0
  56. package/src/core/strands.ts +262 -0
  57. package/src/core/usage.test.ts +69 -0
  58. package/src/core/usage.ts +171 -0
  59. package/src/desktop/bridge.test.ts +331 -0
  60. package/src/desktop/bridge.ts +729 -0
  61. package/src/desktop/open-local.test.ts +40 -0
  62. package/src/desktop/open-local.ts +52 -0
  63. package/src/desktop/preview-cache.test.ts +36 -0
  64. package/src/desktop/preview-cache.ts +63 -0
  65. package/src/desktop/secrets.test.ts +44 -0
  66. package/src/desktop/secrets.ts +60 -0
  67. package/src/evals/runner.test.ts +43 -0
  68. package/src/evals/runner.ts +225 -0
  69. package/src/index.ts +132 -0
  70. package/src/init.test.ts +54 -0
  71. package/src/init.ts +117 -0
  72. package/src/integrations/catalog-data.json +424 -0
  73. package/src/integrations/catalog.ts +81 -0
  74. package/src/integrations/connect.ts +231 -0
  75. package/src/integrations/integrations.test.ts +329 -0
  76. package/src/integrations/marks/airtable.svg +1 -0
  77. package/src/integrations/marks/algolia-mcp.svg +1 -0
  78. package/src/integrations/marks/canva.jpg +0 -0
  79. package/src/integrations/marks/cloudflare-mcp.svg +1 -0
  80. package/src/integrations/marks/contentful-mcp.svg +1 -0
  81. package/src/integrations/marks/craft.png +0 -0
  82. package/src/integrations/marks/dinero.png +0 -0
  83. package/src/integrations/marks/figma.svg +1 -0
  84. package/src/integrations/marks/gitlab.svg +1 -0
  85. package/src/integrations/marks/google-calendar.svg +1 -0
  86. package/src/integrations/marks/google-docs.svg +1 -0
  87. package/src/integrations/marks/google-drive.svg +1 -0
  88. package/src/integrations/marks/google-gmail.svg +1 -0
  89. package/src/integrations/marks/google-sheets.svg +1 -0
  90. package/src/integrations/marks/google-slides.svg +1 -0
  91. package/src/integrations/marks/granola.png +0 -0
  92. package/src/integrations/marks/jira.svg +1 -0
  93. package/src/integrations/marks/linear.svg +1 -0
  94. package/src/integrations/marks/microsoft-365.svg +7 -0
  95. package/src/integrations/marks/miro.svg +1 -0
  96. package/src/integrations/marks/mixpanel-mcp.svg +1 -0
  97. package/src/integrations/marks/monday.png +0 -0
  98. package/src/integrations/marks/mux-mcp.png +0 -0
  99. package/src/integrations/marks/neon-mcp.svg +1 -0
  100. package/src/integrations/marks/notion.svg +1 -0
  101. package/src/integrations/marks/paddle-mcp.svg +1 -0
  102. package/src/integrations/marks/posthog-mcp.svg +1 -0
  103. package/src/integrations/marks/prismic-mcp.svg +1 -0
  104. package/src/integrations/marks/replicate-mcp.svg +1 -0
  105. package/src/integrations/marks/resend-mcp.svg +1 -0
  106. package/src/integrations/marks/sanity-mcp.svg +1 -0
  107. package/src/integrations/marks/sceneplane.png +0 -0
  108. package/src/integrations/marks/sentry-mcp.svg +1 -0
  109. package/src/integrations/marks/stripe-mcp.svg +1 -0
  110. package/src/integrations/marks/supabase-mcp.svg +1 -0
  111. package/src/integrations/marks/upstash-mcp.svg +1 -0
  112. package/src/integrations/marks/vercel.svg +1 -0
  113. package/src/integrations/marks/webflow.svg +1 -0
  114. package/src/integrations/mcp-oauth.test.ts +39 -0
  115. package/src/integrations/mcp-oauth.ts +330 -0
  116. package/src/integrations/oauth-clients.test.ts +77 -0
  117. package/src/integrations/oauth-clients.ts +127 -0
  118. package/src/integrations/oauth.ts +145 -0
  119. package/src/integrations/remote-mcp.ts +307 -0
  120. package/src/integrations/store.ts +149 -0
  121. package/src/media/openrouter-generate.test.ts +80 -0
  122. package/src/media/openrouter-generate.ts +178 -0
  123. package/src/media/prefs.ts +54 -0
  124. package/src/observability/categories.ts +41 -0
  125. package/src/observability/create.test.ts +56 -0
  126. package/src/observability/create.ts +45 -0
  127. package/src/observability/experiments.ts +113 -0
  128. package/src/observability/fake.ts +191 -0
  129. package/src/observability/index.ts +57 -0
  130. package/src/observability/judges.ts +91 -0
  131. package/src/observability/langfuse.ts +275 -0
  132. package/src/observability/noop.ts +33 -0
  133. package/src/observability/observability.test.ts +113 -0
  134. package/src/observability/prompts.ts +98 -0
  135. package/src/observability/regression-items.ts +158 -0
  136. package/src/observability/sanitize.test.ts +26 -0
  137. package/src/observability/sanitize.ts +57 -0
  138. package/src/observability/types.ts +122 -0
  139. package/src/observability/version.ts +41 -0
  140. package/src/product.ts +2 -0
  141. package/src/runtime.test.ts +98 -0
  142. package/src/runtime.ts +438 -0
  143. package/src/skills/author-skill.ts +49 -0
  144. package/src/skills/create-skill.test.ts +108 -0
  145. package/src/skills/create-skill.ts +70 -0
  146. package/src/skills/loader.test.ts +122 -0
  147. package/src/skills/loader.ts +162 -0
  148. package/src/skills/registry.test.ts +190 -0
  149. package/src/skills/registry.ts +402 -0
  150. package/src/skills/skill-command.ts +53 -0
  151. package/src/skills/user-dir.ts +8 -0
  152. package/src/tools/git.test.ts +71 -0
  153. package/src/tools/git.ts +126 -0
  154. package/src/tools/local.ts +258 -0
  155. package/src/tools/paths.test.ts +24 -0
  156. package/src/tools/paths.ts +39 -0
  157. package/src/tools/read-skill.ts +43 -0
  158. package/src/tools/subagent.test.ts +77 -0
  159. package/src/tools/subagent.ts +74 -0
  160. package/src/tools/todo.test.ts +25 -0
  161. package/src/tools/todo.ts +70 -0
@@ -0,0 +1,178 @@
1
+ import { OPENROUTER_DEFAULT_BASE_URL } from "../config.ts";
2
+ import { PRODUCT_NAME } from "../product.ts";
3
+
4
+ type FetchImpl = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
5
+
6
+ export interface GeneratedMedia {
7
+ kind: "image" | "video";
8
+ mimeType: string;
9
+ dataUrl: string;
10
+ }
11
+
12
+ function authHeaders(apiKey: string): Record<string, string> {
13
+ return {
14
+ Authorization: `Bearer ${apiKey}`,
15
+ "Content-Type": "application/json",
16
+ "HTTP-Referer": "https://caelence.com",
17
+ "X-Title": PRODUCT_NAME,
18
+ };
19
+ }
20
+
21
+ function asDataUrl(raw: string, fallbackMime: string): string {
22
+ if (raw.startsWith("data:")) return raw;
23
+ if (raw.startsWith("http://") || raw.startsWith("https://")) return raw;
24
+ return `data:${fallbackMime};base64,${raw}`;
25
+ }
26
+
27
+ function imageUrls(json: unknown): string[] {
28
+ if (typeof json !== "object" || json === null) return [];
29
+ const rec = json as Record<string, unknown>;
30
+ const found: string[] = [];
31
+ const data = rec.data;
32
+ if (Array.isArray(data)) {
33
+ for (const item of data) {
34
+ if (typeof item !== "object" || item === null) continue;
35
+ const row = item as Record<string, unknown>;
36
+ if (typeof row.b64_json === "string") found.push(asDataUrl(row.b64_json, "image/png"));
37
+ else if (typeof row.url === "string") found.push(asDataUrl(row.url, "image/png"));
38
+ }
39
+ }
40
+ if (found.length > 0) return found;
41
+ const images = rec.images;
42
+ if (Array.isArray(images)) {
43
+ for (const item of images) {
44
+ if (typeof item === "string") found.push(asDataUrl(item, "image/png"));
45
+ if (typeof item !== "object" || item === null) continue;
46
+ const row = item as Record<string, unknown>;
47
+ const nested = row.image_url;
48
+ if (typeof nested === "string") found.push(asDataUrl(nested, "image/png"));
49
+ else if (typeof nested === "object" && nested !== null) {
50
+ const url = (nested as { url?: unknown }).url;
51
+ if (typeof url === "string") found.push(asDataUrl(url, "image/png"));
52
+ } else if (typeof row.url === "string") found.push(asDataUrl(row.url, "image/png"));
53
+ }
54
+ }
55
+ return found;
56
+ }
57
+
58
+ async function readError(res: Response): Promise<string> {
59
+ const detail = await res.text().catch(() => "");
60
+ const snippet = detail.replace(/\s+/g, " ").trim().slice(0, 240);
61
+ return snippet ? `: ${snippet}` : "";
62
+ }
63
+
64
+ export async function generateImage(input: {
65
+ prompt: string;
66
+ model: string;
67
+ apiKey: string;
68
+ baseUrl?: string;
69
+ fetchImpl?: FetchImpl;
70
+ }): Promise<GeneratedMedia> {
71
+ const prompt = input.prompt.trim();
72
+ if (!prompt) throw new Error("Describe the image.");
73
+ if (!input.apiKey.trim()) throw new Error("OpenRouter API key is missing. Add it in Settings.");
74
+ const base = (input.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
75
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch;
76
+ const res = await fetchImpl(`${base}/images`, {
77
+ method: "POST",
78
+ headers: authHeaders(input.apiKey),
79
+ body: JSON.stringify({ model: input.model, prompt }),
80
+ });
81
+ if (!res.ok) throw new Error(`Image generation failed (${res.status})${await readError(res)}`);
82
+ const urls = imageUrls(await res.json());
83
+ if (urls.length === 0) throw new Error("Image generation returned no image.");
84
+ return { kind: "image", mimeType: "image/png", dataUrl: urls[0] ?? "" };
85
+ }
86
+
87
+ interface VideoJob {
88
+ id?: string;
89
+ status?: string;
90
+ polling_url?: string;
91
+ unsigned_urls?: string[];
92
+ error?: { message?: string } | string;
93
+ }
94
+
95
+ export async function generateVideo(input: {
96
+ prompt: string;
97
+ model: string;
98
+ apiKey: string;
99
+ baseUrl?: string;
100
+ fetchImpl?: FetchImpl;
101
+ sleep?: (ms: number) => Promise<void>;
102
+ }): Promise<GeneratedMedia> {
103
+ const prompt = input.prompt.trim();
104
+ if (!prompt) throw new Error("Describe the clip.");
105
+ if (!input.apiKey.trim()) throw new Error("OpenRouter API key is missing. Add it in Settings.");
106
+ const base = (input.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
107
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch;
108
+ const sleep = input.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
109
+ const res = await fetchImpl(`${base}/videos`, {
110
+ method: "POST",
111
+ headers: authHeaders(input.apiKey),
112
+ body: JSON.stringify({
113
+ model: input.model,
114
+ prompt,
115
+ duration: 5,
116
+ aspect_ratio: "16:9",
117
+ }),
118
+ });
119
+ if (!res.ok) throw new Error(`Video generation failed (${res.status})${await readError(res)}`);
120
+ let job = (await res.json()) as VideoJob;
121
+ const deadline = Date.now() + 10 * 60_000;
122
+ while (job.status === "pending" || job.status === "in_progress" || job.status === "processing") {
123
+ if (Date.now() > deadline) throw new Error("Video generation timed out.");
124
+ await sleep(2_000);
125
+ const pollUrl =
126
+ job.polling_url || (job.id ? `${base}/videos/${encodeURIComponent(job.id)}` : "");
127
+ if (!pollUrl) throw new Error("Video generation did not return a job id.");
128
+ const poll = await fetchImpl(pollUrl, { headers: authHeaders(input.apiKey) });
129
+ if (!poll.ok)
130
+ throw new Error(`Video generation failed (${poll.status})${await readError(poll)}`);
131
+ job = (await poll.json()) as VideoJob;
132
+ }
133
+ if (job.status && job.status !== "completed") {
134
+ const message = typeof job.error === "string" ? job.error : job.error?.message || job.status;
135
+ throw new Error(`Video generation ${message}`);
136
+ }
137
+ const contentUrl = job.id ? `${base}/videos/${encodeURIComponent(job.id)}/content` : "";
138
+ for (const url of [...(job.unsigned_urls ?? []), contentUrl].filter(Boolean)) {
139
+ const clip = await fetchImpl(url, { headers: { Authorization: `Bearer ${input.apiKey}` } });
140
+ if (!clip.ok) continue;
141
+ const type = clip.headers.get("content-type") || "video/mp4";
142
+ if (type.includes("application/json")) continue;
143
+ const buf = Buffer.from(await clip.arrayBuffer());
144
+ if (buf.byteLength === 0) continue;
145
+ return {
146
+ kind: "video",
147
+ mimeType: type.split(";")[0] || "video/mp4",
148
+ dataUrl: `data:${type.split(";")[0] || "video/mp4"};base64,${buf.toString("base64")}`,
149
+ };
150
+ }
151
+ throw new Error("Video generation finished but returned no clip.");
152
+ }
153
+
154
+ export async function transcribeAudio(input: {
155
+ data: string;
156
+ format: string;
157
+ model: string;
158
+ apiKey: string;
159
+ baseUrl?: string;
160
+ fetchImpl?: FetchImpl;
161
+ }): Promise<string> {
162
+ if (!input.apiKey.trim()) throw new Error("OpenRouter API key is missing. Add it in Settings.");
163
+ const base = (input.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
164
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch;
165
+ const res = await fetchImpl(`${base}/audio/transcriptions`, {
166
+ method: "POST",
167
+ headers: authHeaders(input.apiKey),
168
+ body: JSON.stringify({
169
+ model: input.model,
170
+ input_audio: { data: input.data, format: input.format },
171
+ }),
172
+ });
173
+ if (!res.ok) throw new Error(`Transcription failed (${res.status})${await readError(res)}`);
174
+ const json = (await res.json()) as { text?: string };
175
+ const text = json.text?.trim() ?? "";
176
+ if (!text) throw new Error("Transcription returned no text.");
177
+ return text;
178
+ }
@@ -0,0 +1,54 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import {
4
+ DEFAULT_IMAGE_MODEL,
5
+ DEFAULT_TRANSCRIBE_MODEL,
6
+ DEFAULT_VIDEO_MODEL,
7
+ } from "../cli/media-models.ts";
8
+ import { harnessHome } from "../desktop/secrets.ts";
9
+
10
+ export interface MediaPrefs {
11
+ imageModel: string;
12
+ videoModel: string;
13
+ transcribeModel: string;
14
+ }
15
+
16
+ function prefsPath(env: Record<string, string | undefined> = process.env): string {
17
+ return resolve(harnessHome(env), "media.json");
18
+ }
19
+
20
+ export function readMediaPrefs(env: Record<string, string | undefined> = process.env): MediaPrefs {
21
+ const path = prefsPath(env);
22
+ if (!existsSync(path)) {
23
+ return {
24
+ imageModel: DEFAULT_IMAGE_MODEL,
25
+ videoModel: DEFAULT_VIDEO_MODEL,
26
+ transcribeModel: DEFAULT_TRANSCRIBE_MODEL,
27
+ };
28
+ }
29
+ try {
30
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<MediaPrefs>;
31
+ return {
32
+ imageModel: parsed.imageModel?.trim() || DEFAULT_IMAGE_MODEL,
33
+ videoModel: parsed.videoModel?.trim() || DEFAULT_VIDEO_MODEL,
34
+ transcribeModel: parsed.transcribeModel?.trim() || DEFAULT_TRANSCRIBE_MODEL,
35
+ };
36
+ } catch {
37
+ return {
38
+ imageModel: DEFAULT_IMAGE_MODEL,
39
+ videoModel: DEFAULT_VIDEO_MODEL,
40
+ transcribeModel: DEFAULT_TRANSCRIBE_MODEL,
41
+ };
42
+ }
43
+ }
44
+
45
+ export function writeMediaPrefs(
46
+ patch: Partial<MediaPrefs>,
47
+ env: Record<string, string | undefined> = process.env,
48
+ ): MediaPrefs {
49
+ const next = { ...readMediaPrefs(env), ...patch };
50
+ const path = prefsPath(env);
51
+ mkdirSync(resolve(path, ".."), { recursive: true });
52
+ writeFileSync(path, `${JSON.stringify(next, null, "\t")}\n`);
53
+ return next;
54
+ }
@@ -0,0 +1,41 @@
1
+ import type { FailureCategory } from "./types.ts";
2
+
3
+ export interface FailureSignals {
4
+ errorType?: string;
5
+ phase?: string;
6
+ typecheckPass?: boolean;
7
+ testsPass?: boolean;
8
+ uiPass?: boolean;
9
+ timedOut?: boolean;
10
+ toolFailed?: boolean;
11
+ message?: string;
12
+ }
13
+
14
+ /** Map implement-cycle / error-log signals onto a Langfuse failure category. */
15
+ export function categorizeFailure(signals: FailureSignals): FailureCategory | undefined {
16
+ if (signals.timedOut) return "TIMEOUT";
17
+ const type = (signals.errorType ?? "").toLowerCase();
18
+ const phase = (signals.phase ?? "").toLowerCase();
19
+ const message = (signals.message ?? "").toLowerCase();
20
+
21
+ if (type.includes("timeout") || message.includes("timed out")) return "TIMEOUT";
22
+ if (signals.toolFailed || phase === "mcp" || type.includes("tool")) return "TOOL_ERROR";
23
+ if (type.includes("mode_classify") || type.includes("planning") || phase === "planning") {
24
+ return "PLANNING_ERROR";
25
+ }
26
+ if (signals.typecheckPass === false) return "BUILD_ERROR";
27
+ if (signals.testsPass === false) return "BUILD_ERROR";
28
+ if (signals.uiPass === false) return "RUNTIME_ERROR";
29
+ if (type.includes("tdd") || type.includes("code_review") || type.includes("cycle_missing")) {
30
+ return "CODE_GENERATION_ERROR";
31
+ }
32
+ if (type.includes("model") || (phase === "agent" && message.includes("provider")))
33
+ return "MODEL_ERROR";
34
+ if (type.includes("responsive") || message.includes("viewport")) return "RESPONSIVE_ERROR";
35
+ if (type.includes("design")) return "DESIGN_ERROR";
36
+ if (type.includes("requirement") || type.includes("instruction"))
37
+ return "USER_REQUIREMENT_MISMATCH";
38
+ if (phase === "sandbox") return "BUILD_ERROR";
39
+ if (phase === "agent") return "CODE_GENERATION_ERROR";
40
+ return undefined;
41
+ }
@@ -0,0 +1,56 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { createObservability, resetObservabilityForTests } from "./create.ts";
3
+ import { createRecordingObservability } from "./fake.ts";
4
+ import { noopObservability } from "./noop.ts";
5
+ import { langfuseKeysPresent, resolveAgentVersion } from "./version.ts";
6
+
7
+ describe("createObservability", () => {
8
+ test("no-ops when keys are unset", async () => {
9
+ resetObservabilityForTests();
10
+ const obs = await createObservability({ env: {} });
11
+ expect(obs.enabled).toBe(false);
12
+ expect(obs).toBe(noopObservability);
13
+ let ran = false;
14
+ await obs.startTurn({ name: "agent_turn" }, async () => {
15
+ ran = true;
16
+ });
17
+ expect(ran).toBe(true);
18
+ });
19
+
20
+ test("keysPresent requires both public and secret", () => {
21
+ expect(langfuseKeysPresent({})).toBe(false);
22
+ expect(langfuseKeysPresent({ LANGFUSE_PUBLIC_KEY: "pk" })).toBe(false);
23
+ expect(langfuseKeysPresent({ LANGFUSE_PUBLIC_KEY: "pk", LANGFUSE_SECRET_KEY: "sk" })).toBe(
24
+ true,
25
+ );
26
+ });
27
+ });
28
+
29
+ describe("resolveAgentVersion", () => {
30
+ test("env wins over fallback", () => {
31
+ expect(resolveAgentVersion("pkg", { CAELENCE_AGENT_VERSION: "website-agent-v42" })).toBe(
32
+ "website-agent-v42",
33
+ );
34
+ expect(resolveAgentVersion("0.1.0", {})).toBe("0.1.0");
35
+ });
36
+ });
37
+
38
+ describe("recording observer", () => {
39
+ test("nests tools under a turn", async () => {
40
+ const obs = createRecordingObservability();
41
+ await obs.startTurn({ name: "agent_turn", sessionId: "sess_1" }, async (root) => {
42
+ root.update({ input: "hi" });
43
+ await obs.tool("write_file", async (span) => {
44
+ span.update({ input: { path: "a.ts" }, output: "ok" });
45
+ });
46
+ await obs.generation("llm", async (gen) => {
47
+ gen.update({ model: "fake", output: "done" });
48
+ });
49
+ obs.score({ name: "build_success", value: 1 });
50
+ });
51
+ expect(obs.turns).toHaveLength(1);
52
+ expect(obs.turns[0]?.children.map((c) => c.kind)).toEqual(["tool", "generation"]);
53
+ expect(obs.scores[0]?.name).toBe("build_success");
54
+ expect(obs.currentTraceId()).toBeUndefined();
55
+ });
56
+ });
@@ -0,0 +1,45 @@
1
+ import { tryCreateLangfuseObservability } from "./langfuse.ts";
2
+ import { noopObservability } from "./noop.ts";
3
+ import type { CreateObservabilityOptions, Observability } from "./types.ts";
4
+ import { langfuseKeysPresent } from "./version.ts";
5
+
6
+ let singleton: Observability | undefined;
7
+ let singletonPromise: Promise<Observability> | undefined;
8
+
9
+ /**
10
+ * Keys present → Langfuse (if packages load). Missing keys or `enabled: false` → no-op.
11
+ * Safe to call more than once; subsequent calls reuse the first instance.
12
+ */
13
+ export async function createObservability(
14
+ options: CreateObservabilityOptions = {},
15
+ ): Promise<Observability> {
16
+ if (options.enabled === false) return noopObservability;
17
+ const env = options.env ?? process.env;
18
+ if (!langfuseKeysPresent(env)) return noopObservability;
19
+ const created = await tryCreateLangfuseObservability(options);
20
+ return created ?? noopObservability;
21
+ }
22
+
23
+ /** Process-wide observer. The CLI starts this once at boot. */
24
+ export async function startObservability(
25
+ options: CreateObservabilityOptions = {},
26
+ ): Promise<Observability> {
27
+ if (singleton) return singleton;
28
+ if (!singletonPromise) {
29
+ singletonPromise = createObservability(options).then((obs) => {
30
+ singleton = obs;
31
+ return obs;
32
+ });
33
+ }
34
+ return singletonPromise;
35
+ }
36
+
37
+ export function getObservability(): Observability {
38
+ return singleton ?? noopObservability;
39
+ }
40
+
41
+ /** Test-only: drop the process singleton. */
42
+ export function resetObservabilityForTests(): void {
43
+ singleton = undefined;
44
+ singletonPromise = undefined;
45
+ }
@@ -0,0 +1,113 @@
1
+ import { postDeterministicScores } from "./judges.ts";
2
+ import type { Observability } from "./types.ts";
3
+
4
+ export interface ExperimentItem {
5
+ id?: string;
6
+ input: unknown;
7
+ expectedOutput?: unknown;
8
+ metadata?: Record<string, unknown>;
9
+ }
10
+
11
+ export interface ExperimentEvaluator {
12
+ name: string;
13
+ run: (args: {
14
+ input: unknown;
15
+ output: unknown;
16
+ expectedOutput?: unknown;
17
+ metadata?: Record<string, unknown>;
18
+ }) => { value: number; comment?: string } | Promise<{ value: number; comment?: string }>;
19
+ }
20
+
21
+ export interface ExperimentResult {
22
+ name: string;
23
+ ok: boolean;
24
+ itemResults: Array<{
25
+ id?: string;
26
+ output: unknown;
27
+ scores: Record<string, number>;
28
+ error?: string;
29
+ }>;
30
+ aggregates: Record<string, number>;
31
+ }
32
+
33
+ export async function runLocalExperiment(input: {
34
+ name: string;
35
+ items: ExperimentItem[];
36
+ task: (item: ExperimentItem) => Promise<unknown>;
37
+ evaluators?: ExperimentEvaluator[];
38
+ observability?: Observability;
39
+ /** Fail the run when this named aggregate is below the threshold. */
40
+ gate?: { score: string; min: number };
41
+ }): Promise<ExperimentResult> {
42
+ const obs = input.observability;
43
+ const itemResults: ExperimentResult["itemResults"] = [];
44
+ await (obs
45
+ ? obs.startTurn(
46
+ { name: input.name, tags: ["experiment"], metadata: { requestType: "eval" } },
47
+ runItems,
48
+ )
49
+ : runItems());
50
+
51
+ async function runItems(): Promise<void> {
52
+ for (const item of input.items) {
53
+ try {
54
+ const output = await input.task(item);
55
+ const scores: Record<string, number> = {};
56
+ for (const evaluator of input.evaluators ?? []) {
57
+ const result = await evaluator.run({
58
+ input: item.input,
59
+ output,
60
+ expectedOutput: item.expectedOutput,
61
+ metadata: item.metadata,
62
+ });
63
+ scores[evaluator.name] = result.value;
64
+ obs?.score({
65
+ name: evaluator.name,
66
+ value: result.value,
67
+ comment: result.comment,
68
+ dataType: "NUMERIC",
69
+ });
70
+ }
71
+ itemResults.push({ id: item.id, output, scores });
72
+ } catch (err) {
73
+ itemResults.push({
74
+ id: item.id,
75
+ output: undefined,
76
+ scores: {},
77
+ error: err instanceof Error ? err.message : String(err),
78
+ });
79
+ }
80
+ }
81
+ }
82
+
83
+ const aggregates: Record<string, number> = {};
84
+ const names = new Set(itemResults.flatMap((r) => Object.keys(r.scores)));
85
+ for (const name of names) {
86
+ const values = itemResults
87
+ .map((r) => r.scores[name])
88
+ .filter((n): n is number => n !== undefined);
89
+ if (values.length === 0) continue;
90
+ aggregates[name] = values.reduce((a, b) => a + b, 0) / values.length;
91
+ }
92
+ aggregates.item_success =
93
+ itemResults.filter((r) => !r.error).length / Math.max(1, itemResults.length);
94
+ if (obs) postDeterministicScores(obs, aggregates);
95
+ await obs?.flush();
96
+
97
+ const gateOk =
98
+ !input.gate ||
99
+ (aggregates[input.gate.score] !== undefined && aggregates[input.gate.score]! >= input.gate.min);
100
+ return {
101
+ name: input.name,
102
+ ok: gateOk && itemResults.every((r) => !r.error),
103
+ itemResults,
104
+ aggregates,
105
+ };
106
+ }
107
+
108
+ export const DEFAULT_GATES = {
109
+ build_success: 0.98,
110
+ instruction_following: 0.85,
111
+ visual_quality: 0.85,
112
+ costIncrease: 0.2,
113
+ } as const;
@@ -0,0 +1,191 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type {
3
+ EventInput,
4
+ GenerationFields,
5
+ GenerationHandle,
6
+ Observability,
7
+ ScoreInput,
8
+ SpanFields,
9
+ SpanHandle,
10
+ TurnOptions,
11
+ } from "./types.ts";
12
+
13
+ export interface RecordedSpan {
14
+ kind: "turn" | "span" | "generation" | "tool" | "event";
15
+ name: string;
16
+ input?: unknown;
17
+ output?: unknown;
18
+ metadata?: Record<string, unknown>;
19
+ model?: string;
20
+ level?: string;
21
+ statusMessage?: string;
22
+ ended: boolean;
23
+ children: RecordedSpan[];
24
+ }
25
+
26
+ export interface RecordedScore extends ScoreInput {
27
+ traceId?: string;
28
+ }
29
+
30
+ interface Store {
31
+ turn: RecordedSpan;
32
+ }
33
+
34
+ const als = new AsyncLocalStorage<Store>();
35
+
36
+ function applyFields(span: RecordedSpan, fields: SpanFields | GenerationFields): void {
37
+ if ("input" in fields) span.input = fields.input;
38
+ if ("output" in fields) span.output = fields.output;
39
+ if (fields.metadata) span.metadata = { ...span.metadata, ...fields.metadata };
40
+ if (fields.level) span.level = fields.level;
41
+ if (fields.statusMessage) span.statusMessage = fields.statusMessage;
42
+ if ("model" in fields && fields.model) span.model = fields.model;
43
+ }
44
+
45
+ function handleFor(span: RecordedSpan, traceId: string): GenerationHandle {
46
+ return {
47
+ get traceId() {
48
+ return traceId;
49
+ },
50
+ update(fields) {
51
+ applyFields(span, fields);
52
+ },
53
+ end() {
54
+ span.ended = true;
55
+ },
56
+ };
57
+ }
58
+
59
+ function attach(child: RecordedSpan): void {
60
+ const store = als.getStore();
61
+ if (store) store.turn.children.push(child);
62
+ }
63
+
64
+ /**
65
+ * In-memory observer for tests. Nested startSpan/tool/generation attach to the
66
+ * active startTurn via AsyncLocalStorage.
67
+ */
68
+ export function createRecordingObservability(): Observability & {
69
+ turns: RecordedSpan[];
70
+ scores: RecordedScore[];
71
+ events: Array<{ name: string; input?: EventInput }>;
72
+ traceId: string;
73
+ } {
74
+ const turns: RecordedSpan[] = [];
75
+ const scores: RecordedScore[] = [];
76
+ const events: Array<{ name: string; input?: EventInput }> = [];
77
+ const traceId = "trace_test";
78
+
79
+ const runChild = async <T>(
80
+ span: RecordedSpan,
81
+ fn: (handle: SpanHandle) => Promise<T>,
82
+ ): Promise<T> => {
83
+ attach(span);
84
+ try {
85
+ const result = await fn(handleFor(span, traceId));
86
+ span.ended = true;
87
+ return result;
88
+ } catch (err) {
89
+ span.ended = true;
90
+ span.level = "ERROR";
91
+ span.statusMessage = err instanceof Error ? err.message : String(err);
92
+ throw err;
93
+ }
94
+ };
95
+
96
+ return {
97
+ enabled: true,
98
+ turns,
99
+ scores,
100
+ events,
101
+ traceId,
102
+ async startTurn(options: TurnOptions, fn) {
103
+ const span: RecordedSpan = {
104
+ kind: "turn",
105
+ name: options.name,
106
+ input: options.input,
107
+ metadata: {
108
+ ...options.metadata,
109
+ ...(options.sessionId ? { sessionId: options.sessionId } : {}),
110
+ ...(options.userId ? { userId: options.userId } : {}),
111
+ },
112
+ ended: false,
113
+ children: [],
114
+ };
115
+ const parent = als.getStore();
116
+ if (parent) parent.turn.children.push(span);
117
+ else turns.push(span);
118
+ return als.run({ turn: span }, async () => {
119
+ try {
120
+ const result = await fn(handleFor(span, traceId));
121
+ span.ended = true;
122
+ return result;
123
+ } catch (err) {
124
+ span.ended = true;
125
+ span.level = "ERROR";
126
+ span.statusMessage = err instanceof Error ? err.message : String(err);
127
+ throw err;
128
+ }
129
+ });
130
+ },
131
+ startSpan(name, fn, options) {
132
+ return runChild(
133
+ {
134
+ kind: "span",
135
+ name,
136
+ input: options?.input,
137
+ metadata: options?.metadata,
138
+ ended: false,
139
+ children: [],
140
+ },
141
+ fn,
142
+ );
143
+ },
144
+ generation(name, fn, options) {
145
+ return runChild(
146
+ {
147
+ kind: "generation",
148
+ name,
149
+ input: options?.input,
150
+ metadata: options?.metadata,
151
+ model: options?.model,
152
+ ended: false,
153
+ children: [],
154
+ },
155
+ fn,
156
+ );
157
+ },
158
+ tool(name, fn, options) {
159
+ return runChild(
160
+ {
161
+ kind: "tool",
162
+ name,
163
+ input: options?.input,
164
+ metadata: options?.metadata,
165
+ ended: false,
166
+ children: [],
167
+ },
168
+ fn,
169
+ );
170
+ },
171
+ score(input) {
172
+ scores.push({ ...input, traceId: input.traceId ?? (als.getStore() ? traceId : undefined) });
173
+ },
174
+ event(name, input) {
175
+ events.push({ name, input });
176
+ attach({
177
+ kind: "event",
178
+ name,
179
+ input: input?.input,
180
+ metadata: input?.metadata,
181
+ ended: true,
182
+ children: [],
183
+ });
184
+ },
185
+ currentTraceId() {
186
+ return als.getStore() ? traceId : undefined;
187
+ },
188
+ async flush() {},
189
+ async shutdown() {},
190
+ };
191
+ }