@exulu/backend 4.3.2 → 5.0.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.
@@ -1,9 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { microCall } from "./micro-call";
3
3
  import { withTiming } from "./timing";
4
- import { singleSearch } from "./multi-query";
5
4
  import { fuzzyPrefilter } from "./prefilter";
6
- import { deriveKeywordVariants, normalizeFileName, stripSeparators } from "./text-utils";
5
+ import { normalizeFileName } from "./text-utils";
7
6
  import type { Chunk, ChunkWithScore, MemoryPhaseResult, PhaseStep } from "./types";
8
7
 
9
8
  // ---------------------------------------------------------------------------
@@ -12,115 +11,6 @@ import type { Chunk, ChunkWithScore, MemoryPhaseResult, PhaseStep } from "./type
12
11
 
13
12
  const MEMORY_OVERRIDE_MIN_CONFIDENCE = "high";
14
13
  const MEMORY_SYNTHETIC_RERANK_SCORE = 1;
15
- const ITEM_CACHE_TTL_MS = 5 * 60 * 1000;
16
-
17
- // ---------------------------------------------------------------------------
18
- // 5-min item cache (keyed by memoryContext.id)
19
- // ---------------------------------------------------------------------------
20
-
21
- type MemoryItem = { id: string; name: string; description?: string; information?: string };
22
-
23
- let memoryItemCache = new Map<string, { items: MemoryItem[]; tsp: Date }>();
24
-
25
- export function clearMemoryItemCache(): void {
26
- memoryItemCache = new Map();
27
- }
28
-
29
- async function loadMemoryItems(context: {
30
- id: string;
31
- getItems: (o: any) => Promise<MemoryItem[]>;
32
- }): Promise<MemoryItem[]> {
33
- const cached = memoryItemCache.get(context.id);
34
- if (cached && Date.now() - cached.tsp.getTime() < ITEM_CACHE_TTL_MS) {
35
- return cached.items;
36
- }
37
- const items = await context.getItems({
38
- fields: ["id", "name", "description", "information"],
39
- filters: [],
40
- });
41
- memoryItemCache.set(context.id, { items, tsp: new Date() });
42
- return items;
43
- }
44
-
45
- // ---------------------------------------------------------------------------
46
- // Keyword recall (ported from newton-memory.ts:91-169)
47
- // ---------------------------------------------------------------------------
48
-
49
- export async function recallMemoryByKeywords({
50
- keywords,
51
- importantKeyword,
52
- user,
53
- role,
54
- memoryContext,
55
- timings,
56
- }: {
57
- keywords: string[];
58
- importantKeyword: string;
59
- user: any;
60
- role: any;
61
- memoryContext: { id: string; getItems: (o: any) => Promise<MemoryItem[]> };
62
- timings?: Record<string, number>;
63
- }): Promise<Chunk[]> {
64
- const allKeywords = [
65
- ...new Set(
66
- [importantKeyword, ...keywords].filter(
67
- (k): k is string => !!k && k.trim().length > 0,
68
- ),
69
- ),
70
- ];
71
- if (!allKeywords.length) return [];
72
-
73
- const importantVariants = importantKeyword
74
- ? [...new Set(deriveKeywordVariants(importantKeyword).map(stripSeparators))].filter(
75
- (v) => v.length >= 4,
76
- )
77
- : [];
78
- const allVariants = [
79
- ...new Set(allKeywords.flatMap(deriveKeywordVariants).map(stripSeparators)),
80
- ].filter((v) => v.length >= 4);
81
- if (!allVariants.length) return [];
82
-
83
- const items = await withTiming(timings, "memory.keywordRecall.itemsMs", () => loadMemoryItems(memoryContext));
84
-
85
- type Scored = { id: string; hits: number; importantHit: boolean; name: string };
86
- const scored: Scored[] = [];
87
- for (const item of items) {
88
- const haystack = stripSeparators(
89
- [item.name, item.description, item.information].filter(Boolean).join(" "),
90
- );
91
- if (!haystack) continue;
92
- const hits = allVariants.filter((v) => haystack.includes(v)).length;
93
- if (hits === 0) continue;
94
- const importantHit = importantVariants.some((v) => haystack.includes(v));
95
- scored.push({ id: item.id, hits, importantHit, name: item.name ?? "" });
96
- }
97
-
98
- scored.sort((a, b) => {
99
- if (a.importantHit !== b.importantHit) return a.importantHit ? -1 : 1;
100
- return b.hits - a.hits;
101
- });
102
- const topMatches = scored.slice(0, 25);
103
- if (!topMatches.length) return [];
104
-
105
- console.log(
106
- "[EXULU pipeline] keyword-triggered memory matches:",
107
- topMatches.map((s) => `${s.name} (hits=${s.hits}, important=${s.importantHit})`),
108
- );
109
-
110
- // Full-text only: the items were already selected by keyword above, so this
111
- // call just ranks their chunks. The hybrid method would add an embedding
112
- // round trip (0.5-1.2 s, up to 5 s cold) on the memory phase's critical path.
113
- const chunks = await withTiming(timings, "memory.keywordRecall.searchMs", () => singleSearch({
114
- query: allKeywords.join(", "),
115
- config: { method: "tsvector", cutoffs: undefined, limit: 50 },
116
- user,
117
- role,
118
- pinnedItemIds: topMatches.map((s) => s.id),
119
- context: memoryContext,
120
- }));
121
-
122
- return chunks;
123
- }
124
14
 
