@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,40 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { localOpenCommand, resolveLocalPath } from "./open-local.ts";
6
+
7
+ describe("resolveLocalPath", () => {
8
+ test("expands a home path and requires the file to exist", async () => {
9
+ const dir = join(tmpdir(), `harness-open-${Date.now()}`);
10
+ const file = join(dir, "note.txt");
11
+ await mkdir(dir, { recursive: true });
12
+ try {
13
+ await writeFile(file, "x");
14
+ expect(resolveLocalPath(file)).toBe(file);
15
+ expect(resolveLocalPath(join(dir, "missing.txt"))).toBeUndefined();
16
+ expect(resolveLocalPath("note.txt", dir)).toBe(file);
17
+ } finally {
18
+ await rm(dir, { recursive: true, force: true });
19
+ }
20
+ });
21
+
22
+ test("rejects empty or injected paths", () => {
23
+ expect(resolveLocalPath("")).toBeUndefined();
24
+ expect(resolveLocalPath("a\nb")).toBeUndefined();
25
+ });
26
+ });
27
+
28
+ describe("localOpenCommand", () => {
29
+ test("reveals on macOS with open -R", () => {
30
+ if (process.platform !== "darwin") return;
31
+ expect(localOpenCommand("/tmp/note.txt", true)).toEqual({
32
+ cmd: "/usr/bin/open",
33
+ args: ["-R", "/tmp/note.txt"],
34
+ });
35
+ expect(localOpenCommand("/tmp/note.txt", false)).toEqual({
36
+ cmd: "/usr/bin/open",
37
+ args: ["/tmp/note.txt"],
38
+ });
39
+ });
40
+ });
@@ -0,0 +1,52 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute, resolve } from "node:path";
5
+
6
+ export function resolveLocalPath(raw: string, cwd?: string): string | undefined {
7
+ let path = raw.trim();
8
+ if (!path || path.includes("\0") || /\n|\r/.test(path)) return undefined;
9
+ if (path.startsWith("file://")) {
10
+ try {
11
+ const url = new URL(path);
12
+ if (url.protocol !== "file:") return undefined;
13
+ path = decodeURIComponent(url.pathname);
14
+ if (process.platform === "win32" && path.startsWith("/")) path = path.slice(1);
15
+ } catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ if (path === "~") path = homedir();
20
+ else if (path.startsWith("~/")) path = `${homedir()}/${path.slice(2)}`;
21
+ if (!isAbsolute(path)) {
22
+ if (!cwd) return undefined;
23
+ path = resolve(cwd, path);
24
+ }
25
+ if (!existsSync(path)) return undefined;
26
+ return path;
27
+ }
28
+
29
+ export function localOpenCommand(
30
+ absPath: string,
31
+ reveal: boolean,
32
+ ): { cmd: string; args: string[] } {
33
+ if (process.platform === "darwin") {
34
+ return reveal
35
+ ? { cmd: "/usr/bin/open", args: ["-R", absPath] }
36
+ : { cmd: "/usr/bin/open", args: [absPath] };
37
+ }
38
+ if (process.platform === "win32") {
39
+ return reveal
40
+ ? { cmd: "explorer", args: ["/select,", absPath] }
41
+ : { cmd: "cmd", args: ["/c", "start", "", absPath] };
42
+ }
43
+ if (reveal) {
44
+ return { cmd: "xdg-open", args: [resolve(absPath, "..")] };
45
+ }
46
+ return { cmd: "xdg-open", args: [absPath] };
47
+ }
48
+
49
+ export function openResolvedPath(absPath: string, reveal = false): void {
50
+ const { cmd, args } = localOpenCommand(absPath, reveal);
51
+ spawn(cmd, args, { detached: true, stdio: "ignore" }).unref();
52
+ }
@@ -0,0 +1,36 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ previewCacheKey,
7
+ readPreviewCache,
8
+ stablePreviewKey,
9
+ writePreviewCache,
10
+ } from "./preview-cache.ts";
11
+
12
+ describe("preview cache", () => {
13
+ test("keys Canva document images by design id, not the signed query", () => {
14
+ const a = "https://media.canva.com/v2/document-image/hash:1/id:DAHTOpj1Mso/type:B?sig=old";
15
+ const b = "https://media.canva.com/v2/document-image/hash:2/id:DAHTOpj1Mso/type:B?sig=new";
16
+ expect(stablePreviewKey(a)).toBe("canva:DAHTOpj1Mso");
17
+ expect(previewCacheKey(a)).toBe(previewCacheKey(b));
18
+ });
19
+
20
+ test("round-trips bytes under HARNESS_HOME", async () => {
21
+ const home = await mkdtemp(join(tmpdir(), "harness-prev-"));
22
+ const prev = process.env.HARNESS_HOME;
23
+ process.env.HARNESS_HOME = home;
24
+ try {
25
+ const href = "https://media.canva.com/v2/document-image/id:abc/type:B";
26
+ writePreviewCache(href, "image/png", new Uint8Array([1, 2, 3, 4]));
27
+ const stored = readPreviewCache(href);
28
+ expect(stored?.type).toBe("image/png");
29
+ expect(Array.from(stored?.bytes ?? [])).toEqual([1, 2, 3, 4]);
30
+ } finally {
31
+ if (prev === undefined) delete process.env.HARNESS_HOME;
32
+ else process.env.HARNESS_HOME = prev;
33
+ await rm(home, { recursive: true, force: true });
34
+ }
35
+ });
36
+ });
@@ -0,0 +1,63 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { harnessHome } from "../desktop/secrets.ts";
5
+
6
+ export function previewCacheKey(href: string): string {
7
+ return createHash("sha256").update(stablePreviewKey(href)).digest("hex");
8
+ }
9
+
10
+ export function stablePreviewKey(href: string): string {
11
+ try {
12
+ const url = new URL(href);
13
+ const canvaId = /\/id:([^/]+)/.exec(url.pathname)?.[1];
14
+ if (canvaId) return `canva:${canvaId}`;
15
+ url.search = "";
16
+ url.hash = "";
17
+ return url.toString();
18
+ } catch {
19
+ return href;
20
+ }
21
+ }
22
+
23
+ function previewDir(env: Record<string, string | undefined> = process.env): string {
24
+ return resolve(harnessHome(env), "previews");
25
+ }
26
+
27
+ function previewPath(href: string, env: Record<string, string | undefined> = process.env): string {
28
+ return resolve(previewDir(env), `${previewCacheKey(href)}.bin`);
29
+ }
30
+
31
+ function metaPath(href: string, env: Record<string, string | undefined> = process.env): string {
32
+ return resolve(previewDir(env), `${previewCacheKey(href)}.type`);
33
+ }
34
+
35
+ export function readPreviewCache(
36
+ href: string,
37
+ env: Record<string, string | undefined> = process.env,
38
+ ): { type: string; bytes: Uint8Array } | null {
39
+ const file = previewPath(href, env);
40
+ if (!existsSync(file)) return null;
41
+ try {
42
+ const bytes = new Uint8Array(readFileSync(file));
43
+ if (bytes.byteLength === 0) return null;
44
+ const type = existsSync(metaPath(href, env))
45
+ ? readFileSync(metaPath(href, env), "utf8").trim()
46
+ : "image/png";
47
+ return { type: type || "image/png", bytes };
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ export function writePreviewCache(
54
+ href: string,
55
+ type: string,
56
+ bytes: Uint8Array,
57
+ env: Record<string, string | undefined> = process.env,
58
+ ): void {
59
+ const dir = previewDir(env);
60
+ mkdirSync(dir, { recursive: true });
61
+ writeFileSync(previewPath(href, env), bytes);
62
+ writeFileSync(metaPath(href, env), `${type}\n`);
63
+ }
@@ -0,0 +1,44 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtempSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ applyStoredOpenRouterKey,
7
+ maskSecret,
8
+ readOpenRouterKey,
9
+ writeOpenRouterKey,
10
+ } from "./secrets.ts";
11
+
12
+ describe("openrouter key store", () => {
13
+ test("masks all but the last four characters", () => {
14
+ expect(maskSecret("")).toBe("");
15
+ expect(maskSecret("abcd")).toBe("••••");
16
+ expect(maskSecret("sk-or-v1-hello")).toBe("••••ello");
17
+ });
18
+
19
+ test("writes, reads, and clears a key file", () => {
20
+ const home = mkdtempSync(join(tmpdir(), "harness-secrets-"));
21
+ const env = { HARNESS_HOME: home };
22
+ expect(readOpenRouterKey(env)).toBe("");
23
+ writeOpenRouterKey("sk-test-key", env);
24
+ expect(readOpenRouterKey(env)).toBe("sk-test-key");
25
+ writeOpenRouterKey("", env);
26
+ expect(readOpenRouterKey(env)).toBe("");
27
+ });
28
+
29
+ test("env wins over the stored file", () => {
30
+ const home = mkdtempSync(join(tmpdir(), "harness-secrets-"));
31
+ const env: Record<string, string | undefined> = { HARNESS_HOME: home };
32
+ writeOpenRouterKey("stored-key", env);
33
+ env.OPENROUTER_API_KEY = "env-key";
34
+ expect(applyStoredOpenRouterKey(env)).toBe("env-key");
35
+ });
36
+
37
+ test("loads the file when env is empty", () => {
38
+ const home = mkdtempSync(join(tmpdir(), "harness-secrets-"));
39
+ const env: Record<string, string | undefined> = { HARNESS_HOME: home };
40
+ writeOpenRouterKey("stored-key", env);
41
+ expect(applyStoredOpenRouterKey(env)).toBe("stored-key");
42
+ expect(env.OPENROUTER_API_KEY).toBe("stored-key");
43
+ });
44
+ });
@@ -0,0 +1,60 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, resolve } from "node:path";
4
+
5
+ export function harnessHome(env: Record<string, string | undefined> = process.env): string {
6
+ const override = env.HARNESS_HOME?.trim();
7
+ if (override) return resolve(override);
8
+ return resolve(homedir(), ".harness");
9
+ }
10
+
11
+ export function openRouterKeyPath(env: Record<string, string | undefined> = process.env): string {
12
+ return resolve(harnessHome(env), "openrouter-key");
13
+ }
14
+
15
+ export function maskSecret(value: string): string {
16
+ const key = value.trim();
17
+ if (!key) return "";
18
+ if (key.length <= 4) return "••••";
19
+ return `••••${key.slice(-4)}`;
20
+ }
21
+
22
+ export function readOpenRouterKey(env: Record<string, string | undefined> = process.env): string {
23
+ const path = openRouterKeyPath(env);
24
+ if (!existsSync(path)) return "";
25
+ try {
26
+ return readFileSync(path, "utf8").trim();
27
+ } catch {
28
+ return "";
29
+ }
30
+ }
31
+
32
+ export function writeOpenRouterKey(
33
+ value: string,
34
+ env: Record<string, string | undefined> = process.env,
35
+ ): void {
36
+ const path = openRouterKeyPath(env);
37
+ const key = value.trim();
38
+ if (!key) {
39
+ if (existsSync(path)) unlinkSync(path);
40
+ return;
41
+ }
42
+ mkdirSync(dirname(path), { recursive: true });
43
+ writeFileSync(path, `${key}\n`, { encoding: "utf8", mode: 0o600 });
44
+ try {
45
+ chmodSync(path, 0o600);
46
+ } catch {
47
+ // best-effort on filesystems that ignore mode
48
+ }
49
+ }
50
+
51
+ /** Prefer the process env. Fall back to the file in ~/.harness. */
52
+ export function applyStoredOpenRouterKey(
53
+ env: Record<string, string | undefined> = process.env,
54
+ ): string {
55
+ const fromEnv = env.OPENROUTER_API_KEY?.trim() ?? "";
56
+ if (fromEnv) return fromEnv;
57
+ const stored = readOpenRouterKey(env);
58
+ if (stored) env.OPENROUTER_API_KEY = stored;
59
+ return stored;
60
+ }
@@ -0,0 +1,43 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { type EvalSuite, runEvalSuite } from "./runner.ts";
6
+
7
+ describe("eval runner", () => {
8
+ test("runs steps, writes artifacts, records scan failures", async () => {
9
+ const cwd = await mkdtemp(join(tmpdir(), "harness-eval-"));
10
+ try {
11
+ const suite: EvalSuite = {
12
+ name: "unit",
13
+ steps: [
14
+ {
15
+ id: "echo",
16
+ system: "be brief",
17
+ user: "ping",
18
+ artifact: "echo.txt",
19
+ scan: (text) => ({ ok: text.includes("ok") }),
20
+ },
21
+ {
22
+ id: "fail",
23
+ user: "nope",
24
+ scan: () => ({ ok: false, detail: "expected fail" }),
25
+ },
26
+ ],
27
+ };
28
+ const result = await runEvalSuite({
29
+ suite,
30
+ cwd,
31
+ model: "fake",
32
+ chat: async ({ user }) => (user === "ping" ? "ok" : "no"),
33
+ });
34
+ expect(result.steps[0]?.ok).toBe(true);
35
+ expect(result.steps[1]?.ok).toBe(false);
36
+ expect(result.ok).toBe(false);
37
+ const artifact = await readFile(join(cwd, ".harness", "evals", "unit", "echo.txt"), "utf8");
38
+ expect(artifact).toBe("ok");
39
+ } finally {
40
+ await rm(cwd, { recursive: true, force: true });
41
+ }
42
+ });
43
+ });
@@ -0,0 +1,225 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { type HarnessConfig, OPENROUTER_DEFAULT_BASE_URL } from "../config.ts";
5
+ import { postDeterministicScores } from "../observability/judges.ts";
6
+ import { noopObservability } from "../observability/noop.ts";
7
+ import type { Observability } from "../observability/types.ts";
8
+ import { PRODUCT_NAME } from "../product.ts";
9
+ import { type Skill, skillBodiesForNames } from "../skills/loader.ts";
10
+
11
+ export interface EvalScanResult {
12
+ ok: boolean;
13
+ detail?: string;
14
+ }
15
+
16
+ export interface EvalContext {
17
+ cwd: string;
18
+ previous: Record<string, { text: string; parsed?: unknown }>;
19
+ }
20
+
21
+ export interface EvalStep {
22
+ id: string;
23
+ system?: string;
24
+ skills?: string[];
25
+ user: string | ((ctx: EvalContext) => string | Promise<string>);
26
+ parse?: (text: string) => unknown;
27
+ scan?: (text: string, parsed: unknown | undefined, ctx: EvalContext) => EvalScanResult;
28
+ artifact?: string;
29
+ }
30
+
31
+ export interface EvalSuite {
32
+ name: string;
33
+ steps: EvalStep[];
34
+ }
35
+
36
+ export interface EvalStepResult {
37
+ id: string;
38
+ ok: boolean;
39
+ detail?: string;
40
+ artifact?: string;
41
+ text: string;
42
+ }
43
+
44
+ export interface EvalRunResult {
45
+ name: string;
46
+ ok: boolean;
47
+ steps: EvalStepResult[];
48
+ startedAt: string;
49
+ finishedAt: string;
50
+ model: string;
51
+ }
52
+
53
+ export type ChatFn = (input: { system?: string; user: string; model: string }) => Promise<string>;
54
+
55
+ export async function discoverEvalSuite(evalsDir: string, name: string): Promise<EvalSuite> {
56
+ const dir = resolve(evalsDir, name);
57
+ for (const file of ["eval.ts", "eval.js", "run.ts"]) {
58
+ const path = join(dir, file);
59
+ try {
60
+ const mod = (await import(pathToFileURL(path).href)) as {
61
+ default?: EvalSuite;
62
+ suite?: EvalSuite;
63
+ };
64
+ const suite = mod.default ?? mod.suite;
65
+ if (suite?.steps) return { ...suite, name: suite.name || name };
66
+ } catch {
67
+ // try next
68
+ }
69
+ }
70
+ throw new Error(`No eval suite found at ${dir} (expected eval.ts)`);
71
+ }
72
+
73
+ export async function listEvalSuites(evalsDir: string): Promise<string[]> {
74
+ try {
75
+ const glob = new Bun.Glob("*/eval.ts");
76
+ const names: string[] = [];
77
+ for await (const rel of glob.scan({ cwd: evalsDir, onlyFiles: true })) {
78
+ const name = rel.split("/")[0];
79
+ if (name) names.push(name);
80
+ }
81
+ names.sort();
82
+ return names;
83
+ } catch {
84
+ return [];
85
+ }
86
+ }
87
+
88
+ export function createOpenRouterChat(options: { apiKey: string; baseUrl?: string }): ChatFn {
89
+ const baseUrl = (options.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
90
+ return async ({ system, user, model }) => {
91
+ if (!options.apiKey) throw new Error("OPENROUTER_API_KEY is not set");
92
+ const messages: Array<{ role: string; content: string }> = [];
93
+ if (system?.trim()) messages.push({ role: "system", content: system });
94
+ messages.push({ role: "user", content: user });
95
+ const res = await fetch(`${baseUrl}/chat/completions`, {
96
+ method: "POST",
97
+ headers: {
98
+ Authorization: `Bearer ${options.apiKey}`,
99
+ "Content-Type": "application/json",
100
+ "HTTP-Referer": "https://caelence.com",
101
+ "X-Title": PRODUCT_NAME,
102
+ },
103
+ body: JSON.stringify({ model, messages, temperature: 0.7 }),
104
+ });
105
+ if (!res.ok) {
106
+ const body = await res.text();
107
+ throw new Error(`OpenRouter ${res.status}: ${body.slice(0, 400)}`);
108
+ }
109
+ const json = (await res.json()) as {
110
+ choices?: Array<{ message?: { content?: string } }>;
111
+ };
112
+ return json.choices?.[0]?.message?.content ?? "";
113
+ };
114
+ }
115
+
116
+ export async function runEvalSuite(input: {
117
+ suite: EvalSuite;
118
+ cwd: string;
119
+ outDir?: string;
120
+ model: string;
121
+ skills?: Skill[];
122
+ chat: ChatFn;
123
+ observability?: Observability;
124
+ }): Promise<EvalRunResult> {
125
+ const startedAt = new Date().toISOString();
126
+ const startedMs = Date.now();
127
+ const obs = input.observability ?? noopObservability;
128
+ const outDir = input.outDir ?? join(input.cwd, ".harness", "evals", input.suite.name);
129
+ mkdirSync(outDir, { recursive: true });
130
+ const ctx: EvalContext = { cwd: input.cwd, previous: {} };
131
+ const steps: EvalStepResult[] = [];
132
+
133
+ await obs.startTurn(
134
+ {
135
+ name: "eval_run",
136
+ metadata: { suite: input.suite.name, model: input.model, requestType: "eval" },
137
+ tags: ["eval", input.suite.name],
138
+ },
139
+ async (root) => {
140
+ for (const step of input.suite.steps) {
141
+ const skillBlock =
142
+ step.skills && input.skills ? skillBodiesForNames(input.skills, step.skills) : "";
143
+ const system = [step.system, skillBlock].filter(Boolean).join("\n\n") || undefined;
144
+ const user = typeof step.user === "function" ? await step.user(ctx) : step.user;
145
+ const text = await obs.generation(
146
+ step.id,
147
+ async (gen) => {
148
+ gen.update({ model: input.model, input: { system, user } });
149
+ const out = await input.chat({ system, user, model: input.model });
150
+ gen.update({ output: out });
151
+ return out;
152
+ },
153
+ { model: input.model },
154
+ );
155
+ let parsed: unknown;
156
+ let ok = true;
157
+ let detail: string | undefined;
158
+ try {
159
+ parsed = step.parse ? step.parse(text) : undefined;
160
+ } catch (err) {
161
+ ok = false;
162
+ detail = err instanceof Error ? err.message : String(err);
163
+ }
164
+ if (ok && step.scan) {
165
+ const scan = step.scan(text, parsed, ctx);
166
+ ok = scan.ok;
167
+ detail = scan.detail;
168
+ }
169
+ if (step.artifact) {
170
+ writeFileSync(join(outDir, step.artifact), text, "utf8");
171
+ }
172
+ ctx.previous[step.id] = { text, parsed };
173
+ obs.score({ name: `step_${step.id}`, value: ok ? 1 : 0 });
174
+ steps.push({
175
+ id: step.id,
176
+ ok,
177
+ detail,
178
+ artifact: step.artifact,
179
+ text,
180
+ });
181
+ }
182
+ const resultOk = steps.every((s) => s.ok);
183
+ root.update({
184
+ output: { steps: steps.map((s) => ({ id: s.id, ok: s.ok })) },
185
+ metadata: { status: resultOk ? "success" : "failed" },
186
+ });
187
+ postDeterministicScores(obs, {
188
+ eval_ok: resultOk ? 1 : 0,
189
+ generation_duration: Date.now() - startedMs,
190
+ });
191
+ },
192
+ );
193
+ await obs.flush();
194
+
195
+ const result: EvalRunResult = {
196
+ name: input.suite.name,
197
+ ok: steps.every((s) => s.ok),
198
+ steps,
199
+ startedAt,
200
+ finishedAt: new Date().toISOString(),
201
+ model: input.model,
202
+ };
203
+ writeFileSync(join(outDir, "run-meta.json"), `${JSON.stringify(result, null, 2)}\n`, "utf8");
204
+ return result;
205
+ }
206
+
207
+ export async function runNamedEval(input: {
208
+ config: HarnessConfig;
209
+ cwd: string;
210
+ name: string;
211
+ skills?: Skill[];
212
+ chat: ChatFn;
213
+ observability?: Observability;
214
+ }): Promise<EvalRunResult> {
215
+ const evalsDir = resolve(input.cwd, input.config.evalsDir);
216
+ const suite = await discoverEvalSuite(evalsDir, input.name);
217
+ return runEvalSuite({
218
+ suite,
219
+ cwd: input.cwd,
220
+ model: input.config.model,
221
+ skills: input.skills,
222
+ chat: input.chat,
223
+ observability: input.observability,
224
+ });
225
+ }
package/src/index.ts ADDED
@@ -0,0 +1,132 @@
1
+ export {
2
+ CAELENCE_THEME,
3
+ PLAIN_THEME,
4
+ resolveTheme,
5
+ type Theme,
6
+ type ThemeName,
7
+ } from "./cli/theme.ts";
8
+ export type { ExtraMcpServerConfig, HarnessConfig } from "./config.ts";
9
+ export {
10
+ DEFAULT_CONFIG,
11
+ DEFAULT_MODEL,
12
+ loadConfig,
13
+ resolveConfigPath,
14
+ resolveOpenRouter,
15
+ } from "./config.ts";
16
+ export {
17
+ type ApprovalGate,
18
+ type ApprovalRequest,
19
+ createExecApprovalGate,
20
+ type ExecApprovalPolicy,
21
+ isLikelyDestructive,
22
+ isRiskyToolCall,
23
+ parseExecApprovalPolicy,
24
+ } from "./core/approval.ts";
25
+ export type { AgentEvent, AgentEventEmitter, MainModelProvider } from "./core/events.ts";
26
+ export { isTerminalAgentEvent } from "./core/events.ts";
27
+ export { createHookRunner, type HookConfig, type HookRunner } from "./core/hooks.ts";
28
+ export {
29
+ type InstructionLayers,
30
+ loadInstructionLayers,
31
+ userInstructionsPath,
32
+ } from "./core/instructions.ts";
33
+ export {
34
+ createMcpServer,
35
+ errorResult,
36
+ jsonResult,
37
+ type McpServer,
38
+ type McpToolDefinition,
39
+ textResult,
40
+ } from "./core/mcp.ts";
41
+ export {
42
+ type AgentMode,
43
+ filterToolsForMode,
44
+ modePrompt,
45
+ parseAgentMode,
46
+ toolsAllowedInMode,
47
+ tryParseAgentMode,
48
+ } from "./core/mode.ts";
49
+ export { buildSystemPrompt, type RunTurnDeps, runTurn, type TurnRequest } from "./core/run-turn.ts";
50
+ export {
51
+ createFileSessionStore,
52
+ createMemorySessionStore,
53
+ estimateTokens,
54
+ latestCompactionCover,
55
+ liveContextTokens,
56
+ type Session,
57
+ type SessionMessage,
58
+ type SessionStore,
59
+ sessionToProviderMessages,
60
+ sessionTranscript,
61
+ titleFromUserMessage,
62
+ } from "./core/session.ts";
63
+ export { addUsage, formatUsage, parseTokenUsage, type TokenUsage } from "./core/usage.ts";
64
+ export {
65
+ type ChatFn,
66
+ createOpenRouterChat,
67
+ discoverEvalSuite,
68
+ type EvalRunResult,
69
+ type EvalStep,
70
+ type EvalSuite,
71
+ listEvalSuites,
72
+ runEvalSuite,
73
+ runNamedEval,
74
+ } from "./evals/runner.ts";
75
+ export { initHost } from "./init.ts";
76
+ export {
77
+ createObservability,
78
+ createRecordingObservability,
79
+ DEFAULT_GATES,
80
+ FAILURE_CATEGORIES,
81
+ FEEDBACK_CATEGORIES,
82
+ getObservability,
83
+ noopObservability,
84
+ type Observability,
85
+ resolveAgentVersion,
86
+ runLocalExperiment,
87
+ sanitize,
88
+ startObservability,
89
+ WEBSITE_GENERATION_REGRESSION,
90
+ } from "./observability/index.ts";
91
+ export { PRODUCT_NAME } from "./product.ts";
92
+ export { type CreateHarnessOptions, createHarness, type HarnessRuntime } from "./runtime.ts";
93
+ export { authorSkillMarkdown, SKILL_AUTHOR_SYSTEM } from "./skills/author-skill.ts";
94
+ export { createHostSkill, parseSkillNewArgs, unwrapMarkdownFence } from "./skills/create-skill.ts";
95
+ export {
96
+ bundledSkillsDir,
97
+ CONVENTIONAL_HOST_SKILL_DIRS,
98
+ listBundledSkills,
99
+ loadMergedSkills,
100
+ loadSkills,
101
+ mergeSkills,
102
+ parseSkillMarkdown,
103
+ resolveHostSkillDirs,
104
+ type Skill,
105
+ skillCatalogPrompt,
106
+ stripFrontmatter,
107
+ } from "./skills/loader.ts";
108
+ export {
109
+ BUNDLED_PACKS,
110
+ bundledRegistryHits,
111
+ formatRegistryHits,
112
+ installBundledSkills,
113
+ installSkillFromSource,
114
+ parseBundledSkillRef,
115
+ parseSkillSource,
116
+ removeSkillFromRoots,
117
+ searchSkills,
118
+ searchSkillsSh,
119
+ } from "./skills/registry.ts";
120
+ export { parseSkillCommand, SKILL_COMMAND_USAGE } from "./skills/skill-command.ts";
121
+ export { userSkillsDir } from "./skills/user-dir.ts";
122
+ export { createGitTools } from "./tools/git.ts";
123
+ export { createLocalTools } from "./tools/local.ts";
124
+ export { PathEscapeError, resolveUnderCwd } from "./tools/paths.ts";
125
+ export { createReadSkillTool } from "./tools/read-skill.ts";
126
+ export { createTaskTool } from "./tools/subagent.ts";
127
+ export {
128
+ createMemoryTodoStore,
129
+ createTodoTool,
130
+ type TodoItem,
131
+ type TodoStore,
132
+ } from "./tools/todo.ts";