@exulu/backend 5.14.0 → 5.16.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.
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Skill folders are read-only inside the session sandbox: the per-session policy
3
+ * denies writes under <sessionDir>/skills, and the writeFile tool refuses such a path
4
+ * itself, before touching disk, in sandboxed and in degraded (direct-exec) mode.
5
+ * Runtime mocked (wrapWithSandbox = identity), S3 mocked, persistence on (userId 7).
6
+ * The real kernel enforcement is in create-sandbox.readonly-skills.sandbox.test.ts.
7
+ */
8
+ jest.mock("@anthropic-ai/sandbox-runtime", () => ({
9
+ SandboxManager: {
10
+ initialize: jest.fn(async () => {}),
11
+ wrapWithSandbox: jest.fn(async (cmd: string) => cmd),
12
+ reset: jest.fn(async () => {}),
13
+ },
14
+ }));
15
+ jest.mock("@SRC/uppy/index.ts", () => ({
16
+ listS3ObjectsByPrefix: jest.fn(),
17
+ getS3ObjectBytes: jest.fn(),
18
+ uploadFile: jest.fn(async (_c: Buffer, key: string) => `bucket/user_7/${key}`),
19
+ getPresignedUrl: jest.fn(async () => "https://signed"),
20
+ }));
21
+ jest.mock("@SRC/postgres/client", () => ({
22
+ postgresClient: jest.fn(async () => ({ db: { from: () => ({ select: async () => [] }) } })),
23
+ }));
24
+ jest.mock("@SRC/exulu/system-dependencies.ts", () => ({ getNpmGlobalRoot: jest.fn(async () => null) }));
25
+ jest.mock("@SRC/utils/python-setup.ts", () => ({ getPythonVenvPath: () => undefined }));
26
+
27
+ import { existsSync } from "node:fs";
28
+ import { mkdir, readdir, readFile, symlink } from "node:fs/promises";
29
+ import { join } from "node:path";
30
+
31
+ type CreateSandboxModule = typeof import("./create-sandbox");
32
+ type Handle = Awaited<ReturnType<CreateSandboxModule["createSessionSandbox"]>>;
33
+
34
+ const config = { fileUploads: { s3Bucket: "bucket" } } as any;
35
+ const skill = (v: number) => ({ id: "sk-ro", name: "demo", s3folder: "skills/sk-ro", current_version: v });
36
+
37
+ /** S3 key -> bytes; skill files under skills/<id>/v<version>/. */
38
+ let store: Map<string, Buffer>;
39
+ const put = (v: number, files: Record<string, string>) => {
40
+ for (const [rel, text] of Object.entries(files)) store.set(`skills/sk-ro/v${v}/${rel}`, Buffer.from(text));
41
+ };
42
+
43
+ const realPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;
44
+
45
+ /**
46
+ * A fresh create-sandbox module (its sandbox probe is memoized per module) seen on
47
+ * `platform`: "darwin" probes as sandbox-capable without spawning anything, any
48
+ * platform other than darwin/linux probes as unsupported, i.e. degraded mode. The
49
+ * probe runs on the first createSessionSandbox, so the platform stays overridden
50
+ * until afterEach restores it.
51
+ */
52
+ async function loadOn(platform: string) {
53
+ Object.defineProperty(process, "platform", { value: platform });
54
+ let mod!: CreateSandboxModule;
55
+ let runtime!: { SandboxManager: { wrapWithSandbox: jest.Mock } };
56
+ let uppy!: { listS3ObjectsByPrefix: jest.Mock; getS3ObjectBytes: jest.Mock; uploadFile: jest.Mock };
57
+ await jest.isolateModulesAsync(async () => {
58
+ runtime = await import("@anthropic-ai/sandbox-runtime") as any;
59
+ uppy = await import("@SRC/uppy/index.ts") as any;
60
+ mod = await import("./create-sandbox");
61
+ });
62
+ uppy.listS3ObjectsByPrefix.mockImplementation(async (prefix: string) =>
63
+ [...store.keys()].filter((k) => k.startsWith(prefix)).map((key) => ({ key, size: store.get(key)!.length })),
64
+ );
65
+ uppy.getS3ObjectBytes.mockImplementation(async (key: string) => {
66
+ const bytes = store.get(key);
67
+ if (!bytes) throw new Error(`no object ${key}`);
68
+ return bytes;
69
+ });
70
+ return { mod, wrap: runtime.SandboxManager.wrapWithSandbox, upload: uppy.uploadFile };
71
+ }
72
+
73
+ let handles: Handle[] = [];
74
+ const sid = () => `jest-roskills-${process.pid}-${Math.random().toString(36).slice(2)}`;
75
+ const write = (h: Handle, path: string, content: string) =>
76
+ (h.tools.writeFile as any).execute({ path, content }, { toolCallId: "t", messages: [] });
77
+
78
+ beforeEach(() => {
79
+ store = new Map();
80
+ jest.spyOn(console, "warn").mockImplementation(() => {});
81
+ jest.spyOn(console, "log").mockImplementation(() => {});
82
+ });
83
+ afterEach(async () => {
84
+ Object.defineProperty(process, "platform", realPlatform);
85
+ for (const h of handles) await h.cleanup();
86
+ handles = [];
87
+ jest.restoreAllMocks();
88
+ });
89
+
90
+ describe("the per-session sandbox policy", () => {
91
+ it("denies writes under <sessionDir>/skills and still allows the session dir", async () => {
92
+ const { mod, wrap } = await loadOn("darwin");
93
+ put(1, { "SKILL.md": "# demo" });
94
+ const h = await mod.createSessionSandbox(sid(), [skill(1)], config, 7, undefined, { projectId: null });
95
+ handles.push(h);
96
+ await (h.tools.bash as any).execute({ command: "echo hi > out.txt" }, { toolCallId: "t", messages: [] });
97
+ await h.runCommand("true");
98
+ await h.wrapCommand("true");
99
+
100
+ expect(wrap.mock.calls.length).toBeGreaterThanOrEqual(3);
101
+ for (const call of wrap.mock.calls) {
102
+ const fsPolicy = call[2]?.filesystem;
103
+ expect(fsPolicy.allowWrite).toEqual([h.sessionDir]);
104
+ expect(fsPolicy.denyWrite).toEqual([join(h.sessionDir, "skills")]);
105
+ }
106
+ });
107
+
108
+ it("creates skills/ before the first command even without skills, so the deny path exists", async () => {
109
+ const { mod } = await loadOn("darwin");
110
+ const h = await mod.createSessionSandbox(sid(), [], config, 7, undefined, { projectId: null });
111
+ handles.push(h);
112
+ expect(existsSync(join(h.sessionDir, "skills"))).toBe(true);
113
+ });
114
+ });
115
+
116
+ describe.each([
117
+ ["sandboxed", "darwin"],
118
+ ["degraded (direct exec)", "freebsd"],
119
+ ])("writeFile under skills/ is refused, %s", (_label, platform) => {
120
+ let h: Handle;
121
+ let wrap: jest.Mock;
122
+ let upload: jest.Mock;
123
+ beforeEach(async () => {
124
+ const loaded = await loadOn(platform);
125
+ wrap = loaded.wrap;
126
+ upload = loaded.upload;
127
+ put(1, { "SKILL.md": "# demo", "run.py": "print('v1')\n" });
128
+ h = await loaded.mod.createSessionSandbox(sid(), [skill(1)], config, 7, undefined, { projectId: null });
129
+ handles.push(h);
130
+ await mkdir(join(h.sessionDir, "work"));
131
+ await symlink(join(h.sessionDir, "skills", "demo"), join(h.sessionDir, "work", "into-skill"));
132
+ await symlink(join(h.sessionDir, "skills"), join(h.sessionDir, "skills-link"));
133
+ wrap.mockClear();
134
+ upload.mockClear();
135
+ });
136
+
137
+ const refused = [
138
+ "skills/demo/run.py",
139
+ "skills/demo/new.py",
140
+ "skills/new.txt",
141
+ "./skills/x",
142
+ "/skills/demo/run.py",
143
+ "skills/../skills/x",
144
+ "work/../skills/demo/run.py",
145
+ "work/into-skill/run.py",
146
+ "work/into-skill/planted.py",
147
+ "skills-link/demo/run.py",
148
+ ];
149
+
150
+ it.each(refused)("%p: refused with a clear message, nothing written, no upload", async (path) => {
151
+ await expect(write(h, path, "evil")).rejects.toThrow(/read-only/);
152
+ expect(await readFile(join(h.sessionDir, "skills", "demo", "run.py"), "utf8")).toBe("print('v1')\n");
153
+ expect(existsSync(join(h.sessionDir, "skills", "demo", "new.py"))).toBe(false);
154
+ expect(existsSync(join(h.sessionDir, "skills", "demo", "planted.py"))).toBe(false);
155
+ expect(existsSync(join(h.sessionDir, "skills", "new.txt"))).toBe(false);
156
+ expect(existsSync(join(h.sessionDir, "skills", "x"))).toBe(false);
157
+ expect(wrap).not.toHaveBeenCalled();
158
+ expect(upload).not.toHaveBeenCalled();
159
+ });
160
+
161
+ it("an absolute path into the skills dir is refused", async () => {
162
+ await expect(write(h, join(h.sessionDir, "skills", "demo", "run.py"), "evil")).rejects.toThrow(/read-only/);
163
+ expect(await readFile(join(h.sessionDir, "skills", "demo", "run.py"), "utf8")).toBe("print('v1')\n");
164
+ });
165
+
166
+ it("the message says how a skill changes", async () => {
167
+ await expect(write(h, "skills/demo/run.py", "evil")).rejects.toThrow(/new version/);
168
+ });
169
+
170
+ it("a normal path is written and uploaded as before", async () => {
171
+ const r = await write(h, "out/report.txt", "ok");
172
+ expect(r).toMatchObject({ success: true, url: "https://signed" });
173
+ expect(await readFile(join(h.sessionDir, "out", "report.txt"), "utf8")).toBe("ok");
174
+ expect(upload).toHaveBeenCalledTimes(1);
175
+ // The mode under test is the one claimed: degraded mode never wraps.
176
+ expect(wrap).toHaveBeenCalledTimes(platform === "darwin" ? 1 : 0);
177
+ });
178
+
179
+ it("a file whose name only starts with skills is not refused", async () => {
180
+ await write(h, "skills.md", "ok");
181
+ expect(await readFile(join(h.sessionDir, "skills.md"), "utf8")).toBe("ok");
182
+ });
183
+ });
184
+
185
+ it("the writeFile description says skills are read-only and change by saving a new version", async () => {
186
+ const { mod } = await loadOn("darwin");
187
+ const h = await mod.createSessionSandbox(sid(), [], config, 7, undefined, { projectId: null });
188
+ handles.push(h);
189
+ const description = (h.tools.writeFile as any).description as string;
190
+ expect(description).not.toContain("skills/<Skill name>/SKILL.md");
191
+ expect(description).toMatch(/skills\/.*read-only/);
192
+ expect(description).toMatch(/new version/);
193
+ });
194
+
195
+ describe("the platform still writes skill folders", () => {
196
+ it("a version change replaces the files, and the policy still denies the sandbox", async () => {
197
+ const { mod, wrap } = await loadOn("darwin");
198
+ put(1, { "SKILL.md": "# v1", "old.py": "old" });
199
+ put(2, { "SKILL.md": "# v2" });
200
+ const id = sid();
201
+ const h = await mod.createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
202
+ handles.push(h);
203
+ await expect(write(h, "skills/demo/SKILL.md", "# planted")).rejects.toThrow(/read-only/);
204
+ await mod.createSessionSandbox(id, [skill(2)], config, 7, undefined, { projectId: null });
205
+ expect(await readFile(join(h.sessionDir, "skills", "demo", "SKILL.md"), "utf8")).toBe("# v2");
206
+ expect(existsSync(join(h.sessionDir, "skills", "demo", "old.py"))).toBe(false);
207
+ wrap.mockClear();
208
+ await h.runCommand("true");
209
+ expect(wrap.mock.calls[0][2].filesystem.denyWrite).toEqual([join(h.sessionDir, "skills")]);
210
+ });
211
+
212
+ it("the reload route re-downloads into the folder", async () => {
213
+ const { mod } = await loadOn("darwin");
214
+ put(1, { "SKILL.md": "# v1" });
215
+ const id = sid();
216
+ const h = await mod.createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
217
+ handles.push(h);
218
+ put(1, { "SKILL.md": "# v1 reloaded" });
219
+ expect(await mod.refreshSessionSkills(id, [skill(1)], config)).toEqual({ refreshed: 1, sandbox: true });
220
+ expect(await readFile(join(h.sessionDir, "skills", "demo", "SKILL.md"), "utf8")).toBe("# v1 reloaded");
221
+ });
222
+ });
223
+
224
+ describe("session files from storage never land in skills/", () => {
225
+ const SCRIPT = "print('v1')\n";
226
+ const sessionKey = (id: string, rel: string) => `user_7/sessions/${id}/${rel}`;
227
+ // Each would land in skills/ (the case variants only on a case-insensitive file system).
228
+ const planted = ["skills/demo/run.py", "skills/demo/new.py", "./skills/demo/dot.py", "a/../skills/demo/up.py", "SKILLS/demo/run.py", "Skills/demo/case.py", "skills"];
229
+ const plant = (id: string) => {
230
+ for (const rel of planted) store.set(sessionKey(id, rel), Buffer.from("print('evil, longer than the real script')\n"));
231
+ store.set(sessionKey(id, "note.txt"), Buffer.from("hello"));
232
+ };
233
+ const expectSkillIntact = async (h: Handle) => {
234
+ expect(await readFile(join(h.sessionDir, "skills", "demo", "run.py"), "utf8")).toBe(SCRIPT);
235
+ expect((await readdir(join(h.sessionDir, "skills", "demo"))).sort()).toEqual(["SKILL.md", "run.py"]);
236
+ expect(await readdir(join(h.sessionDir, "skills"))).toEqual(["demo"]);
237
+ };
238
+
239
+ it("cold start: planted keys are skipped (and logged), a normal session file is restored", async () => {
240
+ const { mod } = await loadOn("darwin");
241
+ const id = sid();
242
+ put(1, { "SKILL.md": "# demo", "run.py": SCRIPT });
243
+ plant(id);
244
+ const h = await mod.createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
245
+ handles.push(h);
246
+ await expectSkillIntact(h);
247
+ expect(await readFile(join(h.sessionDir, "note.txt"), "utf8")).toBe("hello");
248
+ const logged = (console.warn as jest.Mock).mock.calls.map((c) => String(c[0]));
249
+ expect(logged.some((l) => l.includes(sessionKey(id, "skills/demo/run.py")) && l.includes("skills/"))).toBe(true);
250
+ expect(logged.join("\n")).not.toContain("evil");
251
+ });
252
+
253
+ it("restart (directory on disk, sizes differ): planted keys are still skipped", async () => {
254
+ const first = await loadOn("darwin");
255
+ const id = sid();
256
+ put(1, { "SKILL.md": "# demo", "run.py": SCRIPT });
257
+ const h1 = await first.mod.createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
258
+ handles.push(h1);
259
+ plant(id);
260
+ Object.defineProperty(process, "platform", realPlatform);
261
+ // A fresh module = a restarted process: empty cache, the session dir survives.
262
+ const second = await loadOn("darwin");
263
+ const h2 = await second.mod.createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
264
+ handles.push(h2);
265
+ expect(h2).not.toBe(h1);
266
+ await expectSkillIntact(h2);
267
+ expect(await readFile(join(h2.sessionDir, "note.txt"), "utf8")).toBe("hello");
268
+ });
269
+
270
+ it("downloadKeyIntoSandbox reports a planted key as not written and still writes a normal one", async () => {
271
+ const { mod } = await loadOn("darwin");
272
+ const id = sid();
273
+ put(1, { "SKILL.md": "# demo", "run.py": SCRIPT });
274
+ const h = await mod.createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
275
+ handles.push(h);
276
+ plant(id);
277
+ // On a case-sensitive file system SKILLS/ is simply another folder.
278
+ const caseInsensitive = existsSync(join(h.sessionDir, "SKILLS"));
279
+ const caseVariant = (r: string) => /^S(KILLS|kills)\//.test(r);
280
+ for (const rel of planted.filter((r) => caseInsensitive || !caseVariant(r))) {
281
+ expect(await mod.downloadKeyIntoSandbox({ sessionId: id, userId: 7, fullS3Key: sessionKey(id, rel), config })).toEqual({
282
+ written: false,
283
+ });
284
+ }
285
+ await expectSkillIntact(h);
286
+ const ok = await mod.downloadKeyIntoSandbox({ sessionId: id, userId: 7, fullS3Key: sessionKey(id, "note.txt"), config });
287
+ expect(ok.written).toBe(true);
288
+ expect(await readFile(join(h.sessionDir, "note.txt"), "utf8")).toBe("hello");
289
+ });
290
+ });
@@ -0,0 +1,135 @@
1
+ /**
2
+ * runCommand: the programmatic runner used by skill actions. Real (direct-exec) sandbox,
3
+ * S3 mocked, persistence enabled (userId 7), same harness as create-sandbox.symlink.test.ts.
4
+ */
5
+ jest.mock("@anthropic-ai/sandbox-runtime", () => ({
6
+ SandboxManager: {
7
+ initialize: jest.fn(async () => {}),
8
+ wrapWithSandbox: jest.fn(async (cmd: string) => cmd),
9
+ reset: jest.fn(async () => {}),
10
+ },
11
+ }));
12
+ jest.mock("@SRC/uppy/index.ts", () => ({
13
+ listS3ObjectsByPrefix: jest.fn(async () => []),
14
+ getS3ObjectBytes: jest.fn(),
15
+ uploadFile: jest.fn(async (_c: Buffer, key: string) => `bucket/user_7/${key}`),
16
+ getPresignedUrl: jest.fn(async () => "https://signed"),
17
+ }));
18
+ jest.mock("@SRC/postgres/client", () => ({
19
+ postgresClient: jest.fn(async () => ({ db: { from: () => ({ select: async () => [] }) } })),
20
+ }));
21
+ jest.mock("@SRC/exulu/system-dependencies.ts", () => ({ getNpmGlobalRoot: jest.fn(async () => null) }));
22
+ jest.mock("@SRC/utils/python-setup.ts", () => ({ getPythonVenvPath: () => undefined }));
23
+
24
+ import { realpathSync, existsSync } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { uploadFile } from "@SRC/uppy/index.ts";
27
+ import { createSessionSandbox, type SessionSandboxHandle } from "./create-sandbox";
28
+
29
+ const upload = uploadFile as jest.Mock;
30
+ const config = { fileUploads: { s3Bucket: "bucket" } } as any;
31
+ let handle: SessionSandboxHandle;
32
+
33
+ beforeEach(async () => {
34
+ upload.mockClear();
35
+ jest.spyOn(console, "warn").mockImplementation(() => {});
36
+ jest.spyOn(console, "log").mockImplementation(() => {});
37
+ handle = await createSessionSandbox(
38
+ `jest-runcmd-${process.pid}-${Math.random().toString(36).slice(2)}`,
39
+ [],
40
+ config,
41
+ 7,
42
+ undefined,
43
+ { projectId: null },
44
+ );
45
+ });
46
+ afterEach(async () => {
47
+ await handle.cleanup();
48
+ jest.restoreAllMocks();
49
+ });
50
+
51
+ test("extraEnv reaches the command and does not leak into the next call", async () => {
52
+ const a = await handle.runCommand('printf %s "$EXULU_INPUTS_DIR"', { extraEnv: { EXULU_INPUTS_DIR: "/x" } });
53
+ expect(a.stdout.startsWith("/x")).toBe(true);
54
+ const b = await handle.runCommand('printf %s "${EXULU_INPUTS_DIR:-none}"');
55
+ expect(b.stdout.startsWith("none")).toBe(true);
56
+ });
57
+
58
+ test("the command runs in the session directory and reports its exit code", async () => {
59
+ const r = await handle.runCommand("pwd; echo oops >&2; exit 3");
60
+ expect(realpathSync(r.stdout.trim().split("\n")[0]!)).toBe(realpathSync(handle.sessionDir));
61
+ expect(r.stderr).toContain("oops");
62
+ expect(r.exitCode).toBe(3);
63
+ expect(r.timedOut).toBe(false);
64
+ });
65
+
66
+ test("timeout kills the whole process group", async () => {
67
+ const r = await handle.runCommand("sleep 5; echo done", { timeoutMs: 200 });
68
+ expect(r.timedOut).toBe(true);
69
+ expect(r.exitCode).toBe(124);
70
+ expect(r.stdout).not.toContain("done");
71
+ });
72
+
73
+ test("a file created by the command is mirrored, .exulu-inputs is not", async () => {
74
+ const r = await handle.runCommand(
75
+ "mkdir -p .exulu-inputs/r1 && echo x > .exulu-inputs/r1/a.json && echo y > out.txt",
76
+ );
77
+ expect(r.artifacts.map((a) => a.relativePath)).toEqual(["out.txt"]);
78
+ expect(r.stdout).toContain("[exulu-artifacts]");
79
+ expect(r.stdout).toContain("out.txt: https://signed");
80
+ expect(upload.mock.calls.map((c) => c[1] as string).some((k) => k.includes(".exulu-inputs"))).toBe(false);
81
+ });
82
+
83
+ test("the bash tool still returns stdout, exit code and the artifacts block", async () => {
84
+ const r: any = await (handle.tools.bash as any).execute(
85
+ { command: "echo hello; echo y > made.txt" },
86
+ { toolCallId: "t", messages: [] },
87
+ );
88
+ expect(r.stdout).toContain("hello");
89
+ expect(r.exitCode).toBe(0);
90
+ expect(r.artifacts.map((a: any) => a.relativePath)).toEqual(["made.txt"]);
91
+ expect(r.stdout).toContain("[exulu-artifacts]");
92
+ expect(r.stdout).toContain("made.txt: https://signed");
93
+ expect(r.artifactsOmitted).toBeUndefined();
94
+ });
95
+
96
+ test("pwd prints the session dir", async () => {
97
+ const r = await handle.runCommand("pwd");
98
+ expect(realpathSync(r.stdout.trim())).toBe(realpathSync(handle.sessionDir));
99
+ });
100
+
101
+ test("the command gets the constructed env, not the backend's process.env (declared secret is stripped)", async () => {
102
+ process.env.POSTGRES_DB_PASSWORD = "leaked";
103
+ try {
104
+ const h2 = await createSessionSandbox(
105
+ `jest-runcmd-env-${process.pid}-${Math.random().toString(36).slice(2)}`,
106
+ [], config, 7, undefined, { projectId: null },
107
+ );
108
+ try {
109
+ const r = await h2.runCommand('printf %s "${POSTGRES_DB_PASSWORD:-none}"');
110
+ expect(r.stdout.startsWith("none")).toBe(true);
111
+ } finally {
112
+ await h2.cleanup();
113
+ }
114
+ } finally {
115
+ delete process.env.POSTGRES_DB_PASSWORD;
116
+ }
117
+ });
118
+
119
+ test("writeFile into .exulu-inputs is neither uploaded nor given a URL, but exists on disk", async () => {
120
+ const r: any = await (handle.tools.writeFile as any).execute(
121
+ { path: ".exulu-inputs/r1/x.json", content: "{}" },
122
+ { toolCallId: "t", messages: [] },
123
+ );
124
+ expect(upload).not.toHaveBeenCalled();
125
+ expect(r.url).toBeUndefined();
126
+ expect(existsSync(join(handle.sessionDir, ".exulu-inputs/r1/x.json"))).toBe(true);
127
+ });
128
+
129
+ test("a multi-byte character split across output chunks arrives intact", async () => {
130
+ // The first byte of "ä" (0xC3), a pause so the pipe delivers it as its own chunk, then 0xA4.
131
+ const r = await handle.runCommand("printf 'Gr\\303'; sleep 0.3; printf '\\244\\303'; sleep 0.3; printf '\\274'; printf '\\303' >&2; sleep 0.3; printf '\\266' >&2");
132
+ expect(r.stdout.startsWith("Gräü")).toBe(true);
133
+ expect(r.stderr).toBe("ö");
134
+ expect(r.stdout).not.toContain("�");
135
+ });
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Skill actions are pinned from the bytes downloaded from skill storage, never re-read from
3
+ * the session copy the agent can write. Real (direct-exec) sandbox, S3 mocked, no persistence.
4
+ */
5
+ jest.mock("@anthropic-ai/sandbox-runtime", () => ({
6
+ SandboxManager: {
7
+ initialize: jest.fn(async () => {}),
8
+ wrapWithSandbox: jest.fn(async (cmd: string) => cmd),
9
+ reset: jest.fn(async () => {}),
10
+ },
11
+ }));
12
+ jest.mock("@SRC/uppy/index.ts", () => ({
13
+ listS3ObjectsByPrefix: jest.fn(),
14
+ getS3ObjectBytes: jest.fn(),
15
+ uploadFile: jest.fn(async (_c: Buffer, key: string) => `bucket/${key}`),
16
+ getPresignedUrl: jest.fn(async () => "https://signed"),
17
+ }));
18
+ jest.mock("@SRC/postgres/client", () => ({
19
+ postgresClient: jest.fn(async () => ({ db: { from: () => ({ select: async () => [] }) } })),
20
+ }));
21
+ jest.mock("@SRC/exulu/system-dependencies.ts", () => ({ getNpmGlobalRoot: jest.fn(async () => null) }));
22
+ jest.mock("@SRC/utils/python-setup.ts", () => ({ getPythonVenvPath: () => undefined }));
23
+
24
+ import { promises as fs } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { getS3ObjectBytes, listS3ObjectsByPrefix } from "@SRC/uppy/index.ts";
27
+ import { createSessionSandbox, refreshSessionSkills, type SessionSandboxHandle, type SkillRef } from "./create-sandbox";
28
+ import { loadSkillActions } from "./skill-actions/load";
29
+
30
+ const config = { fileUploads: { s3Bucket: "bucket" } } as any;
31
+
32
+ const actionsYaml = (name: string, context = "deals") => `version: 1
33
+ actions:
34
+ ${name}:
35
+ description: Does ${name}.
36
+ run: python3 "$EXULU_SKILL_DIR/run.py"
37
+ inputs:
38
+ deal:
39
+ type: item
40
+ context: ${context}
41
+ `;
42
+
43
+ /** S3 key -> bytes. Skill files live under skills/<id>/v<version>/. */
44
+ let store: Map<string, Buffer>;
45
+ const put = (skill: SkillRef, version: number, files: Record<string, string>) => {
46
+ for (const [rel, text] of Object.entries(files)) store.set(`skills/${skill.id}/v${version}/${rel}`, Buffer.from(text));
47
+ };
48
+
49
+ let sessionId: string;
50
+ let handle: SessionSandboxHandle | undefined;
51
+ const turn = async (skills: SkillRef[]) => {
52
+ handle = await createSessionSandbox(sessionId, skills, config, undefined, undefined, { projectId: null });
53
+ return handle;
54
+ };
55
+ const actionsOf = (h: SessionSandboxHandle, skills: SkillRef[]) => loadSkillActions(h.sessionDir, skills, h.skillActions);
56
+
57
+ beforeEach(() => {
58
+ store = new Map();
59
+ (listS3ObjectsByPrefix as jest.Mock).mockImplementation(async (prefix: string) =>
60
+ [...store.keys()].filter((k) => k.startsWith(prefix)).map((key) => ({ key })),
61
+ );
62
+ (getS3ObjectBytes as jest.Mock).mockImplementation(async (key: string) => {
63
+ const bytes = store.get(key);
64
+ if (!bytes) throw new Error(`no object ${key}`);
65
+ return bytes;
66
+ });
67
+ jest.spyOn(console, "warn").mockImplementation(() => {});
68
+ jest.spyOn(console, "log").mockImplementation(() => {});
69
+ sessionId = `jest-skillactions-${process.pid}-${Math.random().toString(36).slice(2)}`;
70
+ handle = undefined;
71
+ });
72
+ afterEach(async () => {
73
+ await handle?.cleanup();
74
+ jest.restoreAllMocks();
75
+ });
76
+
77
+ const plain: SkillRef = { id: "s-plain", name: "plain", s3folder: "skills/s-plain", current_version: 1 };
78
+ const exporter: SkillRef = { id: "s-export", name: "exporter", s3folder: "skills/s-export", current_version: 1 };
79
+
80
+ test("an actions.yaml written into the session copy after download adds no action", async () => {
81
+ put(plain, 1, { "SKILL.md": "# plain" });
82
+ const h = await turn([plain]);
83
+ const file = join(h.sessionDir, "skills", "plain", "actions.yaml");
84
+ await fs.writeFile(file, actionsYaml("steal", "secrets"));
85
+ // The agent's own writeFile refuses the path (skills/ is read-only in a session);
86
+ // the direct write above stands in for degraded mode, where bash can still write it.
87
+ await expect(
88
+ (h.tools.writeFile as any).execute(
89
+ { path: "skills/plain/actions.yaml", content: actionsYaml("steal", "secrets") },
90
+ { toolCallId: "t", messages: [] },
91
+ ),
92
+ ).rejects.toThrow(/read-only/);
93
+ const next = await turn([plain]); // cache hit, same version: nothing is re-downloaded
94
+ expect(next).toBe(h);
95
+ expect(await fs.readFile(file, "utf8")).toContain("steal");
96
+ expect(actionsOf(next, [plain])).toEqual({ bySkill: {}, problems: [] });
97
+ });
98
+
99
+ test("modifying, replacing with a link or deleting the session copy leaves the pinned action intact", async () => {
100
+ put(exporter, 1, { "SKILL.md": "# exporter", "actions.yaml": actionsYaml("export") });
101
+ const h = await turn([exporter]);
102
+ const file = join(h.sessionDir, "skills", "exporter", "actions.yaml");
103
+ const expectPinned = async () => {
104
+ const loaded = actionsOf(await turn([exporter]), [exporter]);
105
+ expect(Object.keys(loaded.bySkill.exporter!.actions)).toEqual(["export"]);
106
+ expect(loaded.bySkill.exporter!.actions.export!.inputs.deal).toMatchObject({ context: "deals" });
107
+ expect(loaded.bySkill.exporter!.skillDir).toBe(join(h.sessionDir, "skills", "exporter"));
108
+ expect(loaded.problems).toEqual([]);
109
+ };
110
+ await expectPinned();
111
+
112
+ await fs.writeFile(file, actionsYaml("other", "secrets"));
113
+ await expectPinned();
114
+
115
+ await fs.rm(file);
116
+ const decoy = join(h.sessionDir, "decoy.yaml");
117
+ await fs.writeFile(decoy, actionsYaml("linked", "secrets"));
118
+ await fs.symlink(decoy, file);
119
+ await expectPinned();
120
+
121
+ await fs.rm(file);
122
+ await expectPinned();
123
+ });
124
+
125
+ test("a nested actions.yaml in the download declares nothing", async () => {
126
+ put(plain, 1, { "SKILL.md": "# plain", "scripts/actions.yaml": actionsYaml("nested") });
127
+ const h = await turn([plain]);
128
+ expect(actionsOf(h, [plain])).toEqual({ bySkill: {}, problems: [] });
129
+ });
130
+
131
+ test("a version change replaces the pinned declaration from the new bytes", async () => {
132
+ put(exporter, 1, { "actions.yaml": actionsYaml("export") });
133
+ put(exporter, 2, { "actions.yaml": actionsYaml("export_v2") });
134
+ put(exporter, 3, { "SKILL.md": "# no actions any more" });
135
+ await turn([exporter]);
136
+
137
+ const v2 = { ...exporter, current_version: 2 };
138
+ let loaded = actionsOf(await turn([v2]), [v2]);
139
+ expect(Object.keys(loaded.bySkill.exporter!.actions)).toEqual(["export_v2"]);
140
+
141
+ const v3 = { ...exporter, current_version: 3 };
142
+ loaded = actionsOf(await turn([v3]), [v3]);
143
+ expect(loaded).toEqual({ bySkill: {}, problems: [] });
144
+ });
145
+
146
+ test("reloading the skills re-pins from the re-downloaded bytes", async () => {
147
+ put(exporter, 1, { "actions.yaml": actionsYaml("export") });
148
+ const h = await turn([exporter]);
149
+ put(exporter, 1, { "actions.yaml": actionsYaml("reloaded") });
150
+ await fs.writeFile(join(h.sessionDir, "skills", "exporter", "actions.yaml"), actionsYaml("planted"));
151
+ expect(await refreshSessionSkills(sessionId, [exporter], config)).toEqual({ refreshed: 1, sandbox: true });
152
+ expect(Object.keys(actionsOf(h, [exporter]).bySkill.exporter!.actions)).toEqual(["reloaded"]);
153
+ });
154
+
155
+ test("a skill no longer enabled contributes no actions", async () => {
156
+ put(exporter, 1, { "actions.yaml": actionsYaml("export") });
157
+ put(plain, 1, { "SKILL.md": "# plain" });
158
+ await turn([exporter, plain]);
159
+ const h = await turn([plain]);
160
+ expect(actionsOf(h, [plain])).toEqual({ bySkill: {}, problems: [] });
161
+ });
162
+
163
+ test("an invalid downloaded actions.yaml yields a problem entry and no actions", async () => {
164
+ put(exporter, 1, { "actions.yaml": "version: 2\n" });
165
+ const h = await turn([exporter]);
166
+ const loaded = actionsOf(h, [exporter]);
167
+ expect(loaded.bySkill).toEqual({});
168
+ expect(loaded.problems).toEqual([{ skill: "exporter", error: expect.any(String) }]);
169
+ });
170
+
171
+ test("a skill with a path-like name and no actions.yaml yields no problem", async () => {
172
+ const odd: SkillRef = { id: "s-odd", name: "Vertrieb/Angebote", s3folder: "skills/s-odd", current_version: 1 };
173
+ put(odd, 1, { "SKILL.md": "# odd" });
174
+ const h = await turn([odd]);
175
+ expect(actionsOf(h, [odd])).toEqual({ bySkill: {}, problems: [] });
176
+ });