@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.
@@ -2,7 +2,7 @@ import { constants } from 'node:fs'
2
2
  import { lstat, mkdir, open, readlink, realpath, rename, unlink, writeFile } from 'node:fs/promises'
3
3
  import { randomBytes } from 'node:crypto'
4
4
  import { discardEntry } from './project-sync'
5
- import { dirname, isAbsolute, join, sep } from 'node:path'
5
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'
6
6
  import { MAX_ADOPT_UPLOAD_BYTES } from '@SRC/exulu/session-file-adopt'
7
7
 
8
8
  /**
@@ -151,12 +151,24 @@ async function ensureDirInside(sessionDir: string, segments: string[]): Promise<
151
151
  * exclusive temp file in the same directory which is then renamed over the
152
152
  * destination: rename replaces a link planted at the destination instead of
153
153
  * writing through it. Returns the absolute destination path.
154
+ *
155
+ * `opts.notUnder` (a session-relative directory, e.g. "skills"): refuse when the
156
+ * destination really lands there (landsInside), checked again after the parents
157
+ * exist, so a parent swapped for a link in between is caught too.
154
158
  */
155
- export async function writeFileInside(sessionDir: string, relativePath: string, bytes: Buffer | string): Promise<string> {
159
+ export async function writeFileInside(
160
+ sessionDir: string,
161
+ relativePath: string,
162
+ bytes: Buffer | string,
163
+ opts: { notUnder?: string } = {},
164
+ ): Promise<string> {
156
165
  const segments = safeSegments(relativePath)
157
166
  const name = segments[segments.length - 1]!
158
167
  const parent = await ensureDirInside(sessionDir, segments.slice(0, -1))
159
168
  const destination = join(parent, name)
169
+ if (opts.notUnder !== undefined && (await landsInside(sessionDir, destination, opts.notUnder))) {
170
+ throw new UnsafeSessionPathError(`Refusing to write ${destination}: it lands in ${opts.notUnder}/.`)
171
+ }
160
172
  const temp = join(parent, `.exulu-write-${randomBytes(8).toString('hex')}`)
161
173
  // 'wx' = O_CREAT | O_EXCL: never opens an existing entry (link or not).
162
174
  await writeFile(temp, bytes, { flag: 'wx' })
@@ -214,3 +226,50 @@ export async function removeEntryInside(sessionDir: string, relativePath: string
214
226
  // moved copy with an fd-based rm that a process still inside cannot steer.
215
227
  await discardEntry(target, sessionDir)
216
228
  }
229
+
230
+ /** Symlink hops followed before giving up, as the kernel's own limit (MAXSYMLINKS = 40). */
231
+ const MAX_LINK_HOPS = 40
232
+
233
+ /**
234
+ * Where a write to `path` would really land: links are followed the way the kernel
235
+ * follows them when it creates a file, including a final link whose target does not
236
+ * exist yet (writing through a dangling link creates its target). Throws ELOOP past
237
+ * MAX_LINK_HOPS and passes on any error other than a missing component.
238
+ */
239
+ async function realLocation(path: string, hops = { n: 0 }): Promise<string> {
240
+ try {
241
+ return await realpath(path)
242
+ } catch (err) {
243
+ if (errCode(err) !== 'ENOENT') throw err
244
+ }
245
+ const st = await lstat(path).catch((err) => (errCode(err) === 'ENOENT' ? null : Promise.reject(err)))
246
+ if (st?.isSymbolicLink()) {
247
+ if (++hops.n > MAX_LINK_HOPS) throw Object.assign(new Error(`Too many links resolving ${path}`), { code: 'ELOOP' })
248
+ return realLocation(resolve(dirname(path), await readlink(path)), hops)
249
+ }
250
+ const parent = dirname(path)
251
+ if (parent === path) return path
252
+ return join(await realLocation(parent, hops), basename(path))
253
+ }
254
+
255
+ /**
256
+ * Whether a write to `path` (absolute) would land in `<sessionDir>/<relativeDir>` or
257
+ * below it, judged by where it really lands: `..` segments, links (also dangling ones)
258
+ * and a session directory reached through a link are all resolved first. A path that
259
+ * cannot be resolved (a link cycle, no permission) counts as inside, so a caller that
260
+ * refuses on true refuses it; one blocked by a file in the way (ENOTDIR) cannot be
261
+ * written at all and counts as outside.
262
+ *
263
+ * A check, not a lock: the agent can change links after it returns. Callers rely on it
264
+ * for a clear refusal before touching disk; the sandbox policy is what enforces.
265
+ */
266
+ export async function landsInside(sessionDir: string, path: string, relativeDir: string): Promise<boolean> {
267
+ const segments = safeSegments(relativeDir)
268
+ try {
269
+ const entry = await realLocation(join(sessionDir, ...segments))
270
+ const target = await realLocation(resolve(path))
271
+ return isInside(entry, target)
272
+ } catch (err) {
273
+ return errCode(err) !== 'ENOTDIR'
274
+ }
275
+ }
@@ -0,0 +1,88 @@
1
+ import { join } from "node:path";
2
+ import { declarationFromBytes, describeActions, loadSkillActions, type PinnedSkillActions } from "./load";
3
+
4
+ const VALID = `version: 1
5
+ actions:
6
+ export:
7
+ description: Writes the workbook.
8
+ run: python export.py
9
+ inputs:
10
+ deal:
11
+ type: item
12
+ context: deals
13
+ description: The deal
14
+ notes:
15
+ type: text
16
+ required: false
17
+ rows:
18
+ type: items
19
+ context: rows
20
+ `;
21
+
22
+ const sessionDir = "/tmp/exulu-sessions/s1";
23
+ const skill = (name: string, version = 1) => ({ id: `id-${name}`, name, current_version: version });
24
+ const pin = (name: string, bytes: string | undefined, version = 1): [string, PinnedSkillActions] => [
25
+ `id-${name}`,
26
+ {
27
+ skillId: `id-${name}`,
28
+ name,
29
+ version,
30
+ declaration: declarationFromBytes(bytes === undefined ? undefined : Buffer.from(bytes)),
31
+ },
32
+ ];
33
+
34
+ describe("declarationFromBytes", () => {
35
+ it("no file is none, a valid one is ok, an invalid or oversized one is a problem", () => {
36
+ expect(declarationFromBytes(undefined)).toEqual({ kind: "none" });
37
+ expect(declarationFromBytes(Buffer.from(VALID)).kind).toBe("ok");
38
+ expect(declarationFromBytes(Buffer.from("version: 2\n")).kind).toBe("problem");
39
+ const big = declarationFromBytes(Buffer.from("#" + "x".repeat(70 * 1024)));
40
+ expect(big).toEqual({ kind: "problem", error: expect.stringContaining("exceeds") });
41
+ });
42
+ });
43
+
44
+ describe("loadSkillActions", () => {
45
+ it("loads valid pins, reports invalid ones, ignores skills without a file", () => {
46
+ const pinned = new Map([pin("a", VALID), pin("b", "version: 2\n"), pin("c", undefined)]);
47
+ const loaded = loadSkillActions(sessionDir, [skill("a"), skill("b"), skill("c")], pinned);
48
+ expect(Object.keys(loaded.bySkill)).toEqual(["a"]);
49
+ expect(loaded.bySkill.a!.skillDir).toBe(join(sessionDir, "skills", "a"));
50
+ expect(loaded.problems.map((p) => p.skill)).toEqual(["b"]);
51
+ const text = describeActions(loaded);
52
+ expect(text).toContain("a / export — Writes the workbook.");
53
+ expect(text).toContain(" deal (item, context deals) — The deal");
54
+ expect(text).toContain(" notes (text, optional)");
55
+ expect(text).not.toContain("notes (text, optional) —");
56
+ expect(text).toContain(" rows (items, context rows)");
57
+ expect(text).toContain('skill "b": actions.yaml ignored —');
58
+ });
59
+
60
+ it("a skill with a path-like name and no actions.yaml contributes nothing and no problem", () => {
61
+ const names = ["../x", "a/b", "a\\b", ".."];
62
+ const pinned = new Map(names.map((n) => pin(n, undefined)));
63
+ const loaded = loadSkillActions(sessionDir, names.map((n) => skill(n)), pinned);
64
+ expect(loaded).toEqual({ bySkill: {}, problems: [] });
65
+ });
66
+
67
+ it("a skill with a path-like name that ships actions.yaml gets a problem, never actions", () => {
68
+ const pinned = new Map([pin("a/b", VALID)]);
69
+ const loaded = loadSkillActions(sessionDir, [skill("a/b")], pinned);
70
+ expect(loaded.bySkill).toEqual({});
71
+ expect(loaded.problems.map((p) => p.skill)).toEqual(["a/b"]);
72
+ });
73
+
74
+ it("only enabled skills with a pin of their current name and version contribute", () => {
75
+ const pinned = new Map([pin("a", VALID, 1), pin("b", VALID), pin("old", VALID)]);
76
+ const loaded = loadSkillActions(
77
+ sessionDir,
78
+ [skill("a", 2), skill("b"), { id: "id-old", name: "renamed", current_version: 1 }, skill("never-pinned")],
79
+ pinned,
80
+ );
81
+ expect(Object.keys(loaded.bySkill)).toEqual(["b"]);
82
+ expect(loaded.problems).toEqual([]);
83
+ });
84
+
85
+ it("describeActions is empty when nothing is declared", () => {
86
+ expect(describeActions({ bySkill: {}, problems: [] })).toBe("");
87
+ });
88
+ });
@@ -0,0 +1,107 @@
1
+ import { join } from "node:path";
2
+ import { ACTIONS_FILE, ACTIONS_MAX_BYTES, parseActionsYaml, type SkillAction } from "./schema";
3
+
4
+ export type LoadedSkillActions = {
5
+ bySkill: Record<string, { skillDir: string; actions: Record<string, SkillAction> }>;
6
+ problems: Array<{ skill: string; error: string }>;
7
+ };
8
+
9
+ /**
10
+ * A skill's action declaration as parsed from the bytes the platform downloaded
11
+ * from skill storage. "none" = the skill version ships no actions.yaml.
12
+ */
13
+ export type ActionsDeclaration =
14
+ | { kind: "none" }
15
+ | { kind: "ok"; actions: Record<string, SkillAction> }
16
+ | { kind: "problem"; error: string };
17
+
18
+ /**
19
+ * One skill's pinned declaration, kept on the cached session sandbox. It is set
20
+ * only when the skill's files are (re)downloaded and never re-read from the
21
+ * session directory, so a file the agent writes at skills/<name>/actions.yaml
22
+ * has no effect on which actions exist or what they read.
23
+ */
24
+ export type PinnedSkillActions = {
25
+ skillId: string;
26
+ name: string;
27
+ version: number;
28
+ declaration: ActionsDeclaration;
29
+ };
30
+
31
+ /** Parses the downloaded actions.yaml bytes (undefined = the skill has none). Never throws. */
32
+ export const declarationFromBytes = (bytes: Buffer | undefined): ActionsDeclaration => {
33
+ if (bytes === undefined) return { kind: "none" };
34
+ try {
35
+ if (bytes.length > ACTIONS_MAX_BYTES) {
36
+ return { kind: "problem", error: `${ACTIONS_FILE} exceeds ${ACTIONS_MAX_BYTES} bytes` };
37
+ }
38
+ const parsed = parseActionsYaml(bytes.toString("utf8"));
39
+ return parsed.ok ? { kind: "ok", actions: parsed.actions } : { kind: "problem", error: parsed.error };
40
+ } catch (err) {
41
+ return {
42
+ kind: "problem",
43
+ error: `${ACTIONS_FILE} could not be loaded: ${err instanceof Error ? err.message : String(err)}`,
44
+ };
45
+ }
46
+ };
47
+
48
+ const isPlainName = (name: unknown): name is string =>
49
+ typeof name === "string" &&
50
+ name !== "" &&
51
+ name !== "." &&
52
+ name !== ".." &&
53
+ !name.includes("/") &&
54
+ !name.includes("\\") &&
55
+ !name.includes("\0") &&
56
+ !name.includes("..");
57
+
58
+ /**
59
+ * The actions of this turn's enabled skills, from the pinned declarations only
60
+ * (never from disk). A skill contributes only when its pin matches its current
61
+ * id, name and version; anything else (not downloaded on this sandbox, a sync
62
+ * that failed, a renamed skill) contributes nothing. A skill without an
63
+ * actions.yaml contributes nothing and no problem, whatever its name.
64
+ */
65
+ export const loadSkillActions = (
66
+ sessionDir: string,
67
+ skills: Array<{ id: string; name: string; current_version: number }>,
68
+ pinned: ReadonlyMap<string, PinnedSkillActions>,
69
+ ): LoadedSkillActions => {
70
+ const result: LoadedSkillActions = { bySkill: {}, problems: [] };
71
+ for (const skill of skills) {
72
+ const pin = pinned.get(skill.id);
73
+ if (!pin || pin.version !== skill.current_version || pin.name !== skill.name) continue;
74
+ const { declaration } = pin;
75
+ if (declaration.kind === "none") continue;
76
+ if (!isPlainName(skill.name)) {
77
+ result.problems.push({
78
+ skill: String(skill.name),
79
+ error: "the skill's name contains a path separator or \"..\", so it cannot declare actions",
80
+ });
81
+ continue;
82
+ }
83
+ if (declaration.kind === "problem") {
84
+ result.problems.push({ skill: skill.name, error: declaration.error });
85
+ continue;
86
+ }
87
+ result.bySkill[skill.name] = { skillDir: join(sessionDir, "skills", skill.name), actions: declaration.actions };
88
+ }
89
+ return result;
90
+ };
91
+
92
+ export const describeActions = (loaded: LoadedSkillActions): string => {
93
+ const lines: string[] = [];
94
+ for (const [skill, { actions }] of Object.entries(loaded.bySkill)) {
95
+ for (const [actionName, action] of Object.entries(actions)) {
96
+ lines.push(`${skill} / ${actionName} — ${action.description}`);
97
+ for (const [inputName, input] of Object.entries(action.inputs)) {
98
+ let qualifiers = input.type;
99
+ if (input.type === "item" || input.type === "items") qualifiers += `, context ${input.context}`;
100
+ if (input.type === "text" && !input.required) qualifiers += ", optional";
101
+ lines.push(` ${inputName} (${qualifiers})${input.description ? ` — ${input.description}` : ""}`);
102
+ }
103
+ }
104
+ }
105
+ for (const p of loaded.problems) lines.push(`skill "${p.skill}": actions.yaml ignored — ${p.error}`);
106
+ return lines.join("\n");
107
+ };
@@ -0,0 +1,72 @@
1
+ import { parseActionsYaml, ACTIONS_MAX_BYTES } from "./schema";
2
+
3
+ const VALID = `version: 1
4
+ actions:
5
+ export:
6
+ description: Writes the workbook.
7
+ run: python3 "$EXULU_SKILL_DIR/scripts/export.py"
8
+ inputs:
9
+ pitch: { type: item, context: mv_pitches, fields: [felder] }
10
+ note: { type: text, required: false }
11
+ `;
12
+
13
+ describe("parseActionsYaml", () => {
14
+ test("valid file", () => {
15
+ const r = parseActionsYaml(VALID);
16
+ expect(r.ok && r.actions.export.timeoutSeconds).toBe(60);
17
+ expect(r.ok && r.actions.export.inputs.note).toEqual({ type: "text", required: false });
18
+ expect(r.ok && r.actions.export.inputs.pitch).toEqual({
19
+ type: "item",
20
+ context: "mv_pitches",
21
+ fields: ["felder"],
22
+ });
23
+ });
24
+
25
+ test("text input is required by default", () => {
26
+ const r = parseActionsYaml(VALID.replace(", required: false", ""));
27
+ expect(r.ok && (r.actions.export.inputs.note as any).required).toBe(true);
28
+ });
29
+
30
+ test("items input accepts a fixed where object", () => {
31
+ const r = parseActionsYaml(
32
+ VALID.replace("note:", "rows: { type: items, context: c, where: { status: open } }\n note:"),
33
+ );
34
+ expect(r.ok && r.actions.export.inputs.rows).toEqual({
35
+ type: "items",
36
+ context: "c",
37
+ where: { status: "open" },
38
+ });
39
+ });
40
+
41
+ test("timeout_seconds maps to timeoutSeconds", () => {
42
+ const r = parseActionsYaml(VALID.replace(" inputs:", " timeout_seconds: 300\n inputs:"));
43
+ expect(r.ok && r.actions.export.timeoutSeconds).toBe(300);
44
+ });
45
+
46
+ test.each([
47
+ ["wrong version", VALID.replace("version: 1", "version: 2")],
48
+ ["unknown top-level key", VALID + "extra: 1\n"],
49
+ ["unknown action key", VALID.replace(" run:", " rnu: x\n run:")],
50
+ ["bad action name", VALID.replace(" export:", " Export-1:")],
51
+ ["unknown input type", VALID.replace("type: text", "type: file")],
52
+ ["item without context", VALID.replace("context: mv_pitches, ", "")],
53
+ ["timeout above 300", VALID.replace(" inputs:", " timeout_seconds: 301\n inputs:")],
54
+ ["timeout zero", VALID.replace(" inputs:", " timeout_seconds: 0\n inputs:")],
55
+ ["not yaml", "{{{"],
56
+ ["oversized", VALID + "#".repeat(ACTIONS_MAX_BYTES)],
57
+ ])("refuses: %s", (_n, text) => {
58
+ const r = parseActionsYaml(text);
59
+ expect(r.ok).toBe(false);
60
+ expect(!r.ok && r.error.length).toBeGreaterThan(0);
61
+ });
62
+
63
+ test("accepts exactly 20 actions and refuses 21", () => {
64
+ const build = (n: number) =>
65
+ "version: 1\nactions:\n" +
66
+ Array.from({ length: n }, (_, i) => ` a${i}:\n description: d\n run: echo\n`).join("");
67
+ expect(parseActionsYaml(build(20)).ok).toBe(true);
68
+ const r = parseActionsYaml(build(21));
69
+ expect(r.ok).toBe(false);
70
+ expect(!r.ok && r.error.length).toBeGreaterThan(0);
71
+ });
72
+ });
@@ -0,0 +1,97 @@
1
+ import { parse } from "yaml";
2
+ import { z } from "zod";
3
+
4
+ export type ActionInput =
5
+ | { type: "item"; context: string; fields?: string[]; description?: string }
6
+ | {
7
+ type: "items";
8
+ context: string;
9
+ fields?: string[];
10
+ where?: Record<string, unknown>;
11
+ description?: string;
12
+ }
13
+ | { type: "text"; required: boolean; description?: string };
14
+
15
+ export type SkillAction = {
16
+ description: string;
17
+ run: string;
18
+ timeoutSeconds: number;
19
+ inputs: Record<string, ActionInput>;
20
+ };
21
+
22
+ export const ACTIONS_FILE = "actions.yaml";
23
+ export const ACTIONS_MAX_BYTES = 64 * 1024;
24
+ export const ACTION_INPUT_TYPES = ["item", "items", "text"] as const;
25
+
26
+ export const MAX_ACTIONS = 20;
27
+ const NAME = /^[a-z][a-z0-9_]{0,39}$/;
28
+ const nameMessage = "must match ^[a-z][a-z0-9_]{0,39}$";
29
+
30
+ const inputSchema = z.discriminatedUnion("type", [
31
+ z.strictObject({
32
+ type: z.literal("item"),
33
+ context: z.string().min(1),
34
+ fields: z.array(z.string()).optional(),
35
+ description: z.string().optional(),
36
+ }),
37
+ z.strictObject({
38
+ type: z.literal("items"),
39
+ context: z.string().min(1),
40
+ fields: z.array(z.string()).optional(),
41
+ where: z.record(z.string(), z.unknown()).optional(),
42
+ description: z.string().optional(),
43
+ }),
44
+ z.strictObject({
45
+ type: z.literal("text"),
46
+ required: z.boolean().default(true),
47
+ description: z.string().optional(),
48
+ }),
49
+ ]);
50
+
51
+ const actionSchema = z
52
+ .strictObject({
53
+ description: z.string().min(1),
54
+ run: z.string().min(1),
55
+ timeout_seconds: z.number().int().min(1).max(300).default(60),
56
+ inputs: z.record(z.string().regex(NAME, nameMessage), inputSchema).default({}),
57
+ })
58
+ .transform(({ timeout_seconds, ...rest }): SkillAction => ({
59
+ description: rest.description,
60
+ run: rest.run,
61
+ timeoutSeconds: timeout_seconds,
62
+ inputs: rest.inputs as Record<string, ActionInput>,
63
+ }));
64
+
65
+ const fileSchema = z.strictObject({
66
+ version: z.literal(1),
67
+ actions: z
68
+ .record(z.string().regex(NAME, nameMessage), actionSchema)
69
+ .refine((a) => Object.keys(a).length <= MAX_ACTIONS, {
70
+ message: `at most ${MAX_ACTIONS} actions per skill`,
71
+ }),
72
+ });
73
+
74
+ export const parseActionsYaml = (
75
+ text: string,
76
+ ): { ok: true; actions: Record<string, SkillAction> } | { ok: false; error: string } => {
77
+ try {
78
+ if (Buffer.byteLength(text, "utf8") > ACTIONS_MAX_BYTES) {
79
+ return { ok: false, error: `${ACTIONS_FILE} exceeds ${ACTIONS_MAX_BYTES} bytes` };
80
+ }
81
+ let raw: unknown;
82
+ try {
83
+ raw = parse(text);
84
+ } catch (e: any) {
85
+ return { ok: false, error: `invalid YAML: ${e?.message ?? String(e)}` };
86
+ }
87
+ const result = fileSchema.safeParse(raw);
88
+ if (!result.success) {
89
+ const issue = result.error.issues[0];
90
+ const path = issue?.path.length ? issue.path.join(".") : "(root)";
91
+ return { ok: false, error: `${path}: ${issue?.message ?? "invalid"}` };
92
+ }
93
+ return { ok: true, actions: result.data.actions };
94
+ } catch (e: any) {
95
+ return { ok: false, error: e?.message ?? String(e) };
96
+ }
97
+ };