@useavalon/caelence-agent 0.2.2-canary.6 → 0.2.2

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.
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import {
3
3
  groupTranscriptLines,
4
+ liveStatusPhrases,
4
5
  type ToolLine,
5
6
  thoughtSummary,
6
7
  thoughtTools,
@@ -10,7 +11,7 @@ import {
10
11
  function tool(partial: Partial<ToolLine> & Pick<ToolLine, "key" | "label" | "status">): ToolLine {
11
12
  return {
12
13
  type: "tool",
13
- name: "notion__notion_fetch",
14
+ name: "read_file",
14
15
  callId: partial.key,
15
16
  count: 1,
16
17
  preview: "",
@@ -22,8 +23,8 @@ describe("thought fold", () => {
22
23
  test("hides consecutive tool rows behind one thought block", () => {
23
24
  const blocks = groupTranscriptLines([
24
25
  { key: "u-0", type: "user", text: "cv", userTurnIndex: 0 },
25
- tool({ key: "t1", label: "Notion fetch", status: "ok" }),
26
- tool({ key: "t2", label: "Notion search", status: "ok", name: "notion__notion_search" }),
26
+ tool({ key: "t1", label: "Reading src/a.ts", status: "ok", name: "read_file" }),
27
+ tool({ key: "t2", label: "Searching files", status: "ok", name: "grep" }),
27
28
  { key: "a-1", type: "assistant", text: "done" },
28
29
  ]);
29
30
  expect(blocks.map((block) => block.type)).toEqual(["line", "thought", "line"]);
@@ -31,14 +32,33 @@ describe("thought fold", () => {
31
32
  expect(
32
33
  thoughtSummary(blocks[1]?.type === "thought" ? thoughtTools(blocks[1].entries) : [], false)
33
34
  .headline,
34
- ).toBe("Explored 1 search");
35
+ ).toBe("Explored 1 file, 1 search");
36
+ });
37
+
38
+ test("keeps integration tools as their own window", () => {
39
+ const blocks = groupTranscriptLines([
40
+ { key: "u-0", type: "user", text: "pages", userTurnIndex: 0 },
41
+ tool({
42
+ key: "t1",
43
+ label: "Notion fetch",
44
+ status: "ok",
45
+ name: "notion__notion_fetch",
46
+ output: '{"title":"Notes"}',
47
+ }),
48
+ { key: "a-1", type: "assistant", text: "here" },
49
+ ]);
50
+ expect(blocks.map((block) => block.type)).toEqual(["line", "line", "line"]);
51
+ expect(blocks[1]).toMatchObject({
52
+ type: "line",
53
+ line: { type: "tool", name: "notion__notion_fetch" },
54
+ });
35
55
  });
36
56
 
37
57
  test("stays live between tool calls until the assistant replies", () => {
38
58
  const blocks = groupTranscriptLines([
39
59
  { key: "u-0", type: "user", text: "cv", userTurnIndex: 0 },
40
- tool({ key: "t1", label: "Notion fetch", status: "ok" }),
41
- tool({ key: "t2", label: "Notion search", status: "ok" }),
60
+ tool({ key: "t1", label: "Reading src/a.ts", status: "ok", name: "read_file" }),
61
+ tool({ key: "t2", label: "Searching files", status: "ok", name: "grep" }),
42
62
  ]);
43
63
  expect(blocks[1]?.type === "thought" && blocks[1].live).toBe(true);
44
64
  const settled = groupTranscriptLines([
@@ -50,22 +70,49 @@ describe("thought fold", () => {
50
70
  });
51
71
 
52
72
  test("warmup headlines rotate without inventing a duration", () => {
53
- expect(warmupHeadline(0)).toBe("Getting ready");
54
- expect(warmupHeadline(1)).toBe("Loading");
55
- expect(warmupHeadline(2)).toBe("Warming up");
56
- expect(warmupHeadline(3)).toBe("Getting ready");
57
- expect(thoughtSummary([], true, { warmup: true, seed: 1 }).headline).toBe("Loading");
73
+ expect(warmupHeadline(0)).toBe("Thinking");
74
+ expect(warmupHeadline(1)).toBe("Looking this over");
75
+ expect(warmupHeadline(2)).toBe("Working it out");
76
+ expect(warmupHeadline(3)).toBe("Thinking");
77
+ expect(thoughtSummary([], true, { warmup: true, seed: 1 }).headline).toBe("Thinking");
78
+ expect(liveStatusPhrases([], true)).toEqual([
79
+ "Thinking",
80
+ "Looking this over",
81
+ "Working it out",
82
+ ]);
58
83
  });
59
84
 
60
- test("live thought keeps Thinking and names the in-flight tool", () => {
85
+ test("live phrases follow the in-flight tool then thinking", () => {
61
86
  const tools = [
62
- tool({ key: "t1", label: "Notion search", status: "ok", name: "notion__notion_search" }),
63
- tool({ key: "t2", label: "Notion fetch", status: "running" }),
87
+ tool({ key: "t1", label: "Searching files", status: "ok", name: "grep" }),
88
+ tool({ key: "t2", label: "Reading src/a.ts", status: "running", name: "read_file" }),
64
89
  ];
65
- expect(thoughtSummary(tools, true)).toEqual({
66
- headline: "Thinking",
67
- activity: "Notion fetch",
68
- });
90
+ expect(liveStatusPhrases(tools)[0]).toBe("Reading src/a.ts");
91
+ expect(liveStatusPhrases(tools)).toContain("Thinking");
92
+ expect(thoughtSummary(tools, true)).toEqual({ headline: "Reading src/a.ts" });
93
+ });
94
+
95
+ test("skill reads use a pipeline headline instead of thinking", () => {
96
+ const tools = [
97
+ tool({
98
+ key: "t1",
99
+ label: "Reading Copywriting",
100
+ status: "ok",
101
+ name: "read_skill",
102
+ preview: '{"name":"copywriting"}',
103
+ }),
104
+ tool({
105
+ key: "t2",
106
+ label: "Reading RMBC",
107
+ status: "running",
108
+ name: "read_skill",
109
+ preview: '{"name":"copy-rmbc"}',
110
+ }),
111
+ ];
112
+ expect(liveStatusPhrases(tools)[0]).toBe("Running RMBC");
113
+ expect(liveStatusPhrases(tools)).toContain("Running Copywriting");
114
+ expect(liveStatusPhrases(tools)).not.toContain("Thinking");
115
+ expect(thoughtSummary(tools, false).headline).toBe("Ran Copywriting");
69
116
  });
70
117
 
71
118
  test("done headlines follow thought, explored, or worked", () => {
@@ -1,3 +1,5 @@
1
+ import { pipelineProgress } from "./pipeline";
2
+ import { isPlatformTool } from "./platform";
1
3
  import type { StreamLine } from "./stream";
2
4
  import { eventCountSuffix } from "./tool-label";
3
5
 
@@ -10,7 +12,8 @@ export type TranscriptBlock =
10
12
  | { type: "thought"; entries: FoldEntry[]; live: boolean };
11
13
 
12
14
  function isFoldLine(line: StreamLine): line is ToolLine | Extract<StreamLine, { type: "thought" }> {
13
- return line.type === "tool" || line.type === "thought";
15
+ if (line.type === "thought") return true;
16
+ return line.type === "tool" && !isPlatformTool(line.name);
14
17
  }
15
18
 
16
19
  export function thoughtTools(entries: FoldEntry[]): ToolLine[] {
@@ -46,14 +49,46 @@ export function groupTranscriptLines(lines: StreamLine[]): TranscriptBlock[] {
46
49
 
47
50
  const WRITE_LABEL = /^(?:Writing|Editing)\b/u;
48
51
  const WRITE_NAME = /write_file|edit_file|str_replace|apply_patch|shell|bash|git_commit/i;
49
- const WARMUP_HEADLINES = ["Getting ready", "Loading", "Warming up"] as const;
52
+ export const WARMUP_PHRASES = ["Thinking", "Looking this over", "Working it out"] as const;
50
53
 
51
54
  function isWriteTool(tool: ToolLine): boolean {
52
55
  return WRITE_LABEL.test(tool.label) || WRITE_NAME.test(tool.name);
53
56
  }
54
57
 
58
+ function pushPhrase(out: string[], value: string): void {
59
+ const text = value.trim();
60
+ if (!text) return;
61
+ if (out.some((item) => item.toLowerCase() === text.toLowerCase())) return;
62
+ out.push(text);
63
+ }
64
+
55
65
  export function warmupHeadline(seed: number): string {
56
- return WARMUP_HEADLINES[Math.abs(seed) % WARMUP_HEADLINES.length] ?? "Getting ready";
66
+ return WARMUP_PHRASES[Math.abs(seed) % WARMUP_PHRASES.length] ?? "Thinking";
67
+ }
68
+
69
+ export function liveStatusPhrases(tools: ToolLine[], warmup = false): string[] {
70
+ if (warmup || tools.length === 0) return [...WARMUP_PHRASES];
71
+ const pipe = pipelineProgress(tools);
72
+ const out: string[] = [];
73
+ if (pipe) {
74
+ pushPhrase(out, pipe.title);
75
+ pushPhrase(out, `Running ${pipe.family}`);
76
+ return out;
77
+ }
78
+ const running = [...tools].reverse().find((tool) => tool.status === "running");
79
+ const current = running ?? [...tools].reverse().find((tool) => tool.label.trim());
80
+ if (current) {
81
+ pushPhrase(out, `${current.label}${eventCountSuffix(current.count)}`);
82
+ if (/^Reading\b/u.test(current.label) || current.name === "read_file")
83
+ pushPhrase(out, "Reading");
84
+ if (/search|grep|glob/i.test(current.name) || /^Searching\b/u.test(current.label)) {
85
+ pushPhrase(out, "Searching");
86
+ }
87
+ if (isWriteTool(current)) pushPhrase(out, "Editing");
88
+ }
89
+ pushPhrase(out, "Thinking");
90
+ pushPhrase(out, "Looking this over");
91
+ return out;
57
92
  }
58
93
 
59
94
  export function thoughtSummary(
@@ -61,16 +96,11 @@ export function thoughtSummary(
61
96
  live: boolean,
62
97
  options?: { warmup?: boolean; seed?: number },
63
98
  ): { headline: string; activity?: string } {
64
- if (live && options?.warmup) {
65
- return { headline: warmupHeadline(options.seed ?? 0) };
66
- }
67
99
  if (live) {
68
- const running = [...tools].reverse().find((tool) => tool.status === "running");
69
- return {
70
- headline: "Thinking",
71
- ...(running ? { activity: `${running.label}${eventCountSuffix(running.count)}` } : {}),
72
- };
100
+ return { headline: liveStatusPhrases(tools, options?.warmup).at(0) ?? "Thinking" };
73
101
  }
102
+ const pipe = pipelineProgress(tools);
103
+ if (pipe && !tools.some(isWriteTool)) return { headline: `Ran ${pipe.family}` };
74
104
  if (tools.some(isWriteTool)) return { headline: "Worked" };
75
105
  if (tools.length === 0) return { headline: "Thought" };
76
106
  const files = new Set<string>();
@@ -14,4 +14,16 @@ describe("tool labels", () => {
14
14
  expect(toolLabel("exec", { command: "bun test" })).toBe("Running: bun test");
15
15
  expect(toolLabel("web_search")).toBe("Searching the web");
16
16
  });
17
+
18
+ test("uses an active phrase for a lone tool name", () => {
19
+ expect(toolLabel("task")).toBe("Handling task");
20
+ expect(toolLabel("mystery")).toBe("Using mystery");
21
+ });
22
+
23
+ test("names the skill on read_skill and task", () => {
24
+ expect(toolLabel("read_skill", { name: "copy-harry-dry" })).toBe("Reading Harry Dry");
25
+ expect(toolLabel("task", { label: "copy-edit", skills: ["copy-editor"] })).toBe(
26
+ "Handling copy-edit",
27
+ );
28
+ });
17
29
  });
@@ -12,10 +12,26 @@ const TOOL_LABELS: Record<string, string> = {
12
12
  todo_write: "Updating todos",
13
13
  grep: "Searching files",
14
14
  glob: "Finding files",
15
+ task: "Handling task",
16
+ read_skill: "Reading skill",
17
+ git_status: "Checking git",
18
+ git_diff: "Reading diff",
19
+ git_log: "Reading log",
20
+ git_commit: "Committing",
15
21
  };
16
22
 
17
23
  const EVENT_COUNT_RE = /\s×(\d+)$/u;
18
24
 
25
+ function prettySkillLabel(raw: string): string {
26
+ const id = raw.trim().split("/").pop()?.split("@").pop() ?? raw;
27
+ if (id === "copy-rmbc") return "RMBC";
28
+ if (id === "copy-harry-dry") return "Harry Dry";
29
+ if (id === "copy-editor") return "Copy editor";
30
+ if (id === "copywriting") return "Copywriting";
31
+ const spaced = id.replace(/[-_]+/g, " ").trim();
32
+ return spaced ? spaced.charAt(0).toUpperCase() + spaced.slice(1) : raw.trim();
33
+ }
34
+
19
35
  export function prettifyToolName(name: string): string {
20
36
  const local = name.includes("__") ? (name.split("__").at(-1) ?? name) : name;
21
37
  const stripped = local.replace(/^[a-z0-9]+_/i, (prefix) => {
@@ -33,6 +49,17 @@ export function toolLabel(toolName: string, input: Record<string, unknown> = {})
33
49
  if (toolName === "edit_file" && path) return `Editing ${path}`;
34
50
  if (toolName === "read_file" && path) return `Reading ${path}`;
35
51
  if (toolName === "exec" && command) return `Running: ${command}`;
52
+ if (toolName === "read_skill") {
53
+ const skill = typeof input.name === "string" ? input.name.trim() : "";
54
+ return skill ? `Reading ${prettySkillLabel(skill)}` : "Reading skill";
55
+ }
56
+ if (toolName === "task") {
57
+ const label = typeof input.label === "string" ? input.label.trim() : "";
58
+ if (label) return `Handling ${label}`;
59
+ const skills = Array.isArray(input.skills) ? input.skills : [];
60
+ const skill = typeof skills[0] === "string" ? skills[0].trim() : "";
61
+ return skill ? `Handling ${prettySkillLabel(skill)}` : "Handling task";
62
+ }
36
63
  const known = TOOL_LABELS[toolName];
37
64
  if (known) return known;
38
65
  const pretty = prettifyToolName(toolName);
@@ -42,6 +69,7 @@ export function toolLabel(toolName: string, input: Record<string, unknown> = {})
42
69
  const hostLabel = host.charAt(0).toUpperCase() + host.slice(1);
43
70
  return `${hostLabel} ${pretty.toLowerCase()}`;
44
71
  }
72
+ if (!/\s/.test(pretty) && !/ing$/i.test(pretty)) return `Using ${pretty.toLowerCase()}`;
45
73
  return pretty;
46
74
  }
47
75
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useavalon/caelence-agent",
3
- "version": "0.2.2-canary.6",
3
+ "version": "0.2.2",
4
4
  "description": "Caelence agent: Strands turn loop, local tools, skills, evals, and a themable terminal UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -39,7 +39,7 @@
39
39
  ],
40
40
  "scripts": {
41
41
  "start": "bun bin/harness.ts",
42
- "test": "bun test src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts desktop/src/queue.test.ts desktop/src/composer-files.test.ts",
42
+ "test": "bun test src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts desktop/src/queue.test.ts desktop/src/composer-files.test.ts desktop/src/tool-label.test.ts desktop/src/reply-sources.test.ts desktop/src/pipeline.test.ts desktop/src/preview-render.test.ts",
43
43
  "typecheck": "bunx tsc --noEmit -p tsconfig.json",
44
44
  "lint": "biome ci .",
45
45
  "format": "biome format --write .",
@@ -12,6 +12,7 @@ export type AgentEvent =
12
12
  callId: string;
13
13
  success: boolean;
14
14
  result?: unknown;
15
+ output?: string;
15
16
  error?: string;
16
17
  }
17
18
  | { kind: "approval_request"; callId: string; toolName: string; input: Record<string, unknown> }
@@ -140,6 +140,7 @@ export async function runTurn(
140
140
  status: event.success ? "ok" : "fail",
141
141
  preview: started?.preview ?? "",
142
142
  ...(event.error ? { error: event.error } : {}),
143
+ ...(event.output ? { output: event.output } : {}),
143
144
  });
144
145
  }
145
146
  emit(event);
@@ -411,6 +412,7 @@ async function invokeGuardedBody(
411
412
  callId,
412
413
  success,
413
414
  ...(success ? { result: finalResult.structuredContent } : {}),
415
+ ...(success ? { output: clipToolOutput(toolResultText(finalResult)) } : {}),
414
416
  ...(errorText !== undefined ? { error: errorText } : {}),
415
417
  });
416
418
  return finalResult;
@@ -426,6 +428,11 @@ function previewToolInput(input: Record<string, unknown>): string {
426
428
  return raw.length > 80 ? `${raw.slice(0, 79)}…` : raw;
427
429
  }
428
430
 
431
+ function clipToolOutput(text: string): string {
432
+ const max = 8000;
433
+ return text.length <= max ? text : `${text.slice(0, max)}\n…`;
434
+ }
435
+
429
436
  export function buildSystemPrompt(input: {
430
437
  name: string;
431
438
  cwd: string;
@@ -17,6 +17,7 @@ export type SessionMessage =
17
17
  status: "ok" | "fail";
18
18
  preview: string;
19
19
  error?: string;
20
+ output?: string;
20
21
  }
21
22
  | {
22
23
  kind: "compaction_checkpoint";
@@ -36,6 +37,7 @@ export type ChatTranscriptLine =
36
37
  status: "ok" | "fail";
37
38
  preview: string;
38
39
  error?: string;
40
+ output?: string;
39
41
  };
40
42
 
41
43
  export interface Session {
@@ -126,6 +128,7 @@ export function sessionTranscript(session: Session): ChatTranscriptLine[] {
126
128
  status: message.status,
127
129
  preview: message.preview,
128
130
  ...(message.error ? { error: message.error } : {}),
131
+ ...(message.output ? { output: message.output } : {}),
129
132
  });
130
133
  }
131
134
  }
@@ -269,6 +269,57 @@ describe("desktop bridge", () => {
269
269
  }
270
270
  });
271
271
 
272
+ test("previews a project file and rejects escape", async () => {
273
+ const ctx = await withBridge();
274
+ try {
275
+ await writeFile(join(ctx.cwd, "note.txt"), "preview me");
276
+ const ok = await fetch(`${ctx.ready.url}/file-preview?path=note.txt`, {
277
+ headers: ctx.headers,
278
+ });
279
+ expect(ok.ok).toBe(true);
280
+ const body = (await ok.json()) as { text?: string; path?: string; kind?: string };
281
+ expect(body.path).toBe("note.txt");
282
+ expect(body.text).toBe("preview me");
283
+ expect(body.kind).toBe("text");
284
+ const blocked = await fetch(`${ctx.ready.url}/file-preview?path=../secret`, {
285
+ headers: ctx.headers,
286
+ });
287
+ expect(blocked.status).toBe(400);
288
+ } finally {
289
+ await ctx.close();
290
+ }
291
+ });
292
+
293
+ test("previews images as bytes and rejects escape", async () => {
294
+ const ctx = await withBridge();
295
+ try {
296
+ const png = Buffer.from(
297
+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082",
298
+ "hex",
299
+ );
300
+ await writeFile(join(ctx.cwd, "dot.png"), png);
301
+ const meta = await fetch(`${ctx.ready.url}/file-preview?path=dot.png`, {
302
+ headers: ctx.headers,
303
+ });
304
+ expect(meta.ok).toBe(true);
305
+ const body = (await meta.json()) as { kind?: string; mime?: string };
306
+ expect(body.kind).toBe("image");
307
+ expect(body.mime).toBe("image/png");
308
+ const bytes = await fetch(`${ctx.ready.url}/file-bytes?path=dot.png`, {
309
+ headers: ctx.headers,
310
+ });
311
+ expect(bytes.ok).toBe(true);
312
+ expect(bytes.headers.get("content-type")).toBe("image/png");
313
+ expect(Buffer.from(await bytes.arrayBuffer()).equals(png)).toBe(true);
314
+ const blocked = await fetch(`${ctx.ready.url}/file-bytes?path=../secret.png`, {
315
+ headers: ctx.headers,
316
+ });
317
+ expect(blocked.status).toBe(400);
318
+ } finally {
319
+ await ctx.close();
320
+ }
321
+ });
322
+
272
323
  test("rejects a missing local path", async () => {
273
324
  const ctx = await withBridge();
274
325
  try {
@@ -1,4 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve } from "node:path";
2
4
  import { mediaModelLabel } from "../cli/media-models.ts";
3
5
  import { HARNESS_MODELS, modelPickerItems } from "../cli/models.ts";
4
6
  import {
@@ -49,8 +51,10 @@ import {
49
51
  searchSkillCatalog,
50
52
  skillNameFromCatalogId,
51
53
  } from "../skills/registry.ts";
54
+ import { resolveUnderCwd, toProjectRel } from "../tools/paths.ts";
52
55
  import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
53
56
  import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
57
+ import { filePreviewKind, filePreviewMime } from "./preview-kind.ts";
54
58
  import { applyStoredOpenRouterKey, maskSecret, writeOpenRouterKey } from "./secrets.ts";
55
59
  import { composeUploadMessage, listUploads, parseIncomingUploads, saveUploads } from "./uploads.ts";
56
60
 
@@ -98,6 +102,23 @@ const CORS_HEADERS = {
98
102
  "access-control-allow-methods": "GET, POST, OPTIONS",
99
103
  };
100
104
 
105
+ function resolvePreviewPath(cwd: string, raw: string): string | undefined {
106
+ const trimmed = raw.trim();
107
+ if (!trimmed) return undefined;
108
+ try {
109
+ const abs =
110
+ !isAbsolute(trimmed) && !trimmed.startsWith("~") && !trimmed.startsWith("file://")
111
+ ? resolveUnderCwd(cwd, trimmed)
112
+ : resolveLocalPath(trimmed, cwd);
113
+ if (!abs) return undefined;
114
+ const rel = relative(resolve(cwd), abs);
115
+ if (rel.startsWith("..") || isAbsolute(rel)) return undefined;
116
+ return abs;
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ }
121
+
101
122
  function modelLabel(id: string): string {
102
123
  return HARNESS_MODELS.find((model) => model.id === id)?.label ?? id;
103
124
  }
@@ -515,6 +536,58 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
515
536
  }
516
537
  };
517
538
 
539
+ const route_get_file_preview = async (_req: Request, url: URL): Promise<Response> => {
540
+ const abs = resolvePreviewPath(options.cwd, url.searchParams.get("path") ?? "");
541
+ if (!abs) return json({ error: "File is missing." }, 400);
542
+ try {
543
+ const info = await stat(abs);
544
+ if (!info.isFile()) return json({ error: "Not a file." }, 400);
545
+ const path = toProjectRel(options.cwd, abs);
546
+ const kind = filePreviewKind(abs);
547
+ if (kind === "image") {
548
+ return json({
549
+ path,
550
+ kind,
551
+ mime: filePreviewMime(abs) ?? "application/octet-stream",
552
+ });
553
+ }
554
+ const buf = await readFile(abs);
555
+ if (buf.includes(0)) return json({ error: "Not a text file." }, 400);
556
+ const text = buf.toString("utf8");
557
+ const max = 200_000;
558
+ const truncated = text.length > max;
559
+ return json({
560
+ path,
561
+ kind,
562
+ text: truncated ? `${text.slice(0, max)}\n…` : text,
563
+ truncated,
564
+ });
565
+ } catch (err) {
566
+ return json({ error: errorMessage(err) || "Could not read the file." }, 400);
567
+ }
568
+ };
569
+
570
+ const route_get_file_bytes = async (_req: Request, url: URL): Promise<Response> => {
571
+ const abs = resolvePreviewPath(options.cwd, url.searchParams.get("path") ?? "");
572
+ if (!abs) return json({ error: "File is missing." }, 400);
573
+ if (filePreviewKind(abs) !== "image") return json({ error: "Not an image." }, 400);
574
+ try {
575
+ const info = await stat(abs);
576
+ if (!info.isFile()) return json({ error: "Not a file." }, 400);
577
+ if (info.size > 8_000_000) return json({ error: "Image is too large." }, 400);
578
+ const buf = await readFile(abs);
579
+ return new Response(buf, {
580
+ headers: {
581
+ "content-type": filePreviewMime(abs) ?? "application/octet-stream",
582
+ "cache-control": "private, max-age=60",
583
+ ...CORS_HEADERS,
584
+ },
585
+ });
586
+ } catch (err) {
587
+ return json({ error: errorMessage(err) || "Could not read the file." }, 400);
588
+ }
589
+ };
590
+
518
591
  const route_post_embed = async (req: Request, _url: URL): Promise<Response> => {
519
592
  const body = await readJson(req);
520
593
  const href = publicHttpHref(typeof body.url === "string" ? body.url : "");
@@ -844,6 +917,8 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
844
917
  "POST /skills/remove": route_post_skills_remove,
845
918
  "POST /open": route_post_open,
846
919
  "POST /open-path": route_post_open_path,
920
+ "GET /file-preview": route_get_file_preview,
921
+ "GET /file-bytes": route_get_file_bytes,
847
922
  "POST /embed": route_post_embed,
848
923
  "GET /embed": route_get_embed,
849
924
  "POST /transcribe": route_post_transcribe,
@@ -0,0 +1,20 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { fileExt, filePreviewKind, filePreviewMime } from "./preview-kind.ts";
3
+
4
+ describe("file preview kind", () => {
5
+ test("classifies markdown, html, images, and text", () => {
6
+ expect(filePreviewKind("README.md")).toBe("markdown");
7
+ expect(filePreviewKind("docs/note.markdown")).toBe("markdown");
8
+ expect(filePreviewKind("page.html")).toBe("html");
9
+ expect(filePreviewKind("brand/logo.png")).toBe("image");
10
+ expect(filePreviewKind("shot.JPEG")).toBe("image");
11
+ expect(filePreviewKind("mark.svg")).toBe("image");
12
+ expect(filePreviewKind("src/app.ts")).toBe("text");
13
+ });
14
+
15
+ test("maps image mime types", () => {
16
+ expect(fileExt("a.b.PNG")).toBe("png");
17
+ expect(filePreviewMime("wordmark.png")).toBe("image/png");
18
+ expect(filePreviewMime("note.md")).toBeUndefined();
19
+ });
20
+ });
@@ -0,0 +1,29 @@
1
+ export type FilePreviewKind = "markdown" | "html" | "image" | "text";
2
+
3
+ const IMAGE_MIME: Record<string, string> = {
4
+ png: "image/png",
5
+ jpg: "image/jpeg",
6
+ jpeg: "image/jpeg",
7
+ gif: "image/gif",
8
+ webp: "image/webp",
9
+ svg: "image/svg+xml",
10
+ };
11
+
12
+ export function fileExt(path: string): string {
13
+ const base = path.replaceAll("\\", "/").split("/").pop() ?? path;
14
+ const dot = base.lastIndexOf(".");
15
+ if (dot <= 0) return "";
16
+ return base.slice(dot + 1).toLowerCase();
17
+ }
18
+
19
+ export function filePreviewKind(path: string): FilePreviewKind {
20
+ const ext = fileExt(path);
21
+ if (ext === "md" || ext === "markdown") return "markdown";
22
+ if (ext === "html" || ext === "htm") return "html";
23
+ if (ext in IMAGE_MIME) return "image";
24
+ return "text";
25
+ }
26
+
27
+ export function filePreviewMime(path: string): string | undefined {
28
+ return IMAGE_MIME[fileExt(path)];
29
+ }