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

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.
@@ -20,6 +20,13 @@ export function isFileWriteTool(toolName: string): boolean {
20
20
  return toolName === "edit_file" || toolName === "write_file";
21
21
  }
22
22
 
23
+ export function isUploadEditRequest(req: ApprovalRequest): boolean {
24
+ return (
25
+ isFileWriteTool(req.toolName) &&
26
+ typeof req.input.originalPath === "string" &&
27
+ req.input.originalPath.trim().length > 0
28
+ );
29
+ }
23
30
  /** Host-side denylist — local exec is the machine, not a sandbox. */
24
31
  export const DESTRUCTIVE_COMMAND_PATTERNS: readonly RegExp[] = [
25
32
  /\bsudo\b/,
@@ -57,6 +64,9 @@ export interface ExecApprovalGateDeps {
57
64
  /** Optional event sink so the TUI can show the permission card. */
58
65
  emit?: AgentEventEmitter;
59
66
  alwaysAllow?: Set<string>;
67
+ resolveUploadEdit?: (
68
+ path: string,
69
+ ) => { rel: string; sourcePath: string; name: string } | undefined;
60
70
  }
61
71
 
62
72
  async function promptAsk(deps: ExecApprovalGateDeps, req: ApprovalRequest): Promise<boolean> {
@@ -74,6 +84,16 @@ export function createExecApprovalGate(deps: ExecApprovalGateDeps): ApprovalGate
74
84
  const always = deps.alwaysAllow ?? new Set<string>();
75
85
  return {
76
86
  async request(req) {
87
+ if (isFileWriteTool(req.toolName) && deps.resolveUploadEdit) {
88
+ const path = typeof req.input.path === "string" ? req.input.path : "";
89
+ const hit = deps.resolveUploadEdit(path);
90
+ if (hit) {
91
+ req.input.copyPath = hit.rel;
92
+ req.input.originalPath = hit.sourcePath;
93
+ req.input.fileName = hit.name;
94
+ return promptAsk(deps, req);
95
+ }
96
+ }
77
97
  if (isFileWriteTool(req.toolName)) {
78
98
  if (always.has("write_file") || always.has("edit_file") || always.has(req.toolName)) {
79
99
  return true;
@@ -1,7 +1,11 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { mediaModelLabel } from "../cli/media-models.ts";
3
3
  import { HARNESS_MODELS, modelPickerItems } from "../cli/models.ts";
4
- import { cachedLiveTargetNames, loadLiveTargetNames } from "../cli/openrouter-live.ts";
4
+ import {
5
+ cachedLiveTargetNames,
6
+ loadLiveTargetNames,
7
+ prettyLiveModelName,
8
+ } from "../cli/openrouter-live.ts";
5
9
  import { cachedModalityModels } from "../cli/openrouter-modality.ts";
6
10
  import { sessionPickerItems } from "../cli/picker.ts";
7
11
  import { isHelpAlias } from "../cli/slash.ts";
@@ -48,7 +52,7 @@ import {
48
52
  import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
49
53
  import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
50
54
  import { applyStoredOpenRouterKey, maskSecret, writeOpenRouterKey } from "./secrets.ts";
51
- import { composeUploadMessage, parseIncomingUploads, saveUploads } from "./uploads.ts";
55
+ import { composeUploadMessage, listUploads, parseIncomingUploads, saveUploads } from "./uploads.ts";
52
56
 
53
57
  export interface DesktopState {
54
58
  name: string;
@@ -69,6 +73,7 @@ export interface DesktopState {
69
73
  skills: Array<{ name: string; source: string }>;
70
74
  busy: boolean;
71
75
  hasApiKey: boolean;
76
+ uploads?: Array<{ name: string; rel: string; sourcePath?: string }>;
72
77
  }
73
78
 
74
79
  export interface BridgeReady {
@@ -229,17 +234,16 @@ async function readJson(req: Request): Promise<Record<string, unknown>> {
229
234
 
230
235
  function snapshot(harness: HarnessRuntime, busy: boolean, title: string): DesktopState {
231
236
  const live = cachedLiveTargetNames();
232
- const target = live.get(harness.modelId);
237
+ const target = prettyLiveModelName(live.get(harness.modelId) ?? "").trim();
233
238
  const prefs = readMediaPrefs();
239
+ const label = modelLabel(harness.modelId);
234
240
  return {
235
241
  name: harness.config.name,
236
242
  cwd: harness.cwd,
237
243
  mode: harness.mode,
238
244
  modelId: harness.modelId,
239
- modelLabel: modelLabel(harness.modelId),
240
- ...(target && target.toLowerCase() !== modelLabel(harness.modelId).toLowerCase()
241
- ? { modelTarget: target }
242
- : {}),
245
+ modelLabel: label,
246
+ ...(target && target.toLowerCase() !== label.toLowerCase() ? { modelTarget: target } : {}),
243
247
  imageModelId: prefs.imageModel,
244
248
  imageModelLabel: mediaModelLabel(cachedModalityModels("image"), prefs.imageModel),
245
249
  videoModelId: prefs.videoModel,
@@ -255,6 +259,11 @@ function snapshot(harness: HarnessRuntime, busy: boolean, title: string): Deskto
255
259
  skills: harness.skills.map((skill) => ({ name: skill.name, source: skill.source })),
256
260
  busy,
257
261
  hasApiKey: harness.hasApiKey,
262
+ uploads: listUploads(harness.cwd).map((item) => ({
263
+ name: item.name,
264
+ rel: item.rel,
265
+ ...(item.sourcePath ? { sourcePath: item.sourcePath } : {}),
266
+ })),
258
267
  };
259
268
  }
260
269
 
@@ -278,7 +287,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
278
287
  let title = "New chat";
279
288
  let busy = false;
280
289
  let abort: AbortController | undefined;
281
- const pending = new Map<string, (ok: boolean) => void>();
290
+ const pending = new Map<string, (decision: string) => void>();
282
291
  const oauthWaiters = new Map<string, (result: OAuthCallback) => void>();
283
292
 
284
293
  const refreshLiveNames = (): void => {
@@ -692,13 +701,13 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
692
701
  if (decision === "always")
693
702
  harness.allowRiskyAlways(typeof body.toolName === "string" ? body.toolName : "exec");
694
703
  pending.delete(callId);
695
- resolve(decision === "yes" || decision === "always");
704
+ resolve(typeof decision === "string" ? decision : "no");
696
705
  return json({ ok: true });
697
706
  };
698
707
 
699
708
  const route_post_abort = async (_req: Request, _url: URL): Promise<Response> => {
700
709
  abort?.abort();
701
- for (const resolve of pending.values()) resolve(false);
710
+ for (const resolve of pending.values()) resolve("no");
702
711
  pending.clear();
703
712
  return json({ ok: true });
704
713
  };
@@ -767,7 +776,21 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
767
776
  signal: abort?.signal,
768
777
  approvalAsk: (req: ApprovalRequest) =>
769
778
  new Promise<boolean>((resolve) => {
770
- pending.set(req.callId, resolve);
779
+ pending.set(req.callId, (decision) => {
780
+ if (
781
+ decision === "original" &&
782
+ typeof req.input.originalPath === "string" &&
783
+ req.input.originalPath.trim()
784
+ ) {
785
+ req.input.path = req.input.originalPath;
786
+ }
787
+ resolve(
788
+ decision === "yes" ||
789
+ decision === "always" ||
790
+ decision === "copy" ||
791
+ decision === "original",
792
+ );
793
+ });
771
794
  }),
772
795
  ...(editUserTurn !== undefined ? { editUserTurn } : {}),
773
796
  })
@@ -872,7 +895,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
872
895
  ready,
873
896
  stop: async () => {
874
897
  abort?.abort();
875
- for (const resolve of pending.values()) resolve(false);
898
+ for (const resolve of pending.values()) resolve("no");
876
899
  pending.clear();
877
900
  for (const resolve of oauthWaiters.values()) resolve({ error: "cancelled" });
878
901
  oauthWaiters.clear();
@@ -0,0 +1,53 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { composeUploadMessage, joinUploadDisplay, parseUploadDisplay } from "./upload-message.ts";
3
+
4
+ describe("upload message display", () => {
5
+ test("strips an excerpted text file from the visible prompt", () => {
6
+ const composed = composeUploadMessage("can you add a title to this doc", [
7
+ {
8
+ name: "zeugg-design-handover.md",
9
+ rel: ".harness/uploads/1-0-zeugg-design-handover.md",
10
+ mime: "text/markdown",
11
+ excerpt: "# Zeugg Design System\n\nDark, technical, precise.",
12
+ original: "~/Downloads/zeugg-design-handover.md",
13
+ },
14
+ ]);
15
+ expect(composed).toContain("# Zeugg Design System");
16
+ const shown = parseUploadDisplay(composed);
17
+ expect(shown.prompt).toBe("can you add a title to this doc");
18
+ expect(shown.attachments).toEqual([
19
+ {
20
+ name: "zeugg-design-handover.md",
21
+ rel: ".harness/uploads/1-0-zeugg-design-handover.md",
22
+ },
23
+ ]);
24
+ expect(shown.suffix).toContain("Attached `");
25
+ expect(joinUploadDisplay("add a title", shown.suffix)).toContain("add a title");
26
+ expect(joinUploadDisplay("add a title", shown.suffix)).toContain("# Zeugg Design System");
27
+ });
28
+
29
+ test("keeps a plain prompt unchanged", () => {
30
+ expect(parseUploadDisplay("just a question")).toEqual({
31
+ prompt: "just a question",
32
+ attachments: [],
33
+ suffix: "",
34
+ });
35
+ });
36
+
37
+ test("parses a binary attachment without an excerpt", () => {
38
+ const composed = composeUploadMessage("", [
39
+ {
40
+ name: "shot.png",
41
+ rel: ".harness/uploads/2-0-shot.png",
42
+ mime: "image/png",
43
+ },
44
+ ]);
45
+ expect(parseUploadDisplay(composed).attachments).toEqual([
46
+ {
47
+ name: "shot.png",
48
+ rel: ".harness/uploads/2-0-shot.png",
49
+ mime: "image/png",
50
+ },
51
+ ]);
52
+ });
53
+ });
@@ -0,0 +1,74 @@
1
+ export interface UploadMessageFile {
2
+ name: string;
3
+ rel: string;
4
+ mime: string;
5
+ excerpt?: string;
6
+ original?: string;
7
+ }
8
+
9
+ export interface ParsedUploadAttachment {
10
+ name: string;
11
+ rel: string;
12
+ mime?: string;
13
+ }
14
+
15
+ const ATTACHED_MARK = /^Attached `(\.harness\/uploads\/[^`]+)` /m;
16
+ const ATTACHED_BLOCK =
17
+ /^Attached `(\.harness\/uploads\/[^`]+)` \(([^)]+)\)\.(?: Original: `([^`]+)`\.)?(?: Use that project path\.)?(?:\n\n```\n[\s\S]*?\n```)?/;
18
+
19
+ export function composeUploadMessage(text: string, files: UploadMessageFile[]): string {
20
+ if (files.length === 0) return text;
21
+ const blocks = files.map((file) => {
22
+ const original = file.original ? ` Original: \`${file.original}\`.` : "";
23
+ if (file.excerpt !== undefined) {
24
+ return `Attached \`${file.rel}\` (${file.name}).${original}\n\n\`\`\`\n${file.excerpt}\n\`\`\``;
25
+ }
26
+ return `Attached \`${file.rel}\` (${file.name}, ${file.mime}).${original} Use that project path.`;
27
+ });
28
+ const body = text.trim();
29
+ return body ? `${body}\n\n${blocks.join("\n\n")}` : blocks.join("\n\n");
30
+ }
31
+
32
+ export function parseUploadDisplay(text: string): {
33
+ prompt: string;
34
+ attachments: ParsedUploadAttachment[];
35
+ suffix: string;
36
+ } {
37
+ const match = ATTACHED_MARK.exec(text);
38
+ if (!match || match.index === undefined) {
39
+ return { prompt: text, attachments: [], suffix: "" };
40
+ }
41
+ const prompt = text.slice(0, match.index).trim();
42
+ const suffix = text.slice(match.index).trim();
43
+ return { prompt, attachments: parseAttachedBlocks(suffix), suffix };
44
+ }
45
+
46
+ export function joinUploadDisplay(prompt: string, suffix?: string): string {
47
+ const body = prompt.trim();
48
+ const extra = suffix?.trim() ?? "";
49
+ if (!extra) return body;
50
+ return body ? `${body}\n\n${extra}` : extra;
51
+ }
52
+
53
+ function parseAttachedBlocks(suffix: string): ParsedUploadAttachment[] {
54
+ const attachments: ParsedUploadAttachment[] = [];
55
+ let rest = suffix.trim();
56
+ while (rest) {
57
+ const match = ATTACHED_BLOCK.exec(rest);
58
+ if (match == null) break;
59
+ if (match.index !== 0) break;
60
+ const rel = match[1] ?? "";
61
+ const paren = match[2] ?? "";
62
+ attachments.push({ rel, ...splitNameMime(paren) });
63
+ rest = rest.slice(match[0].length).trimStart();
64
+ }
65
+ return attachments;
66
+ }
67
+
68
+ function splitNameMime(paren: string): { name: string; mime?: string } {
69
+ const cut = paren.lastIndexOf(", ");
70
+ if (cut > 0 && paren.slice(cut + 2).includes("/")) {
71
+ return { name: paren.slice(0, cut), mime: paren.slice(cut + 2) };
72
+ }
73
+ return { name: paren };
74
+ }
@@ -5,6 +5,8 @@ import { join } from "node:path";
5
5
  import {
6
6
  composeUploadMessage,
7
7
  isTextUpload,
8
+ listUploads,
9
+ matchUploadEdit,
8
10
  parseIncomingUploads,
9
11
  safeUploadName,
10
12
  saveUploads,
@@ -20,6 +22,11 @@ describe("uploads", () => {
20
22
  "nope",
21
23
  ]),
22
24
  ).toEqual([{ name: "a.txt", mime: "text/plain", data: "YQ==" }]);
25
+ expect(
26
+ parseIncomingUploads([
27
+ { name: "cv.md", mime: "text/markdown", data: "YQ==", sourcePath: "/Users/mads/cv.md" },
28
+ ])[0]?.sourcePath,
29
+ ).toBe("/Users/mads/cv.md");
23
30
  });
24
31
 
25
32
  test("treats source and markdown as text", () => {
@@ -50,6 +57,33 @@ describe("uploads", () => {
50
57
  expect(composeUploadMessage("look", saved)).toContain(saved[0]?.rel ?? "");
51
58
  expect(composeUploadMessage("look", saved)).toContain("```\nhello\n```");
52
59
  expect(composeUploadMessage("", saved)).toContain(saved[1]?.rel ?? "");
60
+ expect(listUploads(cwd).map((item) => item.name)).toEqual(["shot.png", "note.txt"]);
61
+ } finally {
62
+ await rm(cwd, { recursive: true, force: true });
63
+ }
64
+ });
65
+
66
+ test("keeps the original path and matches it for edit prompts", async () => {
67
+ const cwd = await mkdtemp(join(tmpdir(), "harness-uploads-"));
68
+ const original = join(cwd, "source.md");
69
+ try {
70
+ await Bun.write(original, "draft");
71
+ const saved = saveUploads(cwd, [
72
+ {
73
+ name: "source.md",
74
+ mime: "text/markdown",
75
+ data: Buffer.from("draft").toString("base64"),
76
+ sourcePath: original,
77
+ },
78
+ ]);
79
+ expect(saved[0]?.sourcePath).toBe(original);
80
+ expect(composeUploadMessage("edit", saved)).toContain("Original:");
81
+ expect(matchUploadEdit(cwd, saved[0]?.rel ?? "")).toEqual({
82
+ rel: saved[0]?.rel ?? "",
83
+ sourcePath: original,
84
+ name: "source.md",
85
+ });
86
+ expect(matchUploadEdit(cwd, original)?.rel).toBe(saved[0]?.rel);
53
87
  } finally {
54
88
  await rm(cwd, { recursive: true, force: true });
55
89
  }
@@ -1,10 +1,14 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
2
- import { resolve } from "node:path";
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, resolve } from "node:path";
3
4
  import { toProjectRel } from "../tools/paths.ts";
5
+ import { composeUploadMessage as buildUploadMessage } from "./upload-message.ts";
4
6
 
5
7
  export const MAX_UPLOADS = 8;
6
8
  export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
7
9
  const TEXT_EXCERPT_BYTES = 100_000;
10
+ const INDEX_NAME = "index.json";
11
+ const MAX_LISTED = 40;
8
12
 
9
13
  const TEXT_MIME =
10
14
  /^(text\/|application\/(json|xml|javascript|sql|yaml|x-yaml|toml|x-sh|x-httpd-php))/i;
@@ -15,6 +19,7 @@ export interface IncomingUpload {
15
19
  name: string;
16
20
  mime: string;
17
21
  data: string;
22
+ sourcePath?: string;
18
23
  }
19
24
 
20
25
  export interface SavedUpload {
@@ -22,6 +27,15 @@ export interface SavedUpload {
22
27
  rel: string;
23
28
  mime: string;
24
29
  excerpt?: string;
30
+ sourcePath?: string;
31
+ }
32
+
33
+ export interface UploadRecord {
34
+ name: string;
35
+ rel: string;
36
+ mime: string;
37
+ sourcePath?: string;
38
+ addedAt: string;
25
39
  }
26
40
 
27
41
  export function parseIncomingUploads(raw: unknown): IncomingUpload[] {
@@ -37,12 +51,38 @@ export function parseIncomingUploads(raw: unknown): IncomingUpload[] {
37
51
  ? rec.mime.trim()
38
52
  : "application/octet-stream";
39
53
  if (!name || !data) continue;
40
- out.push({ name, mime, data });
54
+ const sourcePath = parseSourcePath(rec.sourcePath);
55
+ out.push({ name, mime, data, ...(sourcePath ? { sourcePath } : {}) });
41
56
  if (out.length >= MAX_UPLOADS) break;
42
57
  }
43
58
  return out;
44
59
  }
45
60
 
61
+ export function parseSourcePath(raw: unknown): string | undefined {
62
+ if (typeof raw !== "string") return undefined;
63
+ const trimmed = raw.trim();
64
+ if (!trimmed || trimmed.includes("\0") || /\n|\r/.test(trimmed) || trimmed.length > 1024) {
65
+ return undefined;
66
+ }
67
+ if (trimmed.startsWith("file://")) return undefined;
68
+ if (trimmed === "~" || trimmed.startsWith("~/")) return trimmed;
69
+ if (isAbsolute(trimmed)) return trimmed;
70
+ return undefined;
71
+ }
72
+
73
+ export function expandSourcePath(raw: string): string {
74
+ if (raw === "~") return homedir();
75
+ if (raw.startsWith("~/")) return resolve(homedir(), raw.slice(2));
76
+ return resolve(raw);
77
+ }
78
+
79
+ export function displaySourcePath(abs: string): string {
80
+ const home = homedir();
81
+ if (abs === home) return "~";
82
+ if (abs.startsWith(`${home}/`)) return `~${abs.slice(home.length)}`;
83
+ return abs;
84
+ }
85
+
46
86
  export function isTextUpload(name: string, mime: string): boolean {
47
87
  return TEXT_MIME.test(mime) || TEXT_EXT.test(name);
48
88
  }
@@ -53,11 +93,121 @@ export function safeUploadName(name: string): string {
53
93
  return (base || "file").slice(0, 120);
54
94
  }
55
95
 
96
+ function uploadsDir(cwd: string): string {
97
+ return resolve(cwd, ".harness", "uploads");
98
+ }
99
+
100
+ function storedDisplayName(filename: string): string {
101
+ return filename.replace(/^\d+-\d+-/, "") || filename;
102
+ }
103
+
104
+ function readIndex(dir: string): UploadRecord[] {
105
+ try {
106
+ const parsed: unknown = JSON.parse(readFileSync(resolve(dir, INDEX_NAME), "utf8"));
107
+ if (!parsed || typeof parsed !== "object") return [];
108
+ const files = (parsed as { files?: unknown }).files;
109
+ if (!Array.isArray(files)) return [];
110
+ const out: UploadRecord[] = [];
111
+ for (const item of files) {
112
+ if (!item || typeof item !== "object") continue;
113
+ const rec = item as Record<string, unknown>;
114
+ const name = typeof rec.name === "string" ? rec.name : "";
115
+ const rel = typeof rec.rel === "string" ? rec.rel : "";
116
+ if (!name || !rel) continue;
117
+ const mime = typeof rec.mime === "string" ? rec.mime : "application/octet-stream";
118
+ const addedAt = typeof rec.addedAt === "string" ? rec.addedAt : "";
119
+ const sourcePath = parseSourcePath(rec.sourcePath);
120
+ out.push({
121
+ name,
122
+ rel,
123
+ mime,
124
+ addedAt,
125
+ ...(sourcePath ? { sourcePath } : {}),
126
+ });
127
+ }
128
+ return out;
129
+ } catch {
130
+ return [];
131
+ }
132
+ }
133
+
134
+ function writeIndex(dir: string, files: UploadRecord[]): void {
135
+ writeFileSync(resolve(dir, INDEX_NAME), `${JSON.stringify({ files }, null, 2)}\n`);
136
+ }
137
+
138
+ export function listUploads(cwd: string): UploadRecord[] {
139
+ const dir = uploadsDir(cwd);
140
+ const byRel = new Map<string, UploadRecord>();
141
+ for (const item of readIndex(dir)) byRel.set(item.rel, item);
142
+ try {
143
+ for (const name of readdirSync(dir)) {
144
+ if (name === INDEX_NAME) continue;
145
+ const abs = resolve(dir, name);
146
+ if (!statSync(abs).isFile()) continue;
147
+ const rel = toProjectRel(cwd, abs);
148
+ if (byRel.has(rel)) continue;
149
+ byRel.set(rel, {
150
+ name: storedDisplayName(name),
151
+ rel,
152
+ mime: "application/octet-stream",
153
+ addedAt: new Date(statSync(abs).mtimeMs).toISOString(),
154
+ });
155
+ }
156
+ } catch {
157
+ // no uploads folder yet
158
+ }
159
+ return [...byRel.values()]
160
+ .sort((a, b) => (a.addedAt < b.addedAt ? 1 : a.addedAt > b.addedAt ? -1 : 0))
161
+ .slice(0, MAX_LISTED);
162
+ }
163
+
164
+ export function listUploadOriginals(cwd: string): string[] {
165
+ const out: string[] = [];
166
+ for (const item of listUploads(cwd)) {
167
+ if (!item.sourcePath) continue;
168
+ out.push(expandSourcePath(item.sourcePath));
169
+ }
170
+ return out;
171
+ }
172
+
173
+ export function matchUploadEdit(
174
+ cwd: string,
175
+ path: string,
176
+ ): { rel: string; sourcePath: string; name: string } | undefined {
177
+ const trimmed = path.trim();
178
+ if (!trimmed) return undefined;
179
+ const root = resolve(cwd);
180
+ let abs: string | undefined;
181
+ try {
182
+ abs =
183
+ trimmed.startsWith("~") || isAbsolute(trimmed)
184
+ ? expandSourcePath(trimmed)
185
+ : resolve(root, trimmed);
186
+ } catch {
187
+ abs = undefined;
188
+ }
189
+ for (const item of listUploads(cwd)) {
190
+ if (!item.sourcePath) continue;
191
+ const original = expandSourcePath(item.sourcePath);
192
+ const copyAbs = resolve(root, item.rel);
193
+ if (
194
+ trimmed === item.rel ||
195
+ trimmed === item.sourcePath ||
196
+ abs === original ||
197
+ abs === copyAbs
198
+ ) {
199
+ return { rel: item.rel, sourcePath: original, name: item.name };
200
+ }
201
+ }
202
+ return undefined;
203
+ }
204
+
56
205
  export function saveUploads(cwd: string, items: IncomingUpload[]): SavedUpload[] {
57
206
  if (items.length === 0) return [];
58
- const dir = resolve(cwd, ".harness", "uploads");
207
+ const dir = uploadsDir(cwd);
59
208
  mkdirSync(dir, { recursive: true });
60
209
  const saved: SavedUpload[] = [];
210
+ const records = listUploads(cwd);
61
211
  for (const item of items) {
62
212
  const bytes = Buffer.from(item.data, "base64");
63
213
  if (bytes.byteLength === 0 || bytes.byteLength > MAX_UPLOAD_BYTES) continue;
@@ -69,24 +219,39 @@ export function saveUploads(cwd: string, items: IncomingUpload[]): SavedUpload[]
69
219
  isTextUpload(item.name, item.mime) && bytes.byteLength <= TEXT_EXCERPT_BYTES
70
220
  ? bytes.toString("utf8")
71
221
  : undefined;
222
+ const sourcePath = item.sourcePath
223
+ ? existsSync(expandSourcePath(item.sourcePath))
224
+ ? expandSourcePath(item.sourcePath)
225
+ : undefined
226
+ : undefined;
72
227
  saved.push({
73
228
  name: item.name,
74
229
  rel,
75
230
  mime: item.mime,
76
231
  ...(excerpt !== undefined ? { excerpt } : {}),
232
+ ...(sourcePath ? { sourcePath } : {}),
233
+ });
234
+ records.unshift({
235
+ name: item.name,
236
+ rel,
237
+ mime: item.mime,
238
+ addedAt: new Date().toISOString(),
239
+ ...(sourcePath ? { sourcePath } : {}),
77
240
  });
78
241
  }
242
+ writeIndex(dir, records.slice(0, MAX_LISTED));
79
243
  return saved;
80
244
  }
81
245
 
82
246
  export function composeUploadMessage(text: string, files: SavedUpload[]): string {
83
- if (files.length === 0) return text;
84
- const blocks = files.map((file) => {
85
- if (file.excerpt !== undefined) {
86
- return `Attached \`${file.rel}\` (${file.name}):\n\n\`\`\`\n${file.excerpt}\n\`\`\``;
87
- }
88
- return `Attached \`${file.rel}\` (${file.name}, ${file.mime}). Use that project path.`;
89
- });
90
- const body = text.trim();
91
- return body ? `${body}\n\n${blocks.join("\n\n")}` : blocks.join("\n\n");
247
+ return buildUploadMessage(
248
+ text,
249
+ files.map((file) => ({
250
+ name: file.name,
251
+ rel: file.rel,
252
+ mime: file.mime,
253
+ ...(file.excerpt !== undefined ? { excerpt: file.excerpt } : {}),
254
+ ...(file.sourcePath ? { original: displaySourcePath(file.sourcePath) } : {}),
255
+ })),
256
+ );
92
257
  }
package/src/index.ts CHANGED
@@ -20,6 +20,7 @@ export {
20
20
  type ExecApprovalPolicy,
21
21
  isLikelyDestructive,
22
22
  isRiskyToolCall,
23
+ isUploadEditRequest,
23
24
  parseExecApprovalPolicy,
24
25
  } from "./core/approval.ts";
25
26
  export type { AgentEvent, AgentEventEmitter, MainModelProvider } from "./core/events.ts";
package/src/init.test.ts CHANGED
@@ -68,4 +68,25 @@ describe("local tools", () => {
68
68
  await rm(cwd, { recursive: true, force: true });
69
69
  }
70
70
  });
71
+
72
+ test("can write an uploaded original outside cwd when allowlisted", async () => {
73
+ const cwd = await mkdtemp(join(tmpdir(), "harness-tools-"));
74
+ const outside = await mkdtemp(join(tmpdir(), "harness-orig-"));
75
+ try {
76
+ const original = join(outside, "brief.md");
77
+ await Bun.write(original, "hello");
78
+ const mcp = createLocalTools({ cwd, extraWriteAbsolutes: () => [original] });
79
+ const written = await mcp.callTool("write_file", { path: original, content: "edited\n" });
80
+ expect(written.isError).toBeFalsy();
81
+ expect(await readFile(original, "utf8")).toBe("edited\n");
82
+ const blocked = await mcp.callTool("write_file", {
83
+ path: join(outside, "other.md"),
84
+ content: "nope",
85
+ });
86
+ expect(blocked.isError).toBe(true);
87
+ } finally {
88
+ await rm(cwd, { recursive: true, force: true });
89
+ await rm(outside, { recursive: true, force: true });
90
+ }
91
+ });
71
92
  });
package/src/runtime.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  createConstructAgent,
38
38
  } from "./core/strands.ts";
39
39
  import { addUsage, type TokenUsage } from "./core/usage.ts";
40
+ import { listUploadOriginals, matchUploadEdit } from "./desktop/uploads.ts";
40
41
  import { type ChatFn, createOpenRouterChat } from "./evals/runner.ts";
41
42
  import { buildRemoteMcpTools } from "./integrations/remote-mcp.ts";
42
43
  import { linkedMcpSources } from "./integrations/store.ts";
@@ -172,7 +173,10 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
172
173
  });
173
174
  let systemPrompt = composePrompt(mode);
174
175
  const store = createFileSessionStore(cwd);
175
- const local = createLocalTools({ cwd });
176
+ const local = createLocalTools({
177
+ cwd,
178
+ extraWriteAbsolutes: () => listUploadOriginals(cwd),
179
+ });
176
180
  const todos = createMemoryTodoStore();
177
181
  const hooks = createHookRunner({ cwd, hooks: config.hooks });
178
182
  void hooks.sessionStart();
@@ -447,6 +451,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
447
451
  policy,
448
452
  alwaysAllow,
449
453
  emit,
454
+ resolveUploadEdit: (path) => matchUploadEdit(cwd, path),
450
455
  ask: async (req) => {
451
456
  if (turnOptions?.approvalAsk) return turnOptions.approvalAsk(req);
452
457
  if (policy === "prompt") return false;