125
15
  // ---------------------------------------------------------------------------
126
16
  // Neutral result helper
@@ -290,7 +180,6 @@ function mergedFollowups(
290
180
  export async function runMemoryPhase({
291
181
  timings,
292
182
  memoryChunks,
293
- memoryContext,
294
183
  question,
295
184
  keywords,
296
185
  importantKeyword,
@@ -303,7 +192,6 @@ export async function runMemoryPhase({
303
192
  mergedCall = false,
304
193
  }: {
305
194
  memoryChunks: Chunk[];
306
- memoryContext?: any;
307
195
  question: string;
308
196
  keywords: string[];
309
197
  importantKeyword: string;
@@ -324,33 +212,12 @@ export async function runMemoryPhase({
324
212
  }): Promise<MemoryPhaseResult> {
325
213
  try {
326
214
  // Short-circuit: disabled, or nothing to work with
327
- if (!memoryConfig.enabled || (memoryChunks.length === 0 && !memoryContext)) {
215
+ if (!memoryConfig.enabled || memoryChunks.length === 0) {
328
216
  return neutralResult(question, keywords, importantKeyword);
329
217
  }
330
218
 
331
219
  const steps: PhaseStep[] = [];
332
- let retrieved_memory = [...memoryChunks];
333
-
334
- // Keyword recall: extend memory with items that match the user's keywords
335
- if (memoryContext) {
336
- try {
337
- const keywordMatched = await withTiming(timings, "memory.keywordRecallMs", () => recallMemoryByKeywords({
338
- keywords,
339
- importantKeyword,
340
- user,
341
- role,
342
- memoryContext,
343
- timings,
344
- }));
345
- if (keywordMatched.length > 0) {
346
- const seen = new Set(retrieved_memory.map((c) => c.chunk_id));
347
- const additions = keywordMatched.filter((c) => !seen.has(c.chunk_id));
348
- retrieved_memory = [...retrieved_memory, ...additions];
349
- }
350
- } catch (e) {
351
- console.error("[EXULU pipeline] keyword-triggered memory recall failed:", e);
352
- }
353
- }
220
+ const retrieved_memory = [...memoryChunks];
354
221
 
355
222
  // Step 1: Relevance check
356
223
  const CHECK_MEMORIES_FOR_RELEVANT_INFORMATION = `
@@ -425,11 +292,14 @@ export async function runMemoryPhase({
425
292
  }));
426
293
 
427
294
  if (relevantMemoryChunks.length > 0) {
295
+ // Names/ids only — the full chunk_content already rides along on
296
+ // `chunks` for the model; repeating it in `text` would put a second
297
+ // copy of the memory into the serialized tool result.
428
298
  steps.push({
429
299
  text:
430
- "Retrieved potentially relevant information from memory: " +
300
+ `Retrieved ${relevantMemoryChunks.length} potentially relevant ${relevantMemoryChunks.length === 1 ? "memory" : "memories"}: ` +
431
301
  relevantMemoryChunks
432
- .map((c) => `${c.item_name}: ${c.chunk_content}`)
302
+ .map((c) => `${c.item_name} (${c.item_id})`)
433
303
  .join(", "),
434
304
  chunks: memoryChunksForAnswer,
435
305
  });
@@ -5,6 +5,7 @@ import { fuzzyPrefilter } from "./prefilter";
5
5
  import { withTiming } from "./timing";
6
6
  import { applyRewrites } from "./text-utils";
7
7
  import type { Chunk } from "./types";
8
+ import { isEmbedderNotConfigured } from "@SRC/exulu/embedder-not-configured";
8
9
 
9
10
  /** Attach the source knowledge base to each chunk so citations and the chat UI can
10
11
  * attribute passages deterministically. Only memory chunks were labeled before; the
@@ -184,7 +185,13 @@ export async function searchContexts(opts: {
184
185
 
185
186
  return [];
186
187
  } catch (err) {
187
- console.warn(`[EXULU pipeline] searchContexts failed for context "${ctxId}":`, err);
188
+ if (isEmbedderNotConfigured(err)) {
189
+ console.warn(
190
+ `[EXULU pipeline] context "${ctxId}" is not searchable: ${(err as Error).message}`,
191
+ );
192
+ } else {
193
+ console.warn(`[EXULU pipeline] searchContexts failed for context "${ctxId}":`, err);
194
+ }
188
195
  return [];
189
196
  }
190
197
  })),
@@ -0,0 +1,78 @@
1
+ import { buildSkillSandboxEvent } from "@SRC/exulu/audit/emitters/skill-sandbox";
2
+ import { selectGrantedVariables } from "./variable-grants";
3
+ import type { Variable } from "@EXULU_TYPES/models/variable";
4
+
5
+ test("withheld names are the ungranted variable names, not their values", () => {
6
+ const all = ["JIRA_CLIENT_ID", "ANTHROPIC_API_KEY", "PERPLEXITY_API_KEY"];
7
+ const granted = ["JIRA_CLIENT_ID"];
8
+ const withheld = all.filter((n) => !granted.includes(n));
9
+ const e = buildSkillSandboxEvent({
10
+ skills: [], grantedNames: granted, withheldNames: withheld,
11
+ skippedNames: [], strippedSecretCount: 0, degradedSandbox: false,
12
+ } as any);
13
+ expect(e.data?.withheldVariableNames).toEqual(["ANTHROPIC_API_KEY", "PERPLEXITY_API_KEY"]);
14
+ });
15
+
16
+ // Carried forward from Task 5's review: "names only, never values" is
17
+ // convention, not enforcement — grantedNames/withheldNames/skippedNames are
18
+ // plain string[], and nothing in the types stops a call site passing values
19
+ // instead of names. This test proves that a real call site, fed rows whose
20
+ // VALUES are recognisable secrets, produces an event whose serialized form
21
+ // never contains those values — only the ungranted rows' NAMES, derived via
22
+ // the same row.name key-derivation getAllExuluVariables uses for
23
+ // withheldNames.
24
+ test("a real secret value on an ungranted row never reaches the emitted event", () => {
25
+ const rows: Variable[] = [
26
+ {
27
+ id: "1",
28
+ name: "JIRA_CLIENT_ID",
29
+ value: "jira-client-id-value",
30
+ encrypted: false,
31
+ allow_skill_access: true,
32
+ createdAt: "",
33
+ updatedAt: "",
34
+ },
35
+ {
36
+ id: "2",
37
+ name: "ANTHROPIC_API_KEY",
38
+ value: "sk-ant-SHOULD-NOT-APPEAR",
39
+ encrypted: false,
40
+ allow_skill_access: false,
41
+ createdAt: "",
42
+ updatedAt: "",
43
+ },
44
+ {
45
+ id: "3",
46
+ name: "PERPLEXITY_API_KEY",
47
+ value: "pplx-SHOULD-NOT-APPEAR-EITHER",
48
+ encrypted: false,
49
+ allow_skill_access: false,
50
+ createdAt: "",
51
+ updatedAt: "",
52
+ },
53
+ ];
54
+
55
+ const granted = selectGrantedVariables(rows);
56
+ const withheldNames = rows
57
+ .filter((row) => row?.name && !(row.name in granted))
58
+ .map((row) => row.name)
59
+ .sort();
60
+
61
+ const e = buildSkillSandboxEvent({
62
+ sessionID: "sess-1",
63
+ skills: [],
64
+ grantedNames: Object.keys(granted),
65
+ withheldNames,
66
+ skippedNames: [],
67
+ strippedSecretCount: 0,
68
+ degradedSandbox: false,
69
+ } as any);
70
+
71
+ const serialized = JSON.stringify(e);
72
+ expect(serialized).not.toContain("sk-ant-SHOULD-NOT-APPEAR");
73
+ expect(serialized).not.toContain("pplx-SHOULD-NOT-APPEAR-EITHER");
74
+ expect(serialized).not.toContain("jira-client-id-value");
75
+ // The point of the test, not just its side effect: the withheld names
76
+ // themselves (keys, never values) do make it through.
77
+ expect(e.data?.withheldVariableNames).toEqual(["ANTHROPIC_API_KEY", "PERPLEXITY_API_KEY"]);
78
+ });
@@ -0,0 +1,32 @@
1
+ const src: string = require("fs").readFileSync(
2
+ require("path").join(__dirname, "create-sandbox.ts"),
3
+ "utf8",
4
+ );
5
+
6
+ /**
7
+ * Source-text guards, not behaviour tests: both exec paths inherit the full
8
+ * parent environment if their `env` option is simply absent, and nothing in the
9
+ * type system notices. Deleting `env: sandboxedExecEnv` from either call is a
10
+ * silent, total regression of this branch, so each call site is asserted here.
11
+ */
12
+
13
+ test("the bash tool's execAsync call is given the constructed env", () => {
14
+ // This is the PRIMARY path — every command the bash tool runs goes through
15
+ // it. A guard that only covered the spawn would have let a deletion here
16
+ // through unnoticed.
17
+ const execCalls = [...src.matchAll(/execAsync\(\s*[\s\S]{0,300}?\)/g)];
18
+ expect(execCalls.length).toBeGreaterThan(0);
19
+ for (const call of execCalls) {
20
+ expect(call[0]).toContain("env: sandboxedExecEnv");
21
+ }
22
+ });
23
+
24
+ test("the writeFile spawn is given an explicit env, never the inherited one", () => {
25
+ // Guard against regression of the original leak-by-omission: the spawn
26
+ // passed no `env` at all.
27
+ const spawnCalls = [...src.matchAll(/spawn\(\s*['"]\/bin\/bash['"][\s\S]{0,200}?\)/g)];
28
+ expect(spawnCalls.length).toBeGreaterThan(0);
29
+ for (const call of spawnCalls) {
30
+ expect(call[0]).toContain("env: sandboxedExecEnv");
31
+ }
32
+ });
@@ -10,6 +10,11 @@ import { promisify } from 'node:util'
10
10
  import { listS3ObjectsByPrefix, getS3ObjectBytes, uploadFile, getPresignedUrl, type S3FileObject } from '@SRC/uppy/index.ts'
11
11
  import { isIgnoredArtifactPath, capArtifacts, needsDownload } from './artifact-filter'
12
12
  import { getNpmGlobalRoot } from '@SRC/exulu/system-dependencies.ts'
13
+ import { buildSkillEnv } from './skill-env'
14
+ import { selectGrantedVariables, selectRowsToDecrypt, deriveWithheldNames } from './variable-grants'
15
+ import { readLiteLLMOsEnvironNames } from '@SRC/exulu/litellm/os-environ-names'
16
+ import { getAuditLogger } from '@SRC/exulu/audit/logger'
17
+ import { buildSkillSandboxEvent } from '@SRC/exulu/audit/emitters/skill-sandbox'
13
18
  import type { ExuluConfig } from '@SRC/exulu/app/index.ts'
14
19
  import { createBashTool, type Sandbox } from "bash-tool";
15
20
  import { tool, type Tool } from "ai";
@@ -19,31 +24,46 @@ import CryptoJS from "crypto-js";
19
24
  import { postgresClient } from "@SRC/postgres/client";
20
25
 
21
26
  /**
22
- * Load every variable from the database with its decrypted value. Returns
23
- * a name → value map suitable for spreading into a child-process env.
27
+ * Load the variables an administrator has explicitly granted to the skill
28
+ * sandbox, decrypt only those, and report the withheld NAMES — never values —
29
+ * of every other row, so a broken skill is diagnosable from one log line.
30
+ *
31
+ * Filter before decrypting (per §1 of the design): rows are partitioned on
32
+ * `allow_skill_access === true` first, so a row nobody granted never has its
33
+ * ciphertext touched. `withheldNames` is derived from the UNFILTERED row-name
34
+ * list, which means a row whose decryption fails surfaces as withheld rather
35
+ * than vanishing from both sides of the report.
24
36
  *
25
37
  * Used by the skill sandbox to expose configured secrets to bash commands
26
38
  * (API keys, etc.) so skills can call external services without hard-coding
27
39
  * credentials. Decryption runs server-side; nothing encrypted leaves the
28
- * Node process.
40
+ * Node process. The grant filter (selectGrantedVariables) requires
41
+ * `allow_skill_access === true` — a row with no grant (including legacy rows
42
+ * with a null value from before this column existed) is never exposed.
29
43
  *
30
44
  * Variables whose name starts with `_` or contains `=` are skipped — those
31
45
  * shapes corrupt POSIX env parsing or shadow shell internals.
32
46
  */
33
- const getAllExuluVariables = async (): Promise<Record<string, string>> => {
47
+ const getAllExuluVariables = async (): Promise<{
48
+ granted: Record<string, string>;
49
+ withheldNames: string[];
50
+ }> => {
34
51
  const { db } = await postgresClient();
35
52
  const rows: Variable[] = await db.from("variables").select("*");
36
- const out: Record<string, string> = {};
37
- for (const row of rows) {
38
- if (!row?.name) continue;
39
- if (row.name.startsWith("_")) continue;
40
- if (row.name.includes("=")) continue;
53
+
54
+ // Partition before decrypting: only granted rows have their ciphertext
55
+ // touched. `rows` stays the basis for withheldNames below.
56
+ const decrypted: Variable[] = [];
57
+ for (const row of selectRowsToDecrypt(rows)) {
41
58
  let value = row.value;
42
59
  if (row.encrypted) {
43
60
  try {
44
61
  const bytes = CryptoJS.AES.decrypt(value, process.env.NEXTAUTH_SECRET);
45
62
  value = bytes.toString(CryptoJS.enc.Utf8);
46
63
  } catch (err) {
64
+ // Non-fatal, as before: this row simply is not available to
65
+ // skills. deriveWithheldNames works off the unfiltered `rows`,
66
+ // so it is reported as withheld rather than disappearing.
47
67
  console.error(
48
68
  `[VARIABLES] Failed to decrypt variable "${row.name}"; skipping.`,
49
69
  err,
@@ -51,16 +71,42 @@ const getAllExuluVariables = async (): Promise<Record<string, string>> => {
51
71
  continue;
52
72
  }
53
73
  }
54
- if (typeof value !== "string") continue;
55
- out[row.name] = value;
74
+ decrypted.push({ ...row, value });
56
75
  }
57
- return out;
76
+ const granted = selectGrantedVariables(decrypted);
77
+ return { granted, withheldNames: deriveWithheldNames(rows, granted) };
58
78
  }
59
79
 
60
80
  const execAsync = promisify(exec);
61
81
  // Sandbox commands can be very long (long deny lists) — bump default buffer.
62
82
  const EXEC_MAX_BUFFER = 32 * 1024 * 1024;
63
83
 
84
+ /**
85
+ * Provider credentials the deployment's config.litellm.yaml names via
86
+ * `os.environ/NAME`. Stripped from the skill environment alongside the static
87
+ * inventory, which closes the open-ended provider-credential class without
88
+ * turning the filter into an allowlist.
89
+ *
90
+ * Memoized: the config path is process-level state, and re-reading it on every
91
+ * sandbox creation would buy nothing. Best-effort by construction — the helper
92
+ * returns [] and logs if the config is missing or unreadable, so a sandbox
93
+ * never fails to build because of it.
94
+ */
95
+ let litellmSecretNamesCache: string[] | undefined;
96
+ const litellmConfigSecretNames = (): string[] => {
97
+ if (litellmSecretNamesCache === undefined) {
98
+ litellmSecretNamesCache = readLiteLLMOsEnvironNames();
99
+ if (litellmSecretNamesCache.length) {
100
+ // Names only, logged once, so a skill broken by this strip is
101
+ // diagnosable from one line (design §5).
102
+ console.log(
103
+ `[SKILLS] ${litellmSecretNamesCache.length} provider credential name(s) from config.litellm.yaml are withheld from skills: ${litellmSecretNamesCache.join(", ")}.`,
104
+ )
105
+ }
106
+ }
107
+ return litellmSecretNamesCache;
108
+ };
109
+
64
110
  /**
65
111
  * Probe whether bwrap can actually create a user namespace on this host.
66
112
  * SRT's own dependency check only verifies bwrap is installed, not that the
@@ -85,7 +131,7 @@ function probeSandboxSupport(): Promise<SandboxProbeResult> {
85
131
  // Minimal bwrap invocation: bind / read-only and exit. If the host
86
132
  // refuses unprivileged user namespaces, this returns
87
133
  // "Operation not permitted" — same path SRT would hit on every command.
88
- const child = spawn('bwrap', ['--dev-bind', '/', '/', '--', '/bin/true']);
134
+ const child = spawn('bwrap', ['--dev-bind', '/', '/', '--', '/bin/true'], { env: {} });
89
135
  let stderr = '';
90
136
  child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
91
137
  child.on('error', (err) => {
@@ -411,6 +457,12 @@ export async function createSessionSandbox(
411
457
  skills: SkillRef[],
412
458
  config: ExuluConfig,
413
459
  userId?: number | string,
460
+ /**
461
+ * The agent whose turn is building this sandbox, for the
462
+ * `skill.sandbox.created` audit event's §4 payload (id + name). Optional so
463
+ * callers outside the agent loop are unaffected.
464
+ */
465
+ agent?: { id?: string; name?: string; slug?: string },
414
466
  ): Promise<SessionSandboxHandle> {
415
467
  const cached = sandboxCache.get(sessionId)
416
468
 
@@ -584,8 +636,11 @@ export async function createSessionSandbox(
584
636
  // won't see the variables (an empty map is the same as nothing
585
637
  // configured).
586
638
  let configuredVariables: Record<string, string> = {}
639
+ let withheldNames: string[] = []
587
640
  try {
588
- configuredVariables = await getAllExuluVariables()
641
+ const loaded = await getAllExuluVariables()
642
+ configuredVariables = loaded.granted
643
+ withheldNames = loaded.withheldNames
589
644
  } catch (err) {
590
645
  console.error(
591
646
  `[SKILLS] Failed to load configured variables for session ${sessionId}; bash env will not include them.`,
@@ -593,20 +648,68 @@ export async function createSessionSandbox(
593
648
  )
594
649
  }
595
650
 
596
- // Environment for sandboxed bash invocations.
597
- // - Spread order matters: later spreads win.
598
- // - configuredVariables go first so process.env (PATH, HOME, etc.)
599
- // overrides them. If a variable accidentally collides with a system
600
- // env name, the system value stays authoritative.
601
- // - NODE_PATH is set last so it's always our resolved global root,
602
- // regardless of what process.env or variables already had.
603
- const sandboxedExecEnv: NodeJS.ProcessEnv = {
604
- ...configuredVariables,
605
- ...process.env,
606
- ...(npmGlobalRoot ? { NODE_PATH: npmGlobalRoot } : {}),
607
- ...(pythonVenvPath
608
- ? { PATH: `${join(pythonVenvPath, 'bin')}:${process.env.PATH ?? ''}`, VIRTUAL_ENV: pythonVenvPath }
609
- : {}),
651
+ // Environment for sandboxed bash invocations. buildSkillEnv is the only
652
+ // place this is composed: base runtime env (platform secrets stripped —
653
+ // both the static inventory and the deployment's own
654
+ // config.litellm.yaml `os.environ/` names) → granted variables → computed
655
+ // overrides (NODE_PATH / venv PATH last, so they always win regardless of
656
+ // what process.env or variables already had).
657
+ const { env: sandboxedExecEnv, strippedSecretNames, grantedNames, skippedNames } =
658
+ buildSkillEnv({
659
+ processEnv: process.env,
660
+ grantedVariables: configuredVariables,
661
+ extraSecretNames: litellmConfigSecretNames(),
662
+ overrides: {
663
+ ...(npmGlobalRoot ? { NODE_PATH: npmGlobalRoot } : {}),
664
+ ...(pythonVenvPath
665
+ ? { PATH: `${join(pythonVenvPath, 'bin')}:${process.env.PATH ?? ''}`, VIRTUAL_ENV: pythonVenvPath }
666
+ : {}),
667
+ },
668
+ })
669
+
670
+ if (skippedNames.length) {
671
+ console.warn(
672
+ `[SKILLS] Skipped ${skippedNames.length} variable(s) for session ${sessionId}: ${skippedNames.join(", ")} (invalid env name or collides with a runtime key).`,
673
+ )
674
+ }
675
+
676
+ // One audit event per sandbox creation, gated by
677
+ // sources.skillSandbox.enabled (off by default — see
678
+ // src/exulu/audit/config.ts). Every name array below is key-derived —
679
+ // grantedNames/skippedNames come from buildSkillEnv, withheldNames from
680
+ // getAllExuluVariables' row.name filter — never a row's value, so no
681
+ // credential value can ride along in this event.
682
+ const auditLogger = getAuditLogger(config)
683
+ if (auditLogger.shouldAuditSkillSandbox()) {
684
+ // An audit sink exception must never deny a user their skill: the
685
+ // sandbox is already built at this point, and the event is a record of
686
+ // it, not a precondition for it.
687
+ try {
688
+ auditLogger.record(
689
+ buildSkillSandboxEvent({
690
+ sessionID: sessionId,
691
+ agent,
692
+ user: userId !== undefined ? { id: userId } : undefined,
693
+ skills: skills.map((s) => ({ id: s.id, name: s.name, version: s.current_version })),
694
+ grantedNames,
695
+ withheldNames,
696
+ skippedNames,
697
+ strippedSecretCount: strippedSecretNames.length,
698
+ degradedSandbox: useDirectExec,
699
+ }),
700
+ )
701
+ } catch (err) {
702
+ console.error(
703
+ `[SKILLS] audit: skill-sandbox emit failed for session ${sessionId}; continuing.`,
704
+ err,
705
+ )
706
+ }
707
+ }
708
+
709
+ if (withheldNames.length) {
710
+ console.log(
711
+ `[SKILLS] Session ${sessionId}: ${withheldNames.length} variable(s) not shared with skills: ${withheldNames.join(", ")}.`,
712
+ )
610
713
  }
611
714
 
612
715
  // Either wrap a command with bwrap/sandbox-exec or return it unchanged when
@@ -752,7 +855,7 @@ export async function createSessionSandbox(
752
855
  `mkdir -p ${shellQuote(dirname(file.path))} && cat > ${shellQuote(file.path)}`,
753
856
  )
754
857
  await new Promise<void>((resolveSpawn, rejectSpawn) => {
755
- const child = spawn('/bin/bash', ['-c', wrapped])
858
+ const child = spawn('/bin/bash', ['-c', wrapped], { env: sandboxedExecEnv })
756
859
  let stderr = ''
757
860
  child.stderr.on('data', (chunk) => { stderr += chunk.toString() })
758
861
  child.on('error', rejectSpawn)