@useavalon/caelence-agent 0.2.2-canary.3 → 0.2.2-canary.5
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.
- package/desktop/src/App.tsx +160 -45
- package/desktop/src/ComposerAttach.tsx +2 -26
- package/desktop/src/FilesPanel.tsx +68 -0
- package/desktop/src/McpPanel.tsx +268 -0
- package/desktop/src/api.ts +48 -1
- package/desktop/src/app.css +69 -0
- package/desktop/src/composer-files.test.ts +2 -0
- package/desktop/src/composer-files.ts +10 -0
- package/desktop/src/user-display.test.ts +42 -0
- package/desktop/src/user-display.ts +20 -0
- package/package.json +1 -1
- package/src/cli/slash-dispatch.test.ts +1 -0
- package/src/cli/tui.tsx +40 -5
- package/src/core/approval.test.ts +22 -0
- package/src/core/approval.ts +20 -0
- package/src/desktop/bridge.ts +60 -6
- package/src/desktop/upload-message.test.ts +53 -0
- package/src/desktop/upload-message.ts +74 -0
- package/src/desktop/uploads.test.ts +34 -0
- package/src/desktop/uploads.ts +178 -13
- package/src/index.ts +1 -0
- package/src/init.test.ts +21 -0
- package/src/mcp/user-servers.test.ts +138 -0
- package/src/mcp/user-servers.ts +427 -0
- package/src/runtime.ts +61 -12
package/src/core/approval.ts
CHANGED
|
@@ -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;
|
package/src/desktop/bridge.ts
CHANGED
|
@@ -21,6 +21,12 @@ import {
|
|
|
21
21
|
} from "../integrations/connect.ts";
|
|
22
22
|
import { readProviderOAuth, writeProviderOAuth } from "../integrations/oauth-clients.ts";
|
|
23
23
|
import { listPublicIntegrations, removeConnection } from "../integrations/store.ts";
|
|
24
|
+
import {
|
|
25
|
+
type AddUserMcpInput,
|
|
26
|
+
addUserMcpServer,
|
|
27
|
+
listPublicMcps,
|
|
28
|
+
removeUserMcpServer,
|
|
29
|
+
} from "../mcp/user-servers.ts";
|
|
24
30
|
import { transcribeAudio } from "../media/openrouter-generate.ts";
|
|
25
31
|
import { readMediaPrefs } from "../media/prefs.ts";
|
|
26
32
|
import { PRODUCT_NAME } from "../product.ts";
|
|
@@ -42,7 +48,7 @@ import {
|
|
|
42
48
|
import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
|
|
43
49
|
import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
|
|
44
50
|
import { applyStoredOpenRouterKey, maskSecret, writeOpenRouterKey } from "./secrets.ts";
|
|
45
|
-
import { composeUploadMessage, parseIncomingUploads, saveUploads } from "./uploads.ts";
|
|
51
|
+
import { composeUploadMessage, listUploads, parseIncomingUploads, saveUploads } from "./uploads.ts";
|
|
46
52
|
|
|
47
53
|
export interface DesktopState {
|
|
48
54
|
name: string;
|
|
@@ -63,6 +69,7 @@ export interface DesktopState {
|
|
|
63
69
|
skills: Array<{ name: string; source: string }>;
|
|
64
70
|
busy: boolean;
|
|
65
71
|
hasApiKey: boolean;
|
|
72
|
+
uploads?: Array<{ name: string; rel: string; sourcePath?: string }>;
|
|
66
73
|
}
|
|
67
74
|
|
|
68
75
|
export interface BridgeReady {
|
|
@@ -249,6 +256,11 @@ function snapshot(harness: HarnessRuntime, busy: boolean, title: string): Deskto
|
|
|
249
256
|
skills: harness.skills.map((skill) => ({ name: skill.name, source: skill.source })),
|
|
250
257
|
busy,
|
|
251
258
|
hasApiKey: harness.hasApiKey,
|
|
259
|
+
uploads: listUploads(harness.cwd).map((item) => ({
|
|
260
|
+
name: item.name,
|
|
261
|
+
rel: item.rel,
|
|
262
|
+
...(item.sourcePath ? { sourcePath: item.sourcePath } : {}),
|
|
263
|
+
})),
|
|
252
264
|
};
|
|
253
265
|
}
|
|
254
266
|
|
|
@@ -272,7 +284,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
272
284
|
let title = "New chat";
|
|
273
285
|
let busy = false;
|
|
274
286
|
let abort: AbortController | undefined;
|
|
275
|
-
const pending = new Map<string, (
|
|
287
|
+
const pending = new Map<string, (decision: string) => void>();
|
|
276
288
|
const oauthWaiters = new Map<string, (result: OAuthCallback) => void>();
|
|
277
289
|
|
|
278
290
|
const refreshLiveNames = (): void => {
|
|
@@ -385,6 +397,31 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
385
397
|
return json({ ok: true, items: listPublicIntegrations() });
|
|
386
398
|
};
|
|
387
399
|
|
|
400
|
+
const mcpPage = () => ({ items: listPublicMcps(harness.cwd, harness.config.mcp) });
|
|
401
|
+
|
|
402
|
+
const route_get_mcp = async (_req: Request, _url: URL): Promise<Response> => {
|
|
403
|
+
return json(mcpPage());
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
const route_post_mcp_add = async (req: Request, _url: URL): Promise<Response> => {
|
|
407
|
+
const body = (await readJson(req)) as AddUserMcpInput;
|
|
408
|
+
const added = addUserMcpServer(harness.cwd, body, harness.config.mcp);
|
|
409
|
+
if ("error" in added) return json({ error: added.error }, 400);
|
|
410
|
+
await harness.reloadExtraMcp();
|
|
411
|
+
return json({ ok: true, ...mcpPage() });
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
const route_post_mcp_remove = async (req: Request, _url: URL): Promise<Response> => {
|
|
415
|
+
const body = await readJson(req);
|
|
416
|
+
const id = typeof body.id === "string" ? body.id.trim() : "";
|
|
417
|
+
if (!id) return json({ error: "id is required." }, 400);
|
|
418
|
+
if (!removeUserMcpServer(harness.cwd, id)) {
|
|
419
|
+
return json({ error: "MCP not found." }, 400);
|
|
420
|
+
}
|
|
421
|
+
await harness.reloadExtraMcp();
|
|
422
|
+
return json({ ok: true, ...mcpPage() });
|
|
423
|
+
};
|
|
424
|
+
|
|
388
425
|
const skillsPage = (popular = cachedPopularSkills()) =>
|
|
389
426
|
buildSkillsPage(
|
|
390
427
|
withDisabledCatalogSkills(harness.skills, harness.disabledSkills()),
|
|
@@ -661,13 +698,13 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
661
698
|
if (decision === "always")
|
|
662
699
|
harness.allowRiskyAlways(typeof body.toolName === "string" ? body.toolName : "exec");
|
|
663
700
|
pending.delete(callId);
|
|
664
|
-
resolve(decision === "
|
|
701
|
+
resolve(typeof decision === "string" ? decision : "no");
|
|
665
702
|
return json({ ok: true });
|
|
666
703
|
};
|
|
667
704
|
|
|
668
705
|
const route_post_abort = async (_req: Request, _url: URL): Promise<Response> => {
|
|
669
706
|
abort?.abort();
|
|
670
|
-
for (const resolve of pending.values()) resolve(
|
|
707
|
+
for (const resolve of pending.values()) resolve("no");
|
|
671
708
|
pending.clear();
|
|
672
709
|
return json({ ok: true });
|
|
673
710
|
};
|
|
@@ -736,7 +773,21 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
736
773
|
signal: abort?.signal,
|
|
737
774
|
approvalAsk: (req: ApprovalRequest) =>
|
|
738
775
|
new Promise<boolean>((resolve) => {
|
|
739
|
-
pending.set(req.callId,
|
|
776
|
+
pending.set(req.callId, (decision) => {
|
|
777
|
+
if (
|
|
778
|
+
decision === "original" &&
|
|
779
|
+
typeof req.input.originalPath === "string" &&
|
|
780
|
+
req.input.originalPath.trim()
|
|
781
|
+
) {
|
|
782
|
+
req.input.path = req.input.originalPath;
|
|
783
|
+
}
|
|
784
|
+
resolve(
|
|
785
|
+
decision === "yes" ||
|
|
786
|
+
decision === "always" ||
|
|
787
|
+
decision === "copy" ||
|
|
788
|
+
decision === "original",
|
|
789
|
+
);
|
|
790
|
+
});
|
|
740
791
|
}),
|
|
741
792
|
...(editUserTurn !== undefined ? { editUserTurn } : {}),
|
|
742
793
|
})
|
|
@@ -780,6 +831,9 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
780
831
|
"GET /integrations": route_get_integrations,
|
|
781
832
|
"POST /integrations/connect": route_post_integrations_connect,
|
|
782
833
|
"POST /integrations/disconnect": route_post_integrations_disconnect,
|
|
834
|
+
"GET /mcp": route_get_mcp,
|
|
835
|
+
"POST /mcp/add": route_post_mcp_add,
|
|
836
|
+
"POST /mcp/remove": route_post_mcp_remove,
|
|
783
837
|
"GET /skills": route_get_skills,
|
|
784
838
|
"GET /skills/popular": route_get_skills_popular,
|
|
785
839
|
"GET /skills/search": route_get_skills_search,
|
|
@@ -838,7 +892,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
838
892
|
ready,
|
|
839
893
|
stop: async () => {
|
|
840
894
|
abort?.abort();
|
|
841
|
-
for (const resolve of pending.values()) resolve(
|
|
895
|
+
for (const resolve of pending.values()) resolve("no");
|
|
842
896
|
pending.clear();
|
|
843
897
|
for (const resolve of oauthWaiters.values()) resolve({ error: "cancelled" });
|
|
844
898
|
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
|
}
|
package/src/desktop/uploads.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
-
import {
|
|
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
|
-
|
|
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 =
|
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
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
|
});
